diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift index a0166788f019..ab916ce32fc1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentLanes/SidebarSessionTreeFeed.swift @@ -149,6 +149,21 @@ public final class SidebarSessionTreeFeed { return nil } var state = SidebarSessionTreeState() + // 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 = [] // Even daemon-provided lineage can be cyclic after a corrupted replay or two peers @@ -193,6 +208,11 @@ public final class SidebarSessionTreeFeed { state.parents[id] = parent } } + if localHost == nil { + // Without this install's identity, fleet buckets stay off. Recorded + // lineage remains useful and is still projected by Session Tree. + state.hosts.removeAll() + } return Pass(state: state, asks: asks) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift index 170396a7beb1..c3b5e216e58b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugSidebarNestedFixture.swift @@ -38,10 +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, var tree = SidebarSessionTree.shared.state { - tree.parents.merge(fixture.parents) { _, 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/Logic/RustSidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/RustSidebarRow.swift index cc33cadc1ed6..ade44ead541e 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" @@ -129,7 +133,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, .listHeader, .emptyGroup: + case .folder, .sessionHost, .status, .listHeader, .emptyGroup: continue default: if case .custom = row.section { continue } // the older resolver knows Pinned and machines only @@ -188,6 +192,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/SidebarEmptyArea.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEmptyArea.swift index fe72a659d475..6cb0259c095c 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, .listHeader, .item, .block: nil + case .section, .emptySection, .folder, .sessionHost, .status, .listHeader, .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..113f1d5382ff --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout+SessionHosts.swift @@ -0,0 +1,204 @@ +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], gap: DropPosition?, metrics m: SidebarLayoutMetrics) -> SidebarLayout { + var bundles: [Int: [SidebarRow]] = [:] + var starts: [Int] = [] + for (i, row) in rows.enumerated() { + guard case .workspace = row.key else { continue } + starts.append(i) + 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 + // 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 + guard rows[i].group == nil, case .machine = rows[i].section, + case let .workspace(id) = rows[i].key else { return nil } + return id + }) + 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 + }) + // 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) + && !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()) + let roots = starts.indices.filter { !nested.contains($0) } + 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 } + 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 { + 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: 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) + y += row.height + spacing + } + func family(_ root: Int, depth: Int, groupDepth: Int = 0) { + 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 + // 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 + } + // 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 { + 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) + guard let root = byStart[index] else { + append(row, spacing: m.rowSpacing) + 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.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) } } + 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() } + } + 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 = movedPinnedY + layout.earlierChatsY = movedEarlierY + // 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 + base.pinnedChatsY = pinnedChatsY + base.earlierChatsY = earlierChatsY + return base + } + 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 8ed09a3563ad..c620dd5ef9ec 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, .listHeader: true + case .section, .group, .folder, .sessionHost, .status, .listHeader: true default: false } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift index d49e10b0b2b2..f0a62d3439a5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarLayout.swift @@ -36,6 +36,13 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { public static let empty = SidebarLayout(rows: [], totalHeight: 0, gapY: nil, gapHeight: 0, gapShift: 0) + /// True when opt-in fleet host buckets are actually drawn. Grouped mode + /// disables in-sidebar reordering so the projection cannot disagree with + /// the document landing; drags out to panes and windows remain available. + public var hostHeadersShowing: Bool { + rows.contains { if case .sessionHost = $0.key { true } else { false } } + } + public func row(for key: SidebarRowKey) -> SidebarRow? { index.position(of: key).map { rows[$0] } } /// The position of `key`'s row in `rows`, or nil. @@ -156,6 +163,9 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { var y = m.topPadding var gapY: CGFloat? let filtering = o.filterMatches != nil + // 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 // 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 @@ -380,6 +390,9 @@ 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) + // 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) }, @@ -421,7 +434,9 @@ public nonisolated struct SidebarLayout: Hashable, Sendable { ) layout.rowSpacing = m.rowSpacing (layout.pinnedChatsY, layout.earlierChatsY) = (chats.pinnedY, chats.earlierY) - SidebarPerfCounters.add(.layoutRows, rows.count) + let drawn = groupsSessions ? o.sessionTree.map { layout.groupingSessions($0, sections: sections, gap: o.gap, metrics: m) } : nil + SidebarPerfCounters.add(.layoutRows, (drawn ?? layout).rows.count) + if let drawn { return drawn } return layout } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarRow.swift index c9e027c19828..6587a2ebf0cf 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 new file mode 100644 index 000000000000..d23f54f110b2 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarCategory.swift @@ -0,0 +1,46 @@ +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 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 + case group + case browserTab + case chat + case app + case fleetMachine + case fleetSession + case agentSession + /// 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 + + /// 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 + // A reference has a document owner, so preserve that custom placement. + case .ref: self = .custom + // 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?) -> Self { + peer == nil ? .agentSession : .fleetSession + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarNestedFixture.swift index 12efe6de2401..0e30fa765b0d 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 @@ -199,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 diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarSessionTree.swift index 769fccc838b6..40ece823275c 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`). @@ -153,7 +157,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 @@ -167,11 +177,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. @@ -179,10 +191,17 @@ public final class SidebarSessionTree { state.map { live in var drawn = live drawn.collapsed = collapsed + drawn.collapsedHosts = collapsedHosts return drawn } } + public func toggleHost(_ host: String) { + let stable = Self.hostID(from: host) + if collapsedHosts.remove(stable) == nil { collapsedHosts.insert(stable) } + 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) } @@ -197,6 +216,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) @@ -215,5 +241,21 @@ public final class SidebarSessionTree { defaults.set(collapsed.map(\.rawValue).sorted(), forKey: Self.collapsedKey) } + /// 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 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 nonisolated 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/Store/SidebarDocDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift index 7ef0615007e0..3f30fc78befd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Store/SidebarDocDrag.swift @@ -106,7 +106,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, .listHeader, .doneFold, .showMore: + case .folder, .sessionHost, .status, .listHeader, .doneFold, .showMore: continue } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift index 3624d12ec324..a8a802cb9a39 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift @@ -64,7 +64,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, .listHeader: return + case .section, .emptySection, .emptyGroup, .folder, .item, .block, .doneFold, .showMore, .sessionHost, .status, .listHeader: return } if let row = list.displayed.row(for: key) { list.scrollToVisible(list.frame(for: row)) } list.realizeVisibleRows() @@ -192,7 +192,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, .listHeader: break + case .section, .emptySection, .emptyGroup, .folder, .item, .block, .doneFold, .showMore, .sessionHost, .status, .listHeader: break } list.reload(animated: false) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift index 0c494bc8d954..09ece277714d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListDrag.swift @@ -42,6 +42,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+ContextMenu.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift index 0fe3a3a1a6b3..5e33b93d6d64 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift @@ -29,7 +29,7 @@ extension SidebarListViewComponents { target = fold.group.map(SidebarContextTarget.group) ?? .section(fold.section) case let .item(item)?: target = .layoutItem(LayoutItemID(item)) - case .block?, .status?, .listHeader?: + case .block?, .status?, .sessionHost?, .listHeader?: 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 a6676c53dea2..68743a37f1c2 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, .listHeader: + case .section, .emptySection, .emptyGroup, .folder, .block, .doneFold, .showMore, .sessionHost, .status, .listHeader: return } // A group lifts as one block: its header and the member rows under it (cx-bp40). @@ -79,6 +79,11 @@ 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,7 +111,7 @@ 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 } 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. @@ -115,6 +120,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 { @@ -157,8 +164,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 { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift index b9c6f1c0e9dd..9b8a9cfe2d34 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Layout.swift @@ -515,6 +515,9 @@ 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): + let stableHost = SidebarSessionTree.hostID(from: host) + view.configure(row, title: SidebarSessionTree.shared.state?.hostNames[stableHost] ?? stableHost) case let (.listHeader(header), view as ListHeaderRowView): view.configure(header, count: row.childCount) case (.doneFold, let view as SidebarDoneFoldRowView), (.showMore, let view as SidebarDoneFoldRowView): view.isKeyboardFocused = showsFocusRing && focusedFold == row.key diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift index 92af5a737927..be270970b3be 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, .listHeader: + case .section, .emptySection, .emptyGroup, .folder, .block, .sessionHost, .status, .listHeader: 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/SidebarListView+TabDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift index 9a3a85839dfe..a12db2e788f1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+TabDrop.swift @@ -54,6 +54,12 @@ extension SidebarListViewComponents { if let baseY = DropResolver.baseY(forDisplayY: point.y, gapY: displayed.gapY, gapHeight: displayed.gapShift) { let (base, rules) = tabDragBase(external) var proposal = rules?.drop(y: baseY) + if displayed.hostHeadersShowing { + switch proposal { + case .intoWorkspace?: break + default: proposal = nil + } + } external.slotDeadline = nil if slotDwell > 0, let slot = proposal, case .newWorkspace = slot { let now = CACurrentMediaTime() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift index af8e723f98ce..17cad03c0203 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarRowViewPool.swift @@ -77,7 +77,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 .listHeader: ListHeaderRowView.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 f9542f41991b..4c9a4a11db57 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/SidebarCategoryTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift new file mode 100644 index 000000000000..ef799edb6b57 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarCategoryTests.swift @@ -0,0 +1,48 @@ +@testable import CmuxNextSidebar +import Testing +import Foundation + +struct SidebarCategoryTests { + // 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), + ] + for (body, category) in cases { #expect(SidebarCategory(body: body) == category) } + #expect(SidebarCategory.lane(peer: "remote") == .fleetSession) + #expect(SidebarCategory.lane(peer: 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/SidebarSessionHostIntegrationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift new file mode 100644 index 000000000000..bbf725e3b4f0 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostIntegrationTests.swift @@ -0,0 +1,188 @@ +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 + } + + @MainActor 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 = CmuxNextSidebar.SidebarSection(kind: .machine(SidebarMachine(id: .local, name: "This Mac", kind: .local)), nodes: nodes) + let model = SidebarModel(sections: [section], activeWorkspaceID: dragged) + 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(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(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(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) + 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 draggingAnUnrelatedWorkspaceIsRefusedWhileHostGroupsShow() throws { + try Self.withList { list in + SidebarSessionTreeFeed.publish(Self.pass(enabled: true), to: .shared) + list.reload(animated: false) + 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) + + #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: 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() + #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) + + // 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( + 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: list.convert(point, to: nil)) + #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) } + + // 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: list.convert(workspacePoint, to: nil), sourceMachine: nil) != nil) + list.externalDragExited() + let endPoint = NSPoint(x: 80, y: list.displayed.totalHeight - 4) + #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. + 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: list.convert(NSPoint(x: 80, y: plainControl.y + plainControl.height / 2), to: nil)) + #expect(list.displayed.gapY != nil) + list.cancelDrag() + } + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift new file mode 100644 index 000000000000..cc167a1b5a07 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SidebarSessionHostTests.swift @@ -0,0 +1,360 @@ +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) -> [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 [CmuxNextSidebar.SidebarSection(kind: .machine(local), nodes: parentPresent ? [.workspace(parentRow), .workspace(unrelated)] : [.workspace(unrelated)]), + CmuxNextSidebar.SidebarSection(kind: .machine(remote), nodes: [.workspace(childRow)])] + } + return [CmuxNextSidebar.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(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") + } + + @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(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(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(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[..= gapY + layout.gapHeight) + } + } + + @Test func hostHeadersDisableInSidebarReordering() { + #expect(Self.layout(Self.state()).hostHeadersShowing) + #expect(!Self.layout(nil).hostHeadersShowing) + } + + @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 = CmuxNextSidebar.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(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) + 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 = 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() + 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(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) + } + + @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(SidebarSessionTree.hostKey(Self.host, section: .machine(.local))))?.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 360d70ba904b..0f0bf83f410d 100644 --- a/plans/cmux-next/sidebar-owner.md +++ b/plans/cmux-next/sidebar-owner.md @@ -1715,3 +1715,12 @@ Vertical-tabs commits `fa51dcbb9d6` and `7a076d729ac` were reviewed as Sidebar-L `Metrics.dividerThickness` straight, so it stayed under borders none; it now goes through `Metrics.lineWidth`, and the glass specular rim (`GlassRimView`) through `Borders.width`. Look change only under borders none: no group header edge and no glass rim. Sidebar-Look: Leo 2026-11-07, "the blocky without border kinda vibe". + +## 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. + +- 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.