Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
Jun 26, 2026
bfacdfe
Refresh Swift file length budget for Mac power UI additions
Jun 26, 2026
03c06af
iOS: load Mac power status when capabilities arrive after view appears
Jun 26, 2026
2401f8c
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
Jun 26, 2026
7578512
CmuxMacPower: make pmset parsing a factory on MacKeepAwakeStatus
Jun 26, 2026
dee0eec
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang Jul 3, 2026
fa9d83e
Add mac power holder identity regression test
austinywang Jul 3, 2026
190367d
Fix mac power holder fallback identity
austinywang Jul 3, 2026
0749e86
Add pmset parser parentheses regression test
austinywang Jul 3, 2026
d70c726
Fix mac power command edge cases
austinywang Jul 3, 2026
85061f5
Report mac power status read failures
austinywang Jul 3, 2026
f1b3be0
Harden mobile mac power busy state
austinywang Jul 3, 2026
cdb4b44
Scope caffeinate disable to reported PIDs
austinywang Jul 4, 2026
15fdb0c
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang Jul 4, 2026
63e360b
Revalidate caffeinate PID before signaling
austinywang Jul 4, 2026
091de61
Satisfy Mac power package policy checks
austinywang Jul 4, 2026
d7117a6
Treat Mac sleep timeouts as failures
austinywang Jul 4, 2026
18c9e06
Tighten Mac power status and sleep errors
austinywang Jul 4, 2026
ef90e29
Address Mac power review comments
austinywang Jul 4, 2026
05de121
Avoid reused pid in Mac power timeout
austinywang Jul 4, 2026
a351d0a
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang Jul 4, 2026
bea8bc3
Refresh Swift length budget after base merge
austinywang Jul 4, 2026
2b8d8a6
Merge remote-tracking branch 'origin/main' into issue-6482-cmux-mobil…
austinywang Jul 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .github/swift-file-length-budget.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
34660 CLI/cmux.swift
17954 Sources/AppDelegate.swift
16427 Sources/ContentView.swift
14270 Sources/TerminalController.swift
14318 Sources/TerminalController.swift
13172 Sources/Workspace.swift
12348 cmuxTests/AppDelegateShortcutRoutingTests.swift
12212 Sources/GhosttyTerminalView.swift
11669 Sources/Panels/BrowserPanel.swift
9497 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift
8032 Sources/Panels/BrowserPanelView.swift
8016 CLI/cmux_open.swift
7706 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
7710 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
7405 cmuxTests/WorkspaceUnitTests.swift
7218 cmuxTests/WorkspaceRemoteConnectionTests.swift
6359 cmuxTests/SessionPersistenceTests.swift
Expand Down Expand Up @@ -70,7 +70,7 @@
1363 Sources/CMUXInstalledExtensionSidebarHostView.swift
1360 Sources/Feed/FeedButtonStyleDebugWindowController.swift
1317 Sources/FileExplorerStore.swift
1295 cmuxTests/MobileHostAuthorizationTests.swift
1297 cmuxTests/MobileHostAuthorizationTests.swift
1291 Packages/macOS/CmuxTerminalCore/Sources/CmuxTerminalCore/Config/GhosttyConfig.swift
1290 cmuxTests/TextBoxSubmitActionTests.swift
1287 cmuxTests/RestorableAgentSessionIndexTests.swift
Expand Down Expand Up @@ -169,6 +169,7 @@
644 Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift
642 cmuxTests/RemoteTmuxControlParserTests.swift
641 cmuxTests/CommandPaletteNucleoFFITests.swift
640 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift
637 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift
635 cmuxUITests/RightSidebarChromeHeightUITests.swift
630 Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/ShortcutWhenClause.swift
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
internal import CmuxMobileRPC
internal import Foundation
internal import OSLog

private let macPowerLog = Logger(
subsystem: Bundle.main.bundleIdentifier ?? "dev.cmux.ios",
category: "mobile-mac-power"
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// MARK: - Wire models

/// 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 {
public let pid: Int
public let processName: String
public let assertionTypes: [String]
public let detail: String?

/// Stable per-row identity for SwiftUI lists.
public var id: Int { pid }

private enum CodingKeys: String, CodingKey {
case pid
case processName = "process"
case assertionTypes = "types"
case detail
}

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)) ?? ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 pid: 0 fallback creates duplicate Identifiable IDs for missing-pid holders

MobileMacPowerHolder.id is pid, but when the pid field is absent from JSON the decoder assigns 0, so every such holder shares id = 0. SwiftUI ForEach treats duplicate IDs as the same element and will silently drop or misrender extra rows. Using processName as a fallback (or a composite of pid + processName) keeps identity unique in practice even if the server ever omits the pid field.

Suggested change
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)) ?? ""
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
processName = (try container.decodeIfPresent(String.self, forKey: .processName)) ?? ""
pid = (try container.decodeIfPresent(Int.self, forKey: .pid)) ?? processName.hashValue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: MobileMacPowerHolder.id is now a deterministic composite of pid, process, assertion types, and detail, with regression coverage for missing-pid holders.

— Claude Code

assertionTypes = (try container.decodeIfPresent([String].self, forKey: .assertionTypes)) ?? []
detail = try container.decodeIfPresent(String.self, forKey: .detail)
}

public init(pid: Int, processName: String, assertionTypes: [String], detail: String?) {
self.pid = pid
self.processName = processName
self.assertionTypes = assertionTypes
self.detail = detail
}
}

/// 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 {
public let keptAwake: Bool
public let preventsSystemSleep: Bool
public let preventsDisplaySleep: Bool
public let cmuxKeepingAwake: Bool
public let caffeinateRunning: Bool
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
}

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)) ?? []
}

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
}
}

/// 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
}
}

/// 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
/// (e.g. Automation permission not granted) 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 Automation access not granted).
case refused
/// The request could not be delivered (not connected / auth failure).
case failed
}

// 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 }
do {
let request = try MobileCoreRPCClient.requestData(
method: "mac.power.sleep",
params: ["client_id": clientID]
)
_ = 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
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// 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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
private static let workspaceCloseCapability = "workspace.close.v1"
private static let dogfoodFeedbackCapability = "dogfood.v1"
private static let workspaceGroupsCapability = "workspace.groups.v1"
private static let macPowerControlCapability = "mac.power.control.v1"
private static let terminalOutputCapabilityTimeoutNanoseconds: UInt64 = 750_000_000

/// How long the render-grid stream may stay silent (no event of any topic)
Expand Down Expand Up @@ -311,6 +312,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
public var supportsWorkspaceCloseActions: Bool { supportedHostCapabilities.contains(Self.workspaceCloseCapability) }
/// Whether the Mac supports dogfood feedback submission.
public var supportsDogfoodFeedback: Bool { supportedHostCapabilities.contains(Self.dogfoodFeedbackCapability) }
/// Whether the Mac supports the Mac power controls (sleep / disable
/// keep-awake / keep-awake status) exposed in the per-computer detail view.
public var supportsMacPowerControl: Bool { supportedHostCapabilities.contains(Self.macPowerControlCapability) }
/// The composer's live draft for the currently selected terminal.
///
/// Edits are persisted per-terminal through the FIFO draft pipeline on every
Expand Down
Loading
Loading