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 @@ -636,4 +636,40 @@ extension MobileShellComposite {
)
workspaceGroups[index].isCollapsed = collapsed
}

/// Choose how the aggregated All Computers list orders its rows, on THIS
/// device only. Persists via the device-local sort store and rebuilds the
/// derived list so the change renders immediately; nothing is sent to a
/// Mac (each Mac keeps its own sidebar order).
public func setWorkspaceSortMode(_ mode: MobileWorkspaceSortMode) {
guard workspaceSortMode != mode else { return }
workspaceSortStore.setMode(mode)
workspaceSortMode = mode
recomputeDerivedWorkspaceState()
}

/// Persist the user's computer order for
/// ``MobileWorkspaceSortMode/computerPriority``, highest priority first,
/// as Mac device ids. Device-local, like the mode.
public func setWorkspaceComputerPriority(_ deviceIDs: [String]) {
guard workspaceComputerPriority != deviceIDs else { return }
workspaceSortStore.setComputerPriority(deviceIDs)
workspaceComputerPriority = deviceIDs
recomputeDerivedWorkspaceState()
}

/// The stored computer order expanded with each computer's stored alias
/// device ids, so a per-Mac state that reports an alias id still ranks
/// with its computer. Aliases follow their representative id directly,
/// keeping one physical Mac's entries adjacent in the expanded order.
func expandedWorkspaceComputerPriority() -> [String] {
var expanded: [String] = []
for deviceID in workspaceComputerPriority {
expanded.append(deviceID)
for alias in pairedMacAliasIDs(for: deviceID) where !expanded.contains(alias) {
expanded.append(alias)
}
}
return expanded
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,19 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
/// Mac, then phone-owned. `@ObservationIgnored` (views read `workspaceGroups`);
/// injected so tests/previews can pass a suite-scoped `UserDefaults`.
@ObservationIgnored var groupCollapseStore: MobileWorkspaceGroupCollapseStore
/// Device-local sort preference for the aggregated All Computers list
/// (mode + user computer order). `@ObservationIgnored`: views read the
/// observable ``workspaceSortMode`` / ``workspaceComputerPriority``
/// mirrors below; this store only persists. Injected so tests/previews can
/// pass a suite-scoped `UserDefaults`.
@ObservationIgnored var workspaceSortStore: MobileWorkspaceSortStore
/// Observable mirror of ``MobileWorkspaceSortStore/mode``. Change through
/// ``setWorkspaceSortMode(_:)`` so persistence and the derived list stay
/// in step.
public internal(set) var workspaceSortMode: MobileWorkspaceSortMode = .automatic
/// Observable mirror of ``MobileWorkspaceSortStore/computerPriority``.
/// Change through ``setWorkspaceComputerPriority(_:)``.
public internal(set) var workspaceComputerPriority: [String] = []
/// Device-local task templates used by the iOS task composer.
@ObservationIgnored public let taskTemplateStore: (any MobileTaskTemplateStoring)?
/// Mac/provider model responses observed by the task composer.
Expand Down Expand Up @@ -1440,6 +1453,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
feedbackStampProvider: @escaping @MainActor () -> MobileFeedbackStamp = { MobileShellComposite.emptyFeedbackStamp },
draftStore: (any TerminalDraftStoring)? = nil,
groupCollapseStore: MobileWorkspaceGroupCollapseStore = MobileWorkspaceGroupCollapseStore(),
workspaceSortStore: MobileWorkspaceSortStore = MobileWorkspaceSortStore(),
workspaceChangesHintDismissalStore: MobileWorkspaceChangesHintDismissalStore = MobileWorkspaceChangesHintDismissalStore(),
workspaceChangesSchedulingClock: any Clock<Duration> = ContinuousClock(),
controlPlaneSchedulingClock: any Clock<Duration> = ContinuousClock(),
Expand All @@ -1452,6 +1466,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
self.runtime = runtime
self.draftStore = draftStore
self.groupCollapseStore = groupCollapseStore
self.workspaceSortStore = workspaceSortStore
self.workspaceSortMode = workspaceSortStore.mode
self.workspaceComputerPriority = workspaceSortStore.computerPriority
self.workspaceChangesHintDismissalStore = workspaceChangesHintDismissalStore
self.workspaceChangesSchedulingClock = workspaceChangesSchedulingClock
self.controlPlaneSchedulingClock = controlPlaneSchedulingClock
Expand Down Expand Up @@ -6542,8 +6559,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {

/// Recompute the derived ``workspaces`` / ``workspaceGroups`` from the per-Mac
/// source of truth. Pure and cheap; the only place those two are assigned,
/// called on any ``workspacesByMac`` or foreground change.
private func recomputeDerivedWorkspaceState() {
/// called on any ``workspacesByMac``, foreground, or sort-preference change.
func recomputeDerivedWorkspaceState() {
updateStableMacColorSlots(); let previousSelection = selectedWorkspaceID.flatMap { id in
workspaces.first { $0.id == id }
}
Expand All @@ -6563,7 +6580,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
)
let macIDsInDisplayOrder = workspaceAggregation.orderedMacIDs(
statesByMac: statesByAggregateKey,
foregroundMacDeviceID: foregroundKey
foregroundMacDeviceID: foregroundKey,
computerPriority: workspaceSortMode == .computerPriority
? expandedWorkspaceComputerPriority()
: []
)
var derived = workspaceAggregation.derivedWorkspaces(
statesByMac: statesByAggregateKey,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,28 @@ public struct MobileWorkspaceAggregation: Sendable {
/// The aggregate keys in deterministic display order. A key is the
/// foreground owner key or a pairing/device id for secondaries; sibling
/// builds of one Mac order deterministically by instance tag.
///
/// `computerPriority` lists Mac device ids the user ordered by hand
/// (``MobileWorkspaceSortMode/computerPriority``): matching Macs come
/// first, in list order, ahead of even the foreground Mac — an explicit
/// choice must beat the automatic rule or it is not a choice. Sibling
/// builds of one prioritized Mac stay adjacent (same rank, tag tiebreak),
/// and Macs not in the list keep the automatic order after the
/// prioritized ones. Ids that match no live state are ignored.
public func orderedMacIDs(
statesByMac: [String: MacWorkspaceState],
foregroundMacDeviceID foregroundKey: String?
foregroundMacDeviceID foregroundKey: String?,
computerPriority: [String] = []
) -> [String] {
statesByMac.sorted { lhs, rhs in
var priorityRank: [String: Int] = [:]
for (index, deviceID) in computerPriority.enumerated()
where !deviceID.isEmpty && priorityRank[deviceID] == nil {
priorityRank[deviceID] = index
}
return statesByMac.sorted { lhs, rhs in
let lhsRank = priorityRank[lhs.value.macDeviceID] ?? Int.max
let rhsRank = priorityRank[rhs.value.macDeviceID] ?? Int.max
if lhsRank != rhsRank { return lhsRank < rhsRank }
let lhsForeground = lhs.key == foregroundKey
let rhsForeground = rhs.key == foregroundKey
if lhsForeground != rhsForeground { return lhsForeground }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
internal import Foundation

/// Flat, cross-computer presentation order for
/// ``MobileWorkspaceSortMode/recentActivity``.
///
/// This runs at the presentation layer, not in the aggregation: time
/// interleaving across Macs cannot keep one Mac's group members contiguous, so
/// the aggregated `workspaces` array keeps its natural order (group sections,
/// anchors, and move RPCs depend on it) and the list view applies this order to
/// its flat path only.
public struct MobileWorkspaceRecencyOrder: Sendable {
/// Create a recency-order helper.
public init() {}

/// Pinned rows first (the flat list's standing rule), then most recent
/// `lastActivityAt` first. Rows without a timestamp sort last, and every
/// tie keeps the incoming order so the list cannot shuffle between
/// refreshes of equal payloads.
public func displayOrder(_ workspaces: [MobileWorkspacePreview]) -> [MobileWorkspacePreview] {
workspaces.enumerated().sorted { lhs, rhs in
if lhs.element.isPinned != rhs.element.isPinned {
return lhs.element.isPinned
}
switch (lhs.element.lastActivityAt, rhs.element.lastActivityAt) {
case let (lhsDate?, rhsDate?) where lhsDate != rhsDate:
return lhsDate > rhsDate
case (_?, nil):
return true
case (nil, _?):
return false
default:
return lhs.offset < rhs.offset
}
}.map(\.element)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/// How the aggregated multi-computer ("All Computers") workspace list orders
/// its rows.
///
/// Each Mac only owns its own sidebar order, so the cross-Mac order is a
/// per-device presentation choice with no shared source of truth. Raw values
/// are persisted by ``MobileWorkspaceSortStore``.
public enum MobileWorkspaceSortMode: String, CaseIterable, Codable, Sendable {
/// Foreground computer first, remaining computers by display name. Each
/// computer's workspaces keep the Mac's own sidebar order. The historical
/// default.
case automatic
/// Computers in the user-chosen ``MobileWorkspaceSortStore/computerPriority``
/// order first, remaining computers in `automatic` order. Each computer's
/// workspaces keep the Mac's own sidebar order.
case computerPriority
/// One flat list across every computer, most recent activity first. Group
/// sections cannot survive time interleaving, so this mode presents flat.
case recentActivity
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
public import Foundation

/// Device-local sort preference for the aggregated "All Computers" workspace
/// list, persisted in an injected `UserDefaults`.
///
/// The sort is a per-device presentation choice, never sent to a Mac: phones
/// and Macs may order the same workspaces differently. The backing
/// `UserDefaults` is injected so the store is testable without touching
/// `.standard` (mirroring ``MobileWorkspaceGroupCollapseStore``); the app
/// constructs it at the composition root with `UserDefaults.standard`.
public struct MobileWorkspaceSortStore: Sendable {
/// The defaults key under which the mode + computer order payload is stored.
public static let defaultsKey = "dev.cmux.mobile.workspaceList.sort.v1"

/// The persisted shape. `mode` stays a raw string so a value written by a
/// newer build with more modes still decodes here (reading as `.automatic`
/// without being rewritten).
private struct Payload: Codable {
var mode: String
var computerPriority: [String]
}

// UserDefaults is Apple-documented thread-safe; OK to hold nonisolated.
private nonisolated(unsafe) let defaults: UserDefaults
private var payload: Payload

/// Create a store backed by the given defaults.
/// - Parameter defaults: The persistence store. Inject a suite-scoped
/// `UserDefaults` in tests; the app passes `.standard`.
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
if let data = defaults.data(forKey: Self.defaultsKey),
let decoded = try? JSONDecoder().decode(Payload.self, from: data) {
payload = decoded
} else {
payload = Payload(
mode: MobileWorkspaceSortMode.automatic.rawValue,
computerPriority: []
)
}
}

/// The persisted sort mode; unknown stored values read as `.automatic`.
public var mode: MobileWorkspaceSortMode {
MobileWorkspaceSortMode(rawValue: payload.mode) ?? .automatic
}

/// Mac device ids in the user's chosen computer order, highest priority
/// first. Applied only while ``mode`` is `.computerPriority`; ids that no
/// longer match a live computer are ignored by the aggregation, and kept
/// here so a temporarily offline computer retains its slot.
public var computerPriority: [String] { payload.computerPriority }

/// Persist a mode choice. No-op when unchanged.
public mutating func setMode(_ mode: MobileWorkspaceSortMode) {
guard payload.mode != mode.rawValue else { return }
payload.mode = mode.rawValue
persist()
}

/// Persist a user computer order. No-op when unchanged.
public mutating func setComputerPriority(_ deviceIDs: [String]) {
guard payload.computerPriority != deviceIDs else { return }
payload.computerPriority = deviceIDs
persist()
}

private func persist() {
if let data = try? JSONEncoder().encode(payload) {
defaults.set(data, forKey: Self.defaultsKey)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -342,4 +342,132 @@ import Testing
#expect(workspaces.map(\.rpcWorkspaceID.rawValue) == ["b1", "a1"])
#expect(groups.map(\.rpcGroupID.rawValue) == ["group-b", "group-a"])
}

@Test func computerPriorityOverridesForegroundAndNameOrder() {
let states = [
"mac-a": state("mac-a", name: "Alpha", ["a1"]),
"mac-b": state("mac-b", name: "Beta", ["b1"]),
"mac-c": state("mac-c", name: "Charlie", ["c1"]),
]
let ordered = MobileWorkspaceAggregation().orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: "mac-a",
computerPriority: ["mac-c", "mac-b"]
)
// The user's explicit order beats both foreground-first and name order;
// the unprioritized foreground Mac follows the prioritized ones.
#expect(ordered == ["mac-c", "mac-b", "mac-a"])
}

@Test func unprioritizedMacsKeepAutomaticOrderAfterPrioritizedOnes() {
let states = [
"mac-a": state("mac-a", name: "Alpha", ["a1"]),
"mac-b": state("mac-b", name: "Beta", ["b1"]),
"mac-c": state("mac-c", name: "Charlie", ["c1"]),
]
let ordered = MobileWorkspaceAggregation().orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: "mac-c",
computerPriority: ["mac-b"]
)
// mac-b is pinned first; the rest keep foreground-then-name order.
#expect(ordered == ["mac-b", "mac-c", "mac-a"])
}

@Test func computerPriorityIgnoresUnknownAndEmptyEntries() {
let states = [
"mac-a": state("mac-a", name: "Alpha", ["a1"]),
"mac-b": state("mac-b", name: "Beta", ["b1"]),
]
let ordered = MobileWorkspaceAggregation().orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: nil,
computerPriority: ["", "gone-mac", "mac-b"]
)
#expect(ordered == ["mac-b", "mac-a"])
}

@Test func computerPriorityKeepsSiblingBuildsOfOneMacAdjacent() {
var nightly = state("mac-a", name: "Alpha", ["a-nightly"])
nightly.instanceTag = "nightly"
var stable = state("mac-a", name: "Alpha", ["a-stable"])
stable.instanceTag = nil
let states = [
"mac-a\u{1F}nightly": nightly,
"mac-a": stable,
"mac-b": state("mac-b", name: "Beta", ["b1"]),
]
let ordered = MobileWorkspaceAggregation().orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: "mac-b",
computerPriority: ["mac-a"]
)
// Both builds of mac-a share one rank and stay adjacent (tag tiebreak),
// ahead of the unprioritized foreground Mac.
#expect(ordered == ["mac-a", "mac-a\u{1F}nightly", "mac-b"])
}

@Test func emptyComputerPriorityMatchesAutomaticOrder() {
let states = [
"mac-b": state("mac-b", name: "Beta", ["b1"]),
"mac-a": state("mac-a", name: "Alpha", ["a1"]),
]
let aggregation = MobileWorkspaceAggregation()
let automatic = aggregation.orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: "mac-b"
)
let withEmptyPriority = aggregation.orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: "mac-b",
computerPriority: []
)
#expect(automatic == withEmptyPriority)
}

@Test func computerPriorityOrderDrivesWorkspaceAndGroupDerivations() {
var macAWorkspace = ws("a1", mac: "mac-a")
macAWorkspace.groupID = "group-a"
var macBWorkspace = ws("b1", mac: "mac-b")
macBWorkspace.groupID = "group-b"
let states = [
"mac-a": MacWorkspaceState(
macDeviceID: "mac-a",
displayName: "Alpha",
workspaces: [macAWorkspace],
groups: [group("group-a", anchor: "a1")],
status: .connected
),
"mac-b": MacWorkspaceState(
macDeviceID: "mac-b",
displayName: "Beta",
workspaces: [macBWorkspace],
groups: [group("group-b", anchor: "b1")],
status: .connected
),
]
let aggregation = MobileWorkspaceAggregation()
let macIDsInDisplayOrder = aggregation.orderedMacIDs(
statesByMac: states,
foregroundMacDeviceID: "mac-a",
computerPriority: ["mac-b"]
)

let workspaces = aggregation.derivedWorkspaces(
statesByMac: states,
foregroundMacDeviceID: "mac-a",
machineColorIndex: machineColorIndex(statesByMac: states),
macIDsInDisplayOrder: macIDsInDisplayOrder
)
let groups = aggregation.derivedGroups(
statesByMac: states,
foregroundMacDeviceID: "mac-a",
macIDsInDisplayOrder: macIDsInDisplayOrder
)

// Workspaces and group sections both follow the prioritized Mac order,
// so sections never detach from their members.
#expect(workspaces.map(\.rpcWorkspaceID.rawValue) == ["b1", "a1"])
#expect(groups.map(\.rpcGroupID.rawValue) == ["group-b", "group-a"])
}
}
Loading