Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,60 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
return connectionState == .connected
}

// MARK: - Paired Mac switching

/// Every Mac paired with this device, for the host switcher. Refreshed via
/// ``loadPairedMacs()`` and after switch/forget.
public private(set) var pairedMacs: [MobilePairedMac] = []

/// The device id of the Mac the live connection currently targets, if any.
/// Used by the switcher to mark the active row.
public var activeMacDeviceID: String? { activeTicket?.macDeviceID }

/// Reload ``pairedMacs`` from the store, scoped to the signed-in user.
public func loadPairedMacs() async {
guard let pairedMacStore else {
pairedMacs = []
return
}
do {
pairedMacs = try await pairedMacStore.loadAll(stackUserID: identityProvider?.currentUserID)
} catch {
mobileShellLog.error("paired mac store loadAll failed: \(String(describing: error), privacy: .public)")
}
Comment on lines +596 to +608

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Clear pairedMacs when reload fails to avoid stale/cross-account host exposure.

If loadAll throws, the previous in-memory list is kept. After account/scope changes, the UI can continue showing old pairings until a later successful reload.

Suggested fix
public func loadPairedMacs() async {
    guard let pairedMacStore else {
        pairedMacs = []
        return
    }
    do {
        pairedMacs = try await pairedMacStore.loadAll(stackUserID: identityProvider?.currentUserID)
    } catch {
+       pairedMacs = []
        mobileShellLog.error("paired mac store loadAll failed: \(String(describing: error), privacy: .public)")
    }
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
do {
pairedMacs = try await pairedMacStore.loadAll(stackUserID: identityProvider?.currentUserID)
} catch {
mobileShellLog.error("paired mac store loadAll failed: \(String(describing: error), privacy: .public)")
}
do {
pairedMacs = try await pairedMacStore.loadAll(stackUserID: identityProvider?.currentUserID)
} catch {
pairedMacs = []
mobileShellLog.error("paired mac store loadAll failed: \(String(describing: error), privacy: .public)")
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift`
around lines 525 - 529, When pairedMacStore.loadAll throws in
MobileShellComposite.swift, the old in-memory pairedMacs remains and can show
stale/cross-account data; in the catch block for the try await
pairedMacStore.loadAll(stackUserID: identityProvider?.currentUserID) set
pairedMacs to an empty collection (or nil if pairedMacs is optional) before
calling mobileShellLog.error to ensure the UI no longer shows previous pairings
after a failed reload.

}

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.

P1 loadPairedMacs() passes identityProvider?.currentUserID directly to loadAll. When currentUserID is nil — for example right after sign-out while the picker sheet is still on screen — loadAll(stackUserID: nil) omits the WHERE stack_user_id IS ? clause and returns every row for every user stored on the device. On a shared device this surfaces another user's paired Macs in the switcher. A defensive guard that short-circuits with an empty list when there is no known user keeps the picker's scope correct in all lifecycle states.

Suggested change
/// Reload ``pairedMacs`` from the store, scoped to the signed-in user.
public func loadPairedMacs() async {
guard let pairedMacStore else {
pairedMacs = []
return
}
do {
pairedMacs = try await pairedMacStore.loadAll(stackUserID: identityProvider?.currentUserID)
} catch {
mobileShellLog.error("paired mac store loadAll failed: \(String(describing: error), privacy: .public)")
}
}
/// Reload ``pairedMacs`` from the store, scoped to the signed-in user.
public func loadPairedMacs() async {
guard let pairedMacStore else {
pairedMacs = []
return
}
guard let userID = identityProvider?.currentUserID else {
// No signed-in user — show nothing rather than returning every
// user's rows from a shared-device store.
pairedMacs = []
return
}
do {
pairedMacs = try await pairedMacStore.loadAll(stackUserID: userID)
} catch {
mobileShellLog.error("paired mac store loadAll failed: \(String(describing: error), privacy: .public)")
}
}


/// Make `macDeviceID` the active pairing and reconnect to it. A no-op when it
/// is already the active Mac.
/// - Parameter macDeviceID: The stored Mac to switch to.
public func switchToMac(macDeviceID: String) async {
guard let pairedMacStore, macDeviceID != activeMacDeviceID else { return }
do {
try await pairedMacStore.setActive(macDeviceID: macDeviceID)
} catch {
mobileShellLog.error("paired mac store setActive failed mac=\(macDeviceID, privacy: .public) error=\(String(describing: error), privacy: .public)")
return
}
_ = await reconnectActiveMacIfAvailable(stackUserID: identityProvider?.currentUserID)
await loadPairedMacs()
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment on lines +621 to +655

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.

P1 switchToMac drops the live connection before the new one is established

connectManualHost calls beginPairingAttempt() (which cancels pending remote operation tasks) then awaits manualHostTicket(...) over the network. If that server round-trip fails — Mac B offline, auth-server hiccup, or a timeout — the catch block calls clearRemoteConnectionContext() → replaceRemoteClient(with: nil), which disconnects the current Mac A RPC connection. The user ends up disconnected from both Macs.

The doc comment directly above promises the opposite: "a failed switch…leaves the previously-working Mac active and reachable." That is true of the SQLite record (is_active is not updated on failure), but false of the live socket connection, which is severed during the failed attempt. Users switching to an offline Mac lose their working session unexpectedly. The fix would be to either snapshot and restore the existing remoteClient on failure, or at minimum correct the doc comment to match actual behavior.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Forget `macDeviceID`. If it is the active Mac the live connection is
/// dropped too; otherwise only the stored entry is removed.
/// - Parameter macDeviceID: The stored Mac to forget.
public func forgetMac(macDeviceID: String) async {
if macDeviceID == activeMacDeviceID {
disconnectAndForgetActiveMac()
} else {
do {
try await pairedMacStore?.remove(macDeviceID: macDeviceID)
} catch {
mobileShellLog.error("paired mac store remove failed mac=\(macDeviceID, privacy: .public) error=\(String(describing: error), privacy: .public)")
}
}
await loadPairedMacs()
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
Comment on lines +663 to +674

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.

P1 Stale list after forgetting the active Mac

When macDeviceID == activeMacDeviceID, disconnectAndForgetActiveMac() is synchronous and fires an unstructured Task internally to call pairedMacStore.remove(...). Control returns to forgetMac immediately, which then awaits loadPairedMacs(). Because the removal and the reload are now two independent tasks on the MainActor executor, loadPairedMacs() can read the store before the remove task has written its deletion — the forgotten Mac stays in pairedMacs with no subsequent refresh scheduled. The non-active path correctly awaits the removal before reloading, so that branch is clean.

The fix is to await the removal explicitly in the active-Mac path rather than relying on disconnectAndForgetActiveMac's internal fire-and-forget Task, or to call loadPairedMacs() from inside disconnectAndForgetActiveMac's remove-completion handler.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

static func firstReconnectHostPortRoute(
_ routes: [CmxAttachRoute],
supportedKinds: [CmxAttachTransportKind]
Expand Down
2 changes: 2 additions & 0 deletions Packages/CmuxMobileShellUI/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ let package = Package(
.package(path: "../CmuxAuthRuntime"),
.package(path: "../CmuxMobileCamera"),
.package(path: "../CmuxMobileDiagnostics"),
.package(path: "../CmuxMobilePairedMac"),
.package(path: "../CmuxMobileShell"),
.package(path: "../CmuxMobileShellModel"),
.package(path: "../CmuxMobileSupport"),
Expand All @@ -33,6 +34,7 @@ let package = Package(
"CmuxAuthRuntime",
"CmuxMobileCamera",
"CmuxMobileDiagnostics",
"CmuxMobilePairedMac",
"CmuxMobileShell",
"CmuxMobileShellModel",
"CmuxMobileSupport",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#if os(iOS)
import CmuxMobilePairedMac
import CmuxMobileShell
import CmuxMobileSupport
import SwiftUI

/// Lets the user switch which paired Mac this device controls, and pair another.
///
/// Lists every Mac paired with this device (from the on-device store), marks the
/// one the live connection targets, switches on tap, forgets on swipe, and pairs
/// a new Mac by scanning its QR code without dropping the others.
struct MobileHostPickerView: View {
@Bindable var store: CMUXMobileShellStore
@Environment(\.dismiss) private var dismiss
@State private var showingScanner = false

var body: some View {
NavigationStack {
List {
Section {
if store.pairedMacs.isEmpty {
Text(L10n.string("mobile.hostPicker.empty", defaultValue: "No paired Macs yet."))
.foregroundStyle(.secondary)
}
ForEach(store.pairedMacs) { mac in
macRow(mac)
}
} header: {
Text(L10n.string("mobile.hostPicker.header", defaultValue: "Paired Macs"))
} footer: {
Text(L10n.string(
"mobile.hostPicker.footer",
defaultValue: "Switch which Mac this device controls. Pairing another Mac keeps the others, so you can hop between them."
))
}

Section {
Button {
showingScanner = true
} label: {
Label(
L10n.string("mobile.hostPicker.addMac", defaultValue: "Pair Another Mac"),
systemImage: "plus"
)
}
.accessibilityIdentifier("MobileHostPickerAddMac")
}
}
.navigationTitle(L10n.string("mobile.hostPicker.title", defaultValue: "Switch Mac"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button(L10n.string("mobile.common.done", defaultValue: "Done")) {
dismiss()
}
.accessibilityIdentifier("MobileHostPickerDone")
}
}
.task { await store.loadPairedMacs() }
.sheet(isPresented: $showingScanner) {
MobilePairingScannerSheet { code in
showingScanner = false
Task {
_ = await store.connectPairingURL(code)
await store.loadPairedMacs()
dismiss()
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
Comment on lines +61 to +68

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.

P1 QR scan severs existing session on failure, then unconditionally dismisses the picker

connectPairingURL calls beginPairingAttempt() (which rotates pairingAttemptID) and then on any failure — bad QR, decode error, network timeout — calls clearRemoteConnectionContext() before returning .failed. That tears down the live Mac A connection. After that, dismiss() fires regardless of the return value, so the user is ejected from the picker and returned to the workspace list with no active connection.

switchToMac's corresponding failure path at least attempts a fallback via reconnectActiveMacIfAvailable; this path has no fallback and no guard. The user opens "Pair Another Mac", scans an expired or wrong QR, and silently loses their working session.

The fix is to check the return value of connectPairingURL and only call dismiss() on success, and/or use store.reconnectActiveMacIfAvailable as a fallback when the pairing fails.

}
}
.accessibilityIdentifier("MobileHostPicker")
}

@ViewBuilder
private func macRow(_ mac: MobilePairedMac) -> some View {
let isActive = mac.macDeviceID == store.activeMacDeviceID
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Button {
Task { await store.switchToMac(macDeviceID: mac.macDeviceID) }
} label: {
HStack(spacing: 12) {
Image(systemName: "desktopcomputer")
.foregroundStyle(.secondary)
VStack(alignment: .leading, spacing: 2) {
Text(mac.displayName ?? mac.macDeviceID)
.foregroundStyle(.primary)
Text(mac.lastSeenAt, format: .relative(presentation: .named))
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer(minLength: 8)
if isActive {
Image(systemName: "checkmark")
.foregroundStyle(Color.accentColor)
.accessibilityLabel(L10n.string("mobile.hostPicker.active", defaultValue: "Active"))
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityIdentifier("MobileHostPickerRow-\(mac.macDeviceID)")
.swipeActions(edge: .trailing) {
Button(role: .destructive) {
Task { await store.forgetMac(macDeviceID: mac.macDeviceID) }
} label: {
Label(L10n.string("mobile.hostPicker.forget", defaultValue: "Forget"), systemImage: "trash")
}
.accessibilityIdentifier("MobileHostPickerForget-\(mac.macDeviceID)")
}
Comment on lines +77 to +108

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 Unlifecycled fire-and-forget Tasks for switch and forget actions

Both Task { await store.switchToMac(...) } (tap) and Task { await store.forgetMac(...) } (swipe) are unstructured and untracked. A rapid double-tap or swipe queues a second operation before the first completes: switchToMac's guard (macDeviceID != activeMacDeviceID) won't catch the duplicate because activeMacDeviceID still reflects the old value during the first task's await. forgetMac has no guard at all. For actions that trigger reconnection or deletion side-effects, these should be tracked tasks (stored on the store or on a @State binding) so that in-flight operations can be cancelled or gated before a second one starts.

Rule Used: Flag new legacy async patterns in cmux-owned Swift... (source)

}
}
#endif
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#if os(iOS)
import CmuxAuthRuntime
import CmuxMobileShell
import CmuxMobileSupport
import SwiftUI

Expand All @@ -13,9 +14,13 @@ struct MobileSettingsView: View {
let connectedHostName: String
let rescanQR: (() -> Void)?
let signOut: (() -> Void)?
/// The shell store, used to drive the multi-Mac switcher. `nil` in previews,
/// where the "Switch Mac" entry is hidden.
var store: CMUXMobileShellStore?

@Environment(\.dismiss) private var dismiss
@State private var showingShortcuts = false
@State private var showingHostPicker = false

var body: some View {
NavigationStack {
Expand Down Expand Up @@ -58,6 +63,17 @@ struct MobileSettingsView: View {
value: connectedHostName
)
}
if store != nil {
Button {
showingHostPicker = true
} label: {
Label(
L10n.string("mobile.settings.switchMac", defaultValue: "Switch Mac"),
systemImage: "macbook.and.iphone"
)
}
.accessibilityIdentifier("MobileSettingsSwitchMac")
}
if let rescanQR {
Button {
rescanQR()
Expand Down Expand Up @@ -117,6 +133,11 @@ struct MobileSettingsView: View {
.sheet(isPresented: $showingShortcuts) {
TerminalShortcutsSettingsView()
}
.sheet(isPresented: $showingHostPicker) {
if let store {
MobileHostPickerView(store: store)
}
}
}
.accessibilityIdentifier("MobileSettingsView")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import CmuxMobileShell
import CmuxMobileShellModel
import CmuxMobileSupport
import SwiftUI
Expand All @@ -20,6 +21,9 @@ struct WorkspaceListView: View {
/// previews), the menu is hidden.
var rescanQR: (() -> Void)?
var signOut: (() -> Void)?
/// The shell store, forwarded to Settings to drive the multi-Mac switcher.
/// `nil` in previews.
var store: CMUXMobileShellStore?
@State private var searchText = ""
@State private var showingShortcutsSettings = false
@State private var showingSettings = false
Expand Down Expand Up @@ -87,7 +91,8 @@ struct WorkspaceListView: View {
MobileSettingsView(
connectedHostName: host,
rescanQR: rescanQR,
signOut: signOut
signOut: signOut,
store: store
)
}
#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ struct WorkspaceShellView: View {
selectWorkspace: selectWorkspace,
createWorkspace: createWorkspaceInCompactStack,
rescanQR: { store.disconnectAndForgetActiveMac() },
signOut: signOut
signOut: signOut,
store: store
)
.navigationDestination(for: MobileWorkspacePreview.ID.self) { workspaceID in
workspaceDestination(for: workspaceID, createWorkspace: createWorkspaceInCompactStack)
Expand Down Expand Up @@ -113,7 +114,8 @@ struct WorkspaceShellView: View {
selectWorkspace: selectWorkspace,
createWorkspace: store.createWorkspace,
rescanQR: { store.disconnectAndForgetActiveMac() },
signOut: signOut
signOut: signOut,
store: store
)
.navigationSplitViewColumnWidth(min: 320, ideal: 380, max: 440)
} detail: {
Expand Down
Loading
Loading