From 57b9e09ab2657592a00874113f7e79585b9dfeb9 Mon Sep 17 00:00:00 2001 From: RenaCode Date: Tue, 1 Dec 2026 19:31:15 +0100 Subject: [PATCH 1/6] App paska menu: ikona nie powstawala (petla TimelineView) + pilnowanie aplikacji Etykieta MenuBarExtra uzywala TimelineView(.periodic(from: .now)): kazde renderowanie startowalo nowy harmonogram, status item wpadal w nieskonczona petle (100% CPU, brak ikony). Zegar przeniesiony do MenuBarClock. Dodatkowo: NSSupports{Automatic,Sudden}Termination=false, a watchdog backup-health ponownie otwiera aplikacje (AppKeepAlive, limit 15 min, szanuje Quit z menu). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AU1MhuGSAj8JTZKLqUoP7Q --- ...m.renacode.cloudmachine.app.plist.template | 4 + mac-app/Resources/Info.plist | 9 ++ .../MaintenanceCommands.swift | 6 + .../CloudMachineApp/CloudMachineApp.swift | 22 ++-- .../CloudMachineApp/Models/MenuBarClock.swift | 27 +++++ .../CloudMachineApp/Models/MenuBarIcon.swift | 4 +- .../Views/MenuBarContentView.swift | 11 +- .../CloudMachineCore/AppKeepAlive.swift | 106 ++++++++++++++++++ .../AppKeepAliveTests.swift | 105 +++++++++++++++++ .../CloudMachineAppTests/AuditP1Tests.swift | 48 ++++++++ 10 files changed, 331 insertions(+), 11 deletions(-) create mode 100644 mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift create mode 100644 mac-app/Sources/CloudMachineCore/AppKeepAlive.swift create mode 100644 mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift 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..3519c96 100644 --- a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift +++ b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift @@ -54,6 +54,12 @@ struct BackupHealthCommand: AsyncParsableCommand { L10n.tr("Reloaded agents that could not start: %@", repaired.joined(separator: ", "))) } + // The menu bar icon is only a viewer, but a vanished icon looks like a + // dead backup to the person (see `AppKeepAlive`). + if AppKeepAlive().revive() { + print("CloudMachine was not running: reopened it.") + } + if let lastSuccess = report.lastSuccess { print(L10n.tr("Last successful backup: %@", BackupHealth.stamp(lastSuccess))) } else { diff --git a/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift b/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift index 28682f6..b47dc68 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() + + init() { + // The icon must stay until the person quits (see `AppKeepAlive`). + ProcessInfo.processInfo.disableAutomaticTermination("menu bar app") + ProcessInfo.processInfo.disableSuddenTermination() + // Started again: the earlier deliberate Quit no longer applies. + AppKeepAlive().clearQuitMarker() + } 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..e1ecb21 --- /dev/null +++ b/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift @@ -0,0 +1,27 @@ +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. +@MainActor +final class MenuBarClock: ObservableObject { + @Published private(set) var now: Date + private var timer: Timer? + + /// `interval == nil`: no timer (tests tick by hand). + init(start: Date = Date(), interval: TimeInterval? = 30) { + now = start + if let interval { + timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in + Task { @MainActor in self?.tick() } + } + } + } + + func tick(at date: Date = Date()) { now = date } + + deinit { timer?.invalidate() } +} 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..4ec8307 --- /dev/null +++ b/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift @@ -0,0 +1,106 @@ +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). +/// +/// So the 30-minute watchdog (`backup-health`) calls `revive`: when the app is +/// not running it opens it, unless the person quit it from its own menu (the +/// marker `app-quit-by-user`, cleared whenever the app starts), and at most +/// once per `minInterval`. Homebrew quits the app for an upgrade without that +/// marker, so an upgrade is followed by a reopen within 30 minutes. +public struct AppKeepAlive { + public enum Reason: Equatable { case running, quitByUser, tooSoon } + public enum Decision: Equatable { + case launch + case skip(Reason) + } + + public static let minInterval: TimeInterval = 15 * 60 + public static let bundleIdentifier = "com.renacode.cloudmachine" + public static let appPath = "/Applications/CloudMachine.app" + + private let quitMarker: URL + private let attemptFile: URL + + public init(stateDir: URL = CMPaths.stateDir) { + quitMarker = stateDir.appendingPathComponent("app-quit-by-user") + attemptFile = stateDir.appendingPathComponent("app-relaunch-at") + } + + public static func decide( + appRunning: Bool, quitByUser: Bool, lastAttempt: Date?, now: Date + ) -> Decision { + if appRunning { return .skip(.running) } + if quitByUser { return .skip(.quitByUser) } + // 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 + } + + // MARK: - Markers + + public var quitByUser: Bool { FileManager.default.fileExists(atPath: quitMarker.path) } + + public func markQuitByUser() { + try? Data().write(to: quitMarker) + } + + public func clearQuitMarker() { + try? FileManager.default.removeItem(at: quitMarker) + } + + private var lastAttempt: Date? { + guard let text = try? String(contentsOf: attemptFile, encoding: .utf8), + let t = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines)) + else { return nil } + return 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(), + now: Date = Date(), + launch: () -> Bool = AppKeepAlive.openApp + ) -> Bool { + guard + case .launch = Self.decide( + appRunning: appRunning, quitByUser: quitByUser, lastAttempt: lastAttempt, now: now) + else { return false } + try? String(now.timeIntervalSince1970).write( + to: attemptFile, atomically: true, encoding: .utf8) + return launch() + } + + public static func isRunning() -> Bool { + !NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).isEmpty + } + + /// `open -g` (no focus steal), through Launch Services so the app gets its + /// Aqua session. 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() + p.waitUntilExit() + return p.terminationStatus == 0 + } catch { return false } + } +} diff --git a/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift new file mode 100644 index 0000000..25a3754 --- /dev/null +++ b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift @@ -0,0 +1,105 @@ +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 + + func testLaunchesWhenAppIsGone() { + XCTAssertEqual( + AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: nil, now: now), + .launch) + } + + func testDoesNothingWhenRunning() { + XCTAssertEqual( + AppKeepAlive.decide(appRunning: true, quitByUser: false, lastAttempt: nil, now: now), + .skip(.running)) + } + + func testRespectsDeliberateQuit() { + XCTAssertEqual( + AppKeepAlive.decide(appRunning: false, quitByUser: true, lastAttempt: nil, now: now), + .skip(.quitByUser)) + } + + func testRateLimitsRelaunches() { + let recent = now.addingTimeInterval(-60) + XCTAssertEqual( + AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: recent, now: now), + .skip(.tooSoon)) + let old = now.addingTimeInterval(-AppKeepAlive.minInterval - 1) + XCTAssertEqual( + AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: old, now: now), + .launch) + } + + func testFutureAttemptTimestampDoesNotBlockForever() { + let future = now.addingTimeInterval(3600) + XCTAssertEqual( + AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: future, now: now), + .launch) + } + + // MARK: Markers and perform + + func testQuitMarkerRoundTrip() { + let keep = AppKeepAlive(stateDir: dir) + XCTAssertFalse(keep.quitByUser) + keep.markQuitByUser() + XCTAssertTrue(keep.quitByUser) + keep.clearQuitMarker() + XCTAssertFalse(keep.quitByUser) + } + + func testPerformLaunchesOnceThenRateLimits() { + let keep = AppKeepAlive(stateDir: dir) + var launches = 0 + XCTAssertTrue(keep.revive(appRunning: false, now: now, launch: { launches += 1; return true })) + XCTAssertFalse( + keep.revive( + appRunning: false, now: now.addingTimeInterval(60), launch: { launches += 1; return true })) + XCTAssertEqual(launches, 1) + } + + func testPerformSkipsAfterQuit() { + let keep = AppKeepAlive(stateDir: dir) + keep.markQuitByUser() + var launches = 0 + XCTAssertFalse(keep.revive(appRunning: false, now: now, launch: { launches += 1; return true })) + XCTAssertEqual(launches, 0) + } + + func testFailedLaunchStillCountsAsAttempt() { + let keep = AppKeepAlive(stateDir: dir) + XCTAssertFalse(keep.revive(appRunning: false, now: now, launch: { false })) + var launches = 0 + _ = keep.revive( + appRunning: false, now: now.addingTimeInterval(60), launch: { launches += 1; return true }) + XCTAssertEqual(launches, 0) + } +} diff --git a/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift b/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift index 30cef06..3bba19c 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,50 @@ 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. +@MainActor +final class MenuBarClockTests: XCTestCase { + func testClockDoesNotPublishOnItsOwn() { + let start = Date(timeIntervalSince1970: 1_800_000_000) + let clock = MenuBarClock(start: start, interval: nil) + var publishes = 0 + let cancel = clock.objectWillChange.sink { publishes += 1 } + RunLoop.main.run(until: Date().addingTimeInterval(0.3)) + XCTAssertEqual(publishes, 0, "reading or waiting must not invalidate the label") + XCTAssertEqual(clock.now, start) + cancel.cancel() + } + + func testTickAdvancesNowExactlyOnce() { + let clock = MenuBarClock(start: Date(timeIntervalSince1970: 0), interval: nil) + var publishes = 0 + let cancel = clock.objectWillChange.sink { publishes += 1 } + clock.tick(at: Date(timeIntervalSince1970: 30)) + XCTAssertEqual(publishes, 1) + XCTAssertEqual(clock.now, Date(timeIntervalSince1970: 30)) + cancel.cancel() + } + + 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) + } + + func testLabelDoesNotUseTimelineView() throws { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Sources/CloudMachineApp/CloudMachineApp.swift") + let source = try String(contentsOf: url, encoding: .utf8) + XCTAssertFalse(source.contains("TimelineView"), "see the 1 Dec 2026 render loop") + } +} From 1ff10b4e55fc39f84fee5b461ae5b13ddf3d5232 Mon Sep 17 00:00:00 2001 From: RenaCode Date: Tue, 1 Dec 2026 19:40:01 +0100 Subject: [PATCH 2/6] Aplikacja paska menu: uwagi z przegladu (heartbeat, limit prob, brew, timeout open) Heartbeat z zegara + UWAGA o zawieszonej aplikacji, ozywianie po raporcie, timeout open 15 s, pominiecie podczas aktualizacji, max 3 proby do startu aplikacji, tlumaczenia komunikatow, testy zegara przez wstrzykiwany scheduler. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AU1MhuGSAj8JTZKLqUoP7Q --- .../MaintenanceCommands.swift | 27 ++++- .../CloudMachineApp/CloudMachineApp.swift | 6 +- .../CloudMachineApp/Models/MenuBarClock.swift | 41 +++++-- .../CloudMachineCore/AppKeepAlive.swift | 112 +++++++++++++++--- .../CloudMachineCore/L10nPolish+Agent.swift | 4 + .../L10nTranslations+ar.swift | 4 + .../L10nTranslations+da.swift | 4 + .../L10nTranslations+de.swift | 4 + .../L10nTranslations+es.swift | 4 + .../L10nTranslations+fi.swift | 4 + .../L10nTranslations+fr.swift | 4 + .../L10nTranslations+he.swift | 4 + .../L10nTranslations+it.swift | 4 + .../L10nTranslations+ja.swift | 4 + .../L10nTranslations+ko.swift | 4 + .../L10nTranslations+ms.swift | 4 + .../L10nTranslations+nb.swift | 4 + .../L10nTranslations+nl.swift | 4 + .../L10nTranslations+pt-BR.swift | 4 + .../L10nTranslations+ru.swift | 4 + .../L10nTranslations+sv.swift | 4 + .../L10nTranslations+th.swift | 4 + .../L10nTranslations+tr.swift | 4 + .../L10nTranslations+zh-Hans.swift | 4 + .../L10nTranslations+zh-Hant.swift | 4 + .../AppKeepAliveTests.swift | 101 +++++++++------- .../CloudMachineAppTests/AuditP1Tests.swift | 68 +++++++---- 27 files changed, 340 insertions(+), 99 deletions(-) diff --git a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift index 3519c96..fc82066 100644 --- a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift +++ b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift @@ -54,12 +54,6 @@ struct BackupHealthCommand: AsyncParsableCommand { L10n.tr("Reloaded agents that could not start: %@", repaired.joined(separator: ", "))) } - // The menu bar icon is only a viewer, but a vanished icon looks like a - // dead backup to the person (see `AppKeepAlive`). - if AppKeepAlive().revive() { - print("CloudMachine was not running: reopened it.") - } - if let lastSuccess = report.lastSuccess { print(L10n.tr("Last successful backup: %@", BackupHealth.stamp(lastSuccess))) } else { @@ -80,9 +74,21 @@ 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 } @@ -91,6 +97,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. @@ -98,6 +105,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 b47dc68..aaae9dd 100644 --- a/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift +++ b/mac-app/Sources/CloudMachineApp/CloudMachineApp.swift @@ -4,14 +4,14 @@ import SwiftUI @main struct CloudMachineApp: App { @StateObject private var controller = CloudMachineController() - @StateObject private var clock = MenuBarClock() + @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: the earlier deliberate Quit no longer applies. - AppKeepAlive().clearQuitMarker() + // Started again: an earlier deliberate Quit and failed reopen attempts no longer apply. + AppKeepAlive().appStarted() } var body: some Scene { diff --git a/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift b/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift index e1ecb21..6119787 100644 --- a/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift +++ b/mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift @@ -5,23 +5,40 @@ import Foundation /// 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. +/// 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 { - @Published private(set) var now: Date - private var timer: Timer? + /// Starts a repeating action; the returned token cancels it when released. + typealias Scheduler = (TimeInterval, @escaping @MainActor () -> Void) -> AnyCancellable - /// `interval == nil`: no timer (tests tick by hand). - init(start: Date = Date(), interval: TimeInterval? = 30) { - now = start - if let interval { - timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in - Task { @MainActor in self?.tick() } - } + static let liveScheduler: Scheduler = { interval, action in + let timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in + Task { @MainActor in action() } } + return AnyCancellable { timer.invalidate() } } - func tick(at date: Date = Date()) { now = date } + @Published private(set) var now: Date + private var schedule: AnyCancellable? + private let heartbeat: (Date) -> Void - deinit { timer?.invalidate() } + /// `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/CloudMachineCore/AppKeepAlive.swift b/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift index 4ec8307..647e0db 100644 --- a/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift +++ b/mac-app/Sources/CloudMachineCore/AppKeepAlive.swift @@ -11,35 +11,57 @@ import Foundation /// afterwards, and the `app` launchd agent has only `RunAtLoad` (no /// KeepAlive: `open` exits at once, so KeepAlive would loop). /// -/// So the 30-minute watchdog (`backup-health`) calls `revive`: when the app is -/// not running it opens it, unless the person quit it from its own menu (the -/// marker `app-quit-by-user`, cleared whenever the app starts), and at most -/// once per `minInterval`. Homebrew quits the app for an upgrade without that -/// marker, so an upgrade is followed by a reopen within 30 minutes. +/// 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 } + public enum Reason: Equatable { case running, quitByUser, tooSoon, tooManyAttempts, upgrading } public enum Decision: Equatable { case launch case skip(Reason) } - public static let minInterval: TimeInterval = 15 * 60 + 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-at") + attemptFile = stateDir.appendingPathComponent("app-relaunch-attempts") + heartbeatFile = stateDir.appendingPathComponent("app-heartbeat") } public static func decide( - appRunning: Bool, quitByUser: Bool, lastAttempt: Date?, now: Date + 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) @@ -47,6 +69,13 @@ public struct AppKeepAlive { 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) } @@ -55,17 +84,37 @@ public struct AppKeepAlive { try? Data().write(to: quitMarker) } - public func clearQuitMarker() { + /// 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) } - private var lastAttempt: Date? { - guard let text = try? String(contentsOf: attemptFile, encoding: .utf8), - let t = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines)) + 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 @@ -74,14 +123,17 @@ public struct AppKeepAlive { @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, lastAttempt: lastAttempt, now: now) + appRunning: appRunning, quitByUser: quitByUser, attempts: state.count, + lastAttempt: state.last, upgrading: upgrading, now: now) else { return false } - try? String(now.timeIntervalSince1970).write( + try? "\(state.count + 1) \(now.timeIntervalSince1970)".write( to: attemptFile, atomically: true, encoding: .utf8) return launch() } @@ -90,8 +142,29 @@ public struct AppKeepAlive { !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. Does nothing when the app is not installed. + /// 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() @@ -99,7 +172,12 @@ public struct AppKeepAlive { p.arguments = ["-g", "-a", appPath] do { try p.run() - p.waitUntilExit() + 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 index 25a3754..67c19b4 100644 --- a/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift +++ b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift @@ -29,77 +29,98 @@ final class AppKeepAliveTests: XCTestCase { // MARK: Decision - func testLaunchesWhenAppIsGone() { - XCTAssertEqual( - AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: nil, now: now), - .launch) + 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 testDoesNothingWhenRunning() { - XCTAssertEqual( - AppKeepAlive.decide(appRunning: true, quitByUser: false, lastAttempt: nil, now: now), - .skip(.running)) - } - - func testRespectsDeliberateQuit() { - XCTAssertEqual( - AppKeepAlive.decide(appRunning: false, quitByUser: true, lastAttempt: nil, now: now), - .skip(.quitByUser)) - } + 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() { - let recent = now.addingTimeInterval(-60) - XCTAssertEqual( - AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: recent, now: now), - .skip(.tooSoon)) + XCTAssertEqual(decide(attempts: 1, last: now.addingTimeInterval(-60)), .skip(.tooSoon)) let old = now.addingTimeInterval(-AppKeepAlive.minInterval - 1) - XCTAssertEqual( - AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: old, now: now), - .launch) + 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() { - let future = now.addingTimeInterval(3600) - XCTAssertEqual( - AppKeepAlive.decide(appRunning: false, quitByUser: false, lastAttempt: future, now: now), - .launch) + XCTAssertEqual(decide(attempts: 1, last: now.addingTimeInterval(3600)), .launch) } - // MARK: Markers and perform + // 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.clearQuitMarker() + keep.appStarted() XCTAssertFalse(keep.quitByUser) } - func testPerformLaunchesOnceThenRateLimits() { + func testReviveLaunchesThenRateLimits() { let keep = AppKeepAlive(stateDir: dir) var launches = 0 - XCTAssertTrue(keep.revive(appRunning: false, now: now, launch: { launches += 1; return true })) + let go = { launches += 1; return true } + XCTAssertTrue(keep.revive(appRunning: false, upgrading: false, now: now, launch: go)) XCTAssertFalse( - keep.revive( - appRunning: false, now: now.addingTimeInterval(60), launch: { launches += 1; return true })) + keep.revive(appRunning: false, upgrading: false, now: now.addingTimeInterval(60), launch: go)) XCTAssertEqual(launches, 1) } - func testPerformSkipsAfterQuit() { + func testReviveStopsAfterThreeAttemptsUntilTheAppStarts() { let keep = AppKeepAlive(stateDir: dir) - keep.markQuitByUser() var launches = 0 - XCTAssertFalse(keep.revive(appRunning: false, now: now, launch: { launches += 1; return true })) - XCTAssertEqual(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 testFailedLaunchStillCountsAsAttempt() { + func testReviveSkipsAfterQuitAndDuringUpgrade() { let keep = AppKeepAlive(stateDir: dir) - XCTAssertFalse(keep.revive(appRunning: false, now: now, launch: { false })) var launches = 0 - _ = keep.revive( - appRunning: false, now: now.addingTimeInterval(60), launch: { launches += 1; return true }) + 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 3bba19c..ce7fd81 100644 --- a/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift +++ b/mac-app/Tests/CloudMachineAppTests/AuditP1Tests.swift @@ -279,28 +279,62 @@ final class RefreshLoopTests: XCTestCase { /// `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. +/// being created. The clock must live outside the view, with one timer. @MainActor final class MenuBarClockTests: XCTestCase { - func testClockDoesNotPublishOnItsOwn() { + /// 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, interval: nil) + let clock = MenuBarClock(start: start, scheduler: fake.make, heartbeat: { beats.append($0) }) var publishes = 0 - let cancel = clock.objectWillChange.sink { publishes += 1 } - RunLoop.main.run(until: Date().addingTimeInterval(0.3)) - XCTAssertEqual(publishes, 0, "reading or waiting must not invalidate the label") - XCTAssertEqual(clock.now, start) - cancel.cancel() + 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 testTickAdvancesNowExactlyOnce() { - let clock = MenuBarClock(start: Date(timeIntervalSince1970: 0), interval: nil) + func testNothingPublishesWithoutATick() { + let clock = MenuBarClock(start: Date(timeIntervalSince1970: 0), scheduler: nil) var publishes = 0 - let cancel = clock.objectWillChange.sink { publishes += 1 } + 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(publishes, 1) XCTAssertEqual(clock.now, Date(timeIntervalSince1970: 30)) - cancel.cancel() } func testStateUsesTheClockNotTheWallClock() { @@ -312,12 +346,4 @@ final class MenuBarClockTests: XCTestCase { MenuBarIcon.state(for: status, now: t0.addingTimeInterval(AppStatus.staleAfter + 5)), .unknown) } - - func testLabelDoesNotUseTimelineView() throws { - let url = URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - .appendingPathComponent("Sources/CloudMachineApp/CloudMachineApp.swift") - let source = try String(contentsOf: url, encoding: .utf8) - XCTAssertFalse(source.contains("TimelineView"), "see the 1 Dec 2026 render loop") - } } From f3b207dda7a4df1c10658bdb4d58b4df4e9a2ba9 Mon Sep 17 00:00:00 2001 From: RenaCode Date: Tue, 1 Dec 2026 19:41:57 +0100 Subject: [PATCH 3/6] swift-format: poprawki lint Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AU1MhuGSAj8JTZKLqUoP7Q --- .../CloudMachineAgent/MaintenanceCommands.swift | 6 ++++-- .../CloudMachineAppTests/AppKeepAliveTests.swift | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift index fc82066..32bcbe2 100644 --- a/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift +++ b/mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift @@ -79,10 +79,12 @@ struct BackupHealthCommand: AsyncParsableCommand { if AppKeepAlive.isHung( appRunning: AppKeepAlive.isRunning(), heartbeat: keepAlive.heartbeat, now: Date()) { - let age = keepAlive.heartbeat.map { BackupHealth.formatAge(Date().timeIntervalSince($0)) } ?? "" + 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))) + "NOTE: %@", + L10n.tr("The CloudMachine app does not respond (no sign of life for %@).", age))) } guard !report.healthy else { diff --git a/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift index 67c19b4..9c9bf61 100644 --- a/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift +++ b/mac-app/Tests/CloudMachineAppTests/AppKeepAliveTests.swift @@ -91,7 +91,10 @@ final class AppKeepAliveTests: XCTestCase { func testReviveLaunchesThenRateLimits() { let keep = AppKeepAlive(stateDir: dir) var launches = 0 - let go = { launches += 1; return true } + 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)) @@ -101,7 +104,10 @@ final class AppKeepAliveTests: XCTestCase { func testReviveStopsAfterThreeAttemptsUntilTheAppStarts() { let keep = AppKeepAlive(stateDir: dir) var launches = 0 - let go = { launches += 1; return false } + let go = { + launches += 1 + return false + } for i in 0..<6 { keep.revive( appRunning: false, upgrading: false, @@ -117,7 +123,10 @@ final class AppKeepAliveTests: XCTestCase { func testReviveSkipsAfterQuitAndDuringUpgrade() { let keep = AppKeepAlive(stateDir: dir) var launches = 0 - let go = { launches += 1; return true } + 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)) From 2b6a90f29ee5fcf4d47df34a34803d882fff5c7f Mon Sep 17 00:00:00 2001 From: RenaCode Date: Tue, 1 Dec 2026 22:13:10 +0100 Subject: [PATCH 4/6] Time Machine po nazwie mDNS (lima-.local) zamiast adresu DHCP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maszyna ogłasza nazwę i _smb/_adisk przez systemd-resolved na lima0 (bez pakietów); aplikacja ustawia cel TM na nazwę, gdy Mac ją rozwiązuje do maszyny; vm-status i backup-health sprawdzają rozwiązywanie. Zmiana celu (replace) odłącza najpierw obraz udziału (inaczej pierwsza kopia: "Failed locking the image"). Tłumaczenia 7 nowych kluczy. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AU1MhuGSAj8JTZKLqUoP7Q --- .../CloudMachineAgent/VMCommands.swift | 2 +- .../Services/CloudMachineController.swift | 2 +- .../CloudMachineCore/BackupHealth.swift | 12 +- .../CloudMachineCore/L10nPolish+VM.swift | 14 ++ .../L10nTranslations+ar.swift | 14 ++ .../L10nTranslations+da.swift | 14 ++ .../L10nTranslations+de.swift | 14 ++ .../L10nTranslations+es.swift | 14 ++ .../L10nTranslations+fi.swift | 14 ++ .../L10nTranslations+fr.swift | 14 ++ .../L10nTranslations+he.swift | 14 ++ .../L10nTranslations+it.swift | 14 ++ .../L10nTranslations+ja.swift | 14 ++ .../L10nTranslations+ko.swift | 14 ++ .../L10nTranslations+ms.swift | 14 ++ .../L10nTranslations+nb.swift | 14 ++ .../L10nTranslations+nl.swift | 14 ++ .../L10nTranslations+pt-BR.swift | 14 ++ .../L10nTranslations+ru.swift | 14 ++ .../L10nTranslations+sv.swift | 14 ++ .../L10nTranslations+th.swift | 14 ++ .../L10nTranslations+tr.swift | 14 ++ .../L10nTranslations+zh-Hans.swift | 14 ++ .../L10nTranslations+zh-Hant.swift | 14 ++ .../TimeMachineDestinationFix.swift | 42 ++++- .../Sources/CloudMachineCore/VMMdnsName.swift | 94 ++++++++++ .../Sources/CloudMachineCore/VMStatus.swift | 32 +++- .../TimeMachineDestinationFixTests.swift | 23 +++ .../VMMdnsNameTests.swift | 176 ++++++++++++++++++ vm/cmsmb.yaml | 22 +++ 30 files changed, 693 insertions(+), 6 deletions(-) create mode 100644 mac-app/Sources/CloudMachineCore/VMMdnsName.swift create mode 100644 mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift diff --git a/mac-app/Sources/CloudMachineAgent/VMCommands.swift b/mac-app/Sources/CloudMachineAgent/VMCommands.swift index da82585..45a209e 100644 --- a/mac-app/Sources/CloudMachineAgent/VMCommands.swift +++ b/mac-app/Sources/CloudMachineAgent/VMCommands.swift @@ -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) } diff --git a/mac-app/Sources/CloudMachineApp/Services/CloudMachineController.swift b/mac-app/Sources/CloudMachineApp/Services/CloudMachineController.swift index 044efb6..07551e1 100644 --- a/mac-app/Sources/CloudMachineApp/Services/CloudMachineController.swift +++ b/mac-app/Sources/CloudMachineApp/Services/CloudMachineController.swift @@ -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()) } } diff --git a/mac-app/Sources/CloudMachineCore/BackupHealth.swift b/mac-app/Sources/CloudMachineCore/BackupHealth.swift index 907b3e2..72dcf7b 100644 --- a/mac-app/Sources/CloudMachineCore/BackupHealth.swift +++ b/mac-app/Sources/CloudMachineCore/BackupHealth.swift @@ -163,7 +163,7 @@ public enum BackupHealth { } var chosen: [String: Any]? if let address { - let hosts = [address] + (alias.map { [$0] } ?? []) + let hosts = [address] + (alias.map { [$0] } ?? []) + (VMMdnsName.currentHostName.map { [$0] } ?? []) chosen = candidates.first { ($0["NetworkURL"] as? String).flatMap { VMAddressLease.destinationHost($0) } @@ -898,6 +898,16 @@ public enum BackupHealth { if let pool = DHCPPool.current(address: address, mac: mac, alias: alias) { health.problems.append(contentsOf: DHCPPool.problems(pool, address: address, mac: mac)) } + // The destination's mDNS name must resolve to the machine (01.12.2026). + if let name = VMMdnsName.currentHostName { + health.problems.append( + contentsOf: VMMdnsName.healthProblems( + destinationURL: destinations.flatMap { + VMStatus.machineDestination(in: $0, address: address, alias: alias)?.url + }, + name: name, resolved: VMMdnsName.resolve(name), + machineAddresses: [address] + (alias.map { [$0] } ?? []))) + } // Another device answering on the alias (arp on the Mac). if let alias { health.problems.append( diff --git a/mac-app/Sources/CloudMachineCore/L10nPolish+VM.swift b/mac-app/Sources/CloudMachineCore/L10nPolish+VM.swift index 44315c5..8931f92 100644 --- a/mac-app/Sources/CloudMachineCore/L10nPolish+VM.swift +++ b/mac-app/Sources/CloudMachineCore/L10nPolish+VM.swift @@ -367,5 +367,19 @@ extension L10nPolish { "rclone uruchomiony ponownie bez ponownego powiązania (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm działa jako proces, dla którego ochrona restartu nie odczytała pasm (ostatnie powiązanie dotyczyło innego): pasmo wysłane, zanim zostanie odczytane, może wrócić jako zera. cm-smb-heal co minutę uruchamia pełne ponowne powiązanie. Sprawdź: cloudmachine-agent vm-status, potem w maszynie: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Nazwa celu Time Machine nie jest rozwiązywana", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ nie jest rozwiązywane na tym Macu, więc Time Machine nie może dotrzeć do maszyny. Maszyna ogłasza nazwę przez mDNS na łączu vzNAT: sprawdź, czy maszyna działa i czy jest aktualna (vm-update).", + "Time Machine's destination name points at another device": + "Nazwa celu Time Machine wskazuje inne urządzenie", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ wskazuje na %@, a to nie jest maszyna. Kopie mogą trafiać na inne urządzenie.", + "Name: %@ -> %@": + "Nazwa: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nazwa: %@ NIE jest rozwiązywana - Time Machine nie dotrze do maszyny (mDNS na łączu vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "Nazwa: %@ wskazuje na %@, nie na maszynę", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift index 46cb655..6e58e25 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ar.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "أُعيد تشغيل rclone ولم يُعَد ربطه (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "يعمل rclone-tm كعملية لم تقرأ حماية إعادة التشغيل أشرطتها (آخر ربط كان لعملية أخرى): الشريط الذي يُرفع قبل قراءته قد يعود أصفارًا. يبدأ cm-smb-heal إعادة ربط كاملة كل دقيقة. تحقق: cloudmachine-agent vm-status، ثم داخل الآلة: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "اسم وجهة Time Machine لا يُحلّ", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "لا يُحلّ الاسم %@ على هذا الـ Mac، لذلك لا يستطيع Time Machine الوصول إلى الجهاز. يعلن الجهاز عن الاسم عبر mDNS على رابط vzNAT الخاص به: تحقق من أن الجهاز يعمل ومحدَّث (vm-update).", + "Time Machine's destination name points at another device": + "اسم وجهة Time Machine يشير إلى جهاز آخر", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "يُحلّ الاسم %@ إلى %@ وهو ليس الجهاز. قد تصل النسخ الاحتياطية إلى جهاز آخر.", + "Name: %@ -> %@": + "الاسم: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "الاسم: %@ لا يُحلّ – لا يستطيع Time Machine الوصول إلى الجهاز (mDNS على رابط vzNAT؟)", + "Name: %@ resolves to %@, not to the machine": + "الاسم: %@ يُحلّ إلى %@ وليس إلى الجهاز", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift index 73cd2ee..10b309f 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+da.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone genstartet og ikke genbundet (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm kører som en proces, genstartsvagten ikke har læst for (sidste genbinding gjaldt en anden): et bånd, der uploades, før det er læst, kan komme tilbage som nuller. cm-smb-heal starter en fuld genbinding hvert minut. Tjek: cloudmachine-agent vm-status, derefter i maskinen: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machines destinationsnavn kan ikke slås op", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ kan ikke slås op på denne Mac, så Time Machine kan ikke nå maskinen. Maskinen annoncerer navnet via mDNS på sit vzNAT-link: kontrollér, at maskinen kører og er opdateret (vm-update).", + "Time Machine's destination name points at another device": + "Time Machines destinationsnavn peger på en anden enhed", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ slås op til %@, som ikke er maskinen. Sikkerhedskopier kan nå en anden enhed.", + "Name: %@ -> %@": + "Navn: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Navn: %@ kan IKKE slås op – Time Machine kan ikke nå maskinen (mDNS på vzNAT-linket?)", + "Name: %@ resolves to %@, not to the machine": + "Navn: %@ slås op til %@, ikke til maskinen", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift index 46c9bb9..5d9b411 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+de.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone neu gestartet und nicht neu gebunden (PID %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm läuft als Prozess, für den der Neustartschutz nichts gelesen hat (die letzte Bindung galt einem anderen): Ein Band, das vor dem Lesen hochgeladen wird, kann als Nullen zurückkommen. cm-smb-heal startet jede Minute eine vollständige Neubindung. Prüfen: cloudmachine-agent vm-status, dann in der Maschine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Der Zielname von Time Machine wird nicht aufgelöst", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ wird auf diesem Mac nicht aufgelöst, daher kann Time Machine die Maschine nicht erreichen. Die Maschine kündigt den Namen über mDNS auf ihrer vzNAT-Verbindung an: Prüfen Sie, ob die Maschine läuft und aktuell ist (vm-update).", + "Time Machine's destination name points at another device": + "Der Zielname von Time Machine verweist auf ein anderes Gerät", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ wird zu %@ aufgelöst, das nicht die Maschine ist. Backups könnten ein anderes Gerät erreichen.", + "Name: %@ -> %@": + "Name: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Name: %@ wird NICHT aufgelöst – Time Machine kann die Maschine nicht erreichen (mDNS auf der vzNAT-Verbindung?)", + "Name: %@ resolves to %@, not to the machine": + "Name: %@ wird zu %@ aufgelöst, nicht zur Maschine", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift index 10ac10d..2ecdf72 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+es.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone reiniciado y sin revincular (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm se ejecuta como un proceso para el que la guarda de reinicio no ha leído nada (la última revinculación fue para otro): una banda subida antes de leerse puede volver como ceros. cm-smb-heal inicia una revinculación completa cada minuto. Comprueba: cloudmachine-agent vm-status y luego, en la máquina: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "El nombre de destino de Time Machine no se resuelve", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ no se resuelve en este Mac, así que Time Machine no puede llegar a la máquina. La máquina anuncia el nombre por mDNS en su enlace vzNAT: comprueba que la máquina funciona y está actualizada (vm-update).", + "Time Machine's destination name points at another device": + "El nombre de destino de Time Machine apunta a otro dispositivo", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ se resuelve a %@, que no es la máquina. Las copias podrían llegar a otro dispositivo.", + "Name: %@ -> %@": + "Nombre: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nombre: %@ NO se resuelve – Time Machine no puede llegar a la máquina (¿mDNS en el enlace vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "Nombre: %@ se resuelve a %@, no a la máquina", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift index 08fb0cf..9a50345 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+fi.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone käynnistyi uudelleen eikä sitä sidottu (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm toimii prosessina, jolle käynnistysvahti ei ole lukenut kaistoja (viimeisin sidonta koski toista): ennen lukemista lähetetty kaista voi palata nollina. cm-smb-heal aloittaa täyden uudelleensidonnan joka minuutti. Tarkista: cloudmachine-agent vm-status, sitten koneessa: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machinen kohdenimeä ei voi selvittää", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ ei selviä tällä Macilla, joten Time Machine ei tavoita konetta. Kone ilmoittaa nimen mDNS:n kautta vzNAT-yhteydellään: tarkista, että kone on käynnissä ja ajan tasalla (vm-update).", + "Time Machine's destination name points at another device": + "Time Machinen kohdenimi osoittaa toiseen laitteeseen", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ selviää osoitteeksi %@, joka ei ole kone. Varmuuskopiot voivat päätyä toiselle laitteelle.", + "Name: %@ -> %@": + "Nimi: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nimi: %@ EI selviä – Time Machine ei tavoita konetta (mDNS vzNAT-yhteydellä?)", + "Name: %@ resolves to %@, not to the machine": + "Nimi: %@ selviää osoitteeksi %@, ei koneeksi", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift index 63c892d..071b16c 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+fr.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone redémarré et non relié (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm tourne dans un processus pour lequel la garde de redémarrage n'a rien lu (le dernier reliage concernait un autre) : une bande envoyée avant d'être lue peut revenir sous forme de zéros. cm-smb-heal lance un reliage complet chaque minute. Vérifiez : cloudmachine-agent vm-status, puis dans la machine : journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Le nom de destination de Time Machine ne se résout pas", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ ne se résout pas sur ce Mac, donc Time Machine ne peut pas joindre la machine. La machine annonce son nom via mDNS sur sa liaison vzNAT : vérifiez qu'elle fonctionne et qu'elle est à jour (vm-update).", + "Time Machine's destination name points at another device": + "Le nom de destination de Time Machine pointe vers un autre appareil", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ se résout en %@, qui n'est pas la machine. Les sauvegardes pourraient atteindre un autre appareil.", + "Name: %@ -> %@": + "Nom : %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nom : %@ ne se résout PAS – Time Machine ne peut pas joindre la machine (mDNS sur la liaison vzNAT ?)", + "Name: %@ resolves to %@, not to the machine": + "Nom : %@ se résout en %@, pas vers la machine", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift index f3fb83a..94e63e6 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+he.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone הופעל מחדש ולא נקשר מחדש (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm רץ כתהליך שהגנת ההפעלה מחדש לא קראה עבורו (הקישור האחרון היה לתהליך אחר): רצועה שהועלתה לפני שנקראה עלולה לחזור כאפסים. cm-smb-heal מתחיל קישור מחדש מלא בכל דקה. בדוק: cloudmachine-agent vm-status, ואז בתוך המכונה: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "שם היעד של Time Machine אינו מתורגם לכתובת", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ אינו מתורגם לכתובת ב-Mac הזה, ולכן Time Machine לא יכול להגיע למכונה. המכונה מכריזה על השם דרך mDNS בקישור vzNAT שלה: בדקו שהמכונה פועלת ומעודכנת (vm-update).", + "Time Machine's destination name points at another device": + "שם היעד של Time Machine מצביע על מכשיר אחר", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ מתורגם ל-%@, שאינו המכונה. גיבויים עלולים להגיע למכשיר אחר.", + "Name: %@ -> %@": + "שם: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "שם: %@ אינו מתורגם לכתובת – Time Machine לא יכול להגיע למכונה (mDNS בקישור vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "שם: %@ מתורגם ל-%@, ולא למכונה", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift index 90ed3ca..6b172aa 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+it.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone riavviato e non ricollegato (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm gira come un processo per cui la guardia riavvio non ha letto nulla (l'ultimo ricollegamento era per un altro): una banda caricata prima di essere letta può tornare come zeri. cm-smb-heal avvia un ricollegamento completo ogni minuto. Controlla: cloudmachine-agent vm-status, poi nella macchina: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Il nome di destinazione di Time Machine non si risolve", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ non si risolve su questo Mac, quindi Time Machine non può raggiungere la macchina. La macchina annuncia il nome tramite mDNS sul suo collegamento vzNAT: verifica che la macchina sia in funzione e aggiornata (vm-update).", + "Time Machine's destination name points at another device": + "Il nome di destinazione di Time Machine punta a un altro dispositivo", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ si risolve in %@, che non è la macchina. I backup potrebbero raggiungere un altro dispositivo.", + "Name: %@ -> %@": + "Nome: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nome: %@ NON si risolve – Time Machine non può raggiungere la macchina (mDNS sul collegamento vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "Nome: %@ si risolve in %@, non nella macchina", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift index 98650aa..0fb602f 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ja.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone が再起動され、再バインドされていません(pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm は再起動ガードがまだ読み取っていないプロセスとして動作しています(最後の再バインドは別のプロセス向けでした)。読み取られる前にアップロードされたバンドは、ゼロとして戻ることがあります。cm-smb-heal は毎分完全な再バインドを開始します。確認: cloudmachine-agent vm-status、次にマシン内で: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machine の宛先名を解決できません", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ をこの Mac で解決できないため、Time Machine がマシンに到達できません。マシンは vzNAT リンク上で mDNS によって名前を通知します。マシンが動作しており最新であること (vm-update) を確認してください。", + "Time Machine's destination name points at another device": + "Time Machine の宛先名が別のデバイスを指しています", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ は %@ に解決されますが、これはマシンではありません。バックアップが別のデバイスに届く可能性があります。", + "Name: %@ -> %@": + "名前: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "名前: %@ を解決できません – Time Machine がマシンに到達できません (vzNAT リンクの mDNS?)", + "Name: %@ resolves to %@, not to the machine": + "名前: %@ は %@ に解決され、マシンではありません", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift index 93b74f5..ee63df0 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ko.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone이 재시작되었지만 다시 바인딩되지 않음(pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm이 재시작 보호가 아직 읽지 않은 프로세스로 실행 중입니다(마지막 바인딩은 다른 프로세스 대상). 읽기 전에 업로드된 밴드는 0으로 돌아올 수 있습니다. cm-smb-heal이 매분 전체 재바인딩을 시작합니다. 확인: cloudmachine-agent vm-status, 그다음 머신 안에서: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machine 대상 이름을 확인할 수 없습니다", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "이 Mac에서 %@ 을(를) 확인할 수 없어 Time Machine이 머신에 연결할 수 없습니다. 머신은 vzNAT 링크에서 mDNS로 이름을 알립니다. 머신이 실행 중이고 최신 상태인지 확인하세요 (vm-update).", + "Time Machine's destination name points at another device": + "Time Machine 대상 이름이 다른 기기를 가리킵니다", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ 은(는) 머신이 아닌 %@ (으)로 확인됩니다. 백업이 다른 기기에 전달될 수 있습니다.", + "Name: %@ -> %@": + "이름: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "이름: %@ 을(를) 확인할 수 없음 – Time Machine이 머신에 연결할 수 없습니다 (vzNAT 링크의 mDNS?)", + "Name: %@ resolves to %@, not to the machine": + "이름: %@ 은(는) 머신이 아닌 %@ (으)로 확인됩니다", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift index 835bfc2..1ec19d0 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ms.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone dimulakan semula dan tidak diikat semula (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm berjalan sebagai proses yang belum dibaca oleh pengawal mula semula (ikatan terakhir untuk proses lain): jalur yang dimuat naik sebelum dibaca boleh kembali sebagai sifar. cm-smb-heal memulakan ikatan semula penuh setiap minit. Semak: cloudmachine-agent vm-status, kemudian dalam mesin: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Nama destinasi Time Machine tidak dapat diselesaikan", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ tidak dapat diselesaikan pada Mac ini, jadi Time Machine tidak dapat mencapai mesin. Mesin mengumumkan nama melalui mDNS pada pautan vzNAT-nya: semak bahawa mesin berjalan dan terkini (vm-update).", + "Time Machine's destination name points at another device": + "Nama destinasi Time Machine menuju ke peranti lain", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ diselesaikan kepada %@, yang bukan mesin. Sandaran mungkin sampai ke peranti lain.", + "Name: %@ -> %@": + "Nama: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nama: %@ TIDAK dapat diselesaikan – Time Machine tidak dapat mencapai mesin (mDNS pada pautan vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "Nama: %@ diselesaikan kepada %@, bukan kepada mesin", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift index 21ecc8e..8ddc036 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+nb.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone startet på nytt og ikke bundet på nytt (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm kjører som en prosess omstartsvakten ikke har lest for (siste binding gjaldt en annen): et bånd som lastes opp før det er lest, kan komme tilbake som nuller. cm-smb-heal starter en full ny binding hvert minutt. Sjekk: cloudmachine-agent vm-status, deretter i maskinen: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machines målnavn kan ikke slås opp", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ kan ikke slås opp på denne Macen, så Time Machine når ikke maskinen. Maskinen kunngjør navnet via mDNS på vzNAT-lenken: kontroller at maskinen kjører og er oppdatert (vm-update).", + "Time Machine's destination name points at another device": + "Time Machines målnavn peker på en annen enhet", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ slås opp til %@, som ikke er maskinen. Sikkerhetskopier kan havne på en annen enhet.", + "Name: %@ -> %@": + "Navn: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Navn: %@ kan IKKE slås opp – Time Machine når ikke maskinen (mDNS på vzNAT-lenken?)", + "Name: %@ resolves to %@, not to the machine": + "Navn: %@ slås opp til %@, ikke til maskinen", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift index 7750128..c9354ea 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+nl.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone herstart en niet opnieuw gekoppeld (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm draait als een proces waarvoor de herstartbewaking niets heeft gelezen (de laatste koppeling gold een ander): een band die wordt geüpload voordat hij gelezen is, kan als nullen terugkomen. cm-smb-heal start elke minuut een volledige nieuwe koppeling. Controleer: cloudmachine-agent vm-status, daarna in de machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "De doelnaam van Time Machine wordt niet omgezet", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ wordt op deze Mac niet omgezet, dus Time Machine kan de machine niet bereiken. De machine kondigt de naam aan via mDNS op de vzNAT-verbinding: controleer of de machine draait en bijgewerkt is (vm-update).", + "Time Machine's destination name points at another device": + "De doelnaam van Time Machine wijst naar een ander apparaat", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ wordt omgezet naar %@, dat niet de machine is. Back-ups kunnen een ander apparaat bereiken.", + "Name: %@ -> %@": + "Naam: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Naam: %@ wordt NIET omgezet – Time Machine kan de machine niet bereiken (mDNS op de vzNAT-verbinding?)", + "Name: %@ resolves to %@, not to the machine": + "Naam: %@ wordt omgezet naar %@, niet naar de machine", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift index 9bc5773..67549bf 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+pt-BR.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone reiniciado e sem nova vinculação (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "O rclone-tm roda como um processo para o qual a guarda de reinício não leu nada (a última vinculação foi para outro): uma banda enviada antes de ser lida pode voltar como zeros. O cm-smb-heal inicia uma nova vinculação completa a cada minuto. Verifique: cloudmachine-agent vm-status e depois, na máquina: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "O nome de destino do Time Machine não é resolvido", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ não é resolvido neste Mac, então o Time Machine não consegue alcançar a máquina. A máquina anuncia o nome por mDNS no link vzNAT: verifique se a máquina está em execução e atualizada (vm-update).", + "Time Machine's destination name points at another device": + "O nome de destino do Time Machine aponta para outro dispositivo", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ é resolvido para %@, que não é a máquina. Os backups podem chegar a outro dispositivo.", + "Name: %@ -> %@": + "Nome: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Nome: %@ NÃO é resolvido – o Time Machine não consegue alcançar a máquina (mDNS no link vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "Nome: %@ é resolvido para %@, não para a máquina", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift index f1db69e..347d18f 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+ru.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone перезапущен и не привязан заново (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm работает как процесс, для которого защита перезапуска ничего не прочитала (последняя привязка была для другого): полоса, отправленная до чтения, может вернуться нулями. cm-smb-heal каждую минуту запускает полную повторную привязку. Проверьте: cloudmachine-agent vm-status, затем в машине: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Имя назначения Time Machine не разрешается", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ не разрешается на этом Mac, поэтому Time Machine не может связаться с машиной. Машина объявляет имя по mDNS в своей сети vzNAT: проверьте, что машина работает и обновлена (vm-update).", + "Time Machine's destination name points at another device": + "Имя назначения Time Machine указывает на другое устройство", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ разрешается в %@, а это не машина. Резервные копии могут попасть на другое устройство.", + "Name: %@ -> %@": + "Имя: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Имя: %@ НЕ разрешается – Time Machine не может связаться с машиной (mDNS в сети vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "Имя: %@ разрешается в %@, а не в машину", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift index ca02bb6..f0616cd 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+sv.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone omstartat och inte ombundet (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm körs som en process som omstartsvakten inte har läst för (senaste bindningen gällde en annan): ett band som laddas upp innan det lästs kan komma tillbaka som nollor. cm-smb-heal startar en fullständig ombindning varje minut. Kontrollera: cloudmachine-agent vm-status, sedan i maskinen: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machines målnamn kan inte slås upp", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ kan inte slås upp på den här Macen, så Time Machine når inte maskinen. Maskinen annonserar namnet via mDNS på sin vzNAT-länk: kontrollera att maskinen körs och är uppdaterad (vm-update).", + "Time Machine's destination name points at another device": + "Time Machines målnamn pekar på en annan enhet", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ slås upp till %@, som inte är maskinen. Säkerhetskopior kan hamna på en annan enhet.", + "Name: %@ -> %@": + "Namn: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Namn: %@ kan INTE slås upp – Time Machine når inte maskinen (mDNS på vzNAT-länken?)", + "Name: %@ resolves to %@, not to the machine": + "Namn: %@ slås upp till %@, inte till maskinen", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift index 546ef28..59c3f51 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+th.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone รีสตาร์ตแล้วแต่ยังไม่ได้ผูกใหม่ (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm ทำงานเป็นโปรเซสที่การป้องกันรีสตาร์ตยังไม่ได้อ่านให้ (การผูกล่าสุดเป็นของโปรเซสอื่น): แถบที่อัปโหลดก่อนถูกอ่านอาจกลับมาเป็นศูนย์ cm-smb-heal เริ่มการผูกใหม่ทั้งหมดทุกนาที ตรวจสอบ: cloudmachine-agent vm-status แล้วในเครื่อง: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "ไม่สามารถ resolve ชื่อปลายทางของ Time Machine ได้", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "Mac เครื่องนี้ไม่สามารถ resolve %@ ได้ Time Machine จึงเข้าถึงเครื่องไม่ได้ เครื่องประกาศชื่อผ่าน mDNS บนลิงก์ vzNAT ของตน: ตรวจสอบว่าเครื่องทำงานอยู่และอัปเดตแล้ว (vm-update)", + "Time Machine's destination name points at another device": + "ชื่อปลายทางของ Time Machine ชี้ไปยังอุปกรณ์อื่น", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ ถูก resolve เป็น %@ ซึ่งไม่ใช่เครื่องนี้ การสำรองข้อมูลอาจไปถึงอุปกรณ์อื่น", + "Name: %@ -> %@": + "ชื่อ: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "ชื่อ: %@ resolve ไม่ได้ – Time Machine เข้าถึงเครื่องไม่ได้ (mDNS บนลิงก์ vzNAT?)", + "Name: %@ resolves to %@, not to the machine": + "ชื่อ: %@ ถูก resolve เป็น %@ ไม่ใช่เครื่องนี้", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift index a800aca..7dd9fcd 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+tr.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone yeniden başlatıldı ve yeniden bağlanmadı (pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm, yeniden başlatma korumasının henüz okumadığı bir süreç olarak çalışıyor (son bağlama başka bir süreç içindi): okunmadan yüklenen bir bant sıfır olarak geri dönebilir. cm-smb-heal her dakika tam bir yeniden bağlama başlatır. Kontrol: cloudmachine-agent vm-status, ardından makinede: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "Time Machine hedef adı çözümlenemiyor", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "%@ bu Mac'te çözümlenmiyor, bu yüzden Time Machine makineye ulaşamıyor. Makine adı vzNAT bağlantısında mDNS ile duyurur: makinenin çalıştığını ve güncel olduğunu kontrol edin (vm-update).", + "Time Machine's destination name points at another device": + "Time Machine hedef adı başka bir cihazı gösteriyor", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@, makine olmayan %@ adresine çözümleniyor. Yedekler başka bir cihaza ulaşabilir.", + "Name: %@ -> %@": + "Ad: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "Ad: %@ ÇÖZÜMLENMİYOR – Time Machine makineye ulaşamıyor (vzNAT bağlantısında mDNS?)", + "Name: %@ resolves to %@, not to the machine": + "Ad: %@, makineye değil %@ adresine çözümleniyor", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift index 7d32fbf..343a2a7 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hans.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone 已重启但未重新绑定(pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm 正以重启防护尚未读取过的进程运行(上次绑定针对的是另一个进程):在读取之前上传的分段可能以全零返回。cm-smb-heal 每分钟启动一次完整的重新绑定。检查:cloudmachine-agent vm-status,然后在机器内:journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "无法解析 Time Machine 的目标名称", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "此 Mac 无法解析 %@,因此 Time Machine 无法连接到该机器。机器通过其 vzNAT 链路上的 mDNS 公布名称:请检查机器是否在运行并且是最新的 (vm-update)。", + "Time Machine's destination name points at another device": + "Time Machine 的目标名称指向另一台设备", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ 解析为 %@,而它不是该机器。备份可能会发送到另一台设备。", + "Name: %@ -> %@": + "名称: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "名称: %@ 无法解析 – Time Machine 无法连接到该机器(vzNAT 链路上的 mDNS?)", + "Name: %@ resolves to %@, not to the machine": + "名称: %@ 解析为 %@,而不是该机器", ] } diff --git a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift index 83e94c3..98ed297 100644 --- a/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift +++ b/mac-app/Sources/CloudMachineCore/L10nTranslations+zh-Hant.swift @@ -1146,5 +1146,19 @@ extension L10nTranslations { "rclone 已重新啟動但未重新綁定(pid %@)", "rclone-tm runs as a process the restart guard has not read for (the last rebind was for another one): a band uploaded before it is read can come back as zeros. cm-smb-heal starts a whole rebind every minute. Check: cloudmachine-agent vm-status, then in the machine: journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard": "rclone-tm 正以重新啟動防護尚未讀取過的程序執行(上次綁定針對的是另一個程序):在讀取之前上傳的分段可能以全零傳回。cm-smb-heal 每分鐘啟動一次完整的重新綁定。檢查:cloudmachine-agent vm-status,然後在機器內:journalctl -u punchfs -u cm-smb-heal | grep cm-vfs-guard", + "Time Machine's destination name does not resolve": + "無法解析 Time Machine 的目的地名稱", + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).": + "此 Mac 無法解析 %@,因此 Time Machine 無法連線到該機器。機器透過其 vzNAT 連結上的 mDNS 公告名稱:請檢查機器是否正在執行且為最新版本 (vm-update)。", + "Time Machine's destination name points at another device": + "Time Machine 的目的地名稱指向另一部裝置", + "%@ resolves to %@, which is not the machine. Backups may reach another device.": + "%@ 解析為 %@,而它不是該機器。備份可能會傳送到另一部裝置。", + "Name: %@ -> %@": + "名稱: %@ -> %@", + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)": + "名稱: %@ 無法解析 – Time Machine 無法連線到該機器(vzNAT 連結上的 mDNS?)", + "Name: %@ resolves to %@, not to the machine": + "名稱: %@ 解析為 %@,而不是該機器", ] } diff --git a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift index e517bb0..a893c4e 100644 --- a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift +++ b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift @@ -41,8 +41,7 @@ public enum TimeMachineDestinationFix { /// A destination at the machine's static `alias` (`VMAddressLease`) is /// correct too: only the reservation is made, the destination stays. static func plan( - destinations: [TimeMachineStatus.Destination], address: String, alias: String? = nil - ) -> Plan { + destinations: [TimeMachineStatus.Destination], address: String, alias: String? = nil) -> Plan { guard let ours = VMStatus.machineDestination(in: destinations, address: nil) else { return .add } @@ -53,6 +52,32 @@ public enum TimeMachineDestinationFix { return .add } + /// What Time Machine should point at: the machine's mDNS name when the Mac resolves it to + /// the machine right now (no address, no `/etc/bootptab`), the address otherwise. + enum Target: Equatable { + case name(String) + case address(String) + case none + } + + static func target( + address: String?, name: String? = VMMdnsName.currentHostName, + resolve: (String) -> [String] = VMMdnsName.resolve + ) -> Target { + guard let address else { return .none } + if let name, resolve(name).contains(address) { return .name(name) } + return .address(address) + } + + /// `run`, by name when that works (`target`): no reservation is written, so the one + /// administrator dialog only changes Time Machine. By address otherwise, as before. + public static func runPreferringName(address: String?, mac: String?) async -> CMActionResult { + switch target(address: address) { + case .name(let name): return await run(address: name, mac: nil) + case .address, .none: return await run(address: address, mac: mac) + } + } + /// The destination without a password. static func url(address: String) -> String { "smb://\(VMLayout.smbUser)@\(address)/\(VMLayout.shareName)" @@ -88,6 +113,18 @@ public enum TimeMachineDestinationFix { + "[ -n \"$id\" ] && /usr/bin/tmutil setquota \"$id\" \(quotaGB)" } + /// Detaches the image of the machine's share, whatever address it was mounted from. Time + /// Machine leaves it attached after a backup, and a destination added while it is attached + /// fails its first backup with "Failed locking the image" (Resource busy; measured on a + /// macOS client, 01.12). Best effort (`true`): an image that is busy stays, as before. + static var detachShareImageCommand: String { + let share = "/\(VMLayout.shareName)/" + return "{ /usr/bin/hdiutil info | /usr/bin/awk " + + "'/^image-path/{m=(index($0,\"/.timemachine/\")>0)" + + "*(index($0,\"\(share)\")>0)} /^\\/dev\\/disk/{if(m){print $1;m=0}}'" + + " | while read d; do /usr/bin/hdiutil detach \"$d\"; done; true; }" + } + /// What root runs, in order: the reservation, then the Time Machine part of /// the plan. A failed step stops the rest. `nil` = nothing to run. static func shellCommand( @@ -106,6 +143,7 @@ public enum TimeMachineDestinationFix { case .add, .replace: if case .replace(let id) = plan { guard matches(id, "^[A-Za-z0-9-]+$") else { return nil } + steps.append(detachShareImageCommand) steps.append("/usr/bin/tmutil removedestination \(id)") } steps.append(addCommand(address: address, passwordFile: passwordFile, uid: uid)) diff --git a/mac-app/Sources/CloudMachineCore/VMMdnsName.swift b/mac-app/Sources/CloudMachineCore/VMMdnsName.swift new file mode 100644 index 0000000..dea9081 --- /dev/null +++ b/mac-app/Sources/CloudMachineCore/VMMdnsName.swift @@ -0,0 +1,94 @@ +import Darwin +import Foundation + +/// The machine's mDNS name, `lima-.local`: what Time Machine's destination points at +/// instead of an address. +/// +/// 01.12.2026: bootpd (the Mac's DHCP server) gave `192.168.64.10` to a CI machine and backups +/// stopped; every address-based fix (`RequestAddress`, the alias, a `/etc/bootptab` line) needs +/// root or is only a bet against the pool. The machine's systemd-resolved announces the guest's +/// host name over mDNS on `lima0` (the vzNAT link) - `vm/cmsmb.yaml` turns that on and +/// publishes `_smb._tcp` and `_adisk._tcp` - and the Mac's mDNSResponder resolves the name at +/// every mount. Nothing is installed in the machine and nothing runs as root on the Mac apart +/// from the one `tmutil` call that changes the destination. +public enum VMMdnsName { + /// Lima names the guest `lima-`. + public static func hostName(instance: String) -> String? { + guard instance.range(of: "^[a-z0-9][a-z0-9-]{0,56}$", options: .regularExpression) != nil + else { return nil } + return "lima-\(instance).local" + } + + /// The name of the machine this process works on. + public static var currentHostName: String? { hostName(instance: VMLayout.instanceName) } + + public enum Problem: Equatable { + /// mDNS did not answer: the machine's announcement does not reach the Mac. + case unresolved + /// The name answers, but with an address that is not the machine's. + case wrongDevice([String]) + } + + /// What is wrong with a name's resolution. `nil` = fine, or no verdict (the machine's own + /// addresses are not known). Link-local IPv6 answers are ignored: only IPv4 is compared. + public static func problem(resolved: [String], machineAddresses: [String]) -> Problem? { + guard !machineAddresses.isEmpty else { return nil } + let v4 = resolved.filter { VMAddressLease.isIPv4($0) } + guard !v4.isEmpty else { return .unresolved } + return v4.contains(where: machineAddresses.contains) ? nil : .wrongDevice(v4) + } + + /// backup-health problems: only when Time Machine's destination is at the name. + public static func healthProblems( + destinationURL: String?, name: String?, resolved: [String], machineAddresses: [String] + ) -> [BackupHealth.Problem] { + guard let name, let url = destinationURL, url.lowercased().contains("@\(name)/") else { + return [] + } + switch problem(resolved: resolved, machineAddresses: machineAddresses) { + case nil: return [] + case .unresolved?: + return [ + BackupHealth.Problem( + summary: L10n.tr("Time Machine's destination name does not resolve"), + detail: L10n.tr( + "%@ does not resolve on this Mac, so Time Machine cannot reach the machine. The machine announces the name over mDNS on its vzNAT link: check that the machine runs and that it is up to date (vm-update).", + name), + code: "mdns-name-unresolved") + ] + case .wrongDevice(let found)?: + return [ + BackupHealth.Problem( + summary: L10n.tr("Time Machine's destination name points at another device"), + detail: L10n.tr( + "%@ resolves to %@, which is not the machine. Backups may reach another device.", + name, found.joined(separator: ", ")), + code: "mdns-name-wrong-device") + ] + } + } + + /// The IPv4 addresses `host` resolves to (the system resolver: mDNSResponder for `.local`). + public static func resolve(_ host: String) -> [String] { + var hints = addrinfo() + hints.ai_family = AF_INET + hints.ai_socktype = SOCK_STREAM + var list: UnsafeMutablePointer? + guard getaddrinfo(host, nil, &hints, &list) == 0, let first = list else { return [] } + defer { freeaddrinfo(list) } + var out: [String] = [] + var cursor: UnsafeMutablePointer? = first + while let info = cursor { + if let sa = info.pointee.ai_addr { + var buffer = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN)) + sa.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { sin in + var addr = sin.pointee.sin_addr + inet_ntop(AF_INET, &addr, &buffer, socklen_t(INET_ADDRSTRLEN)) + } + out.append(String(cString: buffer)) + } + cursor = info.pointee.ai_next + } + return out + } +} diff --git a/mac-app/Sources/CloudMachineCore/VMStatus.swift b/mac-app/Sources/CloudMachineCore/VMStatus.swift index bf91867..9aa1c7e 100644 --- a/mac-app/Sources/CloudMachineCore/VMStatus.swift +++ b/mac-app/Sources/CloudMachineCore/VMStatus.swift @@ -385,12 +385,19 @@ public enum VMStatus { /// /// `alias` is the static address the machine has next to the DHCP one /// (`VMAddressLease`): a destination at the alias is the machine's too. - public static func isMachineShare(_ url: String, address: String?, alias: String? = nil) -> Bool { + /// + /// `name` is the machine's mDNS name (`VMMdnsName`): a destination at it is the machine's + /// whatever the address is - that is the point of the name. + public static func isMachineShare( + _ url: String, address: String?, alias: String? = nil, + name: String? = VMMdnsName.currentHostName + ) -> Bool { guard url.hasPrefix("smb://"), url.hasSuffix("/\(VMLayout.shareName)"), url.contains("\(VMLayout.smbUser)@") || url.contains("\(VMLayout.smbUser):") else { return false } guard let address else { return true } if url.contains("@\(address)/") { return true } + if let name, url.lowercased().contains("@\(name.lowercased())/") { return true } return alias.map { url.contains("@\($0)/") } ?? false } @@ -549,6 +556,29 @@ public enum VMStatus { machineDestination(in: destinations, address: $0, alias: alias)?.url }) { out.append(L10n.tr("Time Machine: %@", redactedPassword(ours))) + if let name = VMMdnsName.currentHostName, + ours.lowercased().contains("@\(name)/") + { + let resolved = VMMdnsName.resolve(name) + let addresses = [address, alias].compactMap { $0 } + switch VMMdnsName.problem(resolved: resolved, machineAddresses: addresses) { + case nil: + out.append( + L10n.tr("Name: %@ -> %@", name, resolved.joined(separator: ", "))) + case .unresolved?: + out.append( + L10n.tr( + "Name: %@ does NOT resolve - Time Machine cannot reach the machine (mDNS on the vzNAT link?)", + name)) + healthy = false + case .wrongDevice(let found)?: + out.append( + L10n.tr( + "Name: %@ resolves to %@, not to the machine", name, + found.joined(separator: ", "))) + healthy = false + } + } } else { out.append( L10n.tr( diff --git a/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift b/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift index 0dea1d5..5646636 100644 --- a/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift +++ b/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift @@ -132,6 +132,29 @@ final class TimeMachineDestinationFixTests: XCTestCase { XCTAssertFalse(command.contains("setdestination -p")) } + /// Measured on a macOS client (01.12): the image of the old destination stayed attached, and the + /// first backup to the new one failed with "Failed locking the image" (Resource busy). + func testReplaceDetachesTheShareImageBeforeRemovingTheOldDestination() throws { + let command = try XCTUnwrap( + TimeMachineDestinationFix.shellCommand( + address: "lima-cmsmb.local", passwordFile: "/p/tm.pass", uid: 501, + plan: .replace(id: "OLD-ID"))) + let detach = try XCTUnwrap(command.range(of: "/usr/bin/hdiutil detach")) + let remove = try XCTUnwrap(command.range(of: "tmutil removedestination OLD-ID")) + XCTAssertLessThan(detach.lowerBound, remove.lowerBound) + XCTAssertTrue(command.contains("/CloudMachine/"), "only the machine's share image") + // A busy image must not stop the replacement: the detach is best effort. + let step = try XCTUnwrap(command.components(separatedBy: " && ").first) + XCTAssertTrue(step.hasSuffix("true; }"), step) + } + + func testAddDoesNotDetachAnything() throws { + let command = try XCTUnwrap( + TimeMachineDestinationFix.shellCommand( + address: "lima-cmsmb.local", passwordFile: "/p/tm.pass", uid: 501, plan: .add)) + XCTAssertFalse(command.contains("hdiutil")) + } + func testReplaceRemovesOnlyTheMachinesDestinationThenAddsThenRestoresTheQuota() throws { let command = try XCTUnwrap( TimeMachineDestinationFix.shellCommand( diff --git a/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift b/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift new file mode 100644 index 0000000..cfb7313 --- /dev/null +++ b/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift @@ -0,0 +1,176 @@ +import XCTest + +@testable import CloudMachineCore + +/// 01.12.2026: Time Machine pointed at `smb://tm@192.168.64.10/CloudMachine`; bootpd gave +/// `.10` to a CI machine and backups stopped. The machine now announces itself over mDNS +/// (systemd-resolved, no extra package) and Time Machine points at `lima-.local`, +/// which the Mac resolves at every mount. +final class VMMdnsNameTests: XCTestCase { + func testHostNameIsLimaInstanceDotLocal() { + XCTAssertEqual(VMMdnsName.hostName(instance: "cmsmb"), "lima-cmsmb.local") + XCTAssertEqual(VMMdnsName.hostName(instance: "cm-test2"), "lima-cm-test2.local") + } + + func testHostNameRefusesWhatIsNotADNSLabel() { + for bad in ["", "Cm", "a b", "a;b", "a/b", "-a", "a.b", "\u{105}"] { + XCTAssertNil(VMMdnsName.hostName(instance: bad), bad) + } + } + + func testMachineShareAcceptsTheNameWhateverTheAddress() { + let url = "smb://tm@lima-cmsmb.local/CloudMachine" + XCTAssertTrue( + VMStatus.isMachineShare(url, address: "192.168.64.29", name: "lima-cmsmb.local")) + XCTAssertTrue( + VMStatus.isMachineShare( + "smb://tm@Lima-CMSMB.local/CloudMachine", address: "192.168.64.29", + name: "lima-cmsmb.local")) + } + + func testMachineShareRejectsAnotherName() { + XCTAssertFalse( + VMStatus.isMachineShare( + "smb://tm@lima-other.local/CloudMachine", address: "192.168.64.29", + name: "lima-cmsmb.local")) + XCTAssertFalse( + VMStatus.isMachineShare( + "smb://tm@evil-lima-cmsmb.local/CloudMachine", address: "192.168.64.29", + name: "lima-cmsmb.local")) + } + + func testAddressShareStillWorksWithAName() { + XCTAssertTrue( + VMStatus.isMachineShare( + "smb://tm@192.168.64.29/CloudMachine", address: "192.168.64.29", + name: "lima-cmsmb.local")) + } + + // MARK: the plan for the destination + + private func dest(_ host: String) -> TimeMachineStatus.Destination { + TimeMachineStatus.Destination( + name: "CloudMachine", kind: "Network", url: "smb://tm@\(host)/CloudMachine", id: "ID-1") + } + + func testDestinationAtAnAddressIsReplacedByTheName() { + XCTAssertEqual( + TimeMachineDestinationFix.plan( + destinations: [dest("192.168.64.10")], address: "lima-cmsmb.local", alias: nil), + .replace(id: "ID-1")) + } + + func testDestinationAtTheNameIsKept() { + XCTAssertEqual( + TimeMachineDestinationFix.plan( + destinations: [dest("lima-cmsmb.local")], address: "lima-cmsmb.local", alias: nil), + .reserveOnly) + } + + func testNoDestinationIsAdded() { + XCTAssertEqual( + TimeMachineDestinationFix.plan( + destinations: [], address: "lima-cmsmb.local", alias: nil), + .add) + } + + func testNameCommandHasNoBootptabReservation() throws { + let shell = try XCTUnwrap( + TimeMachineDestinationFix.shellCommand( + address: "lima-cmsmb.local", passwordFile: "/tmp/p", uid: 501, mac: nil, + plan: .replace(id: "ID-1"), quotaGB: 3220)) + XCTAssertFalse(shell.contains("bootptab")) + XCTAssertTrue(shell.contains("smb://tm@lima-cmsmb.local/CloudMachine")) + XCTAssertTrue(shell.contains("removedestination ID-1")) + XCTAssertTrue(shell.contains("@lima-cmsmb.local/CloudMachine")) + } + + // MARK: which target the app picks + + func testTargetIsTheNameWhenItResolvesToTheMachine() { + XCTAssertEqual( + TimeMachineDestinationFix.target( + address: "192.168.64.29", name: "lima-cmsmb.local", resolve: { _ in ["192.168.64.29"] }), + .name("lima-cmsmb.local")) + } + + func testTargetFallsBackToTheAddressWhenTheNameDoesNotResolve() { + XCTAssertEqual( + TimeMachineDestinationFix.target( + address: "192.168.64.29", name: "lima-cmsmb.local", resolve: { _ in [] }), + .address("192.168.64.29")) + XCTAssertEqual( + TimeMachineDestinationFix.target( + address: "192.168.64.29", name: "lima-cmsmb.local", resolve: { _ in ["192.168.64.40"] }), + .address("192.168.64.29")) + } + + func testTargetWithoutAnAddressIsNone() { + XCTAssertEqual( + TimeMachineDestinationFix.target(address: nil, name: "lima-cmsmb.local", resolve: { _ in [] }), + .none) + } + + // MARK: resolving the name (vm-status, backup-health) + + func testProblemWhenTheNameDoesNotResolve() { + XCTAssertEqual( + VMMdnsName.problem(resolved: [], machineAddresses: ["192.168.64.29"]), .unresolved) + } + + func testProblemWhenTheNameResolvesToAnotherDevice() { + XCTAssertEqual( + VMMdnsName.problem(resolved: ["192.168.64.40"], machineAddresses: ["192.168.64.29"]), + .wrongDevice(["192.168.64.40"])) + } + + func testNoProblemWhenTheNameResolvesToTheMachineOrItsAlias() { + XCTAssertNil( + VMMdnsName.problem( + resolved: ["192.168.64.10"], machineAddresses: ["192.168.64.29", "192.168.64.10"])) + } + + func testHealthProblemsOnlyWhenTimeMachinePointsAtTheName() { + let name = "lima-cmsmb.local" + XCTAssertTrue( + VMMdnsName.healthProblems( + destinationURL: "smb://tm@192.168.64.10/CloudMachine", name: name, resolved: [], + machineAddresses: ["192.168.64.10"] + ).isEmpty) + let problems = VMMdnsName.healthProblems( + destinationURL: "smb://tm@\(name)/CloudMachine", name: name, resolved: [], + machineAddresses: ["192.168.64.29"]) + XCTAssertEqual(problems.map(\.code), ["mdns-name-unresolved"]) + let wrong = VMMdnsName.healthProblems( + destinationURL: "smb://tm@\(name)/CloudMachine", name: name, resolved: ["192.168.64.40"], + machineAddresses: ["192.168.64.29"]) + XCTAssertEqual(wrong.map(\.code), ["mdns-name-wrong-device"]) + XCTAssertTrue( + VMMdnsName.healthProblems( + destinationURL: "smb://tm@\(name)/CloudMachine", name: name, + resolved: ["192.168.64.29"], machineAddresses: ["192.168.64.29"] + ).isEmpty) + } + + func testNoVerdictWithoutAMachineAddress() { + XCTAssertNil(VMMdnsName.problem(resolved: ["192.168.64.40"], machineAddresses: [])) + } + + func testLinkLocalIPv6IsIgnored() { + XCTAssertNil( + VMMdnsName.problem( + resolved: ["fe80::1%bridge100", "192.168.64.29"], machineAddresses: ["192.168.64.29"])) + } + + // MARK: the template announces the machine + + func testTemplateTurnsOnMdnsOnLima0AndAnnouncesTheShare() throws { + let yaml = try String( + contentsOf: VMEmbedTests.vmDir.appendingPathComponent("cmsmb.yaml"), encoding: .utf8) + XCTAssertTrue(yaml.contains("MulticastDNS=yes")) + XCTAssertTrue(yaml.contains("/etc/systemd/dnssd/")) + XCTAssertTrue(yaml.contains("Type=_smb._tcp")) + XCTAssertTrue(yaml.contains("Type=_adisk._tcp")) + XCTAssertTrue(yaml.contains("dk0=adVN=CloudMachine,adVF=0x82")) + } +} diff --git a/vm/cmsmb.yaml b/vm/cmsmb.yaml index 664fb40..0e98e30 100644 --- a/vm/cmsmb.yaml +++ b/vm/cmsmb.yaml @@ -131,6 +131,28 @@ provision: chown tm:tm /srv/tm-local printf 'TM_UID=%s\nTM_GID=%s\n' "$(id -u tm)" "$(id -g tm)" > /etc/cloudmachine/tm-ids.env + # 4b. The machine's name on the vzNAT link. systemd-resolved announces the host name + # (lima-.local) over mDNS on lima0 and publishes the SMB share, so Time + # Machine can point at the NAME and the Mac resolves it at every mount: the DHCP + # address (bootpd) may change, the destination does not. Nothing is installed. + # mDNS is link-local: lima0 faces the Mac's private vzNAT bridge only, never the LAN + # (eth0, Lima's own link, is left as it is). + mdns_changed=0 + put() { # put : write only when it differs + mkdir -p "$(dirname "$1")" + if [ "$(cat "$1" 2>/dev/null)" != "$2" ]; then printf '%s\n' "$2" > "$1"; mdns_changed=1; fi + } + put /etc/systemd/network/10-netplan-lima0.network.d/70-cloudmachine-mdns.conf \ + "$(printf '[Network]\nMulticastDNS=yes')" + put /etc/systemd/dnssd/cloudmachine-smb.dnssd \ + "$(printf '[Service]\nName=CloudMachine\nType=_smb._tcp\nPort=445')" + put /etc/systemd/dnssd/cloudmachine-adisk.dnssd \ + "$(printf '[Service]\nName=CloudMachine\nType=_adisk._tcp\nPort=9\nTxtText=sys=waMa=0,adVF=0x100 dk0=adVN=CloudMachine,adVF=0x82')" + if [ "$mdns_changed" = 1 ]; then + networkctl reload || true + systemctl restart systemd-resolved || true + fi + # 5. punchfs, rebuilt only when its source changed. The sources arrive as # one archive (see the `file:` entry above); unpack it first. base64 -d /opt/cloudmachine/punchfs/src.tar.gz.b64 | tar -xz --no-same-owner -C /opt/cloudmachine/punchfs From c7526ba47f467802d1ad690156f71323e05a6a7b Mon Sep 17 00:00:00 2001 From: RenaCode Date: Tue, 1 Dec 2026 22:14:53 +0100 Subject: [PATCH 5/6] Odlaczanie obrazu: tylko obraz starego hosta, log gdy nic nie znaleziono, test filtra awk Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AU1MhuGSAj8JTZKLqUoP7Q --- .../TimeMachineDestinationFix.swift | 52 +++++++++--- .../TimeMachineDestinationFixTests.swift | 80 +++++++++++++++++-- 2 files changed, 112 insertions(+), 20 deletions(-) diff --git a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift index a893c4e..70eed4e 100644 --- a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift +++ b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift @@ -113,23 +113,42 @@ public enum TimeMachineDestinationFix { + "[ -n \"$id\" ] && /usr/bin/tmutil setquota \"$id\" \(quotaGB)" } - /// Detaches the image of the machine's share, whatever address it was mounted from. Time - /// Machine leaves it attached after a backup, and a destination added while it is attached - /// fails its first backup with "Failed locking the image" (Resource busy; measured on a - /// macOS client, 01.12). Best effort (`true`): an image that is busy stays, as before. - static var detachShareImageCommand: String { - let share = "/\(VMLayout.shareName)/" - return "{ /usr/bin/hdiutil info | /usr/bin/awk " - + "'/^image-path/{m=(index($0,\"/.timemachine/\")>0)" - + "*(index($0,\"\(share)\")>0)} /^\\/dev\\/disk/{if(m){print $1;m=0}}'" - + " | while read d; do /usr/bin/hdiutil detach \"$d\"; done; true; }" + /// The host of a destination URL (`smb://user@host[:port]/share`), when it is a plain name + /// or address. + static func host(ofURL url: String) -> String? { + guard let at = url.firstIndex(of: "@") else { return nil } + var rest = url[url.index(after: at)...] + if let slash = rest.firstIndex(of: "/") { rest = rest[../.../CloudMachine/`. Another host's image does not match. + static var detachFilterAwk: String { + "/^image-path/{m=index($0,\"/.timemachine/\" h \"/\")>0 && index($0,\"/\(VMLayout.shareName)/\")>0}" + + " /^\\/dev\\/disk/{if(m){print $1;m=0}}" + } + + /// Detaches the image of the machine's share that is mounted from `host`, the old + /// destination. Time Machine leaves it attached after a backup, and a destination added while + /// it is attached fails its first backup with "Failed locking the image" (Resource busy; + /// measured on a macOS client, 01.12). Best effort (`true`): a busy image stays, as before. + /// It says on stdout what it did (the app logs it), also when it found nothing. + static func detachShareImageCommand(host: String) -> String { + "{ l=$(/usr/bin/hdiutil info | /usr/bin/awk -v h=\(shellQuoted(host)) \(shellQuoted(detachFilterAwk)));" + + " [ -n \"$l\" ] || echo \"no attached image of \(host) found\";" + + " for d in $l; do /usr/bin/hdiutil detach \"$d\" && echo \"detached $d\"; done; true; }" } /// What root runs, in order: the reservation, then the Time Machine part of /// the plan. A failed step stops the rest. `nil` = nothing to run. static func shellCommand( address: String, passwordFile: String, uid: uid_t = getuid(), mac: String? = nil, - name: String = defaultName, plan: Plan = .add, quotaGB: Int? = nil + name: String = defaultName, plan: Plan = .add, quotaGB: Int? = nil, + oldHost: String? = nil ) -> String? { var steps: [String] = [] if let mac { @@ -143,7 +162,9 @@ public enum TimeMachineDestinationFix { case .add, .replace: if case .replace(let id) = plan { guard matches(id, "^[A-Za-z0-9-]+$") else { return nil } - steps.append(detachShareImageCommand) + if let oldHost, matches(oldHost, "^[A-Za-z0-9.-]+$") { + steps.append(detachShareImageCommand(host: oldHost)) + } steps.append("/usr/bin/tmutil removedestination \(id)") } steps.append(addCommand(address: address, passwordFile: passwordFile, uid: uid)) @@ -262,7 +283,8 @@ public enum TimeMachineDestinationFix { guard let shell = shellCommand( address: address, passwordFile: passwordFile.path, uid: uid, mac: mac, name: name, - plan: plan, quotaGB: quota) + plan: plan, quotaGB: quota, + oldHost: VMStatus.machineDestination(in: before, address: nil)?.url.flatMap(host(ofURL:))) else { return couldNot("invalid MAC address, name or destination id") } let script = appleScript( @@ -295,6 +317,10 @@ public enum TimeMachineDestinationFix { if let mac, !DHCPPool.bootptabReserves(readBootptab() ?? "", mac: mac, address: address) { return fail(L10n.tr("The address reservation was not written to /etc/bootptab.")) } + let said = scrubbed(result.stdout).trimmingCharacters(in: .whitespacesAndNewlines) + if !said.isEmpty { + CMLogger.log("fix-destination: \(said.replacingOccurrences(of: "\n", with: "; "))") + } CMLogger.log("fix-destination: done") return CMActionResult( succeeded: true, diff --git a/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift b/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift index 5646636..570293a 100644 --- a/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift +++ b/mac-app/Tests/CloudMachineAppTests/TimeMachineDestinationFixTests.swift @@ -134,27 +134,93 @@ final class TimeMachineDestinationFixTests: XCTestCase { /// Measured on a macOS client (01.12): the image of the old destination stayed attached, and the /// first backup to the new one failed with "Failed locking the image" (Resource busy). - func testReplaceDetachesTheShareImageBeforeRemovingTheOldDestination() throws { + func testReplaceDetachesTheOldHostsImageBeforeRemovingTheOldDestination() throws { let command = try XCTUnwrap( TimeMachineDestinationFix.shellCommand( address: "lima-cmsmb.local", passwordFile: "/p/tm.pass", uid: 501, - plan: .replace(id: "OLD-ID"))) + plan: .replace(id: "OLD-ID"), oldHost: "192.168.64.10")) let detach = try XCTUnwrap(command.range(of: "/usr/bin/hdiutil detach")) let remove = try XCTUnwrap(command.range(of: "tmutil removedestination OLD-ID")) XCTAssertLessThan(detach.lowerBound, remove.lowerBound) - XCTAssertTrue(command.contains("/CloudMachine/"), "only the machine's share image") - // A busy image must not stop the replacement: the detach is best effort. - let step = try XCTUnwrap(command.components(separatedBy: " && ").first) - XCTAssertTrue(step.hasSuffix("true; }"), step) + XCTAssertTrue(command.contains("h='192.168.64.10'"), command) + // A busy image must not stop the replacement: the detach step ends in `true; }` and is + // followed directly by the removal. + let between = command[detach.lowerBound.. [String] { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/awk") + process.arguments = ["-v", "h=\(host)", TimeMachineDestinationFix.detachFilterAwk] + let input = Pipe() + let output = Pipe() + process.standardInput = input + process.standardOutput = output + try process.run() + input.fileHandleForWriting.write(Data(Self.hdiutilInfo.utf8)) + try input.fileHandleForWriting.close() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return String(decoding: data, as: UTF8.self).split(separator: "\n").map(String.init) + } + + func testDetachFilterPicksOnlyTheOldHostsShareImage() throws { + XCTAssertEqual(try filtered(host: "10.99.0.1"), ["/dev/disk6"]) + XCTAssertEqual(try filtered(host: "192.168.64.77"), ["/dev/disk8"]) + XCTAssertEqual(try filtered(host: "192.168.64.5"), [], "no image of that host: nothing") + XCTAssertEqual(try filtered(host: "10.99.0"), [], "a prefix of a host is not the host") + } + func testReplaceRemovesOnlyTheMachinesDestinationThenAddsThenRestoresTheQuota() throws { let command = try XCTUnwrap( TimeMachineDestinationFix.shellCommand( From b6a6286f3d4a25def695ebd5606637ff61bafbd6 Mon Sep 17 00:00:00 2001 From: RenaCode Date: Tue, 1 Dec 2026 22:42:03 +0100 Subject: [PATCH 6/6] swift-format: zawijanie dlugich linii Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AU1MhuGSAj8JTZKLqUoP7Q --- mac-app/Sources/CloudMachineCore/BackupHealth.swift | 3 ++- .../Sources/CloudMachineCore/TimeMachineDestinationFix.swift | 3 ++- mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/mac-app/Sources/CloudMachineCore/BackupHealth.swift b/mac-app/Sources/CloudMachineCore/BackupHealth.swift index 72dcf7b..123d95b 100644 --- a/mac-app/Sources/CloudMachineCore/BackupHealth.swift +++ b/mac-app/Sources/CloudMachineCore/BackupHealth.swift @@ -163,7 +163,8 @@ public enum BackupHealth { } var chosen: [String: Any]? if let address { - let hosts = [address] + (alias.map { [$0] } ?? []) + (VMMdnsName.currentHostName.map { [$0] } ?? []) + let hosts = + [address] + (alias.map { [$0] } ?? []) + (VMMdnsName.currentHostName.map { [$0] } ?? []) chosen = candidates.first { ($0["NetworkURL"] as? String).flatMap { VMAddressLease.destinationHost($0) } diff --git a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift index 70eed4e..eeaa8f1 100644 --- a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift +++ b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift @@ -41,7 +41,8 @@ public enum TimeMachineDestinationFix { /// A destination at the machine's static `alias` (`VMAddressLease`) is /// correct too: only the reservation is made, the destination stays. static func plan( - destinations: [TimeMachineStatus.Destination], address: String, alias: String? = nil) -> Plan { + destinations: [TimeMachineStatus.Destination], address: String, alias: String? = nil + ) -> Plan { guard let ours = VMStatus.machineDestination(in: destinations, address: nil) else { return .add } diff --git a/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift b/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift index cfb7313..334b5a8 100644 --- a/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift +++ b/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift @@ -107,7 +107,8 @@ final class VMMdnsNameTests: XCTestCase { func testTargetWithoutAnAddressIsNone() { XCTAssertEqual( - TimeMachineDestinationFix.target(address: nil, name: "lima-cmsmb.local", resolve: { _ in [] }), + TimeMachineDestinationFix.target( + address: nil, name: "lima-cmsmb.local", resolve: { _ in [] }), .none) }