From a4d940c88e64f472f8ef096b5b5c9199c14cbb65 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 06:17:11 +0000 Subject: [PATCH 01/29] feat(sidebar): categorize and group lane sessions Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../RemoteMachinesSidebar.swift | 5 +- .../Model/SidebarCategory.swift | 63 +++++++++++++++++++ .../SidebarCategoryTests.swift | 31 +++++++++ 3 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift create mode 100644 Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift index f4b844e81172..2ab18a0cad0b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift @@ -308,9 +308,12 @@ public final class RemoteMachinesSidebar { /// The groups: every peer the daemon lists (none listed yet: every peer a lane names), each /// with its live chats newest first, reachable machines first. A peer the daemon cannot reach has no chats. static func machines(lanes: some Collection, peers: [AcpmuxPeerList.Peer]?) -> [Machine] { + // Fleet sessions always enter the existing machine group keyed by peer; + // local sessions stay with their workspace/lineage projection instead of + // becoming loose rows in this feed. var byPeer: [String: [AgentActivityLane]] = [:] for lane in lanes { - guard let peer = lane.peer else { continue } + guard case .fleet(let peer) = SidebarLaneGroup.forLane(peer: lane.peer, workspaceID: lane.workspaceID, parent: lane.parent) else { continue } byPeer[peer, default: []].append(lane) } let online = Dictionary((peers ?? []).map { ($0.name, $0.connected) }, uniquingKeysWith: { first, _ in first }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift new file mode 100644 index 000000000000..d7381b3c97c7 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift @@ -0,0 +1,63 @@ +import Foundation + +/// The home for every kind of thing that can reach the sidebar. +/// +/// This is deliberately a taxonomy, not a new section or a default toggle. Existing +/// projections decide whether a category is visible; this type makes it impossible to +/// silently send a new item to an ungrouped bucket. +public nonisolated enum SidebarCategory: Hashable, Sendable { + case home + case workspace + case group + case browserTab + case chat + case app + case fleetMachine + case fleetSession + case agentSession + case fold + case custom + case unknown + + /// Every persisted sidebar document body has an explicit home. + public init(body: SidebarDocBody) { + switch body { + case .workspace: self = .workspace + case .group: self = .group + case .tab, .url: self = .browserTab + case .builtin(let value): self = value == SidebarBuiltIn.home.rawValue ? .home : .app + case .app: self = .app + case .room: self = .chat + case .savedGroup: self = .group + // Forward-compatible references stay in their document/custom section; + // they must never become a loose top-level row merely because the App + // does not know their payload yet. + case .ref, .other: self = .custom + } + } + + /// The existing destination for an acpmux lane. No new default surface is enabled. + public static func lane(peer: String?, workspaceID: String?, parent: String?) -> Self { + if peer != nil { return .fleetSession } + if parent != nil || workspaceID != nil { return .agentSession } + return .agentSession + } + + public var isCategorized: Bool { self != .unknown } +} + +/// Stable group keys used by existing machine, workspace and lineage projections. +public nonisolated enum SidebarLaneGroup: Hashable, Sendable { + case fleet(String) + case workspace(String) + case lineage(String) + case agent + + public static func forLane(peer: String?, workspaceID: String?, parent: String?) -> Self { + if let peer { return .fleet(peer) } + if let workspaceID { return .workspace(workspaceID) } + if let parent { return .lineage(parent) } + return .agent + } +} + diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift new file mode 100644 index 000000000000..e328fe0974f1 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift @@ -0,0 +1,31 @@ +@testable import CmuxNextSidebar +import Testing + +/// Every sidebar input has a home. The taxonomy is an audit of existing destinations; +/// it does not turn on a new section or change defaults. +struct SidebarCategoryTests { + @Test func everyPersistedItemTypeHasACategory() { + let bodies: [SidebarDocBody] = [ + .workspace(.init(sessionID: "local", workspaceID: "ws")), + .group(name: "Project", color: nil, icon: nil, collapsed: false), + .builtin(SidebarBuiltIn.home.rawValue), + .builtin(SidebarBuiltIn.settings.rawValue), + .app("com.example.app"), + .url("https://example.com", title: "Example"), + .tab("tab-1"), + .room("room-1"), + .savedGroup("saved"), + .ref(kind: "future", value: "item"), + .other("future") + ] + #expect(bodies.allSatisfy { SidebarCategory(body: $0).isCategorized }) + } + + @Test func lanesUseExistingGroupingDestinations() { + #expect(SidebarLaneGroup.forLane(peer: "build-mac", workspaceID: nil, parent: nil) == .fleet("build-mac")) + #expect(SidebarLaneGroup.forLane(peer: nil, workspaceID: "ws-1", parent: nil) == .workspace("ws-1")) + #expect(SidebarLaneGroup.forLane(peer: nil, workspaceID: nil, parent: "session-1") == .lineage("session-1")) + #expect(SidebarCategory.lane(peer: "build-mac", workspaceID: nil, parent: nil) == .fleetSession) + #expect(SidebarCategory.lane(peer: nil, workspaceID: "ws-1", parent: nil) == .agentSession) + } +} From 3c8cd860231e52cdf49d2d75f76ad7dc731d7561 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 13:33:47 +0000 Subject: [PATCH 02/29] Keep fleet lineage children under their live parent Agent-Session: https://cmux.com/deeplink/agent?id=aid-8cb69b83335e3c13053b --- .../RemoteMachinesSidebar.swift | 18 +++++++++++++----- .../Model/SidebarCategory.swift | 16 +++++++++++----- .../RemoteMachinesSidebarTests.swift | 13 +++++++++++-- .../SidebarCategoryTests.swift | 2 ++ 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift index 2ab18a0cad0b..ccead748e76e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift @@ -308,12 +308,20 @@ public final class RemoteMachinesSidebar { /// The groups: every peer the daemon lists (none listed yet: every peer a lane names), each /// with its live chats newest first, reachable machines first. A peer the daemon cannot reach has no chats. static func machines(lanes: some Collection, peers: [AcpmuxPeerList.Peer]?) -> [Machine] { - // Fleet sessions always enter the existing machine group keyed by peer; - // local sessions stay with their workspace/lineage projection instead of - // becoming loose rows in this feed. + // Lineage wins over machine grouping. A child whose spawnedBy parent is + // live in this daemon stays in the session tree under that parent; only + // an orphan (remote/closed parent) enters the existing machine group. + let all = Array(lanes) + let liveIDsByPeer = Dictionary(grouping: all, by: \.peer).mapValues { Set($0.map(\.id)) } var byPeer: [String: [AgentActivityLane]] = [:] - for lane in lanes { - guard case .fleet(let peer) = SidebarLaneGroup.forLane(peer: lane.peer, workspaceID: lane.workspaceID, parent: lane.parent) else { continue } + for lane in all { + guard let peer = lane.peer else { continue } + let liveIDs = liveIDsByPeer[peer] ?? [] + let lineageParent = lane.spawnedBy ?? lane.parent + if case .lineage = SidebarLaneGroup.forLane(peer: peer, workspaceID: lane.workspaceID, parent: lineageParent, + hasLiveParent: lineageParent.map(liveIDs.contains) == true) { + continue + } byPeer[peer, default: []].append(lane) } let online = Dictionary((peers ?? []).map { ($0.name, $0.connected) }, uniquingKeysWith: { first, _ in first }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift index d7381b3c97c7..3d5ce2a4ddb0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift @@ -15,6 +15,9 @@ public nonisolated enum SidebarCategory: Hashable, Sendable { case fleetMachine case fleetSession case agentSession + /// The existing local machine section is the safe home for a persisted kind + /// introduced by a newer daemon before this client learns its richer placement. + case localMachine case fold case custom case unknown @@ -29,10 +32,12 @@ public nonisolated enum SidebarCategory: Hashable, Sendable { case .app: self = .app case .room: self = .chat case .savedGroup: self = .group - // Forward-compatible references stay in their document/custom section; - // they must never become a loose top-level row merely because the App - // does not know their payload yet. - case .ref, .other: self = .custom + // A reference has a document owner, so preserve that custom placement. + case .ref: self = .custom + // A newer persisted kind may have no placement metadata at all. The + // reducer's existing fallback is this Mac's machine section; never make + // an ungrouped row for it. + case .other: self = .localMachine } } @@ -53,7 +58,8 @@ public nonisolated enum SidebarLaneGroup: Hashable, Sendable { case lineage(String) case agent - public static func forLane(peer: String?, workspaceID: String?, parent: String?) -> Self { + public static func forLane(peer: String?, workspaceID: String?, parent: String?, hasLiveParent: Bool = false) -> Self { + if hasLiveParent, let parent { return .lineage(parent) } if let peer { return .fleet(peer) } if let workspaceID { return .workspace(workspaceID) } if let parent { return .lineage(parent) } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift index 093d8e63b60d..6345fc640129 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift @@ -12,9 +12,10 @@ import Testing @MainActor struct RemoteMachinesSidebarTests { static func lane(_ name: String, peer: String?, _ state: AgentActivityLane.State = .idle, since: TimeInterval = 0, - title: String? = nil) -> AgentActivityLane { + title: String? = nil, spawnedBy: String? = nil) -> AgentActivityLane { AgentActivityLane(id: "id-" + name, name: peer.map { "\($0)/\(name)" } ?? name, title: title ?? (peer.map { "\($0)/\(name)" } ?? name), - peer: peer, parent: nil, state: state, since: Date(timeIntervalSince1970: since), error: nil, harness: "codex") + peer: peer, parent: nil, state: state, since: Date(timeIntervalSince1970: since), error: nil, harness: "codex", + spawnedBy: spawnedBy) } static func rows(_ machines: [RemoteMachinesSidebar.Machine], expanded: Set = [], pages: [String: Int] = [:]) -> [SidebarTransientItem] { @@ -28,6 +29,14 @@ struct RemoteMachinesSidebarTests { #expect(machines.allSatisfy { $0.online && $0.chats.count == 1 }) } + @Test func liveFleetLineageChildStaysWithItsParent() { + let parent = Self.lane("parent", peer: "build-mac") + let child = Self.lane("child", peer: "build-mac", spawnedBy: parent.id) + let machines = RemoteMachinesSidebar.machines(lanes: [parent, child], peers: nil) + #expect(machines.count == 1) + #expect(machines[0].chats.map(\.id) == [parent.id]) + } + @Test func newestStateChangeFirstAndTitlesDropThePeerPrefix() { let machine = RemoteMachinesSidebar.machines(lanes: [Self.lane("old", peer: "cmux16", since: 10), Self.lane("new", peer: "cmux16", .working, since: 20, title: "Fix the rail")], diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift index e328fe0974f1..687f53f91750 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift @@ -19,10 +19,12 @@ struct SidebarCategoryTests { .other("future") ] #expect(bodies.allSatisfy { SidebarCategory(body: $0).isCategorized }) + #expect(SidebarCategory(body: .other("future")) == .localMachine) } @Test func lanesUseExistingGroupingDestinations() { #expect(SidebarLaneGroup.forLane(peer: "build-mac", workspaceID: nil, parent: nil) == .fleet("build-mac")) + #expect(SidebarLaneGroup.forLane(peer: "build-mac", workspaceID: nil, parent: "parent", hasLiveParent: true) == .lineage("parent")) #expect(SidebarLaneGroup.forLane(peer: nil, workspaceID: "ws-1", parent: nil) == .workspace("ws-1")) #expect(SidebarLaneGroup.forLane(peer: nil, workspaceID: nil, parent: "session-1") == .lineage("session-1")) #expect(SidebarCategory.lane(peer: "build-mac", workspaceID: nil, parent: nil) == .fleetSession) From 449f1478be292001a5af74aafa71419869101ec0 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 14:39:57 +0000 Subject: [PATCH 03/29] Group visible session workspaces by host without dropping lineage children Sidebar-Look: i feel like there's still a big mess of uncategorized stuff in the sidebar Agent-Session: https://cmux.com/deeplink/agent?id=aid-c392704fa555cb00e9da --- .../RemoteMachinesSidebar.swift | 13 +- .../SidebarSessionTreeFeed.swift | 6 + .../Logic/RustSidebarRow.swift | 6 +- .../Logic/SidebarEmptyArea.swift | 2 +- .../Logic/SidebarLayout+SessionHosts.swift | 110 +++++++++++++ .../Logic/SidebarLayout+Viewport.swift | 2 +- .../CmuxNextSidebar/Logic/SidebarLayout.swift | 8 +- .../CmuxNextSidebar/Logic/SidebarRow.swift | 2 + .../Model/SidebarCategory.swift | 38 +---- .../Model/SidebarSessionTree.swift | 28 +++- .../Store/SidebarDocDrag.swift | 2 +- .../Views/SidebarInlineRename.swift | 4 +- .../Views/SidebarListView+ContextMenu.swift | 2 +- .../Views/SidebarListView+Drag.swift | 2 +- .../Views/SidebarListView+Layout.swift | 2 + .../Views/SidebarListView+Mouse.swift | 4 +- .../Views/SidebarRowViewPool.swift | 2 +- .../Views/StatusHeaderRowView.swift | 18 ++- .../RemoteMachinesSidebarTests.swift | 13 +- .../SidebarCategoryTests.swift | 63 +++++--- .../SidebarSessionHostTests.swift | 144 ++++++++++++++++++ plans/cmux-next/sidebar-owner.md | 6 + 22 files changed, 384 insertions(+), 93 deletions(-) create mode 100644 Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift create mode 100644 Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift index ccead748e76e..f4b844e81172 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/RemoteMachinesSidebar.swift @@ -308,20 +308,9 @@ public final class RemoteMachinesSidebar { /// The groups: every peer the daemon lists (none listed yet: every peer a lane names), each /// with its live chats newest first, reachable machines first. A peer the daemon cannot reach has no chats. static func machines(lanes: some Collection, peers: [AcpmuxPeerList.Peer]?) -> [Machine] { - // Lineage wins over machine grouping. A child whose spawnedBy parent is - // live in this daemon stays in the session tree under that parent; only - // an orphan (remote/closed parent) enters the existing machine group. - let all = Array(lanes) - let liveIDsByPeer = Dictionary(grouping: all, by: \.peer).mapValues { Set($0.map(\.id)) } var byPeer: [String: [AgentActivityLane]] = [:] - for lane in all { + for lane in lanes { guard let peer = lane.peer else { continue } - let liveIDs = liveIDsByPeer[peer] ?? [] - let lineageParent = lane.spawnedBy ?? lane.parent - if case .lineage = SidebarLaneGroup.forLane(peer: peer, workspaceID: lane.workspaceID, parent: lineageParent, - hasLiveParent: lineageParent.map(liveIDs.contains) == true) { - continue - } byPeer[peer, default: []].append(lane) } let online = Dictionary((peers ?? []).map { ($0.name, $0.connected) }, uniquingKeysWith: { first, _ in first }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift index 6952c962dc9b..8204db5cf120 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift @@ -149,6 +149,12 @@ public final class SidebarSessionTreeFeed { return nil } var state = SidebarSessionTreeState() + for (id, refs) in chats { + guard let ref = refs.first(where: { $0.session != nil }) else { continue } + let host = keys(ref.host).min() ?? ref.host + state.hosts[id] = host + state.hostNames[host] = state.hostNames[host] ?? ref.hostName ?? ref.host + } var agentStates: [SidebarWorkspaceID: SidebarAgentState] = [:] var asks: Set = [] for (id, refs) in remote { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift index 5361e764e363..9ed8793eabb8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift @@ -28,6 +28,10 @@ nonisolated struct RustRowKey: Codable { kind = "folder" id = nil section = RustSectionID(value) + case let .sessionHost(host): + kind = "session_host" + id = host + section = nil case let .status(status): // Never sent either: Group by Status's headers are labels and fold controls only. kind = "status" @@ -124,7 +128,7 @@ nonisolated struct RustRow: Codable { case .item: if let group = row.group?.rawValue { itemTops[group] = max(itemTops[group] ?? -.infinity, Double(row.y)) } continue - case .folder, .status, .emptyGroup: + case .folder, .sessionHost, .status, .emptyGroup: continue default: if case .custom = row.section { continue } // the older resolver knows Pinned and machines only diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEmptyArea.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEmptyArea.swift index 45cf3ba23cb8..50ab4ecfa13b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEmptyArea.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEmptyArea.swift @@ -40,7 +40,7 @@ extension SidebarLayout { switch row.key { case .workspace, .doneFold, .showMore, .emptyGroup: row.group case .group(let group): row.isCollapsed ? nil : group - case .section, .emptySection, .folder, .status, .item, .block: nil + case .section, .emptySection, .folder, .sessionHost, .status, .item, .block: nil } } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift new file mode 100644 index 000000000000..4343086a804c --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -0,0 +1,110 @@ +import Foundation + +nonisolated extension SidebarLayout { + /// Group only existing loose agent workspaces. The window's drawn rows decide whether a + /// lineage parent is live, never the daemon's lane census. Retain each row's document section + /// and sibling index so selection, close and drop continue to target the original workspace. + func groupingSessions(_ tree: SidebarSessionTreeState, sections: [SidebarSection], metrics m: SidebarLayoutMetrics) -> SidebarLayout { + var bundles: [Int: [SidebarRow]] = [:] + var starts: [Int] = [] + var tabRows: Set = [] + for (i, row) in rows.enumerated() { + guard case let .workspace(id) = row.key else { continue } + starts.append(i) + var bundle = [row] + var next = i + 1 + while next < rows.count, case let .tab(workspace, _) = rows[next].key, workspace == id { + bundle.append(rows[next]) + tabRows.insert(next) + next += 1 + } + bundles[i] = bundle + } + let ids: [WorkspaceID?] = starts.map { if case let .workspace(id) = rows[$0].key { id } else { nil } } + // A visible parent inside an explicit user group is still a lineage anchor. Only + // loose children move; explicitly placed members keep the user's document order. + let looseIDs = Set(starts.compactMap { i -> WorkspaceID? in + guard rows[i].group == nil, case let .workspace(id) = rows[i].key else { return nil } + return id + }) + let parents = tree.parents.filter { looseIDs.contains($0.key) } + let children = Self.treeChildren(ids, parents: parents) + let nested = Set(children.values.joined()) + let roots = ids.indices.filter { !nested.contains($0) } + var hosts: [String: [Int]] = [:] + var rootHosts: [Int: String] = [:] + for root in roots { + guard rows[starts[root]].group == nil, let id = ids[root], let host = tree.hosts[id], + case .machine = rows[starts[root]].section else { continue } + rootHosts[root] = host + hosts[host, default: []].append(root) + } + let workspaceByID = Dictionary(sections.flatMap(\.workspaces).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + func agentState(_ index: Int) -> SidebarAgentState { + guard let id = ids[index], let ws = workspaceByID[id] else { return .idle } + return SidebarAgentState.of(ws, lane: tree.states[id]) + } + // Reordering only the workspace bundles leaves user groups, document items and section + // blocks in their existing order. Each host is emitted at its first root's old position. + var emitted: Set = [] + let byStart = Dictionary(starts.enumerated().map { ($0.element, $0.offset) }, uniquingKeysWith: { first, _ in first }) + var result: [SidebarRow] = [] + var y = rows.first?.y ?? m.topPadding + func append(_ original: SidebarRow, spacing: CGFloat = 0) { + var row = original + row.y = y + result.append(row) + y += row.height + spacing + } + func family(_ root: Int, depth: Int, groupDepth: Int = 0) { + guard let id = ids[root], var bundle = bundles[starts[root]], !bundle.isEmpty else { return } + let (fold, rollUp) = Self.treeFold(root, ids, tree: tree, children: children, states: agentState) + bundle[0].content?.treeDepth = depth + if bundle[0].group == nil || fold != nil { + bundle[0].content?.treeFold = fold + bundle[0].content?.rollUp = rollUp + } + for var row in bundle { + row.depth = max(row.depth, groupDepth) + append(row, spacing: m.rowSpacing) + } + guard !tree.collapsed.contains(id) else { return } + for child in children[id] ?? [] { + family(child, depth: depth + 1, groupDepth: max(groupDepth, bundle[0].depth)) + } + } + for (index, row) in rows.enumerated() { + if tabRows.contains(index) { continue } + guard let root = byStart[index] else { + let gap = index + 1 < rows.count ? rows[index + 1].y - row.maxY : 0 + append(row, spacing: max(0, gap)) + continue + } + guard !nested.contains(root) else { continue } + guard let host = rootHosts[root] else { + family(root, depth: row.content?.treeDepth ?? 0) + continue + } + guard emitted.insert(host).inserted else { continue } + let members = hosts[host] ?? [] + let count = members.reduce(0) { total, member in + total + 1 + (ids[member].map { Self.treeDescendants(of: $0, ids, children: children).count } ?? 0) + } + let collapsed = tree.collapsedHosts.contains(host) + append(SidebarRow(key: .sessionHost(host), y: y, height: m.groupHeaderHeight, section: row.section, + group: nil, siblingIndex: row.siblingIndex, parentIndex: nil, isLastInGroup: false, + isCollapsed: collapsed, childCount: count, groupColor: nil), spacing: m.rowSpacing) + if !collapsed { for member in members { family(member, depth: 1) } } + } + let oldEnd = rows.last?.maxY ?? m.topPadding + // The final workspace bundle already added row spacing; preserve the normal bottom padding. + let newEnd = result.last?.maxY ?? m.topPadding + let shift = newEnd - oldEnd + var layout = SidebarLayout(rows: result, totalHeight: totalHeight + shift, + gapY: gapY, gapHeight: gapHeight, gapShift: gapShift) + layout.rowSpacing = rowSpacing + layout.pinnedChatsY = pinnedChatsY + layout.earlierChatsY = earlierChatsY.map { $0 + shift } + return layout + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+Viewport.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+Viewport.swift index 00cb30960441..7b19f1709c33 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+Viewport.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+Viewport.swift @@ -54,7 +54,7 @@ private extension SidebarRowKey { /// A row that only titles the rows below it. var isRevealHeader: Bool { switch self { - case .section, .group, .folder, .status: true + case .section, .group, .folder, .sessionHost, .status: true default: false } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift index 6f88f70187d9..7a33b10c281c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift @@ -144,6 +144,9 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { var y = m.topPadding var gapY: CGFloat? let filtering = o.filterMatches != nil + // User-chosen folder/status views and drag targets keep their own layout. + let groupsSessions = o.sessionTree?.hosts.isEmpty == false && !filtering + && !o.grouping.byStatus && !o.groupsByFolder && !o.showEmptyPinned && o.gap == nil // One machine needs no machine header: its name adds nothing. let machineCount = SidebarSection.machineCount(sections) // One list (cx-mdo0, Lawrence 2026-10-10: "just have linear list of @@ -443,7 +446,7 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { let byFolder = o.groupsByFolder && section.machine != nil && machineCount == 1 && !filtering guard byFolder else { let fold = SidebarDoneFoldID(section: section.id, group: nil) - let tree = Self.treeRows(nodes.map { $0.node }, tree: o.sessionTree, filtering: filtering) + let tree = Self.treeRows(nodes.map { $0.node }, tree: groupsSessions ? nil : o.sessionTree, filtering: filtering) let treeRow = Dictionary(tree.map { ($0.index, $0) }, uniquingKeysWith: { first, _ in first }) let drawn = Self.foldingDone(tree.map { ($0.index, $0.depth) }, workspace: { if case let .workspace(ws) = nodes[$0].node { ws } else { nil } }, fold: fold, @@ -482,6 +485,9 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { ) layout.rowSpacing = m.rowSpacing (layout.pinnedChatsY, layout.earlierChatsY) = (chats.pinnedY, chats.earlierY) + if groupsSessions, let tree = o.sessionTree { + return layout.groupingSessions(tree, sections: sections, metrics: m) + } return layout } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift index 83cde60402a4..1fa5c9f49b21 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift @@ -16,6 +16,8 @@ public nonisolated enum SidebarRowKey: Hashable, Sendable { case folder(SectionID, String) /// Group by Status's header over one status section's rows (`SidebarLayout+Status`). case status(SidebarStatusSection) + /// Ephemeral machine bucket in the enabled session tree; not a document or drop target. + case sessionHost(String) /// A document item listed as a row (`SidebarNode.item`): its item id. case item(String) /// A document section's items in its own arrangement (tiles, a grid, a diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift index 3d5ce2a4ddb0..7060a4a67c8d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift @@ -3,8 +3,8 @@ import Foundation /// The home for every kind of thing that can reach the sidebar. /// /// This is deliberately a taxonomy, not a new section or a default toggle. Existing -/// projections decide whether a category is visible; this type makes it impossible to -/// silently send a new item to an ungrouped bucket. +/// projections decide placement and visibility. The exhaustive switch (no default) is the +/// compile-time gate: adding a SidebarDocBody case requires an explicit category here. public nonisolated enum SidebarCategory: Hashable, Sendable { case home case workspace @@ -15,12 +15,11 @@ public nonisolated enum SidebarCategory: Hashable, Sendable { case fleetMachine case fleetSession case agentSession - /// The existing local machine section is the safe home for a persisted kind - /// introduced by a newer daemon before this client learns its richer placement. + /// The local machine category for an unfamiliar body. Persisted document items must + /// still carry a section; this taxonomy never overrides their stored placement. case localMachine case fold case custom - case unknown /// Every persisted sidebar document body has an explicit home. public init(body: SidebarDocBody) { @@ -34,36 +33,15 @@ public nonisolated enum SidebarCategory: Hashable, Sendable { case .savedGroup: self = .group // A reference has a document owner, so preserve that custom placement. case .ref: self = .custom - // A newer persisted kind may have no placement metadata at all. The - // reducer's existing fallback is this Mac's machine section; never make - // an ungrouped row for it. + // Unknown bodies use the local category, while the document's required + // section continues to control their actual placement. case .other: self = .localMachine } } /// The existing destination for an acpmux lane. No new default surface is enabled. - public static func lane(peer: String?, workspaceID: String?, parent: String?) -> Self { - if peer != nil { return .fleetSession } - if parent != nil || workspaceID != nil { return .agentSession } - return .agentSession - } - - public var isCategorized: Bool { self != .unknown } -} - -/// Stable group keys used by existing machine, workspace and lineage projections. -public nonisolated enum SidebarLaneGroup: Hashable, Sendable { - case fleet(String) - case workspace(String) - case lineage(String) - case agent - - public static func forLane(peer: String?, workspaceID: String?, parent: String?, hasLiveParent: Bool = false) -> Self { - if hasLiveParent, let parent { return .lineage(parent) } - if let peer { return .fleet(peer) } - if let workspaceID { return .workspace(workspaceID) } - if let parent { return .lineage(parent) } - return .agent + public static func lane(peer: String?) -> Self { + peer == nil ? .agentSession : .fleetSession } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift index ff96216ba2d8..a08118841b73 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift @@ -115,6 +115,10 @@ public nonisolated struct SidebarPullRequestItem: Hashable, Sendable, Codable { public nonisolated struct SidebarSessionTreeState: Hashable, Sendable { /// A child workspace to the workspace whose session started it. public var parents: [WorkspaceID: WorkspaceID] + /// Existing agent-tab hosts, used only by the enabled session tree's machine groups. + public var hosts: [WorkspaceID: String] = [:] + public var hostNames: [String: String] = [:] + public var collapsedHosts: Set = [] public var pullRequests: [WorkspaceID: SidebarPullRequestBadge] /// What each workspace's agents are doing, as acpmux decided it (the lanes); a workspace /// without a lane is read from its own row (`SidebarAgentState.of`). @@ -143,7 +147,13 @@ public nonisolated struct SidebarSessionTreeState: Hashable, Sendable { } /// What the order and the Command-numbers need: the parents and the folds. - public var shape: SidebarSessionTreeState { SidebarSessionTreeState(parents: parents, collapsed: collapsed) } + public var shape: SidebarSessionTreeState { + var shape = SidebarSessionTreeState(parents: parents, collapsed: collapsed) + shape.hosts = hosts + shape.hostNames = hostNames + shape.collapsedHosts = collapsedHosts + return shape + } } /// The session tree's live state; nil while `sidebar.sessionTree` is off, so the list draws as @@ -157,11 +167,13 @@ public final class SidebarSessionTree { public var pullRequests: [WorkspaceID: SidebarPullRequestBadge] = [:] /// The parents the user folded (a chevron on the row), kept across launches. public private(set) var collapsed: Set + public private(set) var collapsedHosts: Set @ObservationIgnored private let defaults: UserDefaults public init(defaults: UserDefaults = .standard) { self.defaults = defaults collapsed = Set((defaults.stringArray(forKey: Self.collapsedKey) ?? []).map(WorkspaceID.init)) + collapsedHosts = Set(defaults.stringArray(forKey: Self.collapsedHostsKey) ?? []) } /// What the list draws: the live state with the user's folds; nil while the tree is off. @@ -169,10 +181,16 @@ public final class SidebarSessionTree { state.map { live in var drawn = live drawn.collapsed = collapsed + drawn.collapsedHosts = collapsedHosts return drawn } } + public func toggleHost(_ host: String) { + if collapsedHosts.remove(host) == nil { collapsedHosts.insert(host) } + defaults.set(collapsedHosts.sorted(), forKey: Self.collapsedHostsKey) + } + /// Folds or opens the subtree under `id`. public func toggle(_ id: WorkspaceID) { if collapsed.remove(id) == nil { collapsed.insert(id) } @@ -187,6 +205,13 @@ public final class SidebarSessionTree { opened.remove(parent) current = parent } + // A recorded ancestor may be in another window. Open every host on the path: + // this window may draw the child as a root under its own host instead. + let openedHosts = collapsedHosts.subtracting(seen.compactMap { state?.hosts[$0] }) + if openedHosts != collapsedHosts { + collapsedHosts = openedHosts + defaults.set(collapsedHosts.sorted(), forKey: Self.collapsedHostsKey) + } guard opened != collapsed else { return } collapsed = opened save(pruning: false) @@ -206,4 +231,5 @@ public final class SidebarSessionTree { } static let collapsedKey = "sidebar.sessionTree.collapsed" + static let collapsedHostsKey = "sidebar.sessionTree.collapsedHosts" } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift index 434f574ebc5d..88606ff2fead 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift @@ -96,7 +96,7 @@ public struct SidebarDocDrag { case .block(let id): // A block's items: tiles and rows of its own arrangement, at their base frames. if let block = blocks[id] { slots += blockSlots(block, at: row.y) } - case .folder, .status, .doneFold, .showMore: + case .folder, .sessionHost, .status, .doneFold, .showMore: continue } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift index 5e35603ad8cc..bf9b75666b35 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift @@ -62,7 +62,7 @@ final class SidebarInlineRename: NSObject, NSTextFieldDelegate { switch key { case let .workspace(id): original = list.workspaces[id]?.title ?? "" case let .group(id): original = list.groups[id]?.name ?? "" - case .section, .emptySection, .emptyGroup, .folder, .item, .block, .doneFold, .showMore, .status: return + case .section, .emptySection, .emptyGroup, .folder, .item, .block, .doneFold, .showMore, .sessionHost, .status: return } if let row = list.displayed.row(for: key) { list.scrollToVisible(list.frame(for: row)) } list.realizeVisibleRows() @@ -150,7 +150,7 @@ final class SidebarInlineRename: NSObject, NSTextFieldDelegate { switch session.key { case let .workspace(id): list.model.send(.rename(id, text)) case let .group(id): list.model.send(.renameGroup(id, text)) - case .section, .emptySection, .emptyGroup, .folder, .item, .block, .doneFold, .showMore, .status: break + case .section, .emptySection, .emptyGroup, .folder, .item, .block, .doneFold, .showMore, .sessionHost, .status: break } list.reload(animated: false) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift index b066674f211c..4624c7ff1dc7 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift @@ -24,7 +24,7 @@ extension SidebarListViewComponents { target = fold.group.map(SidebarContextTarget.group) ?? .section(fold.section) case let .item(item)?: target = .layoutItem(LayoutItemID(item)) - case .block?, .status?: + case .block?, .status?, .sessionHost?: target = .background case nil: target = .background diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift index 494c6944b3ac..05c7f095ffe5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift @@ -59,7 +59,7 @@ extension SidebarListViewComponents { payload = .item(item) hidden = [press.key] origin = .position(DropPosition(section: row.section, group: row.group, index: row.siblingIndex)) // a group's member item: inside it - case .section, .emptySection, .emptyGroup, .folder, .block, .doneFold, .showMore, .status: + case .section, .emptySection, .emptyGroup, .folder, .block, .doneFold, .showMore, .sessionHost, .status: return } // A group lifts as one block: its header and the member rows under it (cx-bp40). diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift index 74509ef51f84..eac684c40e70 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift @@ -416,6 +416,8 @@ extension SidebarListViewComponents { case let (.emptyGroup(id), view as EmptyGroupRowView): view.configure(groupID: id, groupName: groups[id]?.name ?? model.group(id)?.name ?? "") case let (.folder(_, folder), view as FolderHeaderRowView): view.configure(folder: folder) case let (.status, view as StatusHeaderRowView): view.configure(row) + case let (.sessionHost(host), view as StatusHeaderRowView): + view.configure(row, title: SidebarSessionTree.shared.state?.hostNames[host] ?? host) case (.doneFold, let view as SidebarDoneFoldRowView), (.showMore, let view as SidebarDoneFoldRowView): view.isKeyboardFocused = showsFocusRing && focusedFold == row.key view.configure(row) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift index 84bb63eeb845..37e9c0057e37 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift @@ -90,7 +90,7 @@ extension SidebarListViewComponents { // Keyboard focus moves to the clicked disclosure (no ring), so a ring left on another one cannot take // the next Space or Return; the release toggles it. SidebarGroupKeys(list: self).focusFold(row.key, ring: false) - case .section, .emptySection, .emptyGroup, .folder, .block, .status: + case .section, .emptySection, .emptyGroup, .folder, .block, .sessionHost, .status: break } self.press = press @@ -163,6 +163,8 @@ extension SidebarListViewComponents { model.send(.activateItem(LayoutItemID(item), opensWorkspace: event.modifierFlags.contains(.option))) case let .status(section): model.toggleStatusSection(section) + case let .sessionHost(host): + SidebarSessionTree.shared.toggleHost(host) case .doneFold, .showMore: _ = SidebarFoldAction(list: self).toggle(press.key) return diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift index 8e892b22e39f..00d185fafb46 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift @@ -66,7 +66,7 @@ struct SidebarRowViewPool { case .emptySection: EmptySectionRowView.self case .emptyGroup: EmptyGroupRowView.self case .folder: FolderHeaderRowView.self - case .status: StatusHeaderRowView.self + case .status, .sessionHost: StatusHeaderRowView.self case .doneFold, .showMore: SidebarDoneFoldRowView.self } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/StatusHeaderRowView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/StatusHeaderRowView.swift index c562f174c7a6..5d9f498f5ea8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/StatusHeaderRowView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/StatusHeaderRowView.swift @@ -19,19 +19,29 @@ final class StatusHeaderRowView: SidebarRowView { func configure(_ row: SidebarRow) { guard case let .status(section) = row.key else { return } - name.setString(Strings.statusSection(section)) + configure(row, title: Strings.statusSection(section), collapses: section.collapses) + } + + func configure(_ row: SidebarRow, title: String, collapses: Bool = true) { + name.setString(title) count.setString("\(row.childCount)") name.setFont(SidebarStyle.headerFont) count.setFont(SidebarStyle.headerFont) - chevron.isHidden = !section.collapses + chevron.isHidden = !collapses chevron.image = SidebarStyle.chevron(collapsed: row.isCollapsed) setAccessibilityElement(true) - setAccessibilityRole(section.collapses ? .disclosureTriangle : .staticText) + setAccessibilityRole(collapses ? .disclosureTriangle : .staticText) setAccessibilityLabel("\(name.stringValue), \(Strings.groupCount(row.childCount))") - if section.collapses { setAccessibilityExpanded(!row.isCollapsed) } + if collapses { setAccessibilityExpanded(!row.isCollapsed) } needsLayout = true } + override func accessibilityPerformPress() -> Bool { + guard case let .sessionHost(host) = key else { return super.accessibilityPerformPress() } + SidebarSessionTree.shared.toggleHost(host) + return true + } + override func layout() { super.layout() let b = layoutBounds diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift index 6345fc640129..093d8e63b60d 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/RemoteMachinesSidebarTests.swift @@ -12,10 +12,9 @@ import Testing @MainActor struct RemoteMachinesSidebarTests { static func lane(_ name: String, peer: String?, _ state: AgentActivityLane.State = .idle, since: TimeInterval = 0, - title: String? = nil, spawnedBy: String? = nil) -> AgentActivityLane { + title: String? = nil) -> AgentActivityLane { AgentActivityLane(id: "id-" + name, name: peer.map { "\($0)/\(name)" } ?? name, title: title ?? (peer.map { "\($0)/\(name)" } ?? name), - peer: peer, parent: nil, state: state, since: Date(timeIntervalSince1970: since), error: nil, harness: "codex", - spawnedBy: spawnedBy) + peer: peer, parent: nil, state: state, since: Date(timeIntervalSince1970: since), error: nil, harness: "codex") } static func rows(_ machines: [RemoteMachinesSidebar.Machine], expanded: Set = [], pages: [String: Int] = [:]) -> [SidebarTransientItem] { @@ -29,14 +28,6 @@ struct RemoteMachinesSidebarTests { #expect(machines.allSatisfy { $0.online && $0.chats.count == 1 }) } - @Test func liveFleetLineageChildStaysWithItsParent() { - let parent = Self.lane("parent", peer: "build-mac") - let child = Self.lane("child", peer: "build-mac", spawnedBy: parent.id) - let machines = RemoteMachinesSidebar.machines(lanes: [parent, child], peers: nil) - #expect(machines.count == 1) - #expect(machines[0].chats.map(\.id) == [parent.id]) - } - @Test func newestStateChangeFirstAndTitlesDropThePeerPrefix() { let machine = RemoteMachinesSidebar.machines(lanes: [Self.lane("old", peer: "cmux16", since: 10), Self.lane("new", peer: "cmux16", .working, since: 20, title: "Fix the rail")], diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift index 687f53f91750..ef799edb6b57 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift @@ -1,33 +1,48 @@ @testable import CmuxNextSidebar import Testing +import Foundation -/// Every sidebar input has a home. The taxonomy is an audit of existing destinations; -/// it does not turn on a new section or change defaults. struct SidebarCategoryTests { - @Test func everyPersistedItemTypeHasACategory() { - let bodies: [SidebarDocBody] = [ - .workspace(.init(sessionID: "local", workspaceID: "ws")), - .group(name: "Project", color: nil, icon: nil, collapsed: false), - .builtin(SidebarBuiltIn.home.rawValue), - .builtin(SidebarBuiltIn.settings.rawValue), - .app("com.example.app"), - .url("https://example.com", title: "Example"), - .tab("tab-1"), - .room("room-1"), - .savedGroup("saved"), - .ref(kind: "future", value: "item"), - .other("future") + // The no-default switch in SidebarCategory.init is the exhaustiveness gate. This table + // checks each semantic assignment, including the compatibility category for unfamiliar bodies. + @Test func persistedKindsHaveTheirExpectedCategory() { + let cases: [(SidebarDocBody, SidebarCategory)] = [ + (.workspace(.init(sessionID: "local", workspaceID: "ws")), .workspace), + (.group(name: "Project", color: nil, icon: nil, collapsed: false), .group), + (.builtin(SidebarBuiltIn.home.rawValue), .home), + (.builtin(SidebarBuiltIn.settings.rawValue), .app), + (.app("com.example.app"), .app), (.url("https://example.com", title: nil), .browserTab), + (.tab("tab-1"), .browserTab), (.room("room-1"), .chat), (.savedGroup("saved"), .group), + (.ref(kind: "custom", value: "item"), .custom), (.other("future"), .localMachine), ] - #expect(bodies.allSatisfy { SidebarCategory(body: $0).isCategorized }) - #expect(SidebarCategory(body: .other("future")) == .localMachine) + for (body, category) in cases { #expect(SidebarCategory(body: body) == category) } + #expect(SidebarCategory.lane(peer: "remote") == .fleetSession) + #expect(SidebarCategory.lane(peer: nil) == .agentSession) } - @Test func lanesUseExistingGroupingDestinations() { - #expect(SidebarLaneGroup.forLane(peer: "build-mac", workspaceID: nil, parent: nil) == .fleet("build-mac")) - #expect(SidebarLaneGroup.forLane(peer: "build-mac", workspaceID: nil, parent: "parent", hasLiveParent: true) == .lineage("parent")) - #expect(SidebarLaneGroup.forLane(peer: nil, workspaceID: "ws-1", parent: nil) == .workspace("ws-1")) - #expect(SidebarLaneGroup.forLane(peer: nil, workspaceID: nil, parent: "session-1") == .lineage("session-1")) - #expect(SidebarCategory.lane(peer: "build-mac", workspaceID: nil, parent: nil) == .fleetSession) - #expect(SidebarCategory.lane(peer: nil, workspaceID: "ws-1", parent: nil) == .agentSession) + @Test func unfamiliarBodyPreservesLocalAndCustomPlacement() { + let local = SidebarDocSection(id: "sec_m_local", kind: .machine(session: "local")) + let custom = SidebarDocSection(id: "custom", kind: .custom) + let items = [SidebarDocItem(id: "local-item", section: local.id, body: .other("future")), + SidebarDocItem(id: "custom-item", section: custom.id, body: .other("future"))] + let rows = items.map { SidebarDocRow(key: $0.id, kind: "future", section: $0.section, + depth: 0, item: $0.id) } + let records = SidebarDocRecords(revision: 1, sections: [local.id: local, custom.id: custom], + items: Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })) + let projection = SidebarDocProjection(rows: rows, records: records, revision: 1) + #expect(projection.machines["local"]?.count == 1) + if case let .link(item)? = projection.machines["local"]?.first { + #expect(item.id == "local-item") + } else { Issue.record("the existing local section must retain the unfamiliar item") } + #expect(projection.layout.sections.first { $0.id == LayoutSectionID(custom.id) }?.items.map(\.id) + == [LayoutItemID("custom-item")]) } + + @Test func persistedItemRequiresExplicitPlacement() { + let missingSection = Data(#"{"id":"future-item","body":{"type":"future"}}"#.utf8) + #expect(throws: (any Error).self) { + try JSONDecoder().decode(SidebarDocWire.Item.self, from: missingSection) + } + } + } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift new file mode 100644 index 000000000000..d9aea42c324c --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -0,0 +1,144 @@ +import AppKit +@testable import CmuxNextAgentLanes +import CmuxNextDaemon +@testable import CmuxNextSidebar +import Testing + +@MainActor struct SidebarSessionHostTests { + private static let parent = WorkspaceID("parent"), child = WorkspaceID("child"), other = WorkspaceID("other") + private static let host = "registry:build" + + private static func state(crossHost: Bool = false) -> SidebarSessionTreeState { + let childHost = crossHost ? "registry:other" : host + let chats = [(parent, [AgentSessionRef(host: host, hostName: "Build Mac", session: "coordinator")]), + (child, [AgentSessionRef(host: childHost, hostName: "Child Mac", session: "worker")])] + let parents = [AgentSessionParents.identity(host: childHost, session: "worker"): + AgentSessionParents.identity(host: host, session: "coordinator")] + return SidebarSessionTreeFeed.pass(chats, lanes: [:], recordedParents: parents, + localHost: "install:local", pullRequests: [:]).state + } + + private static func sections(parentPresent: Bool = true, crossMachine: Bool = false) -> [SidebarSection] { + let parentRow = SidebarWorkspace(id: parent, title: "Coordinator") + let childRow = SidebarWorkspace(id: child, title: "Worker") + let unrelated = SidebarWorkspace(id: other, title: "Shell") + let local = SidebarMachine(id: .local, name: "This Mac", kind: .local) + if crossMachine { + let remote = SidebarMachine(id: MachineID("remote"), name: "Remote", kind: .ssh) + return [SidebarSection(kind: .machine(local), nodes: parentPresent ? [.workspace(parentRow), .workspace(unrelated)] : [.workspace(unrelated)]), + SidebarSection(kind: .machine(remote), nodes: [.workspace(childRow)])] + } + return [SidebarSection(kind: .machine(local), nodes: + (parentPresent ? [.workspace(parentRow)] : []) + [.workspace(unrelated), .workspace(childRow)])] + } + + private static func layout(_ state: SidebarSessionTreeState?, parentPresent: Bool = true, crossMachine: Bool = false) -> SidebarLayout { + var options = SidebarLayoutOptions() + options.flattensMachines = true + options.sessionTree = state + return SidebarLayout.make(sections: sections(parentPresent: parentPresent, crossMachine: crossMachine), metrics: .standard, options: options) + } + + @Test func liveChildAppearsOnceUnderParentAndCountsInHostBadge() throws { + let layout = Self.layout(Self.state()) + let workspaces = layout.rows.compactMap { row -> WorkspaceID? in + if case let .workspace(id) = row.key { id } else { nil } + } + #expect(workspaces == [Self.parent, Self.child, Self.other]) + #expect(layout.row(for: .workspace(Self.parent))?.content?.treeDepth == 1) + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 2) + #expect(layout.row(for: .workspace(Self.parent))?.content?.treeFold == .expanded) + #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 2) + let child = try #require(layout.row(for: .workspace(Self.child))) + #expect(child.section == .machine(.local)) + #expect(child.siblingIndex == 2, "grouping must preserve document drop/selection identity") + } + + @Test func closedOrOtherWindowParentLeavesChildAtMachineLevel() { + let layout = Self.layout(Self.state(), parentPresent: false) + #expect(layout.row(for: .workspace(Self.parent)) == nil) + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 1) + #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 1) + #expect(layout.rows.filter { $0.key == .workspace(Self.child) }.count == 1) + } + + @Test func crossMachineChildFollowsItsLiveParentInsteadOfGettingASecondGroup() { + let layout = Self.layout(Self.state(crossHost: true), crossMachine: true) + let keys = layout.rows.map(\.key) + #expect(keys == [.sessionHost(Self.host), .workspace(Self.parent), .workspace(Self.child), .workspace(Self.other)]) + #expect(layout.row(for: .workspace(Self.child))?.section == .machine(MachineID("remote"))) + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 2) + #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 2) + } + + @Test func parentAndHostFoldsKeepTheWholeBadgeCount() { + var state = Self.state() + state.collapsed = [Self.parent] + let parentFolded = Self.layout(state) + #expect(parentFolded.row(for: .workspace(Self.child)) == nil) + #expect(parentFolded.row(for: .workspace(Self.parent))?.content?.treeFold == .collapsed) + #expect(parentFolded.row(for: .sessionHost(Self.host))?.childCount == 2) + state.collapsedHosts = [Self.host] + let hostFolded = Self.layout(state) + #expect(hostFolded.rows.map(\.key) == [.sessionHost(Self.host), .workspace(Self.other)]) + #expect(hostFolded.row(for: .sessionHost(Self.host))?.childCount == 2) + } + + @Test func disabledTreeAndWorkspacesWithoutAgentRefsKeepTheirExistingRows() { + let disabled = Self.layout(nil) + #expect(disabled.rows.map(\.key) == [.workspace(Self.parent), .workspace(Self.other), .workspace(Self.child)]) + let plain = SidebarSessionTreeFeed.pass([], lanes: [:], localHost: "install:local", pullRequests: [:]).state + #expect(Self.layout(plain) == disabled) + } + + @Test func explicitUserGroupKeepsItsStoredPlacement() { + let group = SidebarGroup(id: GroupID("user-group"), name: "My project", workspaces: [SidebarWorkspace(id: Self.child, title: "Worker")]) + let section = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + nodes: [.group(group)]) + var options = SidebarLayoutOptions() + options.sessionTree = Self.state() + let layout = SidebarLayout.make(sections: [section], metrics: .standard, options: options) + #expect(layout.row(for: .workspace(Self.child))?.group == group.id) + #expect(!layout.rows.contains { if case .sessionHost = $0.key { true } else { false } }) + } + + @Test func looseChildFollowsVisibleParentInsideAnExplicitUserGroup() { + let group = SidebarGroup(id: GroupID("project"), name: "Project", + workspaces: [SidebarWorkspace(id: Self.parent, title: "Coordinator")]) + let section = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + nodes: [.group(group), .workspace(SidebarWorkspace(id: Self.child, title: "Worker"))]) + var options = SidebarLayoutOptions() + options.sessionTree = Self.state() + let layout = SidebarLayout.make(sections: [section], metrics: .standard, options: options) + #expect(layout.rows.map(\.key) == [.group(group.id), .workspace(Self.parent), .workspace(Self.child)]) + #expect(layout.row(for: .workspace(Self.parent))?.group == group.id) + #expect(layout.row(for: .workspace(Self.child))?.group == nil) + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 1) + #expect(layout.row(for: .workspace(Self.child))?.depth == 1) + } + + @Test func sessionTreeStillKeepsDoneAndLimitedRowsInsideTheCount() { + var options = SidebarLayoutOptions() + options.sessionTree = Self.state() + options.foldsDone = true + options.rowLimit = 1 + options.flattensMachines = true + let layout = SidebarLayout.make(sections: Self.sections(), metrics: .standard, options: options) + #expect(layout.rows.map(\.key) == Self.layout(Self.state()).rows.map(\.key)) + #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 2) + } + + @Test func revealingChildOpensItsRootHostsFold() throws { + let suite = "SidebarSessionHostTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let tree = SidebarSessionTree(defaults: defaults) + tree.state = Self.state(crossHost: true) + tree.toggleHost(Self.host) + tree.toggleHost("registry:other") + tree.toggle(Self.parent) + tree.reveal(Self.child) + #expect(tree.drawn?.collapsedHosts.isEmpty == true) + #expect(tree.drawn?.collapsed.isEmpty == true) + } +} diff --git a/plans/cmux-next/sidebar-owner.md b/plans/cmux-next/sidebar-owner.md index 94945de9c6c1..eadc3b2d3ce3 100644 --- a/plans/cmux-next/sidebar-owner.md +++ b/plans/cmux-next/sidebar-owner.md @@ -837,3 +837,9 @@ Commits logged without a trailer (behavior fixes, no visual change; the card kee ## Top workspace insert lands without a cascade (2026-10-31) - PR #28205, implementation `ac80839dcfa`. Leo: "when you create a workspace at the top it's a huge cascade" and it "pushes all the workspaces below down pretty hard". The proposed `sidebar.insertMotion` default is `.snap`: existing rows land at once and only the new row fades. Nudge, quick and full spring remain available. The real-sidebar gallery exercises all four variants; its PNGs show settled states. Fleet recordings and macOS validation remain follow-up validation. + + +## Session-tree host groups use the drawn workspace projection (2026-10-30) + +Leo: "i feel like there's still a big mess of uncategorized stuff in the sidebar", "i mean we dont want to be too opinionated by defgault", "im saying for my particular sidebar there's a lot of wack stuff there". The existing opt-in session tree groups its loose agent workspaces by their existing tab host, with a foldable host header and a count that includes folded descendants. A live parent in this window wins across machines; a loose child also follows a visible parent inside a user group. Explicit child group placement is retained. The real layout and shortcut order share this projection; the unbound remote-lane feed no longer filters children. No default or row title/subtitle changes. `SidebarSessionHostTests` exercises feed-to-layout lineage, parent absence, cross-machine lineage, folds, explicit groups and the disabled state. + From a6a79eec5bb1b9693f10297922c8dad13e19b050 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 15:03:35 +0000 Subject: [PATCH 04/29] Preserve sidebar placement and drag geometry in opt-in host groups Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b Sidebar-Look: i feel like there's still a big mess of uncategorized stuff in the sidebar --- .../SidebarSessionTreeFeed.swift | 5 +- .../Logic/SidebarLayout+SessionHosts.swift | 78 ++++++++-- .../CmuxNextSidebar/Logic/SidebarLayout.swift | 6 +- .../SidebarSessionHostIntegrationTests.swift | 137 +++++++++++++++++ .../SidebarSessionHostTests.swift | 138 ++++++++++++++++++ plans/cmux-next/sidebar-owner.md | 3 + 6 files changed, 348 insertions(+), 19 deletions(-) create mode 100644 Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift index 8204db5cf120..65ff9759344f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift @@ -149,8 +149,11 @@ public final class SidebarSessionTreeFeed { return nil } var state = SidebarSessionTreeState() + let localHosts: Set = localHost.map { Set(keys($0)) } ?? [] for (id, refs) in chats { - guard let ref = refs.first(where: { $0.session != nil }) else { continue } + // Local agent tabs remain in the ordinary local list. Host grouping is + // reserved for fleet sessions, excluding this install and its aliases. + guard let ref = refs.first(where: { $0.session != nil && !localHosts.contains($0.host) }) else { continue } let host = keys(ref.host).min() ?? ref.host state.hosts[id] = host state.hostNames[host] = state.hostNames[host] ?? ref.hostName ?? ref.host diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index 4343086a804c..007f2cea652e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -4,7 +4,7 @@ nonisolated extension SidebarLayout { /// Group only existing loose agent workspaces. The window's drawn rows decide whether a /// lineage parent is live, never the daemon's lane census. Retain each row's document section /// and sibling index so selection, close and drop continue to target the original workspace. - func groupingSessions(_ tree: SidebarSessionTreeState, sections: [SidebarSection], metrics m: SidebarLayoutMetrics) -> SidebarLayout { + func groupingSessions(_ tree: SidebarSessionTreeState, sections: [SidebarSection], gap: DropPosition?, metrics m: SidebarLayoutMetrics) -> SidebarLayout { var bundles: [Int: [SidebarRow]] = [:] var starts: [Int] = [] var tabRows: Set = [] @@ -24,10 +24,18 @@ nonisolated extension SidebarLayout { // A visible parent inside an explicit user group is still a lineage anchor. Only // loose children move; explicitly placed members keep the user's document order. let looseIDs = Set(starts.compactMap { i -> WorkspaceID? in - guard rows[i].group == nil, case let .workspace(id) = rows[i].key else { return nil } + guard rows[i].group == nil, case .machine = rows[i].section, + case let .workspace(id) = rows[i].key else { return nil } return id }) - let parents = tree.parents.filter { looseIDs.contains($0.key) } + let machineParents = Set(starts.compactMap { i -> WorkspaceID? in + guard case let .workspace(id) = rows[i].key, + case .machine = rows[i].section else { return nil } + return id + }) + // Preserve the Pinned/custom boundary: a fleet child of a pinned workspace + // remains in its own machine group rather than being pulled into Pinned. + let parents = tree.parents.filter { looseIDs.contains($0.key) && machineParents.contains($0.value) } let children = Self.treeChildren(ids, parents: parents) let nested = Set(children.values.joined()) let roots = ids.indices.filter { !nested.contains($0) } @@ -49,8 +57,39 @@ nonisolated extension SidebarLayout { var emitted: Set = [] let byStart = Dictionary(starts.enumerated().map { ($0.element, $0.offset) }, uniquingKeysWith: { first, _ in first }) var result: [SidebarRow] = [] - var y = rows.first?.y ?? m.topPadding + var y: CGFloat = 0 + var movedGapY: CGFloat?, movedPinnedY: CGFloat?, movedEarlierY: CGFloat? + // A drop before a workspace follows that workspace when lineage reorders it. + // Section-end drops stay in their boundary, before history or the next section. + let gapTarget: SidebarRowKey? = gapY.flatMap { oldGap in + guard let gap, let next = rows.first(where: { $0.y >= oldGap + gapShift }), + next.section == gap.section, next.group == gap.group, + case .workspace = next.key else { return nil } + return next.key + } + func openGap() { + guard gapY != nil, movedGapY == nil else { return } + movedGapY = y + y += gapShift + } + // Preserve whitespace at its original section/history boundary, not on a + // workspace that may move into an earlier family. This also maps anchors + // when the original last workspace moves or disappears into a fold. + func boundary(from start: CGFloat, to end: CGFloat) { + let containsGap = gapY.map { $0 >= start && $0 + gapShift <= end } ?? false + let removed = containsGap && gapTarget != nil ? gapShift : 0 + func mapped(_ anchor: CGFloat?) -> CGFloat? { + guard let anchor, anchor >= start, anchor <= end else { return nil } + let adjustment = containsGap && gapTarget != nil && anchor >= (gapY ?? 0) + gapShift ? gapShift : 0 + return y + anchor - start - adjustment + } + if let anchor = mapped(pinnedChatsY) { movedPinnedY = anchor } + if let anchor = mapped(earlierChatsY) { movedEarlierY = anchor } + if containsGap, gapTarget == nil, let gapY { movedGapY = y + gapY - start } + y += end - start - removed + } func append(_ original: SidebarRow, spacing: CGFloat = 0) { + if original.key == gapTarget { openGap() } var row = original row.y = y result.append(row) @@ -64,20 +103,26 @@ nonisolated extension SidebarLayout { bundle[0].content?.treeFold = fold bundle[0].content?.rollUp = rollUp } + // Workspace bundles keep their normal row spacing. Larger gaps belong + // to the following section/block and must not travel with a moved lane. for var row in bundle { row.depth = max(row.depth, groupDepth) append(row, spacing: m.rowSpacing) } - guard !tree.collapsed.contains(id) else { return } + guard !tree.collapsed.contains(id) else { + if let gapTarget, Self.treeDescendants(of: id, ids, children: children) + .contains(where: { ids[$0].map(SidebarRowKey.workspace) == gapTarget }) { openGap() } + return + } for child in children[id] ?? [] { family(child, depth: depth + 1, groupDepth: max(groupDepth, bundle[0].depth)) } } for (index, row) in rows.enumerated() { + boundary(from: index == 0 ? 0 : rows[index - 1].maxY + m.rowSpacing, to: row.y) if tabRows.contains(index) { continue } guard let root = byStart[index] else { - let gap = index + 1 < rows.count ? rows[index + 1].y - row.maxY : 0 - append(row, spacing: max(0, gap)) + append(row, spacing: m.rowSpacing) continue } guard !nested.contains(root) else { continue } @@ -95,16 +140,19 @@ nonisolated extension SidebarLayout { group: nil, siblingIndex: row.siblingIndex, parentIndex: nil, isLastInGroup: false, isCollapsed: collapsed, childCount: count, groupColor: nil), spacing: m.rowSpacing) if !collapsed { for member in members { family(member, depth: 1) } } + else if let gapTarget, members.contains(where: { member in + ids[member].map(SidebarRowKey.workspace) == gapTarget || ids[member].map { id in + Self.treeDescendants(of: id, ids, children: children) + .contains(where: { ids[$0].map(SidebarRowKey.workspace) == gapTarget }) + } == true + }) { openGap() } } - let oldEnd = rows.last?.maxY ?? m.topPadding - // The final workspace bundle already added row spacing; preserve the normal bottom padding. - let newEnd = result.last?.maxY ?? m.topPadding - let shift = newEnd - oldEnd - var layout = SidebarLayout(rows: result, totalHeight: totalHeight + shift, - gapY: gapY, gapHeight: gapHeight, gapShift: gapShift) + boundary(from: rows.last.map { $0.maxY + m.rowSpacing } ?? 0, to: totalHeight) + var layout = SidebarLayout(rows: result, totalHeight: y, + gapY: movedGapY, gapHeight: gapHeight, gapShift: gapShift) layout.rowSpacing = rowSpacing - layout.pinnedChatsY = pinnedChatsY - layout.earlierChatsY = earlierChatsY.map { $0 + shift } + layout.pinnedChatsY = movedPinnedY + layout.earlierChatsY = movedEarlierY return layout } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift index 7a33b10c281c..3e8226a54ea1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift @@ -144,9 +144,9 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { var y = m.topPadding var gapY: CGFloat? let filtering = o.filterMatches != nil - // User-chosen folder/status views and drag targets keep their own layout. + // User-chosen folder/status views keep their own layout; dragging retains host groups. let groupsSessions = o.sessionTree?.hosts.isEmpty == false && !filtering - && !o.grouping.byStatus && !o.groupsByFolder && !o.showEmptyPinned && o.gap == nil + && !o.grouping.byStatus && !o.groupsByFolder // One machine needs no machine header: its name adds nothing. let machineCount = SidebarSection.machineCount(sections) // One list (cx-mdo0, Lawrence 2026-10-10: "just have linear list of @@ -486,7 +486,7 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { layout.rowSpacing = m.rowSpacing (layout.pinnedChatsY, layout.earlierChatsY) = (chats.pinnedY, chats.earlierY) if groupsSessions, let tree = o.sessionTree { - return layout.groupingSessions(tree, sections: sections, metrics: m) + return layout.groupingSessions(tree, sections: sections, gap: o.gap, metrics: m) } return layout } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift new file mode 100644 index 000000000000..e07e7e565954 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -0,0 +1,137 @@ +import AppKit +@testable import CmuxNextAgentLanes +import CmuxNextDaemon +import CmuxNextDesign +@testable import CmuxNextSidebar +import Testing + +/// Exercise the feed-to-view boundary: pure SidebarLayout tests cannot catch a list option +/// dropping the session tree during a drag, or a default-off feed publishing it anyway. +@MainActor @Suite(.serialized, .enabled(if: !NSScreen.screens.isEmpty, "needs a GUI display host")) +struct SidebarSessionHostIntegrationTests { + private static let coordinator = WorkspaceID("host-integration-coordinator") + private static let plain = WorkspaceID("host-integration-plain") + private static let dragged = WorkspaceID("host-integration-dragged") + private static let workers = (0..<12).map { WorkspaceID("host-integration-worker-\($0)") } + private static let host = "registry:host-integration" + + private static func pass(enabled: Bool) -> SidebarSessionTreeFeed.Pass { + let refs = [(coordinator, [AgentSessionRef(host: host, hostName: "Build machine", session: "coordinator")])] + + workers.enumerated().map { index, workspace in + (workspace, [AgentSessionRef(host: host, session: "worker-\(index)")]) + } + let parents = Dictionary(uniqueKeysWithValues: workers.indices.map { ("worker-\($0)", "coordinator") }) + var pass = SidebarSessionTreeFeed.pass(refs, lanes: [:], remoteParentsByHost: [host: parents], + localHost: "install:host-integration-local", pullRequests: [:]) + pass.showsTree = enabled + return pass + } + + private static func withList(_ body: (SidebarListView) throws -> Void) rethrows { + _ = NSApplication.shared + let tree = SidebarSessionTree.shared + let savedState = tree.state + let savedBadges = tree.pullRequests + let savedHistory = SidebarChatHistory.shared.state + defer { + tree.state = savedState + tree.pullRequests = savedBadges + SidebarChatHistory.shared.state = savedHistory + } + tree.state = nil + tree.pullRequests = [:] + SidebarChatHistory.shared.state = nil + let workspace = { (id: WorkspaceID) in SidebarNode.workspace(SidebarWorkspace(id: id, title: id.rawValue)) } + let nodes = [workspace(coordinator), workspace(plain)] + workers.map(workspace) + [workspace(dragged)] + let section = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: nodes) + let model = SidebarModel(sections: [section], activeWorkspaceID: dragged) + model.showWorkspaceTabs = false + model.groupsByComputer = false + let list = SidebarListView(model: model) + let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 280, height: 1000), styleMask: [.borderless], + backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + defer { + list.cancelDrag() + if let landing = list.landing { list.finishLand(landing, then: nil) } + window.close() + } + let root = NSView(frame: NSRect(x: 0, y: 0, width: 280, height: 1000)) + window.contentView = root + list.frame = root.bounds + root.addSubview(list) + window.orderFrontRegardless() + list.reload(animated: false) + try body(list) + } + + @Test func defaultOffPublishLeavesTheProductionListFlatAndCanDisableAnEnabledTree() throws { + try Self.withList { list in + let defaults = SidebarSectionsPreferences.defaults + #expect(!defaults.sessionTree) + SidebarSessionTreeFeed.publish(Self.pass(enabled: defaults.sessionTree), to: .shared) + list.reload(animated: false) + #expect(list.options(includeGap: false).sessionTree == nil) + #expect(list.displayed.row(for: .sessionHost(Self.host)) == nil) + let originalOrder = [Self.coordinator, Self.plain] + Self.workers + [Self.dragged] + #expect(list.displayed.rows.map(\.key) == originalOrder.map(SidebarRowKey.workspace)) + + SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) + list.reload(animated: false) + let header = try #require(list.displayed.row(for: .sessionHost(Self.host))) + #expect(header.childCount == Self.workers.count + 1) + #expect(list.options(includeGap: false).sessionTree?.parents[Self.workers[0]] == Self.coordinator) + #expect(list.displayed.rows.map(\.key) == [.sessionHost(Self.host), .workspace(Self.coordinator)] + + Self.workers.map(SidebarRowKey.workspace) + [.workspace(Self.plain), .workspace(Self.dragged)]) + + SidebarSessionTreeFeed.publish(Self.pass(enabled: defaults.sessionTree), to: .shared) + list.reload(animated: false) + #expect(SidebarSessionTree.shared.state == nil) + #expect(list.options(includeGap: true).sessionTree == nil) + #expect(list.displayed.rows.map(\.key) == originalOrder.map(SidebarRowKey.workspace)) + } + } + + @Test func draggingAnUnrelatedWorkspaceKeepsEnabledCoordinatorLanesAndTheirDropIdentity() throws { + try Self.withList { list in + SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) + list.reload(animated: false) + let hostKey = SidebarRowKey.sessionHost(Self.host) + let before = try #require(list.displayed.row(for: hostKey)) + let key = SidebarRowKey.workspace(Self.dragged) + let row = try #require(list.displayed.row(for: key)) + let press = SidebarPress(key: key, point: NSPoint(x: 80, y: row.y + row.height / 2)) + list.press = press + list.beginDrag(press) + let drag = try #require(list.drag) + + let baseOptions = list.options(includeGap: false) + let gapOptions = list.options(includeGap: true) + #expect(baseOptions.sessionTree?.hosts[Self.coordinator] == Self.host) + #expect(gapOptions.sessionTree == baseOptions.sessionTree) + #expect(baseOptions.excludedWorkspaces == [Self.dragged]) + #expect(baseOptions.gap == nil) + #expect(gapOptions.gap == DropPosition(section: .machine(.local), index: Self.workers.count + 2)) + #expect(gapOptions.gapHeight == drag.gapHeight) + // Both the drop resolver's base and the actual in-place drag layout retain the host. + let base = SidebarLayout.make(sections: list.listSections, metrics: list.metrics, options: baseOptions) + let gap = SidebarLayout.make(sections: list.listSections, metrics: list.metrics, options: gapOptions) + for layout in [base, gap, list.displayed] { + let header = try #require(layout.row(for: hostKey)) + #expect(header.childCount == before.childCount) + for (index, worker) in Self.workers.enumerated() { + let child = try #require(layout.row(for: .workspace(worker))) + #expect(child.section == .machine(.local)) + #expect(child.group == nil) + #expect(child.siblingIndex == index + 2) + #expect(child.content?.treeDepth == 2) + #expect(layout.rows.filter { $0.key == child.key }.count == 1) + } + } + #expect(base.row(for: key) == nil) + #expect(gap.gapY != nil) + #expect(list.displayed.gapY == list.displayed.row(for: key)?.y) + #expect(list.model.sections[0].workspaces.map(\.id) == [Self.coordinator, Self.plain] + Self.workers + [Self.dragged]) + } + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index d9aea42c324c..b5190a8d57f7 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -84,6 +84,45 @@ import Testing #expect(hostFolded.row(for: .sessionHost(Self.host))?.childCount == 2) } + @Test func publishKeepsSessionTreeOffByDefault() { + let tree = SidebarSessionTree(defaults: UserDefaults(suiteName: "SidebarSessionHostTests-off-\(UUID().uuidString)") ?? .standard) + let pass = SidebarSessionTreeFeed.Pass(state: Self.state(), asks: [], showsTree: false) + SidebarSessionTreeFeed.publish(pass, to: tree) + #expect(tree.state == nil) + #expect(tree.pullRequests.isEmpty) + } + + @Test func localOnlyAgentRefsDoNotCreateAHostGroup() { + let chats = [(Self.parent, [AgentSessionRef(host: "install:local", hostName: "This Mac", session: "local-agent")]), + (Self.child, [AgentSessionRef(host: "install:local", hostName: "This Mac", session: "local-worker")])] + let pass = SidebarSessionTreeFeed.pass(chats, lanes: [:], localHost: "install:local", pullRequests: [:]) + #expect(pass.state.hosts.isEmpty) + let alias = SidebarSessionTreeFeed.pass([(Self.parent, [AgentSessionRef(host: "registry:local", session: "alias")])], lanes: [:], + hostAliases: ["install:local": ["registry:local"]], localHost: "install:local", pullRequests: [:]) + #expect(alias.state.hosts.isEmpty) + #expect(Self.layout(pass.state) == Self.layout(nil)) + } + + @Test func pinnedParentDoesNotPullFleetChildAcrossSectionBoundary() { + let pinned = SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "Pinned"))]) + let machine = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + nodes: [.workspace(SidebarWorkspace(id: Self.child, title: "Worker"))]) + var options = SidebarLayoutOptions(); options.sessionTree = Self.state() + let layout = SidebarLayout.make(sections: [pinned, machine], metrics: .standard, options: options) + #expect(layout.row(for: .sessionHost(Self.host)) != nil) + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 1) + } + + @Test func pinnedChildKeepsPinnedPlacementWhenItsParentIsAVisibleFleetLane() { + let machine = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "Coordinator"))]) + let pinned = SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: Self.child, title: "Pinned worker"))]) + var options = SidebarLayoutOptions(); options.sessionTree = Self.state() + let layout = SidebarLayout.make(sections: [machine, pinned], metrics: .standard, options: options) + #expect(layout.row(for: .workspace(Self.child))?.section == .pinned) + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 0) + } + @Test func disabledTreeAndWorkspacesWithoutAgentRefsKeepTheirExistingRows() { let disabled = Self.layout(nil) #expect(disabled.rows.map(\.key) == [.workspace(Self.parent), .workspace(Self.other), .workspace(Self.child)]) @@ -117,6 +156,105 @@ import Testing #expect(layout.row(for: .workspace(Self.child))?.depth == 1) } + @Test func dragGapKeepsHostProjectionAndDropIdentity() throws { + var options = SidebarLayoutOptions() + options.sessionTree = Self.state() + options.gap = DropPosition(section: .machine(.local), index: 1) + options.gapHeight = 24 + options.showEmptyPinned = true + let layout = SidebarLayout.make(sections: Self.sections(), metrics: .standard, options: options) + let gapY = try #require(layout.gapY) + let target = try #require(layout.row(for: .workspace(Self.other))) + #expect(target.y == gapY + layout.gapShift) + #expect(layout.row(at: gapY + layout.gapHeight / 2) == nil) + #expect(layout.row(for: .sessionHost(Self.host)) != nil) + #expect(layout.rows.filter { $0.key == .workspace(Self.child) }.count == 1) + #expect(layout.row(for: .workspace(Self.child))?.siblingIndex == 2) + } + + @Test func dropBeforeReorderedChildAndAtListEndReservesRealSpace() throws { + for index in [2, 3] { + var options = SidebarLayoutOptions() + options.sessionTree = Self.state() + options.gap = DropPosition(section: .machine(.local), index: index) + options.gapHeight = 24 + let layout = SidebarLayout.make(sections: Self.sections(), metrics: .standard, options: options) + let gapY = try #require(layout.gapY) + if index == 2 { + #expect(layout.row(for: .workspace(Self.child))?.y == gapY + layout.gapShift) + } else { + let last = try #require(layout.rows.last) + #expect(gapY == last.maxY + layout.rowSpacing) + } + #expect(layout.row(at: gapY + layout.gapHeight / 2) == nil) + #expect(layout.totalHeight >= gapY + layout.gapHeight) + } + } + + @Test func sectionEndDropDoesNotFollowAWorkspaceFromTheNextMachine() throws { + var options = SidebarLayoutOptions() + var state = Self.state() + state.parents = [:] + options.sessionTree = state + options.flattensMachines = true + options.gap = DropPosition(section: .machine(.local), index: 2) + options.gapHeight = 24 + let layout = SidebarLayout.make(sections: Self.sections(crossMachine: true), metrics: .standard, options: options) + let lastLocal = try #require(layout.row(for: .workspace(Self.other))) + let gapY = try #require(layout.gapY) + #expect(gapY == lastLocal.maxY + layout.rowSpacing) + #expect(layout.row(at: gapY + layout.gapHeight / 2) == nil) + #expect(layout.row(for: .workspace(Self.child))?.section == .machine(MachineID("remote"))) + } + + @Test func historyAndSectionGapsStayAtTheirBoundariesAfterReorderingAndFolding() throws { + let chat = SidebarHistoryChat(id: "old", title: "Earlier chat", updatedAt: .distantPast) + let history = SidebarChatHistoryState(pinned: [chat], earlier: [chat]) + let tail = SidebarSection(kind: .custom(SidebarCustomSection(id: "tail")), nodes: []) + for hasTail in [false, true] { + for folded in [false, true] { + var options = SidebarLayoutOptions() + var state = Self.state() + if folded { state.collapsed = [Self.parent] } + options.sessionTree = state + options.chatHistory = history + options.blockHeights = ["tail": 44] + let sections = Self.sections() + (hasTail ? [tail] : []) + let layout = SidebarLayout.make(sections: sections, metrics: .standard, options: options) + let metrics = SidebarLayoutMetrics.standard.resolved(for: options) + let pinnedY = try #require(layout.pinnedChatsY) + let earlierY = try #require(layout.earlierChatsY) + let header = try #require(layout.row(for: .sessionHost(Self.host))) + let lastWorkspace = try #require(layout.row(for: .workspace(Self.other))) + #expect(header.y == pinnedY + history.pinnedHeight(metrics)) + #expect(earlierY == lastWorkspace.maxY + metrics.rowSpacing + metrics.sectionSpacing) + if hasTail { + #expect(layout.row(for: .block("tail"))?.y == earlierY + history.earlierHeight(metrics)) + } + #expect(layout.totalHeight >= earlierY + history.earlierHeight(metrics)) + // The moved child must not carry the section/history gap into its family. + if !folded { + let parent = try #require(layout.row(for: .workspace(Self.parent))) + #expect(layout.row(for: .workspace(Self.child))?.y == parent.maxY + metrics.rowSpacing) + } + } + } + } + + @Test func pinnedHistoryAfterAnExplicitSectionStaysAboveTheHostHeader() throws { + let pinned = SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: WorkspaceID("pin"), title: "Pinned"))]) + let history = SidebarChatHistoryState(pinned: [.init(id: "chat", title: "Chat", updatedAt: .distantPast)]) + var options = SidebarLayoutOptions() + options.sessionTree = Self.state() + options.chatHistory = history + let layout = SidebarLayout.make(sections: [pinned] + Self.sections(), metrics: .standard, options: options) + let metrics = SidebarLayoutMetrics.standard.resolved(for: options) + let pinnedY = try #require(layout.pinnedChatsY) + #expect(layout.row(for: .sessionHost(Self.host))?.y == pinnedY + history.pinnedHeight(metrics)) + let pin = try #require(layout.row(for: .workspace(WorkspaceID("pin")))) + #expect(pinnedY == pin.maxY + metrics.rowSpacing + metrics.sectionSpacing) + } + @Test func sessionTreeStillKeepsDoneAndLimitedRowsInsideTheCount() { var options = SidebarLayoutOptions() options.sessionTree = Self.state() diff --git a/plans/cmux-next/sidebar-owner.md b/plans/cmux-next/sidebar-owner.md index eadc3b2d3ce3..99da6efaa6eb 100644 --- a/plans/cmux-next/sidebar-owner.md +++ b/plans/cmux-next/sidebar-owner.md @@ -843,3 +843,6 @@ Commits logged without a trailer (behavior fixes, no visual change; the card kee Leo: "i feel like there's still a big mess of uncategorized stuff in the sidebar", "i mean we dont want to be too opinionated by defgault", "im saying for my particular sidebar there's a lot of wack stuff there". The existing opt-in session tree groups its loose agent workspaces by their existing tab host, with a foldable host header and a count that includes folded descendants. A live parent in this window wins across machines; a loose child also follows a visible parent inside a user group. Explicit child group placement is retained. The real layout and shortcut order share this projection; the unbound remote-lane feed no longer filters children. No default or row title/subtitle changes. `SidebarSessionHostTests` exercises feed-to-layout lineage, parent absence, cross-machine lineage, folds, explicit groups and the disabled state. +- Follow-up geometry: host regrouping keeps the drop gap attached to its logical insertion slot, retains section and chat-history boundary spacing, and shifts Earlier by the final visible family extent; Pinned remains above the first host header. + +- Dragging preserves the host projection and drop identity: synthetic headers remain during an open gap, and workspace rows retain their document section and sibling index. Fleet children of Pinned/custom rows stay in their own machine group, preserving the section boundary. From e21e465b7c4ca042d99dcec7764cdc3c9866f435 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 15:28:37 +0000 Subject: [PATCH 05/29] Map grouped sidebar drag slots to document positions Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b Sidebar-Look: no visual change --- .../SidebarSessionTreeFeed.swift | 22 +++++++----- .../Logic/SidebarLayout+SessionHosts.swift | 36 ++++++++++++++++--- .../CmuxNextSidebar/Logic/SidebarLayout.swift | 2 +- .../CmuxNextSidebar/Logic/SidebarRow.swift | 4 +++ .../SidebarSessionHostTests.swift | 33 +++++++++++++++++ plans/cmux-next/sidebar-owner.md | 2 +- 6 files changed, 84 insertions(+), 15 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift index 65ff9759344f..42ac9893e3cd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift @@ -149,14 +149,20 @@ public final class SidebarSessionTreeFeed { return nil } var state = SidebarSessionTreeState() - let localHosts: Set = localHost.map { Set(keys($0)) } ?? [] - for (id, refs) in chats { - // Local agent tabs remain in the ordinary local list. Host grouping is - // reserved for fleet sessions, excluding this install and its aliases. - guard let ref = refs.first(where: { $0.session != nil && !localHosts.contains($0.host) }) else { continue } - let host = keys(ref.host).min() ?? ref.host - state.hosts[id] = host - state.hostNames[host] = state.hostNames[host] ?? ref.hostName ?? ref.host + // A missing local identity means we cannot distinguish this install from + // fleet peers. Leave host grouping off until the identity is known. + if let localHost { + let localHosts = Set(keys(localHost)) + for (id, refs) in chats { + // Local agent tabs remain in the ordinary local list. Host grouping + // is reserved for fleet sessions, excluding this install and aliases. + guard let ref = refs.first(where: { $0.session != nil && !localHosts.contains($0.host) }) else { continue } + // Keep the tab's primary host as the fold identity; alias discovery + // must not rename a user's collapsed host bucket. + let host = ref.host + state.hosts[id] = host + state.hostNames[host] = state.hostNames[host] ?? ref.hostName ?? ref.host + } } var agentStates: [SidebarWorkspaceID: SidebarAgentState] = [:] var asks: Set = [] diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index 007f2cea652e..f13bcdc2c55f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -39,13 +39,18 @@ nonisolated extension SidebarLayout { let children = Self.treeChildren(ids, parents: parents) let nested = Set(children.values.joined()) let roots = ids.indices.filter { !nested.contains($0) } - var hosts: [String: [Int]] = [:] - var rootHosts: [Int: String] = [:] + struct HostKey: Hashable { + let host: String + let section: SectionID + } + var hosts: [HostKey: [Int]] = [:] + var rootHosts: [Int: HostKey] = [:] for root in roots { guard rows[starts[root]].group == nil, let id = ids[root], let host = tree.hosts[id], case .machine = rows[starts[root]].section else { continue } - rootHosts[root] = host - hosts[host, default: []].append(root) + let key = HostKey(host: host, section: rows[starts[root]].section) + rootHosts[root] = key + hosts[key, default: []].append(root) } let workspaceByID = Dictionary(sections.flatMap(\.workspaces).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) func agentState(_ index: Int) -> SidebarAgentState { @@ -54,7 +59,7 @@ nonisolated extension SidebarLayout { } // Reordering only the workspace bundles leaves user groups, document items and section // blocks in their existing order. Each host is emitted at its first root's old position. - var emitted: Set = [] + var emitted: Set = [] let byStart = Dictionary(starts.enumerated().map { ($0.element, $0.offset) }, uniquingKeysWith: { first, _ in first }) var result: [SidebarRow] = [] var y: CGFloat = 0 @@ -147,6 +152,27 @@ nonisolated extension SidebarLayout { } == true }) { openGap() } } + // The visual order is a projection, but the reducer still writes document + // positions. Keep row identity/siblingIndex for selection and give it the + // slot immediately before the next drawn sibling for drop resolution. + func siblingCount(_ row: SidebarRow) -> Int { + guard let section = sections.first(where: { $0.id == row.section }) else { return row.siblingIndex + 1 } + if let group = row.group, + let node = section.nodes.first(where: { $0.id == .group(group) }), + case let .group(value) = node { return value.members.count } + return section.nodes.count + } + for index in result.indices { + guard case .workspace = result[index].key else { continue } + let section = result[index].section + let group = result[index].group + let next = result[(index + 1).. Date: Fri, 30 Oct 2026 15:35:20 +0000 Subject: [PATCH 06/29] Keep sidebar projection flat without a local identity Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift | 6 ++++++ .../Tests/CmuxNextAppTests/SidebarSessionHostTests.swift | 1 + 2 files changed, 7 insertions(+) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift index 42ac9893e3cd..e6b6f4019f6a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift @@ -205,6 +205,12 @@ public final class SidebarSessionTreeFeed { state.parents[id] = parent } } + if localHost == nil { + // Without this install's identity, neither fleet buckets nor lineage + // can be trusted to distinguish local sessions. Leave the projection flat. + state.hosts.removeAll() + state.parents.removeAll() + } return Pass(state: state, asks: asks) } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index 53f17dcd2375..d5ffa265c4a6 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -127,6 +127,7 @@ import Testing let chats = [(Self.parent, [AgentSessionRef(host: "install:unknown", hostName: "This Mac", session: "local")])] let pass = SidebarSessionTreeFeed.pass(chats, lanes: [:], localHost: nil, pullRequests: [:]) #expect(pass.state.hosts.isEmpty) + #expect(pass.state.parents.isEmpty) } @Test func lineageNestingRemainsInPinnedSectionWhenFleetHostsExist() { From cc8aa432e1f4ee4bc66d5f6414741ccbef6786ea Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 15:48:42 +0000 Subject: [PATCH 07/29] Resolve grouped sidebar drops by drawn family and section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b Sidebar-Look: i feel like there’s still a big mess of uncategorized stuff in the sidebar --- .../Logic/SidebarLayout+SessionHosts.swift | 50 ++++++++++++++++++- .../Model/SidebarSessionTree.swift | 13 ++++- .../Views/SidebarListDrag.swift | 10 ++++ .../Views/SidebarListView+Drag.swift | 7 ++- .../Views/SidebarListView+Layout.swift | 3 +- .../SidebarSessionHostIntegrationTests.swift | 8 +-- .../SidebarSessionHostTests.swift | 44 +++++++++++----- plans/cmux-next/sidebar-owner.md | 1 + 8 files changed, 114 insertions(+), 22 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index f13bcdc2c55f..a1c2db9bd089 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -140,8 +140,9 @@ nonisolated extension SidebarLayout { let count = members.reduce(0) { total, member in total + 1 + (ids[member].map { Self.treeDescendants(of: $0, ids, children: children).count } ?? 0) } - let collapsed = tree.collapsedHosts.contains(host) - append(SidebarRow(key: .sessionHost(host), y: y, height: m.groupHeaderHeight, section: row.section, + let collapsed = tree.collapsedHosts.contains(host.host) + let hostKey = SidebarSessionTree.hostKey(host.host, section: host.section) + append(SidebarRow(key: .sessionHost(hostKey), y: y, height: m.groupHeaderHeight, section: row.section, group: nil, siblingIndex: row.siblingIndex, parentIndex: nil, isLastInGroup: false, isCollapsed: collapsed, childCount: count, groupColor: nil), spacing: m.rowSpacing) if !collapsed { for member in members { family(member, depth: 1) } } @@ -182,3 +183,48 @@ nonisolated extension SidebarLayout { return layout } } + + +nonisolated extension SidebarLayout { + /// The host family containing a drawn row, if any. Synthetic headers are + /// stable per host and machine section, so they also provide the drag family. + func sessionHost(for key: SidebarRowKey) -> String? { + guard let index = position(of: key) else { return nil } + return sessionHost(around: index) + } + + private func sessionHost(around index: Int) -> String? { + guard !rows.isEmpty else { return nil } + for i in stride(from: min(index, rows.count - 1), through: 0, by: -1) { + if case let .sessionHost(host) = rows[i].key { return SidebarSessionTree.hostID(from: host) } + if case .workspace = rows[i].key, rows[i].content?.treeDepth == 0 { return nil } + if case .section = rows[i].key { return nil } + } + return nil + } + + /// Resolve a projected row's upper/lower half to the next drawn sibling. + /// `.none` means the ordinary ungrouped resolver should run; `.some(nil)` + /// refuses a slot outside the dragged row's family. + func groupedDropTarget(row: SidebarRow, after: Bool, sourceHost: String?) -> DropTarget?? { + guard rows.contains(where: { if case .sessionHost = $0.key { true } else { false } }) else { return nil } + guard case .workspace = row.key else { return .some(nil) } + let targetHost = sessionHost(for: row.key) + if targetHost != nil && targetHost != sourceHost { return .some(nil) } + let index = position(of: row.key) ?? 0 + let next = rows[(index + 1).. String { + "\(host)\u{1f}\(section.rawValue)" + } + + public static func hostID(from key: String) -> String { + key.split(separator: "\u{1f}", maxSplits: 1).first.map(String.init) ?? key + } + static let collapsedKey = "sidebar.sessionTree.collapsed" static let collapsedHostsKey = "sidebar.sessionTree.collapsedHosts" } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift index e3f0e4b9f10b..ed1fbeb2086c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift @@ -44,6 +44,8 @@ final class SidebarListDrag { var band = SidebarGroupBand() /// Where the dragged workspaces started (what Cmd-Z puts them back to). var origin: DropPosition? + /// Stable host family captured before the source row is hidden. + var sourceHost: String? /// The row a drop grouped with: its new group renames in place once the drag has landed and the rows have settled. var renameOnLand: WorkspaceID? /// The last pointer y in the list and the drag's vertical direction. @@ -116,6 +118,14 @@ final class SidebarListDrag { noteProbe(nil, card: card, displayed: displayed, base: base) return nil } + if displayed.rows.contains(where: { if case .sessionHost = $0.key { true } else { false } }), + let y = DropResolver.baseY(forDisplayY: resolved.probe == .centre ? card.midY : leading, + gapY: displayed.gapY, gapHeight: displayed.gapShift), + let row = base.row(at: y), + let grouped = displayed.groupedDropTarget(row: row, after: y >= row.y + row.height / 2, sourceHost: sourceHost) { + noteProbe(resolved.probe, card: card, displayed: displayed, base: base, target: grouped.flatMap { $0 }) + return grouped + } noteProbe(resolved.probe, card: card, displayed: displayed, base: base, target: resolved.target) return .some(resolved.target) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift index 05c7f095ffe5..c197614df9b0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift @@ -86,6 +86,7 @@ extension SidebarListViewComponents { drag.restFrame.origin.x -= stepIn drag.restFrame.size.width += stepIn drag.morphs = rows.count == 1 + drag.sourceHost = displayed.sessionHost(for: press.key) self.drag = drag // The document's acceptance table: the drag's one reducer call before its drop. if let doc = model.docDrag, let items = doc.items(payload) { @@ -241,7 +242,11 @@ extension SidebarListViewComponents { var blockTarget: SidebarBlockGap? if let docTarget = hit.target { if let row = rows[hit.slot.key] { - target = SidebarDocDrag.display(hit, row: row) + if let grouped = displayed.groupedDropTarget(row: row, after: hit.zone == .after, sourceHost: drag.sourceHost) { + target = grouped.flatMap { $0 } + } else { + target = SidebarDocDrag.display(hit, row: row) + } } else { blockTarget = SidebarBlockGap(section: hit.slot.section, index: blockIndex(docTarget, section: hit.slot.section, moving: drag.docItems ?? [])) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift index eac684c40e70..7b99e1ec7f23 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift @@ -417,7 +417,8 @@ extension SidebarListViewComponents { case let (.folder(_, folder), view as FolderHeaderRowView): view.configure(folder: folder) case let (.status, view as StatusHeaderRowView): view.configure(row) case let (.sessionHost(host), view as StatusHeaderRowView): - view.configure(row, title: SidebarSessionTree.shared.state?.hostNames[host] ?? host) + let stableHost = SidebarSessionTree.hostID(from: host) + view.configure(row, title: SidebarSessionTree.shared.state?.hostNames[stableHost] ?? stableHost) case (.doneFold, let view as SidebarDoneFoldRowView), (.showMore, let view as SidebarDoneFoldRowView): view.isKeyboardFocused = showsFocusRing && focusedFold == row.key view.configure(row) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index e07e7e565954..f1e1d12ad69f 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -72,16 +72,16 @@ struct SidebarSessionHostIntegrationTests { SidebarSessionTreeFeed.publish(Self.pass(enabled: defaults.sessionTree), to: .shared) list.reload(animated: false) #expect(list.options(includeGap: false).sessionTree == nil) - #expect(list.displayed.row(for: .sessionHost(Self.host)) == nil) + #expect(list.displayed.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local)))) == nil) let originalOrder = [Self.coordinator, Self.plain] + Self.workers + [Self.dragged] #expect(list.displayed.rows.map(\.key) == originalOrder.map(SidebarRowKey.workspace)) SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) list.reload(animated: false) - let header = try #require(list.displayed.row(for: .sessionHost(Self.host))) + let header = try #require(list.displayed.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))) #expect(header.childCount == Self.workers.count + 1) #expect(list.options(includeGap: false).sessionTree?.parents[Self.workers[0]] == Self.coordinator) - #expect(list.displayed.rows.map(\.key) == [.sessionHost(Self.host), .workspace(Self.coordinator)] + #expect(list.displayed.rows.map(\.key) == [.sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))), .workspace(Self.coordinator)] + Self.workers.map(SidebarRowKey.workspace) + [.workspace(Self.plain), .workspace(Self.dragged)]) SidebarSessionTreeFeed.publish(Self.pass(enabled: defaults.sessionTree), to: .shared) @@ -96,7 +96,7 @@ struct SidebarSessionHostIntegrationTests { try Self.withList { list in SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) list.reload(animated: false) - let hostKey = SidebarRowKey.sessionHost(Self.host) + let hostKey = SidebarRowKey.sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))) let before = try #require(list.displayed.row(for: hostKey)) let key = SidebarRowKey.workspace(Self.dragged) let row = try #require(list.displayed.row(for: key)) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index d5ffa265c4a6..828ea4a171aa 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -48,7 +48,7 @@ import Testing #expect(layout.row(for: .workspace(Self.parent))?.content?.treeDepth == 1) #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 2) #expect(layout.row(for: .workspace(Self.parent))?.content?.treeFold == .expanded) - #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 2) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 2) let child = try #require(layout.row(for: .workspace(Self.child))) #expect(child.section == .machine(.local)) #expect(child.siblingIndex == 2, "grouping must preserve document drop/selection identity") @@ -58,17 +58,17 @@ import Testing let layout = Self.layout(Self.state(), parentPresent: false) #expect(layout.row(for: .workspace(Self.parent)) == nil) #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 1) - #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 1) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 1) #expect(layout.rows.filter { $0.key == .workspace(Self.child) }.count == 1) } @Test func crossMachineChildFollowsItsLiveParentInsteadOfGettingASecondGroup() { let layout = Self.layout(Self.state(crossHost: true), crossMachine: true) let keys = layout.rows.map(\.key) - #expect(keys == [.sessionHost(Self.host), .workspace(Self.parent), .workspace(Self.child), .workspace(Self.other)]) + #expect(keys == [.sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))), .workspace(Self.parent), .workspace(Self.child), .workspace(Self.other)]) #expect(layout.row(for: .workspace(Self.child))?.section == .machine(MachineID("remote"))) #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 2) - #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 2) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 2) } @Test func parentAndHostFoldsKeepTheWholeBadgeCount() { @@ -77,11 +77,11 @@ import Testing let parentFolded = Self.layout(state) #expect(parentFolded.row(for: .workspace(Self.child)) == nil) #expect(parentFolded.row(for: .workspace(Self.parent))?.content?.treeFold == .collapsed) - #expect(parentFolded.row(for: .sessionHost(Self.host))?.childCount == 2) + #expect(parentFolded.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 2) state.collapsedHosts = [Self.host] let hostFolded = Self.layout(state) - #expect(hostFolded.rows.map(\.key) == [.sessionHost(Self.host), .workspace(Self.other)]) - #expect(hostFolded.row(for: .sessionHost(Self.host))?.childCount == 2) + #expect(hostFolded.rows.map(\.key) == [.sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))), .workspace(Self.other)]) + #expect(hostFolded.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 2) } @Test func publishKeepsSessionTreeOffByDefault() { @@ -109,7 +109,7 @@ import Testing nodes: [.workspace(SidebarWorkspace(id: Self.child, title: "Worker"))]) var options = SidebarLayoutOptions(); options.sessionTree = Self.state() let layout = SidebarLayout.make(sections: [pinned, machine], metrics: .standard, options: options) - #expect(layout.row(for: .sessionHost(Self.host)) != nil) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local)))) != nil) #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 1) } @@ -148,10 +148,12 @@ import Testing let second = SidebarMachine(id: MachineID("two"), name: "Two", kind: .ssh) let one = SidebarSection(kind: .machine(first), nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "One root"))]) let two = SidebarSection(kind: .machine(second), nodes: [.workspace(SidebarWorkspace(id: Self.other, title: "Two root"))]) - var state = Self.state(); state.hosts[Self.other] = "registry:other" + var state = Self.state(); state.hosts[Self.other] = Self.host var options = SidebarLayoutOptions(); options.sessionTree = state let layout = SidebarLayout.make(sections: [one, two], metrics: .standard, options: options) #expect(layout.rows.filter { if case .sessionHost = $0.key { true } else { false } }.count == 2) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(MachineID("one"))))) != nil) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(MachineID("two"))))) != nil) #expect(layout.row(for: .workspace(Self.parent))?.section == .machine(MachineID("one"))) #expect(layout.row(for: .workspace(Self.other))?.section == .machine(MachineID("two"))) } @@ -200,7 +202,7 @@ import Testing let target = try #require(layout.row(for: .workspace(Self.other))) #expect(target.y == gapY + layout.gapShift) #expect(layout.row(at: gapY + layout.gapHeight / 2) == nil) - #expect(layout.row(for: .sessionHost(Self.host)) != nil) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local)))) != nil) #expect(layout.rows.filter { $0.key == .workspace(Self.child) }.count == 1) #expect(layout.row(for: .workspace(Self.child))?.siblingIndex == 2) #expect(layout.row(for: .workspace(Self.child))?.dropIndex == 2) @@ -225,6 +227,22 @@ import Testing } } + @Test func groupedDropSlotsFollowDrawnNeighborsAndRefuseOtherFamilies() throws { + let layout = Self.layout(Self.state()) + let coordinator = try #require(layout.row(for: .workspace(Self.parent))) + let worker = try #require(layout.row(for: .workspace(Self.child))) + let plain = try #require(layout.row(for: .workspace(Self.other))) + let host = SidebarSessionTree.hostKey(Self.host, section: .machine(.local)) + let upper = layout.groupedDropTarget(row: coordinator, after: false, sourceHost: Self.host) + let lower = layout.groupedDropTarget(row: coordinator, after: true, sourceHost: Self.host) + #expect(upper == .some(.position(DropPosition(section: .machine(.local), index: coordinator.siblingIndex)))) + #expect(lower == .some(.position(DropPosition(section: .machine(.local), index: worker.siblingIndex)))) + let familyEnd = layout.groupedDropTarget(row: worker, after: true, sourceHost: Self.host) + #expect(familyEnd == .some(.position(DropPosition(section: .machine(.local), index: plain.siblingIndex)))) + #expect(layout.groupedDropTarget(row: coordinator, after: false, sourceHost: nil) == .some(nil)) + #expect(layout.row(for: .sessionHost(host)) != nil) + } + @Test func sectionEndDropDoesNotFollowAWorkspaceFromTheNextMachine() throws { var options = SidebarLayoutOptions() var state = Self.state() @@ -258,7 +276,7 @@ import Testing let metrics = SidebarLayoutMetrics.standard.resolved(for: options) let pinnedY = try #require(layout.pinnedChatsY) let earlierY = try #require(layout.earlierChatsY) - let header = try #require(layout.row(for: .sessionHost(Self.host))) + let header = try #require(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))) let lastWorkspace = try #require(layout.row(for: .workspace(Self.other))) #expect(header.y == pinnedY + history.pinnedHeight(metrics)) #expect(earlierY == lastWorkspace.maxY + metrics.rowSpacing + metrics.sectionSpacing) @@ -284,7 +302,7 @@ import Testing let layout = SidebarLayout.make(sections: [pinned] + Self.sections(), metrics: .standard, options: options) let metrics = SidebarLayoutMetrics.standard.resolved(for: options) let pinnedY = try #require(layout.pinnedChatsY) - #expect(layout.row(for: .sessionHost(Self.host))?.y == pinnedY + history.pinnedHeight(metrics)) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.y == pinnedY + history.pinnedHeight(metrics)) let pin = try #require(layout.row(for: .workspace(WorkspaceID("pin")))) #expect(pinnedY == pin.maxY + metrics.rowSpacing + metrics.sectionSpacing) } @@ -297,7 +315,7 @@ import Testing options.flattensMachines = true let layout = SidebarLayout.make(sections: Self.sections(), metrics: .standard, options: options) #expect(layout.rows.map(\.key) == Self.layout(Self.state()).rows.map(\.key)) - #expect(layout.row(for: .sessionHost(Self.host))?.childCount == 2) + #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 2) } @Test func revealingChildOpensItsRootHostsFold() throws { diff --git a/plans/cmux-next/sidebar-owner.md b/plans/cmux-next/sidebar-owner.md index 6fabd13cfccb..a79d84f4576d 100644 --- a/plans/cmux-next/sidebar-owner.md +++ b/plans/cmux-next/sidebar-owner.md @@ -846,3 +846,4 @@ Leo: "i feel like there's still a big mess of uncategorized stuff in the sidebar - Follow-up geometry: host regrouping keeps the drop gap attached to its logical insertion slot, retains section and chat-history boundary spacing, and shifts Earlier by the final visible family extent; Pinned remains above the first host header. - Dragging preserves the host projection and row identity: synthetic headers remain during an open gap, workspace rows retain their document section and sibling index, and the drop reducer maps each drawn neighbor to its underlying document slot. Fleet children of Pinned/custom rows stay in their own machine group, preserving the section boundary. +- Grouped drag halves resolve from the drawn family: a drop maps before the row or before its next drawn sibling, and a family mismatch refuses the gap. The ungrouped layout keeps its existing reducer path. From 2fd66d2e0d24620debc59b39f382d298614dd1ba Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:20:40 +0000 Subject: [PATCH 08/29] fix(sidebar): refuse all in-sidebar drops while host groups show Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../SidebarSessionTreeFeed.swift | 5 +- .../Logic/RustSidebarRow.swift | 1 + .../Logic/SidebarLayout+SessionHosts.swift | 66 ------------------- .../CmuxNextSidebar/Logic/SidebarLayout.swift | 7 ++ .../CmuxNextSidebar/Logic/SidebarRow.swift | 1 - .../Model/SidebarSessionTree.swift | 11 +++- .../Views/SidebarListDrag.swift | 11 +--- .../Views/SidebarListView+Drag.swift | 15 +++-- .../Views/SidebarListView+TabDrop.swift | 5 ++ .../SidebarSessionHostTests.swift | 18 +---- 10 files changed, 36 insertions(+), 104 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift index e6b6f4019f6a..78bff35cd474 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift @@ -206,10 +206,9 @@ public final class SidebarSessionTreeFeed { } } if localHost == nil { - // Without this install's identity, neither fleet buckets nor lineage - // can be trusted to distinguish local sessions. Leave the projection flat. + // Without this install's identity, fleet buckets stay off. Recorded + // lineage remains useful and is still projected by Session Tree. state.hosts.removeAll() - state.parents.removeAll() } return Pass(state: state, asks: asks) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift index 9ed8793eabb8..1211d14200cf 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift @@ -187,6 +187,7 @@ nonisolated struct RustRow: Codable { height = Double(row.height) section = RustSectionID(row.section) group = row.group?.rawValue + siblingIndex = row.siblingIndex parentIndex = row.parentIndex isLastInGroup = row.isLastInGroup diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index a1c2db9bd089..0ef76351246d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -153,27 +153,6 @@ nonisolated extension SidebarLayout { } == true }) { openGap() } } - // The visual order is a projection, but the reducer still writes document - // positions. Keep row identity/siblingIndex for selection and give it the - // slot immediately before the next drawn sibling for drop resolution. - func siblingCount(_ row: SidebarRow) -> Int { - guard let section = sections.first(where: { $0.id == row.section }) else { return row.siblingIndex + 1 } - if let group = row.group, - let node = section.nodes.first(where: { $0.id == .group(group) }), - case let .group(value) = node { return value.members.count } - return section.nodes.count - } - for index in result.indices { - guard case .workspace = result[index].key else { continue } - let section = result[index].section - let group = result[index].group - let next = result[(index + 1).. String? { - guard let index = position(of: key) else { return nil } - return sessionHost(around: index) - } - - private func sessionHost(around index: Int) -> String? { - guard !rows.isEmpty else { return nil } - for i in stride(from: min(index, rows.count - 1), through: 0, by: -1) { - if case let .sessionHost(host) = rows[i].key { return SidebarSessionTree.hostID(from: host) } - if case .workspace = rows[i].key, rows[i].content?.treeDepth == 0 { return nil } - if case .section = rows[i].key { return nil } - } - return nil - } - - /// Resolve a projected row's upper/lower half to the next drawn sibling. - /// `.none` means the ordinary ungrouped resolver should run; `.some(nil)` - /// refuses a slot outside the dragged row's family. - func groupedDropTarget(row: SidebarRow, after: Bool, sourceHost: String?) -> DropTarget?? { - guard rows.contains(where: { if case .sessionHost = $0.key { true } else { false } }) else { return nil } - guard case .workspace = row.key else { return .some(nil) } - let targetHost = sessionHost(for: row.key) - if targetHost != nil && targetHost != sourceHost { return .some(nil) } - let index = position(of: row.key) ?? 0 - let next = rows[(index + 1).. SidebarRow? { index.position(of: key).map { rows[$0] } } /// The position of `key`'s row in `rows`, or nil. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift index 6466ce64e1fd..192fa0787cdc 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift @@ -43,7 +43,6 @@ public nonisolated struct SidebarRow: Hashable, Sendable { /// The projected insertion slot used by the shared drop reducer. Session host /// grouping keeps `siblingIndex` as the document identity for selection and /// drag origins, while this optional slot follows the drawn neighbor. - public var dropIndex: Int? /// For a grouped workspace: the group's index in its section. public var parentIndex: Int? public var isLastInGroup: Bool diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift index 18a0789d5c59..1ef921ac3f03 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift @@ -233,11 +233,16 @@ public final class SidebarSessionTree { /// Ephemeral row identity for a host in one machine section. The host id /// remains the fold key, while the section suffix prevents pool/key collisions. - public static func hostKey(_ host: String, section: SectionID) -> String { - "\(host)\u{1f}\(section.rawValue)" + public nonisolated static func hostKey(_ host: String, section: SectionID) -> String { + let sectionKey: String = switch section { + case .pinned: "pinned" + case let .machine(id): "machine:\(id.rawValue)" + case let .custom(id): "custom:\(id)" + } + return "\(host)\u{1f}\(sectionKey)" } - public static func hostID(from key: String) -> String { + public nonisolated static func hostID(from key: String) -> String { key.split(separator: "\u{1f}", maxSplits: 1).first.map(String.init) ?? key } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift index ed1fbeb2086c..616b6ef274e5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift @@ -44,8 +44,6 @@ final class SidebarListDrag { var band = SidebarGroupBand() /// Where the dragged workspaces started (what Cmd-Z puts them back to). var origin: DropPosition? - /// Stable host family captured before the source row is hidden. - var sourceHost: String? /// The row a drop grouped with: its new group renames in place once the drag has landed and the rows have settled. var renameOnLand: WorkspaceID? /// The last pointer y in the list and the drag's vertical direction. @@ -112,20 +110,13 @@ final class SidebarListDrag { /// edge elsewhere (DropResolver.resolveDrag). func resolve(card: CGRect, displayed: SidebarLayout, base: SidebarLayout, sections: [SidebarSection], ungroupedFirst: Bool) -> DropTarget?? { + guard !displayed.hostHeadersShowing else { return .some(nil) } let leading = movingUp ? card.minY : card.maxY guard let resolved = DropResolver.resolveDrag(centreY: card.midY, leadingY: leading, gapY: displayed.gapY, gapHeight: displayed.gapShift, payload: payload, base: base, sections: sections, ungroupedFirst: ungroupedFirst) else { noteProbe(nil, card: card, displayed: displayed, base: base) return nil } - if displayed.rows.contains(where: { if case .sessionHost = $0.key { true } else { false } }), - let y = DropResolver.baseY(forDisplayY: resolved.probe == .centre ? card.midY : leading, - gapY: displayed.gapY, gapHeight: displayed.gapShift), - let row = base.row(at: y), - let grouped = displayed.groupedDropTarget(row: row, after: y >= row.y + row.height / 2, sourceHost: sourceHost) { - noteProbe(resolved.probe, card: card, displayed: displayed, base: base, target: grouped.flatMap { $0 }) - return grouped - } noteProbe(resolved.probe, card: card, displayed: displayed, base: base, target: resolved.target) return .some(resolved.target) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift index c197614df9b0..8509a4712be2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift @@ -86,7 +86,6 @@ extension SidebarListViewComponents { drag.restFrame.origin.x -= stepIn drag.restFrame.size.width += stepIn drag.morphs = rows.count == 1 - drag.sourceHost = displayed.sessionHost(for: press.key) self.drag = drag // The document's acceptance table: the drag's one reducer call before its drop. if let doc = model.docDrag, let items = doc.items(payload) { @@ -188,6 +187,14 @@ extension SidebarListViewComponents { /// pass after the first), then the list shows the drop as before. private func updateDocDrag(_ drag: Drag, point: NSPoint) { guard let doc = model.docDrag else { return } + guard !displayed.hostHeadersShowing else { + drag.docTarget = nil + drag.target = nil + drag.blockTarget = nil + drag.lift.setRefused(true) + showDragLayout() + return + } if drag.docGeometry == nil { drag.geometryRevision = model.sectionsRevision drag.blockBases = blockBases() @@ -242,11 +249,7 @@ extension SidebarListViewComponents { var blockTarget: SidebarBlockGap? if let docTarget = hit.target { if let row = rows[hit.slot.key] { - if let grouped = displayed.groupedDropTarget(row: row, after: hit.zone == .after, sourceHost: drag.sourceHost) { - target = grouped.flatMap { $0 } - } else { - target = SidebarDocDrag.display(hit, row: row) - } + target = SidebarDocDrag.display(hit, row: row) } else { blockTarget = SidebarBlockGap(section: hit.slot.section, index: blockIndex(docTarget, section: hit.slot.section, moving: drag.docItems ?? [])) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index da34ced54156..2beff8c8f1f1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -48,6 +48,11 @@ extension SidebarListViewComponents { self.external = external setHovered(nil) } + if displayed.hostHeadersShowing { + external.proposal = nil + reload(animated: true) + return nil + } autoscroll.update(windowPoint: windowPoint) if let baseY = DropResolver.baseY(forDisplayY: point.y, gapY: displayed.gapY, gapHeight: displayed.gapShift) { let base = SidebarLayout.make(sections: listSections, metrics: metrics, options: options(includeGap: false)) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index 828ea4a171aa..43f83218c947 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -205,7 +205,6 @@ import Testing #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local)))) != nil) #expect(layout.rows.filter { $0.key == .workspace(Self.child) }.count == 1) #expect(layout.row(for: .workspace(Self.child))?.siblingIndex == 2) - #expect(layout.row(for: .workspace(Self.child))?.dropIndex == 2) } @Test func dropBeforeReorderedChildAndAtListEndReservesRealSpace() throws { @@ -227,20 +226,9 @@ import Testing } } - @Test func groupedDropSlotsFollowDrawnNeighborsAndRefuseOtherFamilies() throws { - let layout = Self.layout(Self.state()) - let coordinator = try #require(layout.row(for: .workspace(Self.parent))) - let worker = try #require(layout.row(for: .workspace(Self.child))) - let plain = try #require(layout.row(for: .workspace(Self.other))) - let host = SidebarSessionTree.hostKey(Self.host, section: .machine(.local)) - let upper = layout.groupedDropTarget(row: coordinator, after: false, sourceHost: Self.host) - let lower = layout.groupedDropTarget(row: coordinator, after: true, sourceHost: Self.host) - #expect(upper == .some(.position(DropPosition(section: .machine(.local), index: coordinator.siblingIndex)))) - #expect(lower == .some(.position(DropPosition(section: .machine(.local), index: worker.siblingIndex)))) - let familyEnd = layout.groupedDropTarget(row: worker, after: true, sourceHost: Self.host) - #expect(familyEnd == .some(.position(DropPosition(section: .machine(.local), index: plain.siblingIndex)))) - #expect(layout.groupedDropTarget(row: coordinator, after: false, sourceHost: nil) == .some(nil)) - #expect(layout.row(for: .sessionHost(host)) != nil) + @Test func hostHeadersDisableInSidebarReordering() { + #expect(Self.layout(Self.state()).hostHeadersShowing) + #expect(!Self.layout(nil).hostHeadersShowing) } @Test func sectionEndDropDoesNotFollowAWorkspaceFromTheNextMachine() throws { From 534c2cae8642567cd18bba172243dbc7de22df43 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:24:57 +0000 Subject: [PATCH 09/29] test(sidebar): assert real list refuses host-group drops Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../SidebarSessionHostIntegrationTests.swift | 33 +++---------------- 1 file changed, 4 insertions(+), 29 deletions(-) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index f1e1d12ad69f..3e167c646f6d 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -92,12 +92,10 @@ struct SidebarSessionHostIntegrationTests { } } - @Test func draggingAnUnrelatedWorkspaceKeepsEnabledCoordinatorLanesAndTheirDropIdentity() throws { + @Test func draggingAnUnrelatedWorkspaceIsRefusedWhileHostGroupsShow() throws { try Self.withList { list in SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) list.reload(animated: false) - let hostKey = SidebarRowKey.sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))) - let before = try #require(list.displayed.row(for: hostKey)) let key = SidebarRowKey.workspace(Self.dragged) let row = try #require(list.displayed.row(for: key)) let press = SidebarPress(key: key, point: NSPoint(x: 80, y: row.y + row.height / 2)) @@ -105,32 +103,9 @@ struct SidebarSessionHostIntegrationTests { list.beginDrag(press) let drag = try #require(list.drag) - let baseOptions = list.options(includeGap: false) - let gapOptions = list.options(includeGap: true) - #expect(baseOptions.sessionTree?.hosts[Self.coordinator] == Self.host) - #expect(gapOptions.sessionTree == baseOptions.sessionTree) - #expect(baseOptions.excludedWorkspaces == [Self.dragged]) - #expect(baseOptions.gap == nil) - #expect(gapOptions.gap == DropPosition(section: .machine(.local), index: Self.workers.count + 2)) - #expect(gapOptions.gapHeight == drag.gapHeight) - // Both the drop resolver's base and the actual in-place drag layout retain the host. - let base = SidebarLayout.make(sections: list.listSections, metrics: list.metrics, options: baseOptions) - let gap = SidebarLayout.make(sections: list.listSections, metrics: list.metrics, options: gapOptions) - for layout in [base, gap, list.displayed] { - let header = try #require(layout.row(for: hostKey)) - #expect(header.childCount == before.childCount) - for (index, worker) in Self.workers.enumerated() { - let child = try #require(layout.row(for: .workspace(worker))) - #expect(child.section == .machine(.local)) - #expect(child.group == nil) - #expect(child.siblingIndex == index + 2) - #expect(child.content?.treeDepth == 2) - #expect(layout.rows.filter { $0.key == child.key }.count == 1) - } - } - #expect(base.row(for: key) == nil) - #expect(gap.gapY != nil) - #expect(list.displayed.gapY == list.displayed.row(for: key)?.y) + #expect(list.displayed.hostHeadersShowing) + #expect(drag.target == nil) + #expect(list.displayed.gapY == nil) #expect(list.model.sections[0].workspaces.map(\.id) == [Self.coordinator, Self.plain] + Self.workers + [Self.dragged]) } } From e1095190168aaa0bd6628c49293dc7f79c70f671 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:28:54 +0000 Subject: [PATCH 10/29] fix(sidebar): refuse group and tab drops with host headers Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../Views/SidebarListView+GroupDrag.swift | 11 +++++++++++ .../Views/SidebarListView+TabDrop.swift | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift index e99e341015d5..74dc1204ade3 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift @@ -26,6 +26,17 @@ extension SidebarListViewComponents { /// A pointer move of a held group drag: the slot under the card's centre; the rows move only when it changes. func updateGroupDrag(_ drag: Drag) { + if displayed.hostHeadersShowing { + drag.target = nil + drag.docTarget = nil + if var group = drag.group { + group.slot = group.plan.origin + drag.group = group + } + drag.lift.setRefused(true) + showDragLayout() + return + } if drag.group.map({ $0.revision != model.sectionsRevision }) == true { rebaseGroupDrag(drag) } guard let group = drag.group else { return } let slot = group.plan.slot(cardCentre: groupCardCentre(drag, group)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index 2beff8c8f1f1..40356f068407 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -99,7 +99,7 @@ extension SidebarListViewComponents { /// Ends an external drag and returns what it would do. The App commits /// the proposal (one daemon command) and updates the model. func externalDragEnded() -> SidebarTabDrop? { - let proposal = external?.proposal + let proposal = displayed.hostHeadersShowing ? nil : external?.proposal endExternalDrag(dropping: proposal) return proposal } From b5d3bdaebedb5c9feeda2da7d536557b26f2b292 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:37:55 +0000 Subject: [PATCH 11/29] fix(sidebar): decide host-drop refusal at drag start Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../Logic/SidebarLayout+SessionHosts.swift | 8 ++++++++ .../CmuxNextSidebar/Views/SidebarListDrag.swift | 1 + .../CmuxNextSidebar/Views/SidebarListView+Drag.swift | 11 +++++++++-- .../Views/SidebarListView+GroupDrag.swift | 2 +- .../Views/SidebarListView+TabDrop.swift | 12 ++++++++---- .../CmuxNextAppTests/SidebarSessionHostTests.swift | 9 ++++++--- 6 files changed, 33 insertions(+), 10 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index 0ef76351246d..55ac2c3b02a6 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -159,6 +159,14 @@ nonisolated extension SidebarLayout { layout.rowSpacing = rowSpacing layout.pinnedChatsY = movedPinnedY layout.earlierChatsY = movedEarlierY + if !result.contains(where: { if case .sessionHost = $0.key { true } else { false } }) { + var base = SidebarLayout(rows: rows, totalHeight: totalHeight, gapY: gapY, + gapHeight: gapHeight, gapShift: gapShift) + base.rowSpacing = rowSpacing + base.pinnedChatsY = pinnedChatsY + base.earlierChatsY = earlierChatsY + return base + } return layout } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift index 616b6ef274e5..08dafec2bb39 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift @@ -36,6 +36,7 @@ final class SidebarListDrag { var target: DropTarget? { didSet { if case let .position(position)? = target { lastPosition = position } } } + var refusedAtBegin = false /// The last slot: while the card is over a row's middle /// (`ontoWorkspace`), the list keeps showing it, so nothing moves. private(set) var lastPosition: DropPosition? diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift index 8509a4712be2..d69cc23ca031 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift @@ -79,6 +79,7 @@ extension SidebarListViewComponents { ) drag.grabOffsetX = press.point.x - rowFrame.minX drag.standingWorkspace = standing + drag.refusedAtBegin = displayed.hostHeadersShowing drag.lastY = press.point.y drag.restFrame = rowFrame // A grouped row lifts at the list's inset; its indent comes back only for a drop into a group (morphLift). @@ -105,6 +106,11 @@ extension SidebarListViewComponents { let started = CACurrentMediaTime() defer { lastDragWorkMs = (CACurrentMediaTime() - started) * 1000 } if SidebarListPinDrop.holds(self, drag, at: windowPoint) || offerHandoff(drag, windowPoint: windowPoint) || holdsDragOut(drag, windowPoint: windowPoint) { return } + if drag.refusedAtBegin { + drag.target = nil; drag.docTarget = nil; drag.blockTarget = nil + drag.lift.setRefused(true) + return + } drag.lastWindowPoint = windowPoint let point = convert(windowPoint, from: nil) // The lifted row follows the pointer vertically; x stays locked. A tile has neighbours beside it: it follows both ways. @@ -133,8 +139,9 @@ extension SidebarListViewComponents { func finishDrag(at windowPoint: NSPoint? = nil) { guard let drag else { return } autoscroll.stop() - if SidebarListPinDrop.finish(self, drag) { return } if let windowPoint, finishDragOut(drag, at: windowPoint) { return } // the release decides; none: a programmatic end + if drag.refusedAtBegin { return cancelDrag() } + if SidebarListPinDrop.finish(self, drag) { return } // A group dropped where it came from, or where nothing takes it, moves nothing: it goes back as for a cancel. if let group = drag.group, group.slot == group.plan.origin || group.drops[group.slot] == nil { return cancelDrag() } if let items = drag.docItems, let doc = model.docDrag { @@ -187,7 +194,7 @@ extension SidebarListViewComponents { /// pass after the first), then the list shows the drop as before. private func updateDocDrag(_ drag: Drag, point: NSPoint) { guard let doc = model.docDrag else { return } - guard !displayed.hostHeadersShowing else { + guard !drag.refusedAtBegin else { drag.docTarget = nil drag.target = nil drag.blockTarget = nil diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift index 74dc1204ade3..5f2a9edd9515 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift @@ -26,7 +26,7 @@ extension SidebarListViewComponents { /// A pointer move of a held group drag: the slot under the card's centre; the rows move only when it changes. func updateGroupDrag(_ drag: Drag) { - if displayed.hostHeadersShowing { + if drag.refusedAtBegin { drag.target = nil drag.docTarget = nil if var group = drag.group { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index 40356f068407..a94142b684a1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -49,9 +49,13 @@ extension SidebarListViewComponents { setHovered(nil) } if displayed.hostHeadersShowing { - external.proposal = nil - reload(animated: true) - return nil + switch external.proposal { + case .intoWorkspace?, .beforeTab?: break + default: + external.proposal = nil + reload(animated: true) + return nil + } } autoscroll.update(windowPoint: windowPoint) if let baseY = DropResolver.baseY(forDisplayY: point.y, gapY: displayed.gapY, gapHeight: displayed.gapShift) { @@ -99,7 +103,7 @@ extension SidebarListViewComponents { /// Ends an external drag and returns what it would do. The App commits /// the proposal (one daemon command) and updates the model. func externalDragEnded() -> SidebarTabDrop? { - let proposal = displayed.hostHeadersShowing ? nil : external?.proposal + let proposal = external?.proposal endExternalDrag(dropping: proposal) return proposal } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index 43f83218c947..de03b9fe5dfb 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -124,10 +124,13 @@ import Testing } @Test func missingLocalIdentityNeverTreatsLocalChatsAsFleet() { - let chats = [(Self.parent, [AgentSessionRef(host: "install:unknown", hostName: "This Mac", session: "local")])] - let pass = SidebarSessionTreeFeed.pass(chats, lanes: [:], localHost: nil, pullRequests: [:]) + let chats = [(Self.parent, [AgentSessionRef(host: "install:unknown", hostName: "This Mac", session: "local")]), + (Self.child, [AgentSessionRef(host: "install:unknown", hostName: "This Mac", session: "worker")])] + let recorded = [AgentSessionParents.identity(host: "install:unknown", session: "worker"): + AgentSessionParents.identity(host: "install:unknown", session: "local")] + let pass = SidebarSessionTreeFeed.pass(chats, lanes: [:], recordedParents: recorded, localHost: nil, pullRequests: [:]) #expect(pass.state.hosts.isEmpty) - #expect(pass.state.parents.isEmpty) + #expect(pass.state.parents[Self.child] == Self.parent) } @Test func lineageNestingRemainsInPinnedSectionWhenFleetHostsExist() { From de7799908b5e696e50d805eb01d8d5906988ddf4 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:40:54 +0000 Subject: [PATCH 12/29] fix(sidebar): gate pin drops after host refusal Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift index d69cc23ca031..779599f95a53 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift @@ -105,12 +105,13 @@ extension SidebarListViewComponents { guard let drag else { return } let started = CACurrentMediaTime() defer { lastDragWorkMs = (CACurrentMediaTime() - started) * 1000 } - if SidebarListPinDrop.holds(self, drag, at: windowPoint) || offerHandoff(drag, windowPoint: windowPoint) || holdsDragOut(drag, windowPoint: windowPoint) { return } + if offerHandoff(drag, windowPoint: windowPoint) || holdsDragOut(drag, windowPoint: windowPoint) { return } if drag.refusedAtBegin { drag.target = nil; drag.docTarget = nil; drag.blockTarget = nil drag.lift.setRefused(true) return } + if SidebarListPinDrop.holds(self, drag, at: windowPoint) { return } drag.lastWindowPoint = windowPoint let point = convert(windowPoint, from: nil) // The lifted row follows the pointer vertically; x stays locked. A tile has neighbours beside it: it follows both ways. From 3f09758e780eb7a45510b2cd900ece67d1a16eb2 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:45:51 +0000 Subject: [PATCH 13/29] fix(sidebar): stabilize host refusal and tab proposals Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../CmuxNextSidebar/Logic/SidebarLayout.swift | 5 ++++- .../CmuxNextSidebar/Logic/SidebarRow.swift | 3 --- .../Views/SidebarListView+Drag.swift | 20 ++++++------------- .../Views/SidebarListView+GroupDrag.swift | 11 ---------- .../Views/SidebarListView+TabDrop.swift | 20 ++++++++++--------- .../SidebarSessionHostIntegrationTests.swift | 6 ++++++ 6 files changed, 27 insertions(+), 38 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift index 2cbcff04cfbc..bc624ce84be4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift @@ -453,7 +453,10 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { let byFolder = o.groupsByFolder && section.machine != nil && machineCount == 1 && !filtering guard byFolder else { let fold = SidebarDoneFoldID(section: section.id, group: nil) - let tree = Self.treeRows(nodes.map { $0.node }, tree: (groupsSessions && section.machine != nil) ? nil : o.sessionTree, filtering: filtering) + // Keep ordinary lineage rows in the base projection; host + // buckets are added by groupingSessions after all sections are + // laid out, and may legitimately emit no header. + let tree = Self.treeRows(nodes.map { $0.node }, tree: o.sessionTree, filtering: filtering) let treeRow = Dictionary(tree.map { ($0.index, $0) }, uniquingKeysWith: { first, _ in first }) let drawn = Self.foldingDone(tree.map { ($0.index, $0.depth) }, workspace: { if case let .workspace(ws) = nodes[$0].node { ws } else { nil } }, fold: fold, diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift index 192fa0787cdc..1fa5c9f49b21 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift @@ -40,9 +40,6 @@ public nonisolated struct SidebarRow: Hashable, Sendable { /// Index among the container's siblings, counting only rows not being /// dragged. For group headers this is the group's index in the section. public var siblingIndex: Int - /// The projected insertion slot used by the shared drop reducer. Session host - /// grouping keeps `siblingIndex` as the document identity for selection and - /// drag origins, while this optional slot follows the drawn neighbor. /// For a grouped workspace: the group's index in its section. public var parentIndex: Int? public var isLastInGroup: Bool diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift index 779599f95a53..8331e66b96e7 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Drag.swift @@ -80,6 +80,10 @@ extension SidebarListViewComponents { drag.grabOffsetX = press.point.x - rowFrame.minX drag.standingWorkspace = standing drag.refusedAtBegin = displayed.hostHeadersShowing + if drag.refusedAtBegin { + drag.target = nil + drag.lift.setRefused(true) + } drag.lastY = press.point.y drag.restFrame = rowFrame // A grouped row lifts at the list's inset; its indent comes back only for a drop into a group (morphLift). @@ -106,12 +110,6 @@ extension SidebarListViewComponents { let started = CACurrentMediaTime() defer { lastDragWorkMs = (CACurrentMediaTime() - started) * 1000 } if offerHandoff(drag, windowPoint: windowPoint) || holdsDragOut(drag, windowPoint: windowPoint) { return } - if drag.refusedAtBegin { - drag.target = nil; drag.docTarget = nil; drag.blockTarget = nil - drag.lift.setRefused(true) - return - } - if SidebarListPinDrop.holds(self, drag, at: windowPoint) { return } drag.lastWindowPoint = windowPoint let point = convert(windowPoint, from: nil) // The lifted row follows the pointer vertically; x stays locked. A tile has neighbours beside it: it follows both ways. @@ -120,6 +118,8 @@ extension SidebarListViewComponents { } else { SidebarReorderLift.follow(drag.lift, top: point.y - drag.grabOffsetY, visible: visibleRect) } + if drag.refusedAtBegin { return } + if SidebarListPinDrop.holds(self, drag, at: windowPoint) { return } autoscroll.update(windowPoint: windowPoint) let card = drag.probeCard if point.y != drag.lastY { @@ -195,14 +195,6 @@ extension SidebarListViewComponents { /// pass after the first), then the list shows the drop as before. private func updateDocDrag(_ drag: Drag, point: NSPoint) { guard let doc = model.docDrag else { return } - guard !drag.refusedAtBegin else { - drag.docTarget = nil - drag.target = nil - drag.blockTarget = nil - drag.lift.setRefused(true) - showDragLayout() - return - } if drag.docGeometry == nil { drag.geometryRevision = model.sectionsRevision drag.blockBases = blockBases() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift index 5f2a9edd9515..e99e341015d5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupDrag.swift @@ -26,17 +26,6 @@ extension SidebarListViewComponents { /// A pointer move of a held group drag: the slot under the card's centre; the rows move only when it changes. func updateGroupDrag(_ drag: Drag) { - if drag.refusedAtBegin { - drag.target = nil - drag.docTarget = nil - if var group = drag.group { - group.slot = group.plan.origin - drag.group = group - } - drag.lift.setRefused(true) - showDragLayout() - return - } if drag.group.map({ $0.revision != model.sectionsRevision }) == true { rebaseGroupDrag(drag) } guard let group = drag.group else { return } let slot = group.plan.slot(cardCentre: groupCardCentre(drag, group)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index a94142b684a1..22b50fed50ad 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -48,19 +48,21 @@ extension SidebarListViewComponents { self.external = external setHovered(nil) } - if displayed.hostHeadersShowing { - switch external.proposal { - case .intoWorkspace?, .beforeTab?: break - default: - external.proposal = nil - reload(animated: true) - return nil - } - } autoscroll.update(windowPoint: windowPoint) if let baseY = DropResolver.baseY(forDisplayY: point.y, gapY: displayed.gapY, gapHeight: displayed.gapShift) { let base = SidebarLayout.make(sections: listSections, metrics: metrics, options: options(includeGap: false)) +<<<<<<< HEAD var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine) +======= + var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine, + reordersTabRows: reordersTabRows) + if displayed.hostHeadersShowing { + switch proposal { + case .intoWorkspace?, .beforeTab?: break + default: proposal = nil + } + } +>>>>>>> c38ae523adcf (fix(sidebar): stabilize host refusal and tab proposals) external.slotDeadline = nil if slotDwell > 0, let slot = proposal, case .newWorkspace = slot { let now = CACurrentMediaTime() diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index 3e167c646f6d..9c0bd62a99c0 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -106,6 +106,12 @@ struct SidebarSessionHostIntegrationTests { #expect(list.displayed.hostHeadersShowing) #expect(drag.target == nil) #expect(list.displayed.gapY == nil) + let familyRow = try #require(list.displayed.row(for: .workspace(Self.workers[0]))) + let beforeCardY = drag.lift.frame.minY + list.updateDrag(windowPoint: NSPoint(x: 80, y: familyRow.y + familyRow.height / 2)) + #expect(drag.lift.frame.minY != beforeCardY) + #expect(list.displayed.gapY == nil) + list.finishDrag() #expect(list.model.sections[0].workspaces.map(\.id) == [Self.coordinator, Self.plain] + Self.workers + [Self.dragged]) } } From 282608c4c8b479cecd25c23d49cd668b7db7dcdc Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:47:25 +0000 Subject: [PATCH 14/29] chore(sidebar): remove drag-layout refusal check Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift index 08dafec2bb39..ab1957fc8f2d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift @@ -111,7 +111,6 @@ final class SidebarListDrag { /// edge elsewhere (DropResolver.resolveDrag). func resolve(card: CGRect, displayed: SidebarLayout, base: SidebarLayout, sections: [SidebarSection], ungroupedFirst: Bool) -> DropTarget?? { - guard !displayed.hostHeadersShowing else { return .some(nil) } let leading = movingUp ? card.minY : card.maxY guard let resolved = DropResolver.resolveDrag(centreY: card.midY, leadingY: leading, gapY: displayed.gapY, gapHeight: displayed.gapShift, payload: payload, base: base, sections: sections, ungroupedFirst: ungroupedFirst) else { From 209d3a7fc3761a20df3be86232c3fffa08ede52f Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:53:17 +0000 Subject: [PATCH 15/29] test(sidebar): cover host refusal drag matrix Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../SidebarSessionHostIntegrationTests.swift | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index 9c0bd62a99c0..f9a1c5213a41 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -115,4 +115,64 @@ struct SidebarSessionHostIntegrationTests { #expect(list.model.sections[0].workspaces.map(\.id) == [Self.coordinator, Self.plain] + Self.workers + [Self.dragged]) } } + + /// GUI matrix for the host-group refusal: every in-sidebar target must keep + /// the card moving while showing no gap and must leave the document intact. + @Test func hostGroupRefusalMatrixRunsLegacyAndDocumentPaths() throws { + try Self.withList { list in + SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) + list.reload(animated: false) + let original = list.model.sections[0].workspaces.map(\.id) + let source = SidebarRowKey.workspace(Self.dragged) + + func exercise(_ point: NSPoint, document: Bool) throws { + if document { + list.model.docDrag = SidebarDocDrag( + item: { key in if case let .workspace(id) = key { "workspace-\(id.rawValue)" } else { nil } }, + section: { _ in "machine-local" }, + begin: { ids in Dictionary(uniqueKeysWithValues: ids.map { ($0, SidebarDocAcceptance.none) }) }, + drop: { _, _ in } + ) + } + defer { list.model.docDrag = nil } + let row = try #require(list.displayed.row(for: source)) + let press = SidebarPress(key: source, point: NSPoint(x: 80, y: row.y + row.height / 2)) + list.press = press + list.beginDrag(press) + let drag = try #require(list.drag) + let beforeY = drag.lift.frame.minY + list.updateDrag(windowPoint: point) + #expect(drag.lift.frame.minY != beforeY) + #expect(list.displayed.gapY == nil) + #expect(drag.target == nil) + list.finishDrag() + #expect(list.model.sections[0].workspaces.map(\.id) == original) + } + + let header = try #require(list.displayed.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))) + let family = try #require(list.displayed.row(for: .workspace(Self.workers[0]))) + let plain = try #require(list.displayed.row(for: .workspace(Self.plain))) + let targets = [ + NSPoint(x: 80, y: header.y + header.height / 2), + NSPoint(x: 80, y: family.y + family.height / 2), + NSPoint(x: 80, y: plain.y + plain.height / 2), + NSPoint(x: 80, y: list.displayed.totalHeight - 4), + NSPoint(x: 80, y: 1) + ] + for point in targets { try exercise(point, document: false) } + for point in targets { try exercise(point, document: true) } + + // Control: with no host header, the ordinary resolver still opens a gap. + SidebarSessionTreeFeed.publish(Self.pass(enabled: false), to: .shared) + list.reload(animated: false) + let row = try #require(list.displayed.row(for: source)) + let press = SidebarPress(key: source, point: NSPoint(x: 80, y: row.y + row.height / 2)) + list.press = press + list.beginDrag(press) + let plainControl = try #require(list.displayed.row(for: .workspace(Self.plain))) + list.updateDrag(windowPoint: NSPoint(x: 80, y: plainControl.y + plainControl.height / 2)) + #expect(list.displayed.gapY != nil) + list.cancelDrag() + } + } } From 0510cfc438b0656617741990ca9d80bdac61f83e Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 16:54:01 +0000 Subject: [PATCH 16/29] test(sidebar): cover external tab drop refusal matrix Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../SidebarSessionHostIntegrationTests.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index f9a1c5213a41..7fd99d398c9a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -162,6 +162,16 @@ struct SidebarSessionHostIntegrationTests { for point in targets { try exercise(point, document: false) } for point in targets { try exercise(point, document: true) } + // External tab drops use the same host-header gate only for + // structural reorders; taking a tab into an existing workspace is + // still accepted. + let workspacePoint = NSPoint(x: 80, y: plain.y + plain.height / 2) + #expect(list.externalDragMoved(windowPoint: workspacePoint, sourceMachine: nil) != nil) + list.externalDragExited() + let endPoint = NSPoint(x: 80, y: list.displayed.totalHeight - 4) + #expect(list.externalDragMoved(windowPoint: endPoint, sourceMachine: nil) == nil) + #expect(list.externalDragEnded() == nil) + // Control: with no host header, the ordinary resolver still opens a gap. SidebarSessionTreeFeed.publish(Self.pass(enabled: false), to: .shared) list.reload(animated: false) From 3e968b70266623f899c19cf12b55d6a7f2804547 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Fri, 30 Oct 2026 20:19:45 +0000 Subject: [PATCH 17/29] test(sidebar): disambiguate sections and isolate GUI matrix Sidebar-Look: no visual change Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../SidebarSessionHostIntegrationTests.swift | 6 ++-- .../SidebarSessionHostTests.swift | 32 +++++++++---------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index 7fd99d398c9a..29780adf6afd 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -27,7 +27,7 @@ struct SidebarSessionHostIntegrationTests { return pass } - private static func withList(_ body: (SidebarListView) throws -> Void) rethrows { + @MainActor private static func withList(_ body: (SidebarListView) throws -> Void) rethrows { _ = NSApplication.shared let tree = SidebarSessionTree.shared let savedState = tree.state @@ -43,7 +43,7 @@ struct SidebarSessionHostIntegrationTests { SidebarChatHistory.shared.state = nil let workspace = { (id: WorkspaceID) in SidebarNode.workspace(SidebarWorkspace(id: id, title: id.rawValue)) } let nodes = [workspace(coordinator), workspace(plain)] + workers.map(workspace) + [workspace(dragged)] - let section = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: nodes) + let section = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: nodes) let model = SidebarModel(sections: [section], activeWorkspaceID: dragged) model.showWorkspaceTabs = false model.groupsByComputer = false @@ -125,7 +125,7 @@ struct SidebarSessionHostIntegrationTests { let original = list.model.sections[0].workspaces.map(\.id) let source = SidebarRowKey.workspace(Self.dragged) - func exercise(_ point: NSPoint, document: Bool) throws { + @MainActor func exercise(_ point: NSPoint, document: Bool) throws { if document { list.model.docDrag = SidebarDocDrag( item: { key in if case let .workspace(id) = key { "workspace-\(id.rawValue)" } else { nil } }, diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index de03b9fe5dfb..df52a53aa047 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -18,17 +18,17 @@ import Testing localHost: "install:local", pullRequests: [:]).state } - private static func sections(parentPresent: Bool = true, crossMachine: Bool = false) -> [SidebarSection] { + private static func sections(parentPresent: Bool = true, crossMachine: Bool = false) -> [CmuxNextSidebar.SidebarSection] { let parentRow = SidebarWorkspace(id: parent, title: "Coordinator") let childRow = SidebarWorkspace(id: child, title: "Worker") let unrelated = SidebarWorkspace(id: other, title: "Shell") let local = SidebarMachine(id: .local, name: "This Mac", kind: .local) if crossMachine { let remote = SidebarMachine(id: MachineID("remote"), name: "Remote", kind: .ssh) - return [SidebarSection(kind: .machine(local), nodes: parentPresent ? [.workspace(parentRow), .workspace(unrelated)] : [.workspace(unrelated)]), - SidebarSection(kind: .machine(remote), nodes: [.workspace(childRow)])] + return [CmuxNextSidebar.SidebarSection(kind: .machine(local), nodes: parentPresent ? [.workspace(parentRow), .workspace(unrelated)] : [.workspace(unrelated)]), + CmuxNextSidebar.SidebarSection(kind: .machine(remote), nodes: [.workspace(childRow)])] } - return [SidebarSection(kind: .machine(local), nodes: + return [CmuxNextSidebar.SidebarSection(kind: .machine(local), nodes: (parentPresent ? [.workspace(parentRow)] : []) + [.workspace(unrelated), .workspace(childRow)])] } @@ -104,8 +104,8 @@ import Testing } @Test func pinnedParentDoesNotPullFleetChildAcrossSectionBoundary() { - let pinned = SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "Pinned"))]) - let machine = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + let pinned = CmuxNextSidebar.SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "Pinned"))]) + let machine = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: [.workspace(SidebarWorkspace(id: Self.child, title: "Worker"))]) var options = SidebarLayoutOptions(); options.sessionTree = Self.state() let layout = SidebarLayout.make(sections: [pinned, machine], metrics: .standard, options: options) @@ -114,9 +114,9 @@ import Testing } @Test func pinnedChildKeepsPinnedPlacementWhenItsParentIsAVisibleFleetLane() { - let machine = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + let machine = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "Coordinator"))]) - let pinned = SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: Self.child, title: "Pinned worker"))]) + let pinned = CmuxNextSidebar.SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: Self.child, title: "Pinned worker"))]) var options = SidebarLayoutOptions(); options.sessionTree = Self.state() let layout = SidebarLayout.make(sections: [machine, pinned], metrics: .standard, options: options) #expect(layout.row(for: .workspace(Self.child))?.section == .pinned) @@ -134,11 +134,11 @@ import Testing } @Test func lineageNestingRemainsInPinnedSectionWhenFleetHostsExist() { - let pinned = SidebarSection(kind: .pinned, nodes: [ + let pinned = CmuxNextSidebar.SidebarSection(kind: .pinned, nodes: [ .workspace(SidebarWorkspace(id: Self.parent, title: "Pinned coordinator")), .workspace(SidebarWorkspace(id: Self.child, title: "Pinned worker")), ]) - let machine = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + let machine = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: [.workspace(SidebarWorkspace(id: Self.other, title: "Remote root"))]) var options = SidebarLayoutOptions(); options.sessionTree = Self.state() let layout = SidebarLayout.make(sections: [pinned, machine], metrics: .standard, options: options) @@ -149,8 +149,8 @@ import Testing @Test func hostGroupsStaySeparatedByMachineSection() { let first = SidebarMachine(id: MachineID("one"), name: "One", kind: .ssh) let second = SidebarMachine(id: MachineID("two"), name: "Two", kind: .ssh) - let one = SidebarSection(kind: .machine(first), nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "One root"))]) - let two = SidebarSection(kind: .machine(second), nodes: [.workspace(SidebarWorkspace(id: Self.other, title: "Two root"))]) + let one = CmuxNextSidebar.SidebarSection(kind: .machine(first), nodes: [.workspace(SidebarWorkspace(id: Self.parent, title: "One root"))]) + let two = CmuxNextSidebar.SidebarSection(kind: .machine(second), nodes: [.workspace(SidebarWorkspace(id: Self.other, title: "Two root"))]) var state = Self.state(); state.hosts[Self.other] = Self.host var options = SidebarLayoutOptions(); options.sessionTree = state let layout = SidebarLayout.make(sections: [one, two], metrics: .standard, options: options) @@ -170,7 +170,7 @@ import Testing @Test func explicitUserGroupKeepsItsStoredPlacement() { let group = SidebarGroup(id: GroupID("user-group"), name: "My project", workspaces: [SidebarWorkspace(id: Self.child, title: "Worker")]) - let section = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + let section = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: [.group(group)]) var options = SidebarLayoutOptions() options.sessionTree = Self.state() @@ -182,7 +182,7 @@ import Testing @Test func looseChildFollowsVisibleParentInsideAnExplicitUserGroup() { let group = SidebarGroup(id: GroupID("project"), name: "Project", workspaces: [SidebarWorkspace(id: Self.parent, title: "Coordinator")]) - let section = SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + let section = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: [.group(group), .workspace(SidebarWorkspace(id: Self.child, title: "Worker"))]) var options = SidebarLayoutOptions() options.sessionTree = Self.state() @@ -253,7 +253,7 @@ import Testing @Test func historyAndSectionGapsStayAtTheirBoundariesAfterReorderingAndFolding() throws { let chat = SidebarHistoryChat(id: "old", title: "Earlier chat", updatedAt: .distantPast) let history = SidebarChatHistoryState(pinned: [chat], earlier: [chat]) - let tail = SidebarSection(kind: .custom(SidebarCustomSection(id: "tail")), nodes: []) + let tail = CmuxNextSidebar.SidebarSection(kind: .custom(SidebarCustomSection(id: "tail")), nodes: []) for hasTail in [false, true] { for folded in [false, true] { var options = SidebarLayoutOptions() @@ -285,7 +285,7 @@ import Testing } @Test func pinnedHistoryAfterAnExplicitSectionStaysAboveTheHostHeader() throws { - let pinned = SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: WorkspaceID("pin"), title: "Pinned"))]) + let pinned = CmuxNextSidebar.SidebarSection(kind: .pinned, nodes: [.workspace(SidebarWorkspace(id: WorkspaceID("pin"), title: "Pinned"))]) let history = SidebarChatHistoryState(pinned: [.init(id: "chat", title: "Chat", updatedAt: .distantPast)]) var options = SidebarLayoutOptions() options.sessionTree = Self.state() From 4739057c9d84499d4ee7aae796e632061f96434e Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sat, 31 Oct 2026 04:29:48 +0000 Subject: [PATCH 18/29] fix(sidebar): keep folded families and cross-group lineage in host grouping Code (parentAndHostFoldsKeepTheWholeBadgeCount): the base projection already drops the loose descendants of a folded parent, so groupingSessions saw a childless parent, wiped its .collapsed chevron and counted one row in the host badge. It now carries those folded descendants as undrawn entries, so the fold, roll-up and badge count the whole family. Code (looseChildFollowsVisibleParentInsideAnExplicitUserGroup): when no host header was drawn (the parent sits in a user group), groupingSessions fell back to the base projection and threw away the cross-list nesting it had just built. It now keeps its result whenever lineage nested a row the base drew as a root. Test (hostGroupRefusalMatrixRunsLegacyAndDocumentPaths): the matrix passed list coordinates as window points. The list is flipped, so the external drop aimed at "plain" landed below the last row (a new-workspace slot the host gate refuses). Points now go through list.convert(_:to: nil), as the other sidebar GUI tests do. Sidebar-Look: no visual change Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-63b9964940c20354b639 --- .../Logic/SidebarLayout+SessionHosts.swift | 35 ++++++++++++++++--- .../SidebarSessionHostIntegrationTests.swift | 11 +++--- 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index 55ac2c3b02a6..c1b0f4df4c59 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -20,7 +20,28 @@ nonisolated extension SidebarLayout { } bundles[i] = bundle } - let ids: [WorkspaceID?] = starts.map { if case let .workspace(id) = rows[$0].key { id } else { nil } } + let drawnIDs: [WorkspaceID?] = starts.map { if case let .workspace(id) = rows[$0].key { id } else { nil } } + // The base projection already dropped the descendants of a folded loose parent. Keep + // them as undrawn entries after the drawn ones (indices past `starts`) so that parent + // keeps its chevron and roll-up and its host badge counts the whole family. They never + // draw: `family` stops at a folded parent, and roots are drawn entries only. + let drawn = Set(drawnIDs.compactMap { $0 }) + var seenFolded: Set = [] + // Only loose rows fold away with their parent (a group's members never do). + let loose = sections.flatMap(\.nodes).compactMap { node -> WorkspaceID? in + if case let .workspace(ws) = node { ws.id } else { nil } + } + let folded = loose.filter { id in + guard !drawn.contains(id), seenFolded.insert(id).inserted else { return false } + var path: Set = [id] + var next = tree.parents[id] + while let current = next, path.insert(current).inserted { + if drawn.contains(current) { return tree.collapsed.contains(current) } + next = tree.parents[current] + } + return false + } + let ids: [WorkspaceID?] = drawnIDs + folded.map { Optional($0) } // A visible parent inside an explicit user group is still a lineage anchor. Only // loose children move; explicitly placed members keep the user's document order. let looseIDs = Set(starts.compactMap { i -> WorkspaceID? in @@ -36,9 +57,10 @@ nonisolated extension SidebarLayout { // Preserve the Pinned/custom boundary: a fleet child of a pinned workspace // remains in its own machine group rather than being pulled into Pinned. let parents = tree.parents.filter { looseIDs.contains($0.key) && machineParents.contains($0.value) } + .merging(folded.compactMap { id in tree.parents[id].map { (id, $0) } }, uniquingKeysWith: { first, _ in first }) let children = Self.treeChildren(ids, parents: parents) let nested = Set(children.values.joined()) - let roots = ids.indices.filter { !nested.contains($0) } + let roots = starts.indices.filter { !nested.contains($0) } struct HostKey: Hashable { let host: String let section: SectionID @@ -101,7 +123,7 @@ nonisolated extension SidebarLayout { y += row.height + spacing } func family(_ root: Int, depth: Int, groupDepth: Int = 0) { - guard let id = ids[root], var bundle = bundles[starts[root]], !bundle.isEmpty else { return } + guard root < starts.count, let id = ids[root], var bundle = bundles[starts[root]], !bundle.isEmpty else { return } let (fold, rollUp) = Self.treeFold(root, ids, tree: tree, children: children, states: agentState) bundle[0].content?.treeDepth = depth if bundle[0].group == nil || fold != nil { @@ -159,7 +181,12 @@ nonisolated extension SidebarLayout { layout.rowSpacing = rowSpacing layout.pinnedChatsY = movedPinnedY layout.earlierChatsY = movedEarlierY - if !result.contains(where: { if case .sessionHost = $0.key { true } else { false } }) { + // With no host header drawn, the base projection stands unless lineage moved a row: + // a loose child nested under a parent outside its own list (a user group's member), + // which the base projection drew as a root. + let regrouped = result.contains(where: { if case .sessionHost = $0.key { true } else { false } }) + || nested.contains { $0 < starts.count && (rows[starts[$0]].content?.treeDepth ?? 0) == 0 } + if !regrouped { var base = SidebarLayout(rows: rows, totalHeight: totalHeight, gapY: gapY, gapHeight: gapHeight, gapShift: gapShift) base.rowSpacing = rowSpacing diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index 29780adf6afd..20684d8f89cf 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -108,7 +108,7 @@ struct SidebarSessionHostIntegrationTests { #expect(list.displayed.gapY == nil) let familyRow = try #require(list.displayed.row(for: .workspace(Self.workers[0]))) let beforeCardY = drag.lift.frame.minY - list.updateDrag(windowPoint: NSPoint(x: 80, y: familyRow.y + familyRow.height / 2)) + list.updateDrag(windowPoint: list.convert(NSPoint(x: 80, y: familyRow.y + familyRow.height / 2), to: nil)) #expect(drag.lift.frame.minY != beforeCardY) #expect(list.displayed.gapY == nil) list.finishDrag() @@ -125,6 +125,7 @@ struct SidebarSessionHostIntegrationTests { let original = list.model.sections[0].workspaces.map(\.id) let source = SidebarRowKey.workspace(Self.dragged) + // Targets are list points (the list is flipped); the drag and drop entry points take window points. @MainActor func exercise(_ point: NSPoint, document: Bool) throws { if document { list.model.docDrag = SidebarDocDrag( @@ -141,7 +142,7 @@ struct SidebarSessionHostIntegrationTests { list.beginDrag(press) let drag = try #require(list.drag) let beforeY = drag.lift.frame.minY - list.updateDrag(windowPoint: point) + list.updateDrag(windowPoint: list.convert(point, to: nil)) #expect(drag.lift.frame.minY != beforeY) #expect(list.displayed.gapY == nil) #expect(drag.target == nil) @@ -166,10 +167,10 @@ struct SidebarSessionHostIntegrationTests { // structural reorders; taking a tab into an existing workspace is // still accepted. let workspacePoint = NSPoint(x: 80, y: plain.y + plain.height / 2) - #expect(list.externalDragMoved(windowPoint: workspacePoint, sourceMachine: nil) != nil) + #expect(list.externalDragMoved(windowPoint: list.convert(workspacePoint, to: nil), sourceMachine: nil) != nil) list.externalDragExited() let endPoint = NSPoint(x: 80, y: list.displayed.totalHeight - 4) - #expect(list.externalDragMoved(windowPoint: endPoint, sourceMachine: nil) == nil) + #expect(list.externalDragMoved(windowPoint: list.convert(endPoint, to: nil), sourceMachine: nil) == nil) #expect(list.externalDragEnded() == nil) // Control: with no host header, the ordinary resolver still opens a gap. @@ -180,7 +181,7 @@ struct SidebarSessionHostIntegrationTests { list.press = press list.beginDrag(press) let plainControl = try #require(list.displayed.row(for: .workspace(Self.plain))) - list.updateDrag(windowPoint: NSPoint(x: 80, y: plainControl.y + plainControl.height / 2)) + list.updateDrag(windowPoint: list.convert(NSPoint(x: 80, y: plainControl.y + plainControl.height / 2), to: nil)) #expect(list.displayed.gapY != nil) list.cancelDrag() } From 6b478a95c3780d4206c3de3a9748ad293178b415 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sat, 31 Oct 2026 04:49:36 +0000 Subject: [PATCH 19/29] fix(sidebar): keep cross-machine lineage inside headed machine sections With per-computer headers drawn, groupingSessions nested a child from a later machine section under its parent recursively, so the child drew under the previous machine's header. A child now follows a parent in another section only when neither section draws a header (one list). Adds a non-flattened, multi-section layout test. Sidebar-Look: no visual change Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-63b9964940c20354b639 --- .../Logic/SidebarLayout+SessionHosts.swift | 14 +++++++++++++- .../SidebarSessionHostTests.swift | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index c1b0f4df4c59..61408258b8ba 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -54,9 +54,21 @@ nonisolated extension SidebarLayout { case .machine = rows[i].section else { return nil } return id }) + // A child crosses into another machine section only in one list, where neither + // section draws a header. Under per-computer headers it stays below its own + // machine's header rather than drawing under the previous machine's. + let headed = Set(rows.compactMap { row -> SectionID? in if case let .section(id) = row.key { id } else { nil } }) + let sectionOf = Dictionary(starts.compactMap { i -> (WorkspaceID, SectionID)? in + if case let .workspace(id) = rows[i].key { (id, rows[i].section) } else { nil } + }, uniquingKeysWith: { first, _ in first }) + func crossesHeader(_ child: WorkspaceID, _ parent: WorkspaceID) -> Bool { + guard let a = sectionOf[child], let b = sectionOf[parent], a != b else { return false } + return headed.contains(a) || headed.contains(b) + } // Preserve the Pinned/custom boundary: a fleet child of a pinned workspace // remains in its own machine group rather than being pulled into Pinned. - let parents = tree.parents.filter { looseIDs.contains($0.key) && machineParents.contains($0.value) } + let parents = tree.parents.filter { looseIDs.contains($0.key) && machineParents.contains($0.value) + && !crossesHeader($0.key, $0.value) } .merging(folded.compactMap { id in tree.parents[id].map { (id, $0) } }, uniquingKeysWith: { first, _ in first }) let children = Self.treeChildren(ids, parents: parents) let nested = Set(children.values.joined()) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index df52a53aa047..bc865773021a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -71,6 +71,23 @@ import Testing #expect(layout.row(for: .sessionHost(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.childCount == 2) } + @Test func crossMachineChildStaysUnderItsOwnMachineHeaderWhenMachinesAreHeaded() throws { + var options = SidebarLayoutOptions() + options.flattensMachines = false + options.sessionTree = Self.state(crossHost: true) + let layout = SidebarLayout.make(sections: Self.sections(crossMachine: true), metrics: .standard, options: options) + let keys = layout.rows.map(\.key) + let remoteHeader = try #require(keys.firstIndex(of: .section(.machine(MachineID("remote"))))) + let child = try #require(keys.firstIndex(of: .workspace(Self.child))) + #expect(child > remoteHeader, "a child must not draw under the previous machine's header") + #expect(layout.row(for: .workspace(Self.child))?.section == .machine(MachineID("remote"))) + #expect(layout.row(for: .workspace(Self.parent))?.content?.treeFold == nil) + for (index, row) in layout.rows.enumerated() where row.key != .section(row.section) { + let header = keys[.. Date: Sat, 31 Oct 2026 04:56:36 +0000 Subject: [PATCH 20/29] test(sidebar): sessionHosts capture fixture for the session tree host groups debug.sidebar_nested_fixture gains a sessionHosts scenario: the needsYou rows and lineage with synthetic fleet hosts on their agent tabs, so a capture shows the host headers. Its before is the existing needsYou scenario (the same rows, no hosts), which the merge-base also has. Sidebar-Look: no visual change Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-63b9964940c20354b639 --- .../Control/DebugSidebarNestedFixture.swift | 4 +++- .../Model/SidebarNestedFixture.swift | 22 +++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift index f698fd10f947..f1d080d32a23 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift @@ -38,8 +38,10 @@ struct DebugSidebarNestedFixture { sidebar.model.filterText = "" sidebar.rows.fixture = fixture.sections // The needs-you scenario's who-started-whom, while the session tree is on (the feed's next pass replaces it). - if !fixture.parents.isEmpty, var tree = SidebarSessionTree.shared.state { + if !fixture.parents.isEmpty || !fixture.hosts.isEmpty, var tree = SidebarSessionTree.shared.state { tree.parents.merge(fixture.parents) { _, fixture in fixture } + tree.hosts.merge(fixture.hosts) { _, fixture in fixture } + tree.hostNames.merge(fixture.hostNames) { _, fixture in fixture } SidebarSessionTree.shared.state = tree } sidebar.container.layoutSubtreeIfNeeded() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift index 12efe6de2401..ba837f229624 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift @@ -38,6 +38,9 @@ public nonisolated struct SidebarNestedFixture: Sendable { /// beside a group of one differently named member and a group of two (Leo 2026-10-29: "why is there all /// this weird stuff at the bottom of the sidebar"). case soleMember + /// ``needsYou``'s rows with fleet hosts on their agent tabs: the session tree's host groups + /// (`SidebarLayout.groupingSessions`). Its before is ``needsYou`` (the same rows, no hosts). + case sessionHosts } /// The state this fixture captures. @@ -47,11 +50,26 @@ public nonisolated struct SidebarNestedFixture: Sendable { /// Who started whom (the session tree's `parents`), for ``Scenario/needsYou``; empty for the others. public var parents: [WorkspaceID: WorkspaceID] { - guard scenario == .needsYou else { return [:] } + guard scenario == .needsYou || scenario == .sessionHosts else { return [:] } let links = ["settings": "release", "shrink": "settings", "notes": "release", "changelog": "notes"] return Dictionary(uniqueKeysWithValues: links.map { (WorkspaceID("w-\($0.key)"), WorkspaceID("w-\($0.value)")) }) } + /// Each workspace's fleet host (the session tree's `hosts`), for ``Scenario/sessionHosts``; the + /// rows left out stay local. Synthetic names only. + public var hosts: [WorkspaceID: String] { + guard scenario == .sessionHosts else { return [:] } + let hosts = ["release": "registry:build-mac", "settings": "registry:build-mac", "shrink": "registry:build-mac", + "notes": "registry:build-mac", "changelog": "registry:build-mac", + "flaky": "registry:ci-runner", "login": "registry:ci-runner"] + return Dictionary(uniqueKeysWithValues: hosts.map { (WorkspaceID("w-\($0.key)"), $0.value) }) + } + + /// The display names of ``hosts``. + public var hostNames: [String: String] { + scenario == .sessionHosts ? ["registry:build-mac": "Build Mac", "registry:ci-runner": "CI runner"] : [:] + } + /// The sidebar width the scenario is captured at. public var width: Double { scenario == .narrow ? 196 : 288 } /// The old rails (one per group, stopping at its own last member), for ``Scenario/before``. @@ -99,7 +117,7 @@ public nonisolated struct SidebarNestedFixture: Sendable { nodes = Self.sixLevels(folded: ["g-builders", "g-sidebar"]) case .tallGroup: nodes = Self.tallGroup - case .needsYou: + case .needsYou, .sessionHosts: nodes = Self.needsYouRows.map(SidebarNode.workspace) case .soleMember: nodes = Self.soleMembers From 32a9bc1e68a8956c25fc35c28dab400aea6ab381 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 1 Nov 2026 01:40:03 +0000 Subject: [PATCH 21/29] fix(sidebar): resolve host tab drop merge markers Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift index 7060a4a67c8d..d23f54f110b2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift @@ -44,4 +44,3 @@ public nonisolated enum SidebarCategory: Hashable, Sendable { peer == nil ? .agentSession : .fleetSession } } - From a7c3c7a72e6e02c85bc13c46c6df5e86f71806b7 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 1 Nov 2026 01:40:40 +0000 Subject: [PATCH 22/29] fix(sidebar): remove stale conflict markers Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../CmuxNextSidebar/Views/SidebarListView+TabDrop.swift | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index 22b50fed50ad..a4cb28aa821b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -51,9 +51,6 @@ extension SidebarListViewComponents { autoscroll.update(windowPoint: windowPoint) if let baseY = DropResolver.baseY(forDisplayY: point.y, gapY: displayed.gapY, gapHeight: displayed.gapShift) { let base = SidebarLayout.make(sections: listSections, metrics: metrics, options: options(includeGap: false)) -<<<<<<< HEAD - var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine) -======= var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine, reordersTabRows: reordersTabRows) if displayed.hostHeadersShowing { @@ -62,7 +59,6 @@ extension SidebarListViewComponents { default: proposal = nil } } ->>>>>>> c38ae523adcf (fix(sidebar): stabilize host refusal and tab proposals) external.slotDeadline = nil if slotDwell > 0, let slot = proposal, case .newWorkspace = slot { let now = CACurrentMediaTime() From 8cd1fd1a93a9b5aae1819b53e8e1594dc85e02c2 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 1 Nov 2026 01:43:31 +0000 Subject: [PATCH 23/29] fix(sidebar): group current workspace rows after tab removal Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../Logic/SidebarLayout+SessionHosts.swift | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index 61408258b8ba..10084cfe3e89 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -7,18 +7,10 @@ nonisolated extension SidebarLayout { func groupingSessions(_ tree: SidebarSessionTreeState, sections: [SidebarSection], gap: DropPosition?, metrics m: SidebarLayoutMetrics) -> SidebarLayout { var bundles: [Int: [SidebarRow]] = [:] var starts: [Int] = [] - var tabRows: Set = [] for (i, row) in rows.enumerated() { guard case let .workspace(id) = row.key else { continue } starts.append(i) - var bundle = [row] - var next = i + 1 - while next < rows.count, case let .tab(workspace, _) = rows[next].key, workspace == id { - bundle.append(rows[next]) - tabRows.insert(next) - next += 1 - } - bundles[i] = bundle + bundles[i] = [row] } let drawnIDs: [WorkspaceID?] = starts.map { if case let .workspace(id) = rows[$0].key { id } else { nil } } // The base projection already dropped the descendants of a folded loose parent. Keep @@ -159,7 +151,6 @@ nonisolated extension SidebarLayout { } for (index, row) in rows.enumerated() { boundary(from: index == 0 ? 0 : rows[index - 1].maxY + m.rowSpacing, to: row.y) - if tabRows.contains(index) { continue } guard let root = byStart[index] else { append(row, spacing: m.rowSpacing) continue From d26ad290eb1f957ec9c55ce79d899a126aede5e1 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 1 Nov 2026 01:47:18 +0000 Subject: [PATCH 24/29] fix(sidebar): use current tab-drop resolver signature Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../CmuxNextSidebar/Views/SidebarListView+TabDrop.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index a4cb28aa821b..9161c7e8adda 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -51,8 +51,7 @@ extension SidebarListViewComponents { autoscroll.update(windowPoint: windowPoint) if let baseY = DropResolver.baseY(forDisplayY: point.y, gapY: displayed.gapY, gapHeight: displayed.gapShift) { let base = SidebarLayout.make(sections: listSections, metrics: metrics, options: options(includeGap: false)) - var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine, - reordersTabRows: reordersTabRows) + var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine) if displayed.hostHeadersShowing { switch proposal { case .intoWorkspace?, .beforeTab?: break From 43288ae77f7dc00205261a4bcacbc0c01053095d Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 1 Nov 2026 01:53:07 +0000 Subject: [PATCH 25/29] fix(sidebar): use supported tab drop targets Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index 9161c7e8adda..b2eccd472bfd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -54,7 +54,7 @@ extension SidebarListViewComponents { var proposal = DropResolver.resolveTabDrop(y: baseY, base: base, sections: model.sections, sourceMachine: sourceMachine) if displayed.hostHeadersShowing { switch proposal { - case .intoWorkspace?, .beforeTab?: break + case .intoWorkspace?: break default: proposal = nil } } From a4d09dab84aa5cbed9c9e3dff64e1204d752b6eb Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 1 Nov 2026 02:01:12 +0000 Subject: [PATCH 26/29] test(sidebar): remove retired tab-row fixture setting Agent-Session: https://cmux.com/deeplink/agent?id=aid-9d89b5685bb17a5e172b --- .../CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift | 2 +- .../CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index 10084cfe3e89..cf3e8def8313 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -8,7 +8,7 @@ nonisolated extension SidebarLayout { var bundles: [Int: [SidebarRow]] = [:] var starts: [Int] = [] for (i, row) in rows.enumerated() { - guard case let .workspace(id) = row.key else { continue } + guard case .workspace = row.key else { continue } starts.append(i) bundles[i] = [row] } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift index 20684d8f89cf..bbf725e3b4f0 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -45,7 +45,6 @@ struct SidebarSessionHostIntegrationTests { let nodes = [workspace(coordinator), workspace(plain)] + workers.map(workspace) + [workspace(dragged)] let section = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: nodes) let model = SidebarModel(sections: [section], activeWorkspaceID: dragged) - model.showWorkspaceTabs = false model.groupsByComputer = false let list = SidebarListView(model: model) let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 280, height: 1000), styleMask: [.borderless], From f22d4592ec43f81adb184b2f66e3c35513994e7f Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 8 Nov 2026 08:20:14 +0000 Subject: [PATCH 27/29] sidebar: the nested fixture's session tree merge lives in CmuxNextSidebar The base merge's fixture hosts grew CmuxNextApp by two lines; the merge is a SidebarSessionTreeState method now, and the App calls it in one line. Sidebar-Look: no visual change Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-fab1a60f36c01dfa7f5b --- .../Control/DebugSidebarNestedFixture.swift | 7 +------ .../CmuxNextSidebar/Model/SidebarNestedFixture.swift | 11 +++++++++++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift index 457e90f7193e..c3b5e216e58b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift @@ -38,12 +38,7 @@ struct DebugSidebarNestedFixture { sidebar.model.filterText = "" sidebar.rows.fixture = fixture.sections // The needs-you scenario's who-started-whom, while the session tree is on (the feed's next pass replaces it). - if !fixture.parents.isEmpty || !fixture.hosts.isEmpty, var tree = SidebarSessionTree.shared.state { - tree.parents.merge(fixture.parents) { _, fixture in fixture } - tree.hosts.merge(fixture.hosts) { _, fixture in fixture } - tree.hostNames.merge(fixture.hostNames) { _, fixture in fixture } - SidebarSessionTree.shared.state = tree - } + if var tree = SidebarSessionTree.shared.state, tree.merge(fixture) { SidebarSessionTree.shared.state = tree } sidebar.container.layoutSubtreeIfNeeded() sidebar.container.showNestedFixture(fixture) return .object(["scenario": .string(scenario.rawValue), "width": .number(fixture.width), diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift index ba837f229624..0e30fa765b0d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift @@ -217,4 +217,15 @@ public nonisolated struct SidebarNestedFixture: Sendable { ] } } + +public extension SidebarSessionTreeState { + /// Lays a fixture's who-started-whom and hosts over the live tree. False when the fixture has neither. + mutating func merge(_ fixture: SidebarNestedFixture) -> Bool { + guard !fixture.parents.isEmpty || !fixture.hosts.isEmpty else { return false } + parents.merge(fixture.parents) { _, fixture in fixture } + hosts.merge(fixture.hosts) { _, fixture in fixture } + hostNames.merge(fixture.hostNames) { _, fixture in fixture } + return true + } +} #endif From 26e56effb86b9c5d9ef2d1483f8dfdd5a913fa0a Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 8 Nov 2026 08:27:52 +0000 Subject: [PATCH 28/29] sidebar: test that a host header never takes a Pinned parent's fold away Sidebar-Look: no visual change Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-fab1a60f36c01dfa7f5b --- .../SidebarSessionHostTests.swift | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift index bc865773021a..cc167a1b5a07 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -163,6 +163,24 @@ import Testing #expect(layout.row(for: .workspace(Self.child))?.section == .pinned) } + /// A host header elsewhere in the list never takes a Pinned parent's own fold control away. + @Test func pinnedParentKeepsItsFoldWhenAFleetHostHeaderShows() throws { + let pinned = CmuxNextSidebar.SidebarSection(kind: .pinned, nodes: [ + .workspace(SidebarWorkspace(id: Self.parent, title: "Pinned coordinator")), + .workspace(SidebarWorkspace(id: Self.child, title: "Pinned worker")), + ]) + let machine = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), + nodes: [.workspace(SidebarWorkspace(id: Self.other, title: "Fleet lane"))]) + var state = Self.state() + state.hosts[Self.other] = "registry:fleet" + var options = SidebarLayoutOptions(); options.sessionTree = state + let layout = SidebarLayout.make(sections: [pinned, machine], metrics: .standard, options: options) + #expect(layout.rows.contains { if case .sessionHost = $0.key { true } else { false } }, "the fleet lane draws a host header") + #expect(layout.row(for: .workspace(Self.parent))?.content?.treeFold == .expanded, "the Pinned parent keeps its disclosure") + #expect(layout.row(for: .workspace(Self.child))?.content?.treeDepth == 1) + #expect(layout.row(for: .workspace(Self.child))?.section == .pinned) + } + @Test func hostGroupsStaySeparatedByMachineSection() { let first = SidebarMachine(id: MachineID("one"), name: "One", kind: .ssh) let second = SidebarMachine(id: MachineID("two"), name: "Two", kind: .ssh) From 6e760a3ba34702f7347a9325d70bba9a537b0c3a Mon Sep 17 00:00:00 2001 From: Leo Li Date: Sun, 8 Nov 2026 08:28:00 +0000 Subject: [PATCH 29/29] sidebar: a host header keeps a Pinned or custom parent's fold control family() recomputed every root's fold from the regrouped parent map, which leaves Pinned and custom-section lineage out on purpose; a Pinned parent's working disclosure became nil as soon as any fleet lane drew a host header. Only loose machine rows take the regrouped fold now. Found by the router review at f22d4592. Sidebar-Look: no visual change Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-fab1a60f36c01dfa7f5b --- .../CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift index cf3e8def8313..113f1d5382ff 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -130,7 +130,9 @@ nonisolated extension SidebarLayout { guard root < starts.count, let id = ids[root], var bundle = bundles[starts[root]], !bundle.isEmpty else { return } let (fold, rollUp) = Self.treeFold(root, ids, tree: tree, children: children, states: agentState) bundle[0].content?.treeDepth = depth - if bundle[0].group == nil || fold != nil { + // Pinned and custom rows keep the base projection's fold: their lineage is left out of + // `parents` above, so a nil here means "not regrouped", not "no children". + if fold != nil || (bundle[0].group == nil && machineParents.contains(id)) { bundle[0].content?.treeFold = fold bundle[0].content?.rollUp = rollUp }