Repository navigation
iOS: control Mac sleep & caffeinate from cmux mobile #6902
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
austinywang
wants to merge
23
commits into
main
from
issue-6482-cmux-mobile-should-control-mac-sleep
Closed
Changes from 16 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
f06c69c
iOS: control Mac sleep & caffeinate from cmux mobile
bfacdfe
Refresh Swift file length budget for Mac power UI additions
03c06af
iOS: load Mac power status when capabilities arrive after view appears
2401f8c
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
7578512
CmuxMacPower: make pmset parsing a factory on MacKeepAwakeStatus
dee0eec
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang fa9d83e
Add mac power holder identity regression test
austinywang 190367d
Fix mac power holder fallback identity
austinywang 0749e86
Add pmset parser parentheses regression test
austinywang d70c726
Fix mac power command edge cases
austinywang 85061f5
Report mac power status read failures
austinywang f1b3be0
Harden mobile mac power busy state
austinywang cdb4b44
Scope caffeinate disable to reported PIDs
austinywang 15fdb0c
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang 63e360b
Revalidate caffeinate PID before signaling
austinywang 091de61
Satisfy Mac power package policy checks
austinywang d7117a6
Treat Mac sleep timeouts as failures
austinywang 18c9e06
Tighten Mac power status and sleep errors
austinywang ef90e29
Address Mac power review comments
austinywang 05de121
Avoid reused pid in Mac power timeout
austinywang a351d0a
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang bea8bc3
Refresh Swift length budget after base merge
austinywang 2b8d8a6
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacPowerHolder.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| /// One process keeping the Mac or its display awake, mirrored from the Mac's | ||
| /// `mac.power.status` result (`CmuxMacPower.MacPowerAssertionHolder`). | ||
| public struct MobileMacPowerHolder: Decodable, Sendable, Equatable, Identifiable { | ||
| /// The owning process id, or `0` when an older Mac host omits the field. | ||
| public let pid: Int | ||
|
|
||
| /// The owning process name, such as `caffeinate`, `cmux`, or a GUI app. | ||
| public let processName: String | ||
|
|
||
| /// The power assertion types this process currently holds. | ||
| public let assertionTypes: [String] | ||
|
|
||
| /// The optional assertion reason reported by the Mac host. | ||
| public let detail: String? | ||
|
|
||
| /// Stable per-row identity for SwiftUI lists. | ||
| public var id: String { | ||
| "\(pid)|\(processName)|\(assertionTypes.joined(separator: ","))|\(detail ?? "")" | ||
| } | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case pid | ||
| case processName = "process" | ||
| case assertionTypes = "types" | ||
| case detail | ||
| } | ||
|
|
||
| /// Decodes a holder from the Mac power-control wire payload. | ||
| public init(from decoder: any Decoder) throws { | ||
| let container = try decoder.container(keyedBy: CodingKeys.self) | ||
| pid = (try container.decodeIfPresent(Int.self, forKey: .pid)) ?? 0 | ||
| processName = (try container.decodeIfPresent(String.self, forKey: .processName)) ?? "" | ||
| assertionTypes = (try container.decodeIfPresent([String].self, forKey: .assertionTypes)) ?? [] | ||
| detail = try container.decodeIfPresent(String.self, forKey: .detail) | ||
| } | ||
|
|
||
| /// Creates a holder snapshot for tests and decoded Mac power status models. | ||
| public init(pid: Int, processName: String, assertionTypes: [String], detail: String?) { | ||
| self.pid = pid | ||
| self.processName = processName | ||
| self.assertionTypes = assertionTypes | ||
| self.detail = detail | ||
| } | ||
| } |
61 changes: 61 additions & 0 deletions
61
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacPowerStatus.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| /// Whether the connected Mac is currently being kept awake, and by whom. | ||
| /// | ||
| /// Mirrors the Mac's `mac.power.status` result | ||
| /// (`CmuxMacPower.MacKeepAwakeStatus`). The booleans drive a localized summary | ||
| /// on the phone; `holders` backs the per-process detail rows. | ||
| public struct MobileMacPowerStatus: Decodable, Sendable, Equatable { | ||
| /// True when anything is preventing the Mac or its display from idle-sleeping. | ||
| public let keptAwake: Bool | ||
|
|
||
| /// True when a process holds a system idle or forced sleep-prevention assertion. | ||
| public let preventsSystemSleep: Bool | ||
|
|
||
| /// True when a process holds a display idle sleep-prevention assertion. | ||
| public let preventsDisplaySleep: Bool | ||
|
|
||
| /// True when cmux itself holds a keep-awake assertion. | ||
| public let cmuxKeepingAwake: Bool | ||
|
|
||
| /// True when a `caffeinate` process holds a keep-awake assertion. | ||
| public let caffeinateRunning: Bool | ||
|
|
||
| /// The processes currently holding keep-awake assertions. | ||
| public let holders: [MobileMacPowerHolder] | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case keptAwake = "kept_awake" | ||
| case preventsSystemSleep = "prevents_system_sleep" | ||
| case preventsDisplaySleep = "prevents_display_sleep" | ||
| case cmuxKeepingAwake = "cmux_keeping_awake" | ||
| case caffeinateRunning = "caffeinate_running" | ||
| case holders | ||
| } | ||
|
|
||
| /// Decodes a status snapshot from the Mac power-control wire payload. | ||
| public init(from decoder: any Decoder) throws { | ||
| let container = try decoder.container(keyedBy: CodingKeys.self) | ||
| keptAwake = (try container.decodeIfPresent(Bool.self, forKey: .keptAwake)) ?? false | ||
| preventsSystemSleep = (try container.decodeIfPresent(Bool.self, forKey: .preventsSystemSleep)) ?? false | ||
| preventsDisplaySleep = (try container.decodeIfPresent(Bool.self, forKey: .preventsDisplaySleep)) ?? false | ||
| cmuxKeepingAwake = (try container.decodeIfPresent(Bool.self, forKey: .cmuxKeepingAwake)) ?? false | ||
| caffeinateRunning = (try container.decodeIfPresent(Bool.self, forKey: .caffeinateRunning)) ?? false | ||
| holders = (try container.decodeIfPresent([MobileMacPowerHolder].self, forKey: .holders)) ?? [] | ||
| } | ||
|
|
||
| /// Creates a status snapshot for tests and local UI state. | ||
| public init( | ||
| keptAwake: Bool, | ||
| preventsSystemSleep: Bool, | ||
| preventsDisplaySleep: Bool, | ||
| cmuxKeepingAwake: Bool, | ||
| caffeinateRunning: Bool, | ||
| holders: [MobileMacPowerHolder] | ||
| ) { | ||
| self.keptAwake = keptAwake | ||
| self.preventsSystemSleep = preventsSystemSleep | ||
| self.preventsDisplaySleep = preventsDisplaySleep | ||
| self.cmuxKeepingAwake = cmuxKeepingAwake | ||
| self.caffeinateRunning = caffeinateRunning | ||
| self.holders = holders | ||
| } | ||
| } |
15 changes: 15 additions & 0 deletions
15
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacSleepResult.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| /// The outcome of asking the Mac to sleep. | ||
| /// | ||
| /// A sleep request usually drops the connection as the Mac sleeps, so a | ||
| /// connection error is not treated as a failure; only an explicit RPC error | ||
| /// such as missing Automation permission is `refused`. | ||
| public enum MobileMacSleepResult: Sendable, Equatable { | ||
| /// The Mac acknowledged the request, or the connection dropped as it slept. | ||
| case requested | ||
|
|
||
| /// The Mac explicitly refused, most often because Automation access is missing. | ||
| case refused | ||
|
|
||
| /// The request could not be delivered because the Mac was unreachable or auth failed. | ||
| case failed | ||
| } |
98 changes: 98 additions & 0 deletions
98
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+MacPower.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| internal import CmuxMobileRPC | ||
| internal import Foundation | ||
| internal import OSLog | ||
|
|
||
| nonisolated private let macPowerLog = Logger( | ||
| subsystem: Bundle.main.bundleIdentifier ?? "dev.cmux.ios", | ||
| category: "mobile-mac-power" | ||
| ) | ||
|
|
||
| /// Wrapper for the `mac.power.keep_awake.disable` result `{ terminated_caffeinate, status }`. | ||
| private struct MobileMacKeepAwakeDisableResponse: Decodable { | ||
| let status: MobileMacPowerStatus | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case status | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Mac power control RPCs | ||
|
|
||
| extension MobileShellComposite { | ||
| /// Read the connected Mac's keep-awake status. Returns `nil` if the Mac is | ||
| /// unreachable or the status could not be decoded. | ||
| public func macPowerStatus(macDeviceID: String? = nil) async -> MobileMacPowerStatus? { | ||
| guard let client = macPowerClient(for: macDeviceID) else { return nil } | ||
| do { | ||
| let request = try MobileCoreRPCClient.requestData( | ||
| method: "mac.power.status", | ||
| params: ["client_id": clientID] | ||
| ) | ||
| let data = try await client.sendRequest(request) | ||
| return try? JSONDecoder().decode(MobileMacPowerStatus.self, from: data) | ||
| } catch { | ||
| _ = disconnectForAuthorizationFailureIfNeeded(error) | ||
| macPowerLog.error("mac.power.status failed error=\(String(describing: error), privacy: .public)") | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| /// Put the connected Mac to sleep. | ||
| public func sleepMac(macDeviceID: String? = nil) async -> MobileMacSleepResult { | ||
| guard let client = macPowerClient(for: macDeviceID) else { return .failed } | ||
| let request: Data | ||
| do { | ||
| request = try MobileCoreRPCClient.requestData( | ||
| method: "mac.power.sleep", | ||
| params: ["client_id": clientID] | ||
| ) | ||
| } catch { | ||
| macPowerLog.error("mac.power.sleep request build failed error=\(String(describing: error), privacy: .public)") | ||
| return .failed | ||
| } | ||
| do { | ||
| _ = try await client.sendRequest(request) | ||
| return .requested | ||
| } catch { | ||
| if disconnectForAuthorizationFailureIfNeeded(error) { return .failed } | ||
| // The Mac answered with an explicit error (e.g. Automation access not | ||
| // granted yet): a genuine refusal, the Mac did not sleep. | ||
| if let connectionError = error as? MobileShellConnectionError, | ||
| case .rpcError = connectionError { | ||
| return .refused | ||
| } | ||
| // A closed/timed-out connection right after asking the Mac to sleep is | ||
| // the expected success signature — the Mac slept and the link dropped. | ||
| macPowerLog.info("mac.power.sleep link dropped (treated as slept) error=\(String(describing: error), privacy: .public)") | ||
| return .requested | ||
| } | ||
| } | ||
|
|
||
| /// Disable active keep-awake (terminate caffeinate) on the connected Mac, and | ||
| /// return the fresh status so the caller can reflect whatever still holds it | ||
| /// awake. Returns `nil` if the Mac is unreachable. | ||
| public func disableMacKeepAwake(macDeviceID: String? = nil) async -> MobileMacPowerStatus? { | ||
| guard let client = macPowerClient(for: macDeviceID) else { return nil } | ||
| do { | ||
| let request = try MobileCoreRPCClient.requestData( | ||
| method: "mac.power.keep_awake.disable", | ||
| params: ["client_id": clientID] | ||
| ) | ||
| let data = try await client.sendRequest(request) | ||
| return try? JSONDecoder().decode(MobileMacKeepAwakeDisableResponse.self, from: data).status | ||
| } catch { | ||
| _ = disconnectForAuthorizationFailureIfNeeded(error) | ||
| macPowerLog.error("mac.power.keep_awake.disable failed error=\(String(describing: error), privacy: .public)") | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| /// Resolve the RPC client that owns `macDeviceID`. Power commands target the | ||
| /// Mac the phone is actually connected to; an empty/absent id uses the | ||
| /// foreground connection (mirrors the workspace/notification routing). | ||
| private func macPowerClient(for macDeviceID: String?) -> MobileCoreRPCClient? { | ||
| guard let macDeviceID, !macDeviceID.isEmpty else { return remoteClient } | ||
| if foregroundMacDeviceID == macDeviceID { return remoteClient } | ||
| return secondaryMacSubscriptions[macDeviceID]?.client | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
27 changes: 27 additions & 0 deletions
27
Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileMacPowerHolderTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import Foundation | ||
| import Testing | ||
| @testable import CmuxMobileShell | ||
|
|
||
| @Suite struct MobileMacPowerHolderTests { | ||
| @Test func decodedHoldersWithoutPidsKeepDistinctIdentities() throws { | ||
| let data = Data(""" | ||
| [ | ||
| { | ||
| "process": "caffeinate", | ||
| "types": ["PreventUserIdleSystemSleep"], | ||
| "detail": "assertion one" | ||
| }, | ||
| { | ||
| "process": "backupd", | ||
| "types": ["PreventSystemSleep"], | ||
| "detail": "assertion two" | ||
| } | ||
| ] | ||
| """.utf8) | ||
|
|
||
| let holders = try JSONDecoder().decode([MobileMacPowerHolder].self, from: data) | ||
|
|
||
| #expect(holders.map(\.pid) == [0, 0]) | ||
| #expect(Set(holders.map(\.id)).count == holders.count) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.