diff --git a/launchd/com.renacode.cloudmachine.app.plist.template b/launchd/com.renacode.cloudmachine.app.plist.template index 5b94cc0..e14e622 100644 --- a/launchd/com.renacode.cloudmachine.app.plist.template +++ b/launchd/com.renacode.cloudmachine.app.plist.template @@ -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. --> diff --git a/mac-app/Resources/Info.plist b/mac-app/Resources/Info.plist index 42a4945..620f3e0 100644 --- a/mac-app/Resources/Info.plist +++ b/mac-app/Resources/Info.plist @@ -63,6 +63,15 @@ 14.0 LSUIElement + + NSSupportsAutomaticTermination + + NSSupportsSuddenTermination + NSHumanReadableCopyright Copyright (c) 2026 RenaCode. MIT License. NSHighResolutionCapable diff --git a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift index a836478..32bcbe2 100644 --- a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift +++ b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift @@ -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 } @@ -85,6 +99,7 @@ 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. @@ -92,6 +107,14 @@ struct BackupHealthCommand: AsyncParsableCommand { } } +/// 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 { diff --git a/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift b/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift index 28682f6..aaae9dd 100644 --- a/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift +++ b/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift @@ -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 { @@ -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) @@ -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)) } } diff --git a/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift b/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift new file mode 100644 index 0000000..6119787 --- /dev/null +++ b/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift @@ -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 + } +} diff --git a/mac-app/Sources/CloudMachineApp/Models/MenuBarIcon.swift b/mac-app/Sources/CloudMachineApp/Models/MenuBarIcon.swift index e0b1fd8..ac5227d 100644 --- a/mac-app/Sources/CloudMachineApp/Models/MenuBarIcon.swift +++ b/mac-app/Sources/CloudMachineApp/Models/MenuBarIcon.swift @@ -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 diff --git a/mac-app/Sources/CloudMachineApp/Views/MenuBarContentView.swift b/mac-app/Sources/CloudMachineApp/Views/MenuBarContentView.swift index 2fd23a6..6ca0c3f 100644 --- a/mac-app/Sources/CloudMachineApp/Views/MenuBarContentView.swift +++ b/mac-app/Sources/CloudMachineApp/Views/MenuBarContentView.swift @@ -99,7 +99,7 @@ struct MenuBarPanel: View { } } .buttonStyle(SecondaryGlassButtonStyle()) - Button(action: { NSApplication.shared.terminate(nil) }) { + Button(action: quitByUser) { Image(systemName: "power") } .buttonStyle(SecondaryGlassButtonStyle()) @@ -315,7 +315,7 @@ struct MenuBarPanel: View { } .buttonStyle(SecondaryGlassButtonStyle()) - Button(action: { NSApplication.shared.terminate(nil) }) { + Button(action: quitByUser) { Image(systemName: "power") } .buttonStyle(SecondaryGlassButtonStyle()) @@ -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) +} diff --git a/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift b/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift new file mode 100644 index 0000000..647e0db --- /dev/null +++ b/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift @@ -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) + } + + /// " " + 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 } + } +} diff --git a/mac-app/Sources/CloudMachineCore/L10nPolish+Agent.swift b/mac-app/Sources/CloudMachineCore/L10nPolish+Agent.swift index ff13f7e..d284907 100644 --- a/mac-app/Sources/CloudMachineCore/L10nPolish+Agent.swift +++ b/mac-app/Sources/CloudMachineCore/L10nPolish+Agent.swift @@ -133,6 +133,10 @@ extension L10nPolish { "NIE STARTUJĄ: %@ - otwórz CloudMachine albo uruchom backup-health, żeby je przeładować", "Reloaded agents that could not start: %@": "Przeładowano agentów, którzy nie mogli wystartować: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine nie działał: otwarto go ponownie.", + "The CloudMachine app does not respond (no sign of life for %@).": + "Aplikacja CloudMachine nie odpowiada (brak oznak życia od %@).", "Drive folder: %@": "Folder na Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift index 9e0af26..46cb655 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "تعذّر البدء: %@ - افتح CloudMachine أو شغّل backup-health لإعادة تحميلها", "Reloaded agents that could not start: %@": "أُعيد تحميل الوكلاء الذين تعذّر بدؤهم: %@", + "CloudMachine was not running: reopened it.": + "لم يكن CloudMachine يعمل: تمت إعادة فتحه.", + "The CloudMachine app does not respond (no sign of life for %@).": + "تطبيق CloudMachine لا يستجيب (لا توجد أي إشارة نشاط منذ %@).", "Drive folder: %@": "مجلد Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift index 817f95a..73cd2ee 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "KAN IKKE STARTE: %@ - åbn CloudMachine eller kør backup-health for at indlæse dem igen", "Reloaded agents that could not start: %@": "Genindlæste agenter, der ikke kunne starte: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine kørte ikke: åbnet igen.", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine-appen svarer ikke (intet livstegn i %@).", "Drive folder: %@": "Drive-mappe: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift index f78633d..46c9bb9 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "KANN NICHT STARTEN: %@ – CloudMachine öffnen oder backup-health ausführen, um sie neu zu laden", "Reloaded agents that could not start: %@": "Agents neu geladen, die nicht starten konnten: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine lief nicht: erneut geöffnet.", + "The CloudMachine app does not respond (no sign of life for %@).": + "Die CloudMachine-App reagiert nicht (kein Lebenszeichen seit %@).", "Drive folder: %@": "Drive-Ordner: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift index 7e4d6c5..10ac10d 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "NO PUEDEN INICIARSE: %@ - abre CloudMachine o ejecuta backup-health para volver a cargarlos", "Reloaded agents that could not start: %@": "Agentes recargados que no podían iniciarse: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine no estaba en ejecución: se ha vuelto a abrir.", + "The CloudMachine app does not respond (no sign of life for %@).": + "La app CloudMachine no responde (sin señales de vida desde hace %@).", "Drive folder: %@": "Carpeta de Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift index 1f02e88..08fb0cf 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "EI KÄYNNISTY: %@ - avaa CloudMachine tai suorita backup-health ladataksesi ne uudelleen", "Reloaded agents that could not start: %@": "Uudelleenladattiin agentit, jotka eivät käynnistyneet: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine ei ollut käynnissä: avattu uudelleen.", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine-sovellus ei vastaa (ei elonmerkkejä: %@).", "Drive folder: %@": "Drive-kansio: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift index cbdf713..63c892d 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "DÉMARRAGE IMPOSSIBLE : %@ - ouvrez CloudMachine ou exécutez backup-health pour les recharger", "Reloaded agents that could not start: %@": "Agents rechargés qui n'avaient pas pu démarrer : %@", + "CloudMachine was not running: reopened it.": + "CloudMachine ne tournait pas : réouvert.", + "The CloudMachine app does not respond (no sign of life for %@).": + "L'app CloudMachine ne répond pas (aucun signe de vie depuis %@).", "Drive folder: %@": "Dossier Drive : %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift index 2058dcb..f3fb83a 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "לא ניתן להפעיל: %@ - פתח את CloudMachine או הרץ backup-health כדי לטעון אותם מחדש", "Reloaded agents that could not start: %@": "נטענו מחדש סוכנים שלא הצליחו לעלות: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine לא היה פועל: נפתח מחדש.", + "The CloudMachine app does not respond (no sign of life for %@).": + "אפליקציית CloudMachine אינה מגיבה (אין סימני חיים כבר %@).", "Drive folder: %@": "תיקיית Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift index 89c5f3b..90ed3ca 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "IMPOSSIBILE AVVIARE: %@ - apri CloudMachine o esegui backup-health per ricaricarli", "Reloaded agents that could not start: %@": "Agenti ricaricati che non erano riusciti ad avviarsi: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine non era in esecuzione: riaperto.", + "The CloudMachine app does not respond (no sign of life for %@).": + "L'app CloudMachine non risponde (nessun segno di vita da %@).", "Drive folder: %@": "Cartella su Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift index 046c60c..98650aa 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "起動できません: %@ - CloudMachineを開くか、backup-healthを実行して再読み込みしてください", "Reloaded agents that could not start: %@": "起動できなかったエージェントを再読み込みしました: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine は起動していませんでした。再度開きました。", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine アプリが応答していません(%@ の間、反応がありません)。", "Drive folder: %@": "Driveのフォルダ: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift index 4bec820..93b74f5 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "시작할 수 없음: %@ - CloudMachine을 열거나 backup-health를 실행하여 다시 불러오세요", "Reloaded agents that could not start: %@": "시작하지 못한 에이전트를 다시 불러왔습니다: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine이 실행 중이 아니어서 다시 열었습니다.", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine 앱이 응답하지 않습니다(%@ 동안 반응 없음).", "Drive folder: %@": "Drive 폴더: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift index 3247c9f..835bfc2 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "TIDAK DAPAT DIMULAKAN: %@ - buka CloudMachine atau jalankan backup-health untuk memuatkannya semula", "Reloaded agents that could not start: %@": "Ejen yang tidak dapat dimulakan telah dimuatkan semula: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine tidak berjalan: dibuka semula.", + "The CloudMachine app does not respond (no sign of life for %@).": + "Aplikasi CloudMachine tidak bertindak balas (tiada tanda hidup selama %@).", "Drive folder: %@": "Folder Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift index ae2c645..21ecc8e 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "KAN IKKE STARTE: %@ - åpne CloudMachine eller kjør backup-health for å laste dem på nytt", "Reloaded agents that could not start: %@": "Lastet på nytt agenter som ikke kunne starte: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine kjørte ikke: åpnet på nytt.", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine-appen svarer ikke (ingen livstegn på %@).", "Drive folder: %@": "Drive-mappe: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift index c98f855..7750128 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "KAN NIET STARTEN: %@ - open CloudMachine of voer backup-health uit om ze opnieuw te laden", "Reloaded agents that could not start: %@": "Agents opnieuw geladen die niet konden starten: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine draaide niet: opnieuw geopend.", + "The CloudMachine app does not respond (no sign of life for %@).": + "De CloudMachine-app reageert niet (geen teken van leven sinds %@).", "Drive folder: %@": "Drive-map: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift index a717e47..9bc5773 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "NÃO CONSEGUEM INICIAR: %@ - abra o CloudMachine ou execute backup-health para recarregá-los", "Reloaded agents that could not start: %@": "Agentes recarregados que não conseguiam iniciar: %@", + "CloudMachine was not running: reopened it.": + "O CloudMachine não estava em execução: reaberto.", + "The CloudMachine app does not respond (no sign of life for %@).": + "O app CloudMachine não responde (sem sinal de vida há %@).", "Drive folder: %@": "Pasta no Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift index c710a8c..f1db69e 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "НЕ ЗАПУСКАЮТСЯ: %@ - откройте CloudMachine или выполните backup-health, чтобы перезагрузить их", "Reloaded agents that could not start: %@": "Перезагружены агенты, которые не смогли запуститься: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine не был запущен: открыт снова.", + "The CloudMachine app does not respond (no sign of life for %@).": + "Приложение CloudMachine не отвечает (нет признаков жизни в течение %@).", "Drive folder: %@": "Папка на Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift index 355788f..ca02bb6 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "KAN INTE STARTA: %@ - öppna CloudMachine eller kör backup-health för att läsa in dem igen", "Reloaded agents that could not start: %@": "Agenter som inte kunde starta lästes in igen: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine kördes inte: öppnades igen.", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine-appen svarar inte (inga livstecken på %@).", "Drive folder: %@": "Drive-mapp: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift index 9a0981b..546ef28 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "เริ่มไม่ได้: %@ - เปิด CloudMachine หรือเรียกใช้ backup-health เพื่อโหลดใหม่", "Reloaded agents that could not start: %@": "โหลดเอเจนต์ที่เริ่มไม่ได้ใหม่แล้ว: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine ไม่ได้ทำงานอยู่ จึงเปิดใหม่แล้ว", + "The CloudMachine app does not respond (no sign of life for %@).": + "แอป CloudMachine ไม่ตอบสนอง (ไม่มีสัญญาณการทำงานมา %@)", "Drive folder: %@": "โฟลเดอร์ Drive: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift index da11850..a800aca 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "BAŞLAYAMIYOR: %@ - yeniden yüklemek için CloudMachine'i açın veya backup-health çalıştırın", "Reloaded agents that could not start: %@": "Başlayamayan aracılar yeniden yüklendi: %@", + "CloudMachine was not running: reopened it.": + "CloudMachine çalışmıyordu: yeniden açıldı.", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine uygulaması yanıt vermiyor (%@ boyunca yaşam belirtisi yok).", "Drive folder: %@": "Drive klasörü: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift index c63b28a..7d32fbf 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "无法启动:%@,请打开 CloudMachine 或运行 backup-health 重新载入", "Reloaded agents that could not start: %@": "已重新载入无法启动的代理:%@", + "CloudMachine was not running: reopened it.": + "CloudMachine 未在运行:已重新打开。", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine 应用无响应(已 %@ 没有任何动静)。", "Drive folder: %@": "Drive 文件夹: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift index 12b1502..83e94c3 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift @@ -133,6 +133,10 @@ extension L10nTranslations { "無法啟動:%@,請開啟 CloudMachine 或執行 backup-health 重新載入", "Reloaded agents that could not start: %@": "已重新載入無法啟動的代理程式:%@", + "CloudMachine was not running: reopened it.": + "CloudMachine 未在執行:已重新開啟。", + "The CloudMachine app does not respond (no sign of life for %@).": + "CloudMachine 應用程式沒有回應(已 %@ 沒有任何動靜)。", "Drive folder: %@": "Drive 資料夾: %@", "Name of this Mac's folder on Google Drive (default: derived from the computer name). Set once; it cannot be changed later.": diff --git a/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift new file mode 100644 index 0000000..9c9bf61 --- /dev/null +++ b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift @@ -0,0 +1,135 @@ +import XCTest + +@testable import CloudMachineCore + +/// The menu bar icon vanished on 1 Dec 2026 (loginwindow `appDeath`, no crash +/// report): a UIElement app without windows is a candidate for macOS Automatic +/// Termination, and nothing brought it back. +final class AppKeepAliveTests: XCTestCase { + private var dir: URL! + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + override func setUp() { + dir = FileManager.default.temporaryDirectory + .appendingPathComponent("keepalive-\(UUID().uuidString)") + try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + } + override func tearDown() { try? FileManager.default.removeItem(at: dir) } + + // MARK: Info.plist + + func testInfoPlistDisablesAutomaticAndSuddenTermination() throws { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Resources/Info.plist") + let plist = try XCTUnwrap(NSDictionary(contentsOf: url) as? [String: Any]) + XCTAssertEqual(plist["NSSupportsAutomaticTermination"] as? Bool, false) + XCTAssertEqual(plist["NSSupportsSuddenTermination"] as? Bool, false) + } + + // MARK: Decision + + private func decide( + running: Bool = false, quit: Bool = false, attempts: Int = 0, last: Date? = nil, + upgrading: Bool = false + ) -> AppKeepAlive.Decision { + AppKeepAlive.decide( + appRunning: running, quitByUser: quit, attempts: attempts, lastAttempt: last, + upgrading: upgrading, now: now) + } + + func testLaunchesWhenAppIsGone() { XCTAssertEqual(decide(), .launch) } + func testDoesNothingWhenRunning() { XCTAssertEqual(decide(running: true), .skip(.running)) } + func testRespectsDeliberateQuit() { XCTAssertEqual(decide(quit: true), .skip(.quitByUser)) } + func testSkipsDuringUpgrade() { XCTAssertEqual(decide(upgrading: true), .skip(.upgrading)) } + + func testRateLimitsRelaunches() { + XCTAssertEqual(decide(attempts: 1, last: now.addingTimeInterval(-60)), .skip(.tooSoon)) + let old = now.addingTimeInterval(-AppKeepAlive.minInterval - 1) + XCTAssertEqual(decide(attempts: 1, last: old), .launch) + } + + func testGivesUpAfterMaxAttempts() { + let old = now.addingTimeInterval(-3600) + XCTAssertEqual(decide(attempts: AppKeepAlive.maxAttempts - 1, last: old), .launch) + XCTAssertEqual(decide(attempts: AppKeepAlive.maxAttempts, last: old), .skip(.tooManyAttempts)) + } + + func testFutureAttemptTimestampDoesNotBlockForever() { + XCTAssertEqual(decide(attempts: 1, last: now.addingTimeInterval(3600)), .launch) + } + + // MARK: Hang detection + + func testHungOnlyWhenRunningWithStaleHeartbeat() { + let stale = now.addingTimeInterval(-AppKeepAlive.hangAfter - 1) + XCTAssertTrue(AppKeepAlive.isHung(appRunning: true, heartbeat: stale, now: now)) + XCTAssertFalse( + AppKeepAlive.isHung(appRunning: true, heartbeat: now.addingTimeInterval(-30), now: now)) + XCTAssertFalse(AppKeepAlive.isHung(appRunning: false, heartbeat: stale, now: now)) + XCTAssertFalse(AppKeepAlive.isHung(appRunning: true, heartbeat: nil, now: now)) + } + + func testHeartbeatRoundTrip() { + let keep = AppKeepAlive(stateDir: dir) + XCTAssertNil(keep.heartbeat) + keep.recordHeartbeat(now) + XCTAssertEqual(keep.heartbeat, now) + } + + // MARK: Markers and revive + + func testQuitMarkerRoundTrip() { + let keep = AppKeepAlive(stateDir: dir) + XCTAssertFalse(keep.quitByUser) + keep.markQuitByUser() + XCTAssertTrue(keep.quitByUser) + keep.appStarted() + XCTAssertFalse(keep.quitByUser) + } + + func testReviveLaunchesThenRateLimits() { + let keep = AppKeepAlive(stateDir: dir) + var launches = 0 + let go = { + launches += 1 + return true + } + XCTAssertTrue(keep.revive(appRunning: false, upgrading: false, now: now, launch: go)) + XCTAssertFalse( + keep.revive(appRunning: false, upgrading: false, now: now.addingTimeInterval(60), launch: go)) + XCTAssertEqual(launches, 1) + } + + func testReviveStopsAfterThreeAttemptsUntilTheAppStarts() { + let keep = AppKeepAlive(stateDir: dir) + var launches = 0 + let go = { + launches += 1 + return false + } + for i in 0..<6 { + keep.revive( + appRunning: false, upgrading: false, + now: now.addingTimeInterval(Double(i) * 3600), launch: go) + } + XCTAssertEqual(launches, AppKeepAlive.maxAttempts) + keep.appStarted() + keep.revive( + appRunning: false, upgrading: false, now: now.addingTimeInterval(99_999), launch: go) + XCTAssertEqual(launches, AppKeepAlive.maxAttempts + 1) + } + + func testReviveSkipsAfterQuitAndDuringUpgrade() { + let keep = AppKeepAlive(stateDir: dir) + var launches = 0 + let go = { + launches += 1 + return true + } + XCTAssertFalse(keep.revive(appRunning: false, upgrading: true, now: now, launch: go)) + keep.markQuitByUser() + XCTAssertFalse(keep.revive(appRunning: false, upgrading: false, now: now, launch: go)) + XCTAssertEqual(launches, 0) + } +} diff --git a/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift b/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift index 30cef06..ce7fd81 100644 --- a/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift +++ b/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift @@ -1,3 +1,4 @@ +import Combine import XCTest @testable import CloudMachineApp @@ -273,3 +274,76 @@ final class RefreshLoopTests: XCTestCase { XCTAssertTrue(controller.status.isBusy, "the first action's busy flag must stay") } } + +/// 1 Dec 2026: the menu bar icon never appeared. The label wrapped itself in +/// `TimelineView(.periodic(from: .now, by: 30))`; `.now` is evaluated on every +/// body pass, so every render made a new schedule starting "now", which asked +/// for a refresh at once, and the status item spun at 100 % CPU without ever +/// being created. The clock must live outside the view, with one timer. +@MainActor +final class MenuBarClockTests: XCTestCase { + /// A fake scheduler: counts timers, remembers intervals, lets the test fire + /// the action, and notices when the token is released. + private final class FakeScheduler { + var intervals: [TimeInterval] = [] + var action: (@MainActor () -> Void)? + var cancelled = 0 + func make(_ interval: TimeInterval, _ action: @escaping @MainActor () -> Void) + -> AnyCancellable + { + intervals.append(interval) + self.action = action + return AnyCancellable { [weak self] in self?.cancelled += 1 } + } + } + + func testOneTimerPerClockWithTheGivenIntervalAndItDiesWithTheClock() { + let fake = FakeScheduler() + var clock: MenuBarClock? = MenuBarClock(interval: 30, scheduler: fake.make) + XCTAssertNotNil(clock) + XCTAssertEqual(fake.intervals, [30]) + clock = nil + XCTAssertEqual(fake.cancelled, 1, "the timer must die with the clock") + } + + func testEachFirePublishesExactlyOnceAndWritesHeartbeat() { + let fake = FakeScheduler() + var beats: [Date] = [] + let start = Date(timeIntervalSince1970: 1_800_000_000) + let clock = MenuBarClock(start: start, scheduler: fake.make, heartbeat: { beats.append($0) }) + var publishes = 0 + let sub = clock.objectWillChange.sink { publishes += 1 } + XCTAssertEqual(publishes, 0, "creating the clock must not publish") + fake.action?() + XCTAssertEqual(publishes, 1) + fake.action?() + XCTAssertEqual(publishes, 2) + XCTAssertEqual(beats.count, 3, "start + 2 ticks") + sub.cancel() + } + + func testNothingPublishesWithoutATick() { + let clock = MenuBarClock(start: Date(timeIntervalSince1970: 0), scheduler: nil) + var publishes = 0 + let sub = clock.objectWillChange.sink { publishes += 1 } + RunLoop.main.run(until: Date().addingTimeInterval(0.3)) + XCTAssertEqual(publishes, 0) + sub.cancel() + } + + func testTickAdvancesNow() { + let clock = MenuBarClock(start: Date(timeIntervalSince1970: 0), scheduler: nil) + clock.tick(at: Date(timeIntervalSince1970: 30)) + XCTAssertEqual(clock.now, Date(timeIntervalSince1970: 30)) + } + + func testStateUsesTheClockNotTheWallClock() { + let status = AppStatus.healthyForTests() + let t0 = Date(timeIntervalSince1970: 1_800_000_000) + status.lastRefresh = t0 + XCTAssertEqual(MenuBarIcon.state(for: status, now: t0), .healthy) + XCTAssertEqual( + MenuBarIcon.state(for: status, now: t0.addingTimeInterval(AppStatus.staleAfter + 5)), + .unknown) + } +}