From 97a0eb35d063fcc3b5d10ee0d57854e99a1d1f6c Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 2 Jun 2026 06:39:28 -0700 Subject: [PATCH 01/36] Rebuild sidebar workspace reorder on a SwiftUI DragGesture The old reorder used .onDrag -> NSItemProvider, which spawns a macOS system drag session whose pointer location only updates coarsely via the drop delegate (and only over a valid target). That is what made dragging feel laggy and the follower drift. Replace it with a custom DragGesture that owns the interaction: a 1:1 floating follower, a live gap that animates open via dragPreviewItems, and hysteresis so the landing slot does not flicker at row midpoints. Workspace rows and group-header (anchor) rows both reorder through one shared path, so groups keep full parity. Per-frame cursor updates touch only the isolated follower overlay; the list reflows only on discrete drop-indicator changes, preserving the issue #2586 snapshot boundary. Committed row frames are frozen during a drag so hit-testing does not feed back on its own preview. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 310 ++++++++++++++---- .../Sidebar/SidebarReorderFollowerView.swift | 41 +++ .../SidebarReorderIndicatorResolver.swift | 115 +++++++ .../Sidebar/SidebarReorderRowFrameKey.swift | 39 +++ .../Sidebar/VerticalTabsSidebar+Reorder.swift | 168 ++++++++++ Sources/SidebarWorkspaceGroupHeaderView.swift | 23 +- Sources/SidebarWorkspaceRenderItem.swift | 216 +++++++++++- .../VerticalTabsSidebar+WorkspaceGroups.swift | 79 ++--- cmux.xcodeproj/project.pbxproj | 16 + cmuxTests/WorkspaceGroupTests.swift | 70 +++- 10 files changed, 961 insertions(+), 116 deletions(-) create mode 100644 Sources/Sidebar/SidebarReorderFollowerView.swift create mode 100644 Sources/Sidebar/SidebarReorderIndicatorResolver.swift create mode 100644 Sources/Sidebar/SidebarReorderRowFrameKey.swift create mode 100644 Sources/Sidebar/VerticalTabsSidebar+Reorder.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 7a88354be9b6..4c5a789fd41b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10203,6 +10203,13 @@ final class SidebarDragState { var draggedTabId: UUID? var dropIndicator: SidebarDropIndicator? var dropIndicatorUsesTopLevelRows = false + /// Cursor Y (in the workspace list's coordinate space) of the active + /// gesture-driven reorder. Read ONLY by the isolated `SidebarReorderFollowerView` + /// overlay so the floating follower can track the cursor every frame without + /// invalidating the `LazyVStack` body. The parent body and list rows must + /// never read this — doing so would re-run them per frame and reintroduce + /// the https://github.com/manaflow-ai/cmux/issues/2586 layout-thrash loop. + var followerCursorY: CGFloat? /// True while the `debug.sidebar.simulate_drag` debug-only V2 method is /// driving the drag state. The lifecycle observers honor this by not /// starting `SidebarDragFailsafeMonitor` (which would otherwise post a @@ -10211,8 +10218,56 @@ final class SidebarDragState { /// release flows. var isSimulated: Bool = false + // MARK: Gesture-reorder geometry (not observed) + // These back the gesture-driven reorder hit-testing. They are + // `@ObservationIgnored` so updating them (including the high-frequency + // `rowFramesInList` push during a drag) never invalidates any view; only + // this type's own methods read them, and the indicator/cursor results they + // produce flow through the observed properties above. + + /// The picked-up row's frame in list space, captured at drag start. Sizes + /// and positions the follower. + @ObservationIgnored var draggedRowFrame: CGRect? + /// Offset of the cursor within the picked-up row at drag start, so the + /// follower keeps the same grab point under the cursor. + @ObservationIgnored var grabOffsetY: CGFloat = 0 + /// Live frames of the currently-rendered workspace rows + group headers, + /// keyed by represented workspace id, in list space. + @ObservationIgnored var rowFramesInList: [UUID: CGRect] = [:] + /// Reads the current cursor Y in list space (NSEvent-backed). Set by the + /// view; used by the auto-scroll tick to keep the indicator fresh while the + /// pointer sits still at an edge and content scrolls underneath. + @ObservationIgnored var cursorYProvider: (() -> CGFloat?)? + @ObservationIgnored private var reorderIds: [UUID] = [] + @ObservationIgnored private var pinnedIds: Set = [] + /// For each reorder-scope id, the represented ids of the rendered rows that + /// compose its hit-test band (a single row normally; a group header plus its + /// members when dragging a group anchor at top level). + @ObservationIgnored private var scopeBandComposition: [UUID: [UUID]] = [:] + + /// Dead-zone half-width around a row midpoint within which the landing edge + /// is held, so the gap does not flicker on sub-pixel jitter. + static let hysteresisMargin: CGFloat = 6 + init() {} + /// Pushes the latest rendered row frames. While a drag is active the + /// committed frames are frozen (only newly-rendered rows are added, existing + /// ones are not overwritten): the list reflows to preview the gap, but + /// hit-testing stays against the committed layout so the landing slot does + /// not feed back on its own preview and oscillate. + func updateRowFrames(_ frames: [UUID: CGRect]) { + guard draggedTabId != nil else { + rowFramesInList = frames + return + } + for (id, frame) in frames where rowFramesInList[id] == nil { + rowFramesInList[id] = frame + } + } + + // MARK: simulate_drag / legacy API (drives observed state directly) + func beginDragging(tabId: UUID) { draggedTabId = tabId clearDropIndicator() @@ -10229,8 +10284,100 @@ final class SidebarDragState { func clearDrag() { draggedTabId = nil + followerCursorY = nil + draggedRowFrame = nil + grabOffsetY = 0 + reorderIds = [] + pinnedIds = [] + scopeBandComposition = [:] clearDropIndicator() } + + // MARK: Gesture-driven reorder + + /// Begins a gesture-driven reorder of `tabId`. + func beginReorder( + tabId: UUID, + usesTopLevelRows: Bool, + reorderIds: [UUID], + pinnedIds: Set, + scopeBandComposition: [UUID: [UUID]], + draggedRowFrame: CGRect?, + grabOffsetY: CGFloat, + cursorY: CGFloat + ) { + self.draggedTabId = tabId + self.dropIndicatorUsesTopLevelRows = usesTopLevelRows + self.reorderIds = reorderIds + self.pinnedIds = pinnedIds + self.scopeBandComposition = scopeBandComposition + self.draggedRowFrame = draggedRowFrame + self.grabOffsetY = grabOffsetY + self.followerCursorY = cursorY + recomputeIndicator(cursorY: cursorY) + } + + /// Updates the follower position and landing slot for a moved cursor. + func updateReorder(cursorY: CGFloat) { + followerCursorY = cursorY + recomputeIndicator(cursorY: cursorY) + } + + /// Re-reads the cursor from `cursorYProvider` and refreshes. Called by the + /// auto-scroll tick so the landing slot keeps advancing while the pointer is + /// stationary at an edge. + func refreshFromCursor() { + guard draggedTabId != nil, let cursorY = cursorYProvider?() else { return } + updateReorder(cursorY: cursorY) + } + + /// The committed index the dragged workspace should move to on drop, or nil + /// for a no-op. Reads gesture geometry; call only at drop time, not in a + /// view body. + func gestureReorderTargetIndex() -> Int? { + guard let draggedTabId, dropIndicator != nil else { return nil } + return SidebarDropPlanner.targetIndex( + draggedTabId: draggedTabId, + targetTabId: dropIndicator?.tabId, + indicator: dropIndicator, + tabIds: reorderIds, + pinnedTabIds: pinnedIds + ) + } + + private func recomputeIndicator(cursorY: CGFloat) { + guard let draggedTabId else { return } + let bands = buildBands() + let indicator = SidebarReorderIndicatorResolver.resolve( + cursorY: cursorY, + bands: bands, + draggedId: draggedTabId, + pinnedIds: pinnedIds, + current: dropIndicator, + hysteresisMargin: Self.hysteresisMargin + ) + if indicator != dropIndicator { + dropIndicator = indicator + } + } + + private func buildBands() -> [SidebarReorderIndicatorResolver.Band] { + var bands: [SidebarReorderIndicatorResolver.Band] = [] + bands.reserveCapacity(reorderIds.count) + for scopeId in reorderIds { + let composition = scopeBandComposition[scopeId] ?? [scopeId] + var minY = CGFloat.greatestFiniteMagnitude + var maxY = -CGFloat.greatestFiniteMagnitude + for renderedId in composition { + guard let frame = rowFramesInList[renderedId] else { continue } + minY = min(minY, frame.minY) + maxY = max(maxY, frame.maxY) + } + guard maxY > minY else { continue } + bands.append(.init(id: scopeId, minY: minY, maxY: maxY)) + } + return bands.sorted { $0.minY < $1.minY } + } } #if DEBUG @@ -11968,16 +12115,27 @@ struct VerticalTabsSidebar: View { } private func workspaceRows(renderContext: WorkspaceListRenderContext) -> some View { - let renderItems = SidebarWorkspaceRenderItem.renderItems( + let baseRenderItems = SidebarWorkspaceRenderItem.renderItems( tabs: renderContext.tabs, groupsById: renderContext.workspaceGroupById ) - // LazyVStack is safe here because `dragState` is @Observable: - // drag mutations at 60fps invalidate only the rows/overlays that - // read them, never this sidebar body. See SidebarDragState and + // During a gesture-driven reorder the list reflows to `previewItems` + // (the dragged row moved to its landing slot) so the gap animates open. + // `dropIndicator` is discrete — it changes only when the landing slot + // crosses a row midpoint — so this body re-runs a handful of times per + // drag, never per frame. The per-frame follower position lives in the + // isolated `SidebarReorderFollowerView`, which alone reads + // `dragState.followerCursorY`. LazyVStack is safe here because + // `dragState` is @Observable. See SidebarDragState and // https://github.com/manaflow-ai/cmux/issues/2586. + let previewItems = SidebarWorkspaceRenderItem.dragPreviewItems( + baseRenderItems, + draggedWorkspaceId: dragState.draggedTabId, + dropIndicator: dragState.dropIndicator, + reorderWorkspaceIds: renderContext.sidebarReorderIds + ) return LazyVStack(spacing: tabRowSpacing) { - ForEach(renderItems, id: \.id) { item in + ForEach(previewItems, id: \.id) { item in switch item { case .groupHeader(let group, let memberWorkspaceIds): sidebarWorkspaceGroupHeader( @@ -11985,13 +12143,37 @@ struct VerticalTabsSidebar: View { memberWorkspaceIds: memberWorkspaceIds, renderContext: renderContext ) - case .workspace(let tab): + case .workspace(let tab, _): workspaceRow(tab, renderContext: renderContext) } } } + .animation(Self.sidebarReorderAnimation, value: previewItems.map(\.id)) .padding(.vertical, SidebarWorkspaceListMetrics.rowVerticalPadding) .frame(maxWidth: .infinity, alignment: .leading) + .coordinateSpace(.named(SidebarReorderListCoordinateSpace.name)) + .onPreferenceChange(SidebarReorderRowFrameKey.self) { frames in + dragState.updateRowFrames(frames) + } + .overlay { + SidebarReorderFollowerView( + dragState: dragState, + sourceItems: baseRenderItems, + rowContent: { item in + switch item { + case .groupHeader(let group, let memberWorkspaceIds): + AnyView(sidebarWorkspaceGroupHeader( + group: group, + memberWorkspaceIds: memberWorkspaceIds, + renderContext: renderContext, + role: .dragFollower + )) + case .workspace(let tab, _): + AnyView(workspaceRow(tab, renderContext: renderContext, role: .dragFollower)) + } + } + ) + } .overlayPreferenceValue(SidebarWorkspaceRowFramePreferenceKey.self) { anchors in GeometryReader { proxy in SidebarBonsplitTabWorkspaceDropOverlay( @@ -12048,9 +12230,11 @@ struct VerticalTabsSidebar: View { } } + @ViewBuilder private func workspaceRow( _ tab: Workspace, - renderContext: WorkspaceListRenderContext + renderContext: WorkspaceListRenderContext, + role: SidebarWorkspaceRowRenderRole = .list ) -> some View { let index = renderContext.tabIndexById[tab.id] ?? 0 let usesSelectedContextMenuTargets = selectedTabIds.contains(tab.id) @@ -12108,39 +12292,28 @@ struct VerticalTabsSidebar: View { // is intentional: the parent owns the @Observable store, and these // value snapshots are what get passed to the row. The row's // Equatable conformance ignores closures, so rows whose snapshot is - // unchanged skip re-render when drag state moves. - let isBeingDragged = dragState.draggedTabId == tab.id - let sidebarReorderIds = renderContext.sidebarReorderIds - let topDropIndicatorVisible = SidebarTabDropIndicatorPredicate.topVisible( - forTabId: tab.id, - draggedTabId: dragState.draggedTabId, - dropIndicator: dragState.dropIndicator, - tabIds: sidebarReorderIds - ) - let onDragStart: () -> NSItemProvider = { [tabId = tab.id] in - #if DEBUG - cmuxDebugLog("sidebar.onDrag tab=\(tabId.uuidString.prefix(5))") - #endif - dragState.beginDragging(tabId: tabId) - return SidebarTabDragPayload.provider(for: tabId) - } - let tabDropDelegateFactory: (CGFloat) -> SidebarTabDropDelegate = { [ - tabId = tab.id, - selectedTabIds = $selectedTabIds, - lastSidebarSelectionIndex = $lastSidebarSelectionIndex - ] rowHeight in - SidebarTabDropDelegate( - targetTabId: tabId, - tabManager: tabManager, - dragState: dragState, - selectedTabIds: selectedTabIds, - lastSidebarSelectionIndex: lastSidebarSelectionIndex, - targetRowHeight: rowHeight, - dragAutoScrollController: dragAutoScrollController - ) - } - - return TabItemView( + // unchanged skip re-render when drag state moves. The dragged row in the + // list reads as `isBeingDragged` and renders invisible (the floating + // follower carries the visible copy); the follower copy itself + // (`role == .dragFollower`) renders fully visible. + let isBeingDragged = role == .list && dragState.draggedTabId == tab.id + // The reorder gesture, dispatched into the shared reorder helpers. Wired + // into `TabItemView` so it lives below `.equatable()` and survives the + // parent body re-evaluations that the discrete drop-indicator changes + // trigger, instead of being torn down mid-drag. + let onReorderChanged: (CGPoint, CGPoint) -> Void = { [tabId = tab.id, renderContext] startLocation, location in + sidebarReorderGestureChanged( + draggedId: tabId, + startLocationY: startLocation.y, + cursorY: location.y, + renderContext: renderContext + ) + } + let onReorderEnded: (CGPoint, CGPoint) -> Void = { [tabId = tab.id] _, _ in + sidebarReorderGestureEnded(draggedId: tabId) + } + + let row = TabItemView( tabManager: tabManager, notificationStore: notificationStore, tab: tab, @@ -12162,9 +12335,10 @@ struct VerticalTabsSidebar: View { showsModifierShortcutHints: resolvedShowsModifierShortcutHints, dragAutoScrollController: dragAutoScrollController, isBeingDragged: isBeingDragged, - topDropIndicatorVisible: topDropIndicatorVisible, - onDragStart: onDragStart, - tabDropDelegateFactory: tabDropDelegateFactory, + topDropIndicatorVisible: false, + onReorderChanged: onReorderChanged, + onReorderEnded: onReorderEnded, + isReorderEnabled: role == .list, contextMenuWorkspaceIds: contextMenuWorkspaceIds, remoteContextMenuWorkspaceIds: remoteContextMenuWorkspaceIds, allRemoteContextMenuTargetsConnecting: allRemoteContextMenuTargetsConnecting, @@ -12176,13 +12350,23 @@ struct VerticalTabsSidebar: View { onContextMenuDisappear: onContextMenuDisappear ) .equatable() - .id(tab.id) - .accessibilityIdentifier("sidebarWorkspace.\(tab.id.uuidString)") - .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([tab.id])) - .anchorPreference(key: SidebarWorkspaceRowFramePreferenceKey.self, value: .bounds) { anchor in - [tab.id: anchor] + + let indent: CGFloat = tab.groupId != nil ? SidebarWorkspaceGroupingMetrics.memberIndent : 0 + if role == .dragFollower { + row + .allowsHitTesting(false) + .accessibilityHidden(true) + .padding(.leading, indent) + } else { + row + .id(tab.id) + .accessibilityIdentifier("sidebarWorkspace.\(tab.id.uuidString)") + .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([tab.id])) + .anchorPreference(key: SidebarWorkspaceRowFramePreferenceKey.self, value: .bounds) { anchor in + [tab.id: anchor] + } + .padding(.leading, indent) } - .padding(.leading, tab.groupId != nil ? SidebarWorkspaceGroupingMetrics.memberIndent : 0) } private func debugShortSidebarTabId(_ id: UUID?) -> String { @@ -14642,6 +14826,7 @@ struct TabItemView: View, Equatable { lhs.workspaceGroupMenuSnapshot == rhs.workspaceGroupMenuSnapshot && lhs.isBeingDragged == rhs.isBeingDragged && lhs.topDropIndicatorVisible == rhs.topDropIndicatorVisible && + lhs.isReorderEnabled == rhs.isReorderEnabled && lhs.settings == rhs.settings } @@ -14674,11 +14859,14 @@ struct TabItemView: View, Equatable { // unchanged. let isBeingDragged: Bool let topDropIndicatorVisible: Bool - let onDragStart: () -> NSItemProvider - /// Factory invoked from `body` with the row's measured `rowHeight`. Closure - /// captures the parent's `dragState`, so TabItemView itself never holds an - /// `@Observable` store reference (snapshot-boundary rule). - let tabDropDelegateFactory: (CGFloat) -> SidebarTabDropDelegate + /// Reorder gesture callbacks (start location, current location), dispatched + /// into the shared `VerticalTabsSidebar` reorder helpers via closures so the + /// row never holds an `@Observable` store reference (snapshot-boundary rule). + let onReorderChanged: (CGPoint, CGPoint) -> Void + let onReorderEnded: (CGPoint, CGPoint) -> Void + /// False for the floating follower copy, which is non-interactive and must + /// not report a row frame. + let isReorderEnabled: Bool let contextMenuWorkspaceIds: [UUID] let remoteContextMenuWorkspaceIds: [UUID] let allRemoteContextMenuTargetsConnecting: Bool @@ -15332,7 +15520,10 @@ struct TabItemView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .contentShape(Rectangle()) - .opacity(isBeingDragged ? 0.6 : 1) + // The row being dragged renders fully invisible: its visible copy is the + // floating `SidebarReorderFollowerView`, and this slot is the gap the + // surrounding rows animate open around. + .opacity(isBeingDragged ? 0 : 1) .overlay { SidebarWorkspaceRowHoverTracker(rowInteractionState: $rowInteractionState) } @@ -15404,9 +15595,12 @@ struct TabItemView: View, Equatable { .onChange(of: settings) { _ in refreshWorkspaceSnapshot(force: true) } - .onDrag(onDragStart) - .internalOnlyTabDrag() - .onDrop(of: SidebarTabDragPayload.dropContentTypes, delegate: tabDropDelegateFactory(rowHeight)) + .modifier(SidebarReorderRowModifier( + enabled: isReorderEnabled, + workspaceId: tab.id, + onChanged: onReorderChanged, + onEnded: onReorderEnded + )) .onDrop(of: BonsplitTabDragPayload.dropContentTypes, delegate: SidebarBonsplitTabDropDelegate( targetWorkspaceId: tab.id, tabManager: tabManager, diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift new file mode 100644 index 000000000000..8bf667e54eb5 --- /dev/null +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -0,0 +1,41 @@ +import SwiftUI + +/// The floating copy of the picked-up workspace row that tracks the cursor +/// during a gesture-driven reorder. +/// +/// This is the ONLY view that reads `SidebarDragState.followerCursorY`, the +/// per-frame cursor position. Because it is a sibling overlay over the list (not +/// a row inside the `LazyVStack`/`ForEach`), its per-frame updates repaint just +/// this one view and never invalidate the list body — the property that keeps +/// the drag off the https://github.com/manaflow-ai/cmux/issues/2586 thrash path. +/// Implicit animations are disabled so the follower snaps to the cursor with +/// zero lag while the list rows animate the gap open underneath it. +struct SidebarReorderFollowerView: View { + let dragState: SidebarDragState + /// The committed render list, used to find the picked-up row's content. + let sourceItems: [SidebarWorkspaceRenderItem] + let rowContent: (SidebarWorkspaceRenderItem) -> AnyView + + var body: some View { + if let draggedId = dragState.draggedTabId, + let cursorY = dragState.followerCursorY, + let frame = dragState.draggedRowFrame, + frame.width > 0, + frame.height > 0, + let item = sourceItems.first(where: { $0.representedWorkspaceId == draggedId }) { + let topY = cursorY - dragState.grabOffsetY + rowContent(item) + .frame(width: frame.width, height: frame.height, alignment: .topLeading) + .position(x: frame.midX, y: topY + frame.height / 2) + .shadow(color: Color.black.opacity(0.18), radius: 11, x: 0, y: 5) + .opacity(0.97) + .allowsHitTesting(false) + .accessibilityHidden(true) + .zIndex(1000) + .transaction { transaction in + transaction.disablesAnimations = true + transaction.animation = nil + } + } + } +} diff --git a/Sources/Sidebar/SidebarReorderIndicatorResolver.swift b/Sources/Sidebar/SidebarReorderIndicatorResolver.swift new file mode 100644 index 000000000000..513bc82cb5a3 --- /dev/null +++ b/Sources/Sidebar/SidebarReorderIndicatorResolver.swift @@ -0,0 +1,115 @@ +import CoreGraphics +import Foundation + +/// Maps a drag cursor position to a ``SidebarDropIndicator`` for the gesture +/// driven workspace reorder, with hysteresis so the gap does not flicker when +/// the cursor hovers exactly on a row's midpoint. +/// +/// Pure and self-contained so it is unit-testable without a running app: the +/// caller passes the reorder-scope rows as vertical bands (already resolved +/// from the live row frames) plus the current cursor Y, all in one coordinate +/// space. Edge/insertion/pinned-tier legality is delegated to +/// ``SidebarDropPlanner``; this type only adds hit-testing and stickiness. +enum SidebarReorderIndicatorResolver { + /// One reorder-scope item's vertical extent in list space. For a top-level + /// group drag, a band spans the group header plus all its member rows so + /// the whole group reads as one target. + struct Band: Equatable { + let id: UUID + let minY: CGFloat + let maxY: CGFloat + + var midY: CGFloat { (minY + maxY) / 2 } + var height: CGFloat { max(maxY - minY, 0) } + } + + /// Resolves the drop indicator for `cursorY`. + /// + /// - Parameters: + /// - cursorY: cursor Y in the same list space as the band extents. + /// - bands: reorder-scope bands in scope order, contiguous and sorted. + /// - draggedId: the workspace being dragged. + /// - pinnedIds: pinned ids within the scope (tier constraint). + /// - current: the indicator currently shown, used for hysteresis. + /// - hysteresisMargin: half-width of the dead-zone around a band midpoint + /// within which the current edge is kept (points). + /// - Returns: the indicator to show, or nil for a no-op move. + static func resolve( + cursorY: CGFloat, + bands: [Band], + draggedId: UUID, + pinnedIds: Set, + current: SidebarDropIndicator?, + hysteresisMargin: CGFloat + ) -> SidebarDropIndicator? { + guard !bands.isEmpty else { return nil } + let scopeIds = bands.map(\.id) + + // Below every row: append to the end of the scope. + guard let lastBand = bands.last, cursorY <= lastBand.maxY else { + return SidebarDropPlanner.indicator( + draggedTabId: draggedId, + targetTabId: nil, + tabIds: scopeIds, + pinnedTabIds: pinnedIds + ) + } + + // First band whose bottom edge is below the cursor is the target; this + // also assigns the inter-row spacing gap to the lower band. + let targetBand = bands.first(where: { cursorY < $0.maxY }) ?? lastBand + let pointerY = cursorY - targetBand.minY + + let effectivePointerY = stickyPointerY( + pointerY: pointerY, + band: targetBand, + scopeIds: scopeIds, + current: current, + margin: hysteresisMargin + ) + + return SidebarDropPlanner.indicator( + draggedTabId: draggedId, + targetTabId: targetBand.id, + tabIds: scopeIds, + pinnedTabIds: pinnedIds, + pointerY: effectivePointerY, + targetHeight: targetBand.height + ) + } + + /// Biases `pointerY` toward the current edge while the cursor sits within + /// `margin` of the band midpoint, so the indicator does not oscillate on + /// sub-pixel jitter at the 50% split. + private static func stickyPointerY( + pointerY: CGFloat, + band: Band, + scopeIds: [UUID], + current: SidebarDropIndicator?, + margin: CGFloat + ) -> CGFloat { + let mid = band.height / 2 + guard margin > 0, abs(pointerY - mid) < margin else { return pointerY } + guard let edge = currentEdge(for: band, scopeIds: scopeIds, current: current) else { + return pointerY + } + return edge == .top ? mid - margin : mid + margin + } + + /// The edge of `band` that the current indicator represents, if any. The + /// planner canonicalizes "after row i" to "top of row i+1" (or the end + /// sentinel), so both forms are matched here. + private static func currentEdge( + for band: Band, + scopeIds: [UUID], + current: SidebarDropIndicator? + ) -> SidebarDropEdge? { + guard let current else { return nil } + if current.tabId == band.id, current.edge == .top { return .top } + guard let index = scopeIds.firstIndex(of: band.id) else { return nil } + let afterId: UUID? = index + 1 < scopeIds.count ? scopeIds[index + 1] : nil + if let afterId, current.tabId == afterId, current.edge == .top { return .bottom } + if afterId == nil, current.tabId == nil, current.edge == .bottom { return .bottom } + return nil + } +} diff --git a/Sources/Sidebar/SidebarReorderRowFrameKey.swift b/Sources/Sidebar/SidebarReorderRowFrameKey.swift new file mode 100644 index 000000000000..216fa7b0f967 --- /dev/null +++ b/Sources/Sidebar/SidebarReorderRowFrameKey.swift @@ -0,0 +1,39 @@ +import SwiftUI + +/// Collects the live frames of the workspace sidebar rows (and group headers), +/// keyed by represented workspace id, in the list's `"sidebarReorderList"` +/// coordinate space. +/// +/// The gesture-driven reorder reads these via `.onPreferenceChange` to hit-test +/// the drag cursor against the rows. Resolving concrete `CGRect`s (rather than +/// `Anchor`) lets the value flow straight into `SidebarDragState`'s +/// non-observed geometry without a `GeometryProxy`, so the push never happens +/// inside a view-body computation. +struct SidebarReorderRowFrameKey: PreferenceKey { + static let defaultValue: [UUID: CGRect] = [:] + + static func reduce(value: inout [UUID: CGRect], nextValue: () -> [UUID: CGRect]) { + value.merge(nextValue(), uniquingKeysWith: { _, new in new }) + } +} + +extension View { + /// Reports this row's frame in the reorder list coordinate space under + /// `workspaceId`. + func sidebarReorderRowFrame(_ workspaceId: UUID) -> some View { + background( + GeometryReader { proxy in + Color.clear.preference( + key: SidebarReorderRowFrameKey.self, + value: [workspaceId: proxy.frame(in: .named(SidebarReorderListCoordinateSpace.name))] + ) + } + ) + } +} + +/// The named coordinate space the reorder gesture and row frames share, so the +/// gesture location and the measured row frames are guaranteed to align. +enum SidebarReorderListCoordinateSpace { + static let name = "sidebarReorderList" +} diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift new file mode 100644 index 000000000000..175a8bbc296e --- /dev/null +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -0,0 +1,168 @@ +import AppKit +import SwiftUI + +/// How a sidebar workspace row / group header is being rendered. +enum SidebarWorkspaceRowRenderRole { + /// A normal interactive row in the list. Carries the reorder gesture and + /// reports its frame; renders invisible while it is the one being dragged + /// (its visible copy is the floating follower). + case list + /// The floating follower copy painted over the list during a reorder drag. + /// Always fully visible, never interactive, reports no frame. + case dragFollower +} + +/// Gesture-driven workspace reorder, shared by workspace rows and group-header +/// (anchor) rows so both reorder through one path. Replaces the old +/// `.onDrag` system-drag + `DropDelegate` reorder, whose coarse, target-gated +/// location updates made the drag feel laggy. +extension VerticalTabsSidebar { + /// The spring the list rows use to animate the gap open and to settle into + /// place on drop. + static let sidebarReorderAnimation = Animation.snappy(duration: 0.22, extraBounce: 0.02) + + /// Handles a reorder drag tick: begins the drag on the first event, then + /// updates the follower position and landing slot. + /// + /// - Parameters: + /// - draggedId: the workspace (or group anchor) being dragged. + /// - startLocationY: the gesture's start Y in the reorder list space. + /// - cursorY: the gesture's current Y in the reorder list space. + func sidebarReorderGestureChanged( + draggedId: UUID, + startLocationY: CGFloat, + cursorY: CGFloat, + renderContext: WorkspaceListRenderContext + ) { + if dragState.draggedTabId != draggedId { + #if DEBUG + cmuxDebugLog("sidebar.reorder.begin id=\(draggedId.uuidString.prefix(5)) startY=\(Int(startLocationY)) cursorY=\(Int(cursorY))") + #endif + let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( + forDraggedWorkspaceId: draggedId, + targetWorkspaceId: nil + ) + let reorderIds = tabManager.sidebarReorderWorkspaceIds( + forDraggedWorkspaceId: draggedId, + usesTopLevelRows: usesTopLevelRows + ) + let pinnedIds = tabManager.sidebarReorderPinnedWorkspaceIds( + forDraggedWorkspaceId: draggedId, + usesTopLevelRows: usesTopLevelRows + ) + let composition = sidebarReorderScopeBandComposition( + usesTopLevelRows: usesTopLevelRows, + renderContext: renderContext + ) + let frame = dragState.rowFramesInList[draggedId] + let grabOffsetY = frame.map { startLocationY - $0.minY } ?? 0 + dragState.beginReorder( + tabId: draggedId, + usesTopLevelRows: usesTopLevelRows, + reorderIds: reorderIds, + pinnedIds: pinnedIds, + scopeBandComposition: composition, + draggedRowFrame: frame, + grabOffsetY: grabOffsetY, + cursorY: cursorY + ) + } else { + dragState.updateReorder(cursorY: cursorY) + } + dragAutoScrollController.updateFromDragLocation() + } + + /// Commits the reorder on drag end, animating the list into the landing + /// slot, then clears the drag state. + func sidebarReorderGestureEnded(draggedId: UUID) { + defer { + dragState.clearDrag() + dragAutoScrollController.stop() + } + guard dragState.draggedTabId == draggedId, + let targetIndex = dragState.gestureReorderTargetIndex() else { + #if DEBUG + cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=nil (noop)") + #endif + return + } + let usesTopLevelRows = dragState.dropIndicatorUsesTopLevelRows + #if DEBUG + cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=\(targetIndex) topLevel=\(usesTopLevelRows)") + #endif + withAnimation(Self.sidebarReorderAnimation) { + _ = tabManager.reorderSidebarWorkspace( + tabId: draggedId, + toIndex: targetIndex, + isDragOperation: true, + usesTopLevelRows: usesTopLevelRows + ) + } + } + + /// Maps each reorder-scope id to the rendered rows that compose its hit-test + /// band. Empty (identity) in normal mode; in top-level mode each group + /// anchor's band spans its header plus its members so the group reads as one + /// drop target. + func sidebarReorderScopeBandComposition( + usesTopLevelRows: Bool, + renderContext: WorkspaceListRenderContext + ) -> [UUID: [UUID]] { + guard usesTopLevelRows else { return [:] } + var composition: [UUID: [UUID]] = [:] + for group in renderContext.workspaceGroupById.values { + let memberIds = renderContext.tabs + .filter { $0.groupId == group.id && $0.id != group.anchorWorkspaceId } + .map(\.id) + composition[group.anchorWorkspaceId] = [group.anchorWorkspaceId] + memberIds + } + return composition + } +} + +/// Attaches the reorder `DragGesture` to a row. The gesture runs in the shared +/// `"sidebarReorderList"` space so its location aligns with the measured row +/// frames. A non-zero `minimumDistance` lets a plain click still select the row. +struct SidebarReorderDragModifier: ViewModifier { + let onChanged: (_ startLocation: CGPoint, _ location: CGPoint) -> Void + let onEnded: (_ startLocation: CGPoint, _ location: CGPoint) -> Void + + func body(content: Content) -> some View { + content.gesture( + DragGesture(minimumDistance: 6, coordinateSpace: .named(SidebarReorderListCoordinateSpace.name)) + .onChanged { value in onChanged(value.startLocation, value.location) } + .onEnded { value in onEnded(value.startLocation, value.location) } + ) + } +} + +extension View { + func sidebarReorderDrag( + onChanged: @escaping (_ startLocation: CGPoint, _ location: CGPoint) -> Void, + onEnded: @escaping (_ startLocation: CGPoint, _ location: CGPoint) -> Void + ) -> some View { + modifier(SidebarReorderDragModifier(onChanged: onChanged, onEnded: onEnded)) + } +} + +/// Adds the reorder gesture and frame reporter to an interactive sidebar row. +/// `enabled` is constant for a given row role, so the `if` never re-keys view +/// identity at runtime; the follower copy passes `enabled: false` to stay +/// non-interactive and report no frame. +struct SidebarReorderRowModifier: ViewModifier { + let enabled: Bool + let workspaceId: UUID + let onChanged: (_ startLocation: CGPoint, _ location: CGPoint) -> Void + let onEnded: (_ startLocation: CGPoint, _ location: CGPoint) -> Void + + @ViewBuilder + func body(content: Content) -> some View { + if enabled { + content + .sidebarReorderRowFrame(workspaceId) + .sidebarReorderDrag(onChanged: onChanged, onEnded: onEnded) + } else { + content + } + } +} diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 4d64efc91bca..d0af38928d68 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -27,7 +27,8 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.rowSpacing == rhs.rowSpacing && lhs.isFirstRow == rhs.isFirstRow && lhs.isBeingDragged == rhs.isBeingDragged && - lhs.topDropIndicatorVisible == rhs.topDropIndicatorVisible + lhs.topDropIndicatorVisible == rhs.topDropIndicatorVisible && + lhs.isReorderEnabled == rhs.isReorderEnabled } let groupId: UUID @@ -51,8 +52,11 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isFirstRow: Bool let isBeingDragged: Bool let topDropIndicatorVisible: Bool - let onDragStart: () -> NSItemProvider - let tabDropDelegateFactory: (CGFloat) -> SidebarWorkspaceGroupHeaderDropDelegate + /// Reorder gesture callbacks dispatched into the shared reorder helpers. + let onReorderChanged: (CGPoint, CGPoint) -> Void + let onReorderEnded: (CGPoint, CGPoint) -> Void + /// False for the floating follower copy. + let isReorderEnabled: Bool let onToggleCollapsed: () -> Void let onFocusAnchor: () -> Void let onTapPlus: () -> Void @@ -220,7 +224,9 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) - .opacity(isBeingDragged ? 0.6 : 1) + // The dragged header renders invisible; its visible copy is the floating + // follower and this slot is the gap that opens during a reorder. + .opacity(isBeingDragged ? 0 : 1) .overlay(alignment: .top) { SidebarWorkspaceTopDropIndicator( isVisible: topDropIndicatorVisible, @@ -228,9 +234,12 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { rowSpacing: rowSpacing ) } - .onDrag(onDragStart) - .internalOnlyTabDrag() - .onDrop(of: SidebarTabDragPayload.dropContentTypes, delegate: tabDropDelegateFactory(rowHeight)) + .modifier(SidebarReorderRowModifier( + enabled: isReorderEnabled, + workspaceId: anchorWorkspaceId, + onChanged: onReorderChanged, + onEnded: onReorderEnded + )) .onHover { hovering in isHovered = hovering } diff --git a/Sources/SidebarWorkspaceRenderItem.swift b/Sources/SidebarWorkspaceRenderItem.swift index ceabeaf594f9..a2cd0a36997e 100644 --- a/Sources/SidebarWorkspaceRenderItem.swift +++ b/Sources/SidebarWorkspaceRenderItem.swift @@ -1,19 +1,56 @@ import Foundation /// One drawable item in the workspace sidebar. +/// +/// `.workspace` carries an `effectiveGroupId` so the live reorder preview can +/// show a row indenting into (or out of) a group before the drop commits. It is +/// the group the row currently renders as a member of, which during a drag may +/// differ from `workspace.groupId` (the committed membership). @MainActor enum SidebarWorkspaceRenderItem { case groupHeader(WorkspaceGroup, memberWorkspaceIds: [UUID]) - case workspace(Workspace) + case workspace(Workspace, effectiveGroupId: UUID?) + + /// The workspace this item represents: the row's workspace, or a group + /// header's anchor workspace. + var representedWorkspaceId: UUID { + switch self { + case .groupHeader(let group, _): + return group.anchorWorkspaceId + case .workspace(let workspace, _): + return workspace.id + } + } + + /// The group the row renders as a member of (nil for top-level rows and + /// group headers). + var effectiveGroupId: UUID? { + switch self { + case .groupHeader: + return nil + case .workspace(_, let groupId): + return groupId + } + } var id: String { switch self { case .groupHeader(let group, _): return "group.\(group.id.uuidString)" - case .workspace(let workspace): + case .workspace(let workspace, _): return "workspace.\(workspace.id.uuidString)" } } + + func withEffectiveGroupId(_ groupId: UUID?) -> SidebarWorkspaceRenderItem { + switch self { + case .groupHeader: + return self + case .workspace(let workspace, _): + return .workspace(workspace, effectiveGroupId: groupId) + } + } + static func renderItems( tabs: [Workspace], groupsById: [UUID: WorkspaceGroup] @@ -53,9 +90,182 @@ enum SidebarWorkspaceRenderItem { continue } if groupId == nil || !skipChildrenUntilNextGroup { - items.append(.workspace(tab)) + items.append(.workspace(tab, effectiveGroupId: groupId)) } } return items } + + /// Returns the render list reordered to where the dragged row would land, + /// so the `LazyVStack` can animate the gap open (and the dragged row's slot + /// indent into/out of a group). Pure; drives the live reorder preview. + /// + /// - Parameters: + /// - items: the committed render list (`renderItems`). + /// - draggedWorkspaceId: the row being dragged, or nil when idle. + /// - dropIndicator: where the row would currently land. + /// - reorderWorkspaceIds: the ordered id scope the reorder operates over + /// (top-level rows when dragging a group anchor, otherwise every row). + /// - Returns: the preview-ordered list, or `items` unchanged when there is + /// nothing to preview. + static func dragPreviewItems( + _ items: [SidebarWorkspaceRenderItem], + draggedWorkspaceId: UUID?, + dropIndicator: SidebarDropIndicator?, + reorderWorkspaceIds: [UUID] + ) -> [SidebarWorkspaceRenderItem] { + guard let draggedWorkspaceId, + let dropIndicator, + reorderWorkspaceIds.contains(draggedWorkspaceId), + reorderWorkspaceIds.count > 1 else { + return items + } + + let topLevelMode = Set(reorderWorkspaceIds) != Set(items.map(\.representedWorkspaceId)) + let blocks = dragPreviewBlocks( + items, + reorderWorkspaceIds: reorderWorkspaceIds, + draggedWorkspaceId: draggedWorkspaceId, + topLevelMode: topLevelMode + ) + let blockIds = blocks.map(\.workspaceId) + let reorderIds = reorderWorkspaceIds.filter { blockIds.contains($0) } + guard reorderIds.count == blocks.count, + Set(reorderIds) == Set(blockIds), + reorderIds.contains(draggedWorkspaceId), + let nextReorderIds = dragPreviewWorkspaceIds( + reorderIds, + draggedWorkspaceId: draggedWorkspaceId, + dropIndicator: dropIndicator + ), + nextReorderIds != reorderIds else { + return items + } + + var blocksById: [UUID: [SidebarWorkspaceRenderItem]] = [:] + for block in blocks { + guard blocksById[block.workspaceId] == nil else { + return items + } + blocksById[block.workspaceId] = block.items + } + let reordered = nextReorderIds.flatMap { blocksById[$0] ?? [] } + return applyingDraggedMembership(reordered, draggedWorkspaceId: draggedWorkspaceId) + } + + /// Recomputes the dragged workspace's effective group membership from its + /// new neighbors in the preview list, matching the vertical-position rule + /// used at commit (`TabManager.applyDragInferredGroupMembership`): a member + /// only when sandwiched between two rows of the SAME group. Keeps the live + /// indent preview in sync with where the drop will actually land. + private static func applyingDraggedMembership( + _ renderItems: [SidebarWorkspaceRenderItem], + draggedWorkspaceId: UUID + ) -> [SidebarWorkspaceRenderItem] { + guard let draggedIndex = renderItems.firstIndex(where: { item in + if case .workspace(let workspace, _) = item { return workspace.id == draggedWorkspaceId } + return false + }) else { + return renderItems + } + let beforeGroup = draggedIndex > renderItems.startIndex + ? groupIdentity(renderItems[draggedIndex - 1]) + : nil + let afterGroup = draggedIndex < renderItems.index(before: renderItems.endIndex) + ? groupIdentity(renderItems[draggedIndex + 1]) + : nil + let membership: UUID? = (beforeGroup == afterGroup) ? beforeGroup : nil + guard renderItems[draggedIndex].effectiveGroupId != membership else { return renderItems } + var result = renderItems + result[draggedIndex] = result[draggedIndex].withEffectiveGroupId(membership) + return result + } + + /// The group a render item counts as for neighbor-membership purposes: the + /// group a header anchors, or a workspace row's effective group. + private static func groupIdentity(_ item: SidebarWorkspaceRenderItem) -> UUID? { + switch item { + case .groupHeader(let group, _): + return group.id + case .workspace(_, let effectiveGroupId): + return effectiveGroupId + } + } + + /// The id order after moving the dragged workspace to the indicator slot, + /// or nil when the move is a no-op. + private static func dragPreviewWorkspaceIds( + _ ids: [UUID], + draggedWorkspaceId: UUID, + dropIndicator: SidebarDropIndicator + ) -> [UUID]? { + guard ids.contains(draggedWorkspaceId) else { return nil } + if dropIndicator.tabId == draggedWorkspaceId { + return ids + } + + var result = ids.filter { $0 != draggedWorkspaceId } + let insertionIndex: Int + if let targetWorkspaceId = dropIndicator.tabId { + guard let targetIndex = result.firstIndex(of: targetWorkspaceId) else { + return ids + } + insertionIndex = dropIndicator.edge == .top ? targetIndex : targetIndex + 1 + } else { + insertionIndex = result.count + } + + result.insert(draggedWorkspaceId, at: min(max(insertionIndex, 0), result.count)) + return result + } + + /// Groups the render list into reorderable blocks keyed by the id that + /// `reorderWorkspaceIds` orders. In top-level mode a group header plus its + /// members form one block (so the whole group moves together), except the + /// dragged member which is promoted to its own top-level block. + private static func dragPreviewBlocks( + _ items: [SidebarWorkspaceRenderItem], + reorderWorkspaceIds: [UUID], + draggedWorkspaceId: UUID, + topLevelMode: Bool + ) -> [(workspaceId: UUID, items: [SidebarWorkspaceRenderItem])] { + guard topLevelMode else { + return items.map { item in + (workspaceId: item.representedWorkspaceId, items: [item]) + } + } + + let reorderIdSet = Set(reorderWorkspaceIds) + var blocks: [(workspaceId: UUID, items: [SidebarWorkspaceRenderItem])] = [] + var index = items.startIndex + while index < items.endIndex { + switch items[index] { + case .groupHeader(let group, _): + var groupItems = [items[index]] + var promotedMemberItems: [SidebarWorkspaceRenderItem] = [] + index = items.index(after: index) + while index < items.endIndex { + guard case .workspace(let workspace, _) = items[index], + workspace.groupId == group.id else { + break + } + if workspace.id == draggedWorkspaceId, reorderIdSet.contains(workspace.id) { + promotedMemberItems.append(items[index].withEffectiveGroupId(nil)) + } else { + groupItems.append(items[index]) + } + index = items.index(after: index) + } + blocks.append((workspaceId: group.anchorWorkspaceId, items: groupItems)) + for item in promotedMemberItems { + blocks.append((workspaceId: item.representedWorkspaceId, items: [item])) + } + + case .workspace(let workspace, _): + blocks.append((workspaceId: workspace.id, items: [items[index]])) + index = items.index(after: index) + } + } + return blocks + } } diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 6c5269170ae3..7a8e6308bcb5 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -6,7 +6,8 @@ extension VerticalTabsSidebar { func sidebarWorkspaceGroupHeader( group: WorkspaceGroup, memberWorkspaceIds: [UUID], - renderContext: WorkspaceListRenderContext + renderContext: WorkspaceListRenderContext, + role: SidebarWorkspaceRowRenderRole = .list ) -> some View { let settings = renderContext.tabItemSettings let isAnchorActive = tabManager.selectedTabId == group.anchorWorkspaceId @@ -34,46 +35,21 @@ extension VerticalTabsSidebar { ) let modifierSymbol = renderContext.workspaceNumberShortcut.numberedDigitHintPrefix let showsHintForAnchor = modifierKeyMonitor.isModifierPressed - let topDropIndicatorVisible = SidebarTabDropIndicatorPredicate.topVisible( - forTabId: group.anchorWorkspaceId, - draggedTabId: dragState.draggedTabId, - dropIndicator: dragState.dropIndicator, - tabIds: renderContext.sidebarReorderIds - ) - let onDragStart: () -> NSItemProvider = { [anchorId = group.anchorWorkspaceId] in - #if DEBUG - cmuxDebugLog("sidebar.onDrag groupAnchor=\(anchorId.uuidString.prefix(5))") - #endif - dragState.beginDragging(tabId: anchorId) - return SidebarTabDragPayload.provider(for: anchorId) - } - let tabDropDelegateFactory: (CGFloat) -> SidebarWorkspaceGroupHeaderDropDelegate = { [ - groupId = group.id, - anchorId = group.anchorWorkspaceId, - selectedTabIds = $selectedTabIds, - lastSidebarSelectionIndex = $lastSidebarSelectionIndex - ] rowHeight in - let reorderDelegate = SidebarTabDropDelegate( - targetTabId: anchorId, - tabManager: tabManager, - dragState: dragState, - selectedTabIds: selectedTabIds, - lastSidebarSelectionIndex: lastSidebarSelectionIndex, - targetRowHeight: rowHeight, - dragAutoScrollController: dragAutoScrollController - ) - return SidebarWorkspaceGroupHeaderDropDelegate( - targetGroupId: groupId, - targetAnchorWorkspaceId: anchorId, - tabManager: tabManager, - dragState: dragState, - targetRowHeight: rowHeight, - dragAutoScrollController: dragAutoScrollController, - reorderDelegate: reorderDelegate + // Dragging a group header reorders the whole group at top level; the + // shared reorder helpers handle the anchor/top-level scope. + let onReorderChanged: (CGPoint, CGPoint) -> Void = { [anchorId = group.anchorWorkspaceId, renderContext] startLocation, location in + sidebarReorderGestureChanged( + draggedId: anchorId, + startLocationY: startLocation.y, + cursorY: location.y, + renderContext: renderContext ) } + let onReorderEnded: (CGPoint, CGPoint) -> Void = { [anchorId = group.anchorWorkspaceId] _, _ in + sidebarReorderGestureEnded(draggedId: anchorId) + } - SidebarWorkspaceGroupHeaderView( + let header = SidebarWorkspaceGroupHeaderView( groupId: group.id, anchorWorkspaceId: group.anchorWorkspaceId, name: group.name, @@ -93,10 +69,11 @@ extension VerticalTabsSidebar { newWorkspacePlacement: newWorkspacePlacement, rowSpacing: tabRowSpacing, isFirstRow: renderContext.sidebarReorderIds.first == group.anchorWorkspaceId, - isBeingDragged: dragState.draggedTabId == group.anchorWorkspaceId, - topDropIndicatorVisible: topDropIndicatorVisible, - onDragStart: onDragStart, - tabDropDelegateFactory: tabDropDelegateFactory, + isBeingDragged: role == .list && dragState.draggedTabId == group.anchorWorkspaceId, + topDropIndicatorVisible: false, + onReorderChanged: onReorderChanged, + onReorderEnded: onReorderEnded, + isReorderEnabled: role == .list, onToggleCollapsed: { [weak tabManager, groupId = group.id] in tabManager?.toggleWorkspaceGroupCollapsed(groupId: groupId) }, @@ -152,11 +129,19 @@ extension VerticalTabsSidebar { } ) .equatable() - .id(group.anchorWorkspaceId) - .accessibilityIdentifier("sidebarWorkspaceGroup.\(group.id.uuidString)") - .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([group.anchorWorkspaceId])) - .anchorPreference(key: SidebarWorkspaceRowFramePreferenceKey.self, value: .bounds) { [anchorId = group.anchorWorkspaceId] anchor in - [anchorId: anchor] + + if role == .dragFollower { + header + .allowsHitTesting(false) + .accessibilityHidden(true) + } else { + header + .id(group.anchorWorkspaceId) + .accessibilityIdentifier("sidebarWorkspaceGroup.\(group.id.uuidString)") + .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([group.anchorWorkspaceId])) + .anchorPreference(key: SidebarWorkspaceRowFramePreferenceKey.self, value: .bounds) { [anchorId = group.anchorWorkspaceId] anchor in + [anchorId: anchor] + } } } } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index f68acc6d239d..86aff7b27598 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -436,6 +436,9 @@ C0DEF0A30000000000000001 /* SidebarPortDisplayText.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEF0A30000000000000002 /* SidebarPortDisplayText.swift */; }; C0DE48000000000000000001 /* SidebarProviderMenuRegressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE48000000000000000002 /* SidebarProviderMenuRegressionTests.swift */; }; B9000130A1B2C3D4E5F60719 /* SidebarPullRequestInteractivityUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9000131A1B2C3D4E5F60719 /* SidebarPullRequestInteractivityUITests.swift */; }; + D7AB34300000000000000531 /* SidebarReorderFollowerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000532 /* SidebarReorderFollowerView.swift */; }; + D7AB34300000000000000511 /* SidebarReorderIndicatorResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000512 /* SidebarReorderIndicatorResolver.swift */; }; + D7AB34300000000000000521 /* SidebarReorderRowFrameKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000522 /* SidebarReorderRowFrameKey.swift */; }; B8F266236A1A3D9A45BD840F /* SidebarResizeUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 818DBCD4AB69EB72573E8138 /* SidebarResizeUITests.swift */; }; C0DE35010000000000000001 /* SidebarScrim.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE35010000000000000002 /* SidebarScrim.swift */; }; E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */; }; @@ -528,6 +531,7 @@ A5001204 /* UpdateViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001214 /* UpdateViewModel.swift */; }; B35750000000000000000006 /* VaultAgentProcessScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = B35750000000000000000005 /* VaultAgentProcessScanner.swift */; }; B35750000000000000000002 /* VaultAgentRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = B35750000000000000000001 /* VaultAgentRegistry.swift */; }; + D7AB34300000000000000541 /* VerticalTabsSidebar+Reorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000542 /* VerticalTabsSidebar+Reorder.swift */; }; C9A57209C9A57209C9A57209 /* VerticalTabsSidebar+WorkspaceGroups.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A5720AC9A5720AC9A5720A /* VerticalTabsSidebar+WorkspaceGroups.swift */; }; ACE4FE1A8F1CC6C0B6A673AB /* VMClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CEC6EF35B71AE59FA45BA69 /* VMClient.swift */; }; ACE4FE2A8F1CC6C0B6A673AB /* VMClientSocketCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CEC6F0035B71AE59FA45BA7 /* VMClientSocketCommands.swift */; }; @@ -1057,6 +1061,9 @@ C0DEF0A30000000000000002 /* SidebarPortDisplayText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarPortDisplayText.swift; sourceTree = ""; }; C0DE48000000000000000002 /* SidebarProviderMenuRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarProviderMenuRegressionTests.swift; sourceTree = ""; }; B9000131A1B2C3D4E5F60719 /* SidebarPullRequestInteractivityUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarPullRequestInteractivityUITests.swift; sourceTree = ""; }; + D7AB34300000000000000532 /* SidebarReorderFollowerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarReorderFollowerView.swift; sourceTree = ""; }; + D7AB34300000000000000512 /* SidebarReorderIndicatorResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarReorderIndicatorResolver.swift; sourceTree = ""; }; + D7AB34300000000000000522 /* SidebarReorderRowFrameKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarReorderRowFrameKey.swift; sourceTree = ""; }; 818DBCD4AB69EB72573E8138 /* SidebarResizeUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarResizeUITests.swift; sourceTree = ""; }; C0DE35010000000000000002 /* SidebarScrim.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarScrim.swift; sourceTree = ""; }; 9AD52285508B1D6A9875E7B3 /* SidebarSelectionState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarSelectionState.swift; sourceTree = ""; }; @@ -1147,6 +1154,7 @@ A5001214 /* UpdateViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/UpdateViewModel.swift; sourceTree = ""; }; B35750000000000000000005 /* VaultAgentProcessScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VaultAgentProcessScanner.swift; sourceTree = ""; }; B35750000000000000000001 /* VaultAgentRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VaultAgentRegistry.swift; sourceTree = ""; }; + D7AB34300000000000000542 /* VerticalTabsSidebar+Reorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Sidebar/VerticalTabsSidebar+Reorder.swift"; sourceTree = ""; }; C9A5720AC9A5720AC9A5720A /* VerticalTabsSidebar+WorkspaceGroups.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "VerticalTabsSidebar+WorkspaceGroups.swift"; sourceTree = ""; }; 9CEC6EF35B71AE59FA45BA69 /* VMClient.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = VMClient.swift; sourceTree = ""; }; 9CEC6F0035B71AE59FA45BA7 /* VMClientSocketCommands.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = VMClientSocketCommands.swift; sourceTree = ""; }; @@ -1421,6 +1429,10 @@ C0DEF0A90000000000000002 /* ContentView+ForkAgentConversation.swift */, D7AB00000000000000000004 /* ContentView+MoveTabToNewWorkspace.swift */, D7AB34300000000000000002 /* SidebarDropPlanner.swift */, + D7AB34300000000000000512 /* SidebarReorderIndicatorResolver.swift */, + D7AB34300000000000000522 /* SidebarReorderRowFrameKey.swift */, + D7AB34300000000000000532 /* SidebarReorderFollowerView.swift */, + D7AB34300000000000000542 /* VerticalTabsSidebar+Reorder.swift */, EA1F00000000000000000002 /* SidebarPathFormatter.swift */, EA1F00000000000000000004 /* SidebarDirectoryText.swift */, D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */, @@ -2455,6 +2467,9 @@ D7AB34300000000000000001 /* SidebarDropPlanner.swift in Sources */, EA1F00000000000000000001 /* SidebarPathFormatter.swift in Sources */, C0DEF0A30000000000000001 /* SidebarPortDisplayText.swift in Sources */, + D7AB34300000000000000531 /* SidebarReorderFollowerView.swift in Sources */, + D7AB34300000000000000511 /* SidebarReorderIndicatorResolver.swift in Sources */, + D7AB34300000000000000521 /* SidebarReorderRowFrameKey.swift in Sources */, C0DE35010000000000000001 /* SidebarScrim.swift in Sources */, E62155868BB29FEB5DAAAF25 /* SidebarSelectionState.swift in Sources */, F57072635F25EBCA741E125D /* SidebarState.swift in Sources */, @@ -2519,6 +2534,7 @@ A5001204 /* UpdateViewModel.swift in Sources */, B35750000000000000000006 /* VaultAgentProcessScanner.swift in Sources */, B35750000000000000000002 /* VaultAgentRegistry.swift in Sources */, + D7AB34300000000000000541 /* VerticalTabsSidebar+Reorder.swift in Sources */, C9A57209C9A57209C9A57209 /* VerticalTabsSidebar+WorkspaceGroups.swift in Sources */, ACE4FE1A8F1CC6C0B6A673AB /* VMClient.swift in Sources */, ACE4FE2A8F1CC6C0B6A673AB /* VMClientSocketCommands.swift in Sources */, diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 5df4206e679f..80b1b2450a86 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -183,7 +183,7 @@ struct WorkspaceGroupTests { groupMemberIds = memberWorkspaceIds case .groupHeader: break - case .workspace(let workspace): + case .workspace(let workspace, _): visibleWorkspaceIds.append(workspace.id) } } @@ -709,3 +709,71 @@ struct WorkspaceGroupTests { #expect(RenderableSystemSymbol.resolvedSurfaceTabIcon(" ") == "doc.text") } } + +/// Covers the gesture-driven reorder hit-testing + hysteresis that +/// `SidebarReorderIndicatorResolver` adds on top of `SidebarDropPlanner`. +@Suite("Sidebar reorder indicator resolver") +struct SidebarReorderIndicatorResolverTests { + private func band(_ id: UUID, _ minY: CGFloat, _ maxY: CGFloat) -> SidebarReorderIndicatorResolver.Band { + .init(id: id, minY: minY, maxY: maxY) + } + + @Test func cursorBelowAllRowsAppendsToEnd() { + let a = UUID(); let b = UUID(); let c = UUID() + let bands = [band(a, 0, 20), band(b, 22, 42), band(c, 44, 64)] + let indicator = SidebarReorderIndicatorResolver.resolve( + cursorY: 200, bands: bands, draggedId: a, pinnedIds: [], current: nil, hysteresisMargin: 6 + ) + #expect(indicator?.tabId == nil) + #expect(indicator?.edge == .bottom) + } + + @Test func cursorInTopHalfOfFirstRowTargetsItsTop() { + let a = UUID(); let b = UUID(); let c = UUID() + let bands = [band(a, 0, 20), band(b, 22, 42), band(c, 44, 64)] + // Dragging C; hovering the top half of A should land it before A. + let indicator = SidebarReorderIndicatorResolver.resolve( + cursorY: 3, bands: bands, draggedId: c, pinnedIds: [], current: nil, hysteresisMargin: 6 + ) + #expect(indicator?.tabId == a) + #expect(indicator?.edge == .top) + } + + @Test func hysteresisHoldsCurrentEdgeNearMidpoint() { + let a = UUID(); let b = UUID(); let c = UUID() + let bands = [band(a, 0, 20), band(b, 20, 40), band(c, 40, 60)] + // Dragging A. Current landing slot is "after B" (canonicalized to top of C). + let current = SidebarDropIndicator(tabId: c, edge: .top) + // Cursor just above B's midpoint (30) and within the 6pt dead-zone: the + // raw decision flips to "before B", but stickiness keeps the current slot. + let held = SidebarReorderIndicatorResolver.resolve( + cursorY: 29, bands: bands, draggedId: a, pinnedIds: [], current: current, hysteresisMargin: 6 + ) + #expect(held == current) + // With no hysteresis the same cursor flips the slot. + let flipped = SidebarReorderIndicatorResolver.resolve( + cursorY: 29, bands: bands, draggedId: a, pinnedIds: [], current: current, hysteresisMargin: 0 + ) + #expect(flipped != current) + } + + @Test func clearMidpointCrossingFlipsEdge() { + let a = UUID(); let b = UUID(); let c = UUID() + let bands = [band(a, 0, 20), band(b, 20, 40), band(c, 40, 60)] + let current = SidebarDropIndicator(tabId: c, edge: .top) // after B + // Dragging C; cursor well into the top of B (far outside the dead-zone) + // lands before B. + let indicator = SidebarReorderIndicatorResolver.resolve( + cursorY: 22, bands: bands, draggedId: c, pinnedIds: [], current: current, hysteresisMargin: 6 + ) + #expect(indicator?.tabId == b) + #expect(indicator?.edge == .top) + } + + @Test func emptyBandsResolveToNil() { + let indicator = SidebarReorderIndicatorResolver.resolve( + cursorY: 10, bands: [], draggedId: UUID(), pinnedIds: [], current: nil, hysteresisMargin: 6 + ) + #expect(indicator == nil) + } +} From f81905fce3b2025a28336226f72ab03118a49a60 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Tue, 2 Jun 2026 06:52:28 -0700 Subject: [PATCH 02/36] Keep reorder gesture host stable during drag Move the dragged-row placeholder opacity out of TabItemView / SidebarWorkspaceGroupHeaderView and into the parent builders, and drop isBeingDragged from those views (and their == ). The gesture lives inside the equatable row; if isBeingDragged were an input it would flip when the drag starts, re-evaluate the row body, and could tear down the in-flight DragGesture. With the row's inputs constant during a drag, .equatable() skips its body and the gesture survives. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 13 ++++++------- Sources/SidebarWorkspaceGroupHeaderView.swift | 5 ----- Sources/VerticalTabsSidebar+WorkspaceGroups.swift | 7 ++++++- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 4c5a789fd41b..890cc34ea2b5 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12334,7 +12334,6 @@ struct VerticalTabsSidebar: View { lastSidebarSelectionIndex: $lastSidebarSelectionIndex, showsModifierShortcutHints: resolvedShowsModifierShortcutHints, dragAutoScrollController: dragAutoScrollController, - isBeingDragged: isBeingDragged, topDropIndicatorVisible: false, onReorderChanged: onReorderChanged, onReorderEnded: onReorderEnded, @@ -12352,13 +12351,19 @@ struct VerticalTabsSidebar: View { .equatable() let indent: CGFloat = tab.groupId != nil ? SidebarWorkspaceGroupingMetrics.memberIndent : 0 + // Applying the dragged-row "invisible placeholder" opacity here in the + // parent (rather than inside `TabItemView`) keeps the gesture-hosting + // row's inputs constant during a drag, so `.equatable()` skips its body + // and the in-flight `DragGesture` is not torn down when the drag starts. if role == .dragFollower { row + .opacity(isBeingDragged ? 0 : 1) .allowsHitTesting(false) .accessibilityHidden(true) .padding(.leading, indent) } else { row + .opacity(isBeingDragged ? 0 : 1) .id(tab.id) .accessibilityIdentifier("sidebarWorkspace.\(tab.id.uuidString)") .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([tab.id])) @@ -14824,7 +14829,6 @@ struct TabItemView: View, Equatable { lhs.allRemoteContextMenuTargetsDisconnected == rhs.allRemoteContextMenuTargetsDisconnected && lhs.contextMenuPinState == rhs.contextMenuPinState && lhs.workspaceGroupMenuSnapshot == rhs.workspaceGroupMenuSnapshot && - lhs.isBeingDragged == rhs.isBeingDragged && lhs.topDropIndicatorVisible == rhs.topDropIndicatorVisible && lhs.isReorderEnabled == rhs.isReorderEnabled && lhs.settings == rhs.settings @@ -14857,7 +14861,6 @@ struct TabItemView: View, Equatable { // (see CLAUDE.md). When drag state changes, the parent recomputes these // per-row snapshots and `==` skips re-render for rows whose snapshot is // unchanged. - let isBeingDragged: Bool let topDropIndicatorVisible: Bool /// Reorder gesture callbacks (start location, current location), dispatched /// into the shared `VerticalTabsSidebar` reorder helpers via closures so the @@ -15520,10 +15523,6 @@ struct TabItemView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .contentShape(Rectangle()) - // The row being dragged renders fully invisible: its visible copy is the - // floating `SidebarReorderFollowerView`, and this slot is the gap the - // surrounding rows animate open around. - .opacity(isBeingDragged ? 0 : 1) .overlay { SidebarWorkspaceRowHoverTracker(rowInteractionState: $rowInteractionState) } diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index d0af38928d68..5fef47cc00a1 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -26,7 +26,6 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.newWorkspacePlacement == rhs.newWorkspacePlacement && lhs.rowSpacing == rhs.rowSpacing && lhs.isFirstRow == rhs.isFirstRow && - lhs.isBeingDragged == rhs.isBeingDragged && lhs.topDropIndicatorVisible == rhs.topDropIndicatorVisible && lhs.isReorderEnabled == rhs.isReorderEnabled } @@ -50,7 +49,6 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let newWorkspacePlacement: WorkspaceGroupNewPlacement? let rowSpacing: CGFloat let isFirstRow: Bool - let isBeingDragged: Bool let topDropIndicatorVisible: Bool /// Reorder gesture callbacks dispatched into the shared reorder helpers. let onReorderChanged: (CGPoint, CGPoint) -> Void @@ -224,9 +222,6 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) - // The dragged header renders invisible; its visible copy is the floating - // follower and this slot is the gap that opens during a reorder. - .opacity(isBeingDragged ? 0 : 1) .overlay(alignment: .top) { SidebarWorkspaceTopDropIndicator( isVisible: topDropIndicatorVisible, diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 7a8e6308bcb5..a27696f9cc8d 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -48,6 +48,10 @@ extension VerticalTabsSidebar { let onReorderEnded: (CGPoint, CGPoint) -> Void = { [anchorId = group.anchorWorkspaceId] _, _ in sidebarReorderGestureEnded(draggedId: anchorId) } + // Computed in the parent and applied as opacity below (not passed into + // the header view) so the gesture-hosting header's inputs stay constant + // during a drag and its in-flight `DragGesture` is not torn down. + let isBeingDragged = role == .list && dragState.draggedTabId == group.anchorWorkspaceId let header = SidebarWorkspaceGroupHeaderView( groupId: group.id, @@ -69,7 +73,6 @@ extension VerticalTabsSidebar { newWorkspacePlacement: newWorkspacePlacement, rowSpacing: tabRowSpacing, isFirstRow: renderContext.sidebarReorderIds.first == group.anchorWorkspaceId, - isBeingDragged: role == .list && dragState.draggedTabId == group.anchorWorkspaceId, topDropIndicatorVisible: false, onReorderChanged: onReorderChanged, onReorderEnded: onReorderEnded, @@ -132,10 +135,12 @@ extension VerticalTabsSidebar { if role == .dragFollower { header + .opacity(isBeingDragged ? 0 : 1) .allowsHitTesting(false) .accessibilityHidden(true) } else { header + .opacity(isBeingDragged ? 0 : 1) .id(group.anchorWorkspaceId) .accessibilityIdentifier("sidebarWorkspaceGroup.\(group.id.uuidString)") .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([group.anchorWorkspaceId])) From e120bfd565ebb8ba3d927edb5af0f9948512fd45 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 10 Jun 2026 02:18:08 -0700 Subject: [PATCH 03/36] Sidebar workspace group animations + rollup + focus fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Animate group structure changes and fix two grouping UX issues, built on the promote-in-place workspace→group feature. Animations (shared via SidebarGroupAnimation, so every entrypoint — keyboard, context menu, header buttons, socket/CLI — animates identically): - Promote/ungroup morph: a workspace row now crossfade-morphs into a group header in place (and back). Root fix: key the sidebar ForEach on the anchor/workspace UUID (stable across the morph and also the scrollTo target) and drop the inner per-row .id() that was pinning identity and suppressing the _ConditionalContent transition. Removes the prior .id(groupAnchorSignature) whole-list rebuild hack, which also restores sidebar scroll position on group create/ungroup. - Multi-select grouping (createWorkspaceGroup) wrapped in withAnimation so the fresh anchor fades in and members indent in, matching the single case. - Collapse/expand: members slide+fade, chevron rotates (single rotated glyph instead of swapped images). - Member join/leave (incl. drag-into-group) and drag-reorder drop-settle animate via withAnimation around the TabManager mutations. Group header notification badge now rolls up unread across ALL members (anchor included), collapsed or expanded, instead of only the anchor when expanded. Renamed anchorUnreadCount → groupUnreadCount; animated count via contentTransition(.numericText). Keep focus on the user's current workspace when grouping a multi-selection: interactive ⌘⇧G / "New Group from Selection" pass selectAnchor: false and the collapse step prefers the previously-focused member over the new empty anchor. Socket/CLI path unchanged (non-focus per policy). Removed the blue sidebar drop-indicator line per dogfood feedback. Tests: promote-in-place keeps anchor render identity (round-trips through ungroup); delete removes the header + member rows from render items. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/AppDelegate.swift | 5 +- Sources/ContentView.swift | 81 ++++--- Sources/SidebarWorkspaceGroupHeaderView.swift | 21 +- Sources/SidebarWorkspaceGroupingMetrics.swift | 31 +++ Sources/SidebarWorkspaceRenderItem.swift | 27 ++- Sources/TabItemView+WorkspaceGroups.swift | 4 +- Sources/TabManager.swift | 226 +++++++++++------- .../VerticalTabsSidebar+WorkspaceGroups.swift | 23 +- cmuxTests/WorkspaceGroupTests.swift | 91 +++++++ 9 files changed, 370 insertions(+), 139 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 0ccaa6d607c4..d1a38ea421f2 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -14609,8 +14609,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return false } // No name prompt: TabManager auto-names ("Group N"). Rename via the - // header context menu. - tabManager.createWorkspaceGroup(name: "", childWorkspaceIds: eligibleIds) + // header context menu. selectAnchor: false keeps the user focused on + // the workspace they were already in rather than the new empty anchor. + tabManager.createWorkspaceGroup(name: "", childWorkspaceIds: eligibleIds, selectAnchor: false) return true } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 6df5db533fab..0a1815e3ca25 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -9617,7 +9617,9 @@ struct ContentView: View { let currentIndex = selectedWorkspaceIndex() else { return } let targetIndex = currentIndex + delta guard targetIndex >= 0, targetIndex < tabManager.tabs.count else { return } - _ = tabManager.reorderWorkspace(tabId: workspace.id, toIndex: targetIndex) + withAnimation(SidebarGroupAnimation.structure) { + _ = tabManager.reorderWorkspace(tabId: workspace.id, toIndex: targetIndex) + } tabManager.selectWorkspace(workspace) } @@ -10531,14 +10533,12 @@ struct SidebarWorkspaceTopDropIndicator: View { let isFirstRow: Bool let rowSpacing: CGFloat + // Intentionally renders nothing. The blue insertion line was removed per + // dogfood feedback; sidebar reorder feedback is the dragged row dimming + // plus the animated drop-settle. The inputs are kept so call sites and the + // drag drop-target plumbing stay unchanged. var body: some View { - if isVisible { - Rectangle() - .fill(cmuxAccentColor()) - .frame(height: 2) - .padding(.horizontal, 8) - .offset(y: isFirstRow ? 0 : -(rowSpacing / 2)) - } + EmptyView() } } @@ -12377,20 +12377,28 @@ struct VerticalTabsSidebar: View { // drag mutations at 60fps invalidate only the rows/overlays that // read them, never this sidebar body. See SidebarDragState and // https://github.com/manaflow-ai/cmux/issues/2586. - // Force a clean row rebuild whenever the SET of group anchors changes - // (a workspace becoming, or ceasing to be, a group header). A sidebar - // row that switches in place between a `.workspace` row and a - // `.groupHeader` is mis-diffed by LazyVStack: turning the focused - // workspace into a single-member group left the header invisible, and - // ungrouping left a stale header. Keying on the anchor SET (sorted, so - // it ignores reorders) flips identity on group create/ungroup/anchor - // changes only, so neither drag-reorder nor rename triggers a rebuild. - let groupAnchorSignature = renderContext.workspaceGroups - .map { $0.anchorWorkspaceId.uuidString } - .sorted() - .joined(separator: ",") + // + // No `.id(groupAnchorSignature)` rebuild hack here: a group header now + // shares ForEach identity with its anchor workspace's row (see + // `SidebarWorkspaceRenderItem.id`), so promoting a workspace in place + // or ungrouping keeps the same slot identity and only swaps that row's + // `_ConditionalContent` branch between a `.workspace` row and a + // `.groupHeader`. SwiftUI keeps the materialized row instead of + // dropping it, so the header renders correctly without a whole-list + // rebuild, sidebar scroll is preserved, and the structural change can + // animate. The matching `.transition(.sidebarGroupRow)` on each branch + // crossfades the morph; the `withAnimation` transaction wrapped around + // the `TabManager` group mutations animates the list reflow. + // Identify rows by the anchor/workspace UUID rather than the render-item + // string id. The UUID is stable across promote/ungroup (a header keeps + // its anchor's id), so the slot survives the morph, AND it doubles as + // the `ScrollViewReader.scrollTo(selectedWorkspaceId)` target — which is + // why the inner `.id(...)` on each branch can be dropped. Without those + // inner ids pinning identity, the `_ConditionalContent` swap between a + // workspace row and a group header runs its `.transition`, so the + // promote/ungroup morph crossfades instead of replacing instantly. let rows = LazyVStack(spacing: tabRowSpacing) { - ForEach(renderItems, id: \.id) { item in + ForEach(renderItems, id: \.scrollAnchorWorkspaceId) { item in switch item { case .groupHeader(let group, let memberWorkspaceIds): sidebarWorkspaceGroupHeader( @@ -12399,18 +12407,19 @@ struct VerticalTabsSidebar: View { renderContext: renderContext, shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets ) + .transition(.sidebarGroupRow) case .workspace(let tab): workspaceRow( tab, renderContext: renderContext, shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets ) + .transition(.sidebarGroupRow) } } } .padding(.vertical, SidebarWorkspaceListMetrics.rowVerticalPadding) .frame(maxWidth: .infinity, alignment: .leading) - .id(groupAnchorSignature) // Gate ONLY the per-row frame-anchor *reader* (the virtualization-defeating // work) behind the drag-active check, and keep the Bonsplit drop-capture @@ -12643,7 +12652,10 @@ struct VerticalTabsSidebar: View { onContextMenuDisappear: onContextMenuDisappear ) .equatable() - .id(tab.id) + // No `.id(tab.id)` here: the row identity is set by the ForEach + // (`id: \.scrollAnchorWorkspaceId`), which also serves scroll-to. An + // inner `.id` would re-pin identity and suppress the workspace↔header + // morph transition. .accessibilityIdentifier("sidebarWorkspace.\(tab.id.uuidString)") .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([tab.id])) @@ -16291,7 +16303,10 @@ struct TabItemView: View, Equatable { private func moveBy(_ delta: Int) { let targetIndex = index + delta guard targetIndex >= 0, targetIndex < tabManager.tabs.count else { return } - guard tabManager.reorderWorkspace(tabId: tab.id, toIndex: targetIndex) else { return } + let didReorder = withAnimation(SidebarGroupAnimation.structure) { + tabManager.reorderWorkspace(tabId: tab.id, toIndex: targetIndex) + } + guard didReorder else { return } selectedTabIds = [tab.id] lastSidebarSelectionIndex = tabManager.tabs.firstIndex { $0.id == tab.id } tabManager.selectTab(tab) @@ -17977,12 +17992,18 @@ struct SidebarTabDropDelegate: DropDelegate { existingAnchorIndex: lastSidebarSelectionIndex, liveWorkspaceIds: tabManager.tabs.map(\.id) ) - let didReorder = tabManager.reorderSidebarWorkspace( - tabId: draggedTabId, - toIndex: targetIndex, - isDragOperation: true, - usesTopLevelRows: usesTopLevelRows - ) + // Animate the drop settle: rows glide to their new positions instead of + // snapping. The array mutates once here (the live drag only moves a + // visual indicator, not the model), so this is post-drag and safe under + // the LazyVStack — it does not touch the 60fps drag hot path. + let didReorder = withAnimation(SidebarGroupAnimation.structure) { + tabManager.reorderSidebarWorkspace( + tabId: draggedTabId, + toIndex: targetIndex, + isDragOperation: true, + usesTopLevelRows: usesTopLevelRows + ) + } syncSidebarSelection( preserving: selectionBeforeReorder, preferredAnchorWorkspaceId: anchorWorkspaceIdBeforeReorder diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 9c45d697145d..bafd2b2b9504 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -16,7 +16,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.isPinned == rhs.isPinned && lhs.isAnchorActive == rhs.isAnchorActive && lhs.memberCount == rhs.memberCount && - lhs.anchorUnreadCount == rhs.anchorUnreadCount && + lhs.groupUnreadCount == rhs.groupUnreadCount && lhs.shortcutDigit == rhs.shortcutDigit && lhs.shortcutModifierSymbol == rhs.shortcutModifierSymbol && lhs.showsShortcutHint == rhs.showsShortcutHint && @@ -40,7 +40,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isPinned: Bool let isAnchorActive: Bool let memberCount: Int - let anchorUnreadCount: Int + let groupUnreadCount: Int let shortcutDigit: Int? let shortcutModifierSymbol: String? let showsShortcutHint: Bool @@ -105,9 +105,16 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { var body: some View { HStack(spacing: 4) { - Image(systemName: isCollapsed ? "chevron.right" : "chevron.down") + // One chevron rotated rather than two swapped glyphs, so the + // disclosure twist animates. Rotation is keyed locally to + // `isCollapsed` so it spins even on entrypoints that don't wrap the + // toggle in `withAnimation` (e.g. socket/CLI); `chevron.right` at + // 0° points right (collapsed) and at 90° points down (expanded). + Image(systemName: "chevron.right") .font(.system(size: metrics.chevronFontSize, weight: .semibold)) .foregroundStyle(.secondary) + .rotationEffect(.degrees(isCollapsed ? 0 : 90)) + .animation(SidebarGroupAnimation.collapse, value: isCollapsed) .frame(width: metrics.chevronFrame, height: metrics.chevronFrame) .contentShape(Rectangle()) .onTapGesture { onToggleCollapsed() } @@ -131,16 +138,18 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .foregroundStyle(isAnchorActive ? Color.primary : Color.primary.opacity(0.9)) .lineLimit(1) .truncationMode(.tail) - if anchorUnreadCount > 0 { - Text("\(anchorUnreadCount)") + if groupUnreadCount > 0 { + Text("\(groupUnreadCount)") .font(.system(size: metrics.unreadFontSize, weight: .semibold)) .foregroundStyle(.white) .padding(.horizontal, metrics.unreadHorizontalPadding) .padding(.vertical, metrics.unreadVerticalPadding) .background(Capsule().fill(Color.accentColor)) + .contentTransition(.numericText(value: Double(groupUnreadCount))) + .animation(SidebarGroupAnimation.collapse, value: groupUnreadCount) .accessibilityLabel(Text(String.localizedStringWithFormat( String(localized: "workspaceGroup.unread.a11y", defaultValue: "%lld unread"), - anchorUnreadCount + groupUnreadCount ))) } } diff --git a/Sources/SidebarWorkspaceGroupingMetrics.swift b/Sources/SidebarWorkspaceGroupingMetrics.swift index bfc85aba1d40..5d28e7d96654 100644 --- a/Sources/SidebarWorkspaceGroupingMetrics.swift +++ b/Sources/SidebarWorkspaceGroupingMetrics.swift @@ -4,3 +4,34 @@ enum SidebarWorkspaceGroupingMetrics { /// Leading inset applied to workspace rows that visually nest under a group header. static let memberIndent: CGFloat = 12 } + +/// Shared animation timings for workspace-group structure changes in the +/// sidebar (promote-in-place, ungroup, collapse/expand, member join/leave, +/// drag-reorder settle). +/// +/// One source of truth so every entrypoint that mutates group structure +/// (keyboard shortcut, context menu, group-header buttons, drag-and-drop, +/// socket/CLI) animates identically. The `TabManager` group mutation methods +/// wrap their structural changes in `withAnimation(SidebarGroupAnimation.)`, +/// and the sidebar rows carry `.transition(.sidebarGroupRow)` so inserted or +/// removed rows fade while their siblings reflow within the same transaction. +enum SidebarGroupAnimation { + /// Workspace row morphs into a group header (and back), member rows join or + /// leave a group, drag-reorder drops settle. + static let structure: Animation = .snappy(duration: 0.26) + + /// Group collapse / expand: member rows slide+fade and the chevron rotates. + static let collapse: Animation = .snappy(duration: 0.24) +} + +extension AnyTransition { + /// Transition for a sidebar row appearing or disappearing because of a + /// group-structure change. A plain opacity fade keeps the morph between a + /// workspace row and a group header (same ForEach identity, swapped + /// `_ConditionalContent` branch) reading as a crossfade, while the + /// surrounding `withAnimation` transaction animates the list reflow so + /// collapse/expand and member join/leave feel like a slide for free. + static var sidebarGroupRow: AnyTransition { + .opacity + } +} diff --git a/Sources/SidebarWorkspaceRenderItem.swift b/Sources/SidebarWorkspaceRenderItem.swift index ceabeaf594f9..0bcb2bc8c3ed 100644 --- a/Sources/SidebarWorkspaceRenderItem.swift +++ b/Sources/SidebarWorkspaceRenderItem.swift @@ -9,11 +9,36 @@ enum SidebarWorkspaceRenderItem { var id: String { switch self { case .groupHeader(let group, _): - return "group.\(group.id.uuidString)" + // Share identity with the anchor workspace's row. The group header + // *is* the anchor workspace's sidebar slot, so promoting a + // workspace in place (or ungrouping) keeps the same ForEach + // identity at that position and only swaps the row's content + // between a `.workspace` row and a `.groupHeader`. That lets + // SwiftUI animate the morph instead of insert+delete, and it stops + // the LazyVStack from dropping the materialized row when the slot + // changes kind — the bug that previously forced a whole-list + // `.id(groupAnchorSignature)` rebuild (and reset sidebar scroll). + return "workspace.\(group.anchorWorkspaceId.uuidString)" case .workspace(let workspace): return "workspace.\(workspace.id.uuidString)" } } + + /// The workspace UUID this row occupies, used for the row's SwiftUI `.id()` + /// so `ScrollViewReader.scrollTo(selectedWorkspaceId)` can find it. Applied + /// on the row *wrapper* (not the inner header/workspace branches) so the + /// `_ConditionalContent` swap between a workspace row and a group header + /// still runs its `.transition` and animates the promote/ungroup morph. + /// A group header occupies its anchor workspace's slot, so both kinds map + /// to the same UUID, keeping the slot identity stable across the morph. + var scrollAnchorWorkspaceId: UUID { + switch self { + case .groupHeader(let group, _): + return group.anchorWorkspaceId + case .workspace(let workspace): + return workspace.id + } + } static func renderItems( tabs: [Workspace], groupsById: [UUID: WorkspaceGroup] diff --git a/Sources/TabItemView+WorkspaceGroups.swift b/Sources/TabItemView+WorkspaceGroups.swift index c46ace4ab7c7..a49226623115 100644 --- a/Sources/TabItemView+WorkspaceGroups.swift +++ b/Sources/TabItemView+WorkspaceGroups.swift @@ -91,7 +91,9 @@ extension TabItemView { func promptNewWorkspaceGroup(workspaceIds: [UUID]) { guard !workspaceIds.isEmpty else { return } - tabManager.createWorkspaceGroup(name: "", childWorkspaceIds: workspaceIds) + // selectAnchor: false keeps focus on the workspace the user was already + // in instead of jumping to the new empty group-pivot anchor. + tabManager.createWorkspaceGroup(name: "", childWorkspaceIds: workspaceIds, selectAnchor: false) } func promptWorkspaceGroupFromWorkspace(workspaceId: UUID) { diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 07e3c520e07e..e05bb7e5b787 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -4175,62 +4175,87 @@ class TabManager: ObservableObject { let inferredCwd: String? = anchorWorkingDirectory ?? firstChildTab?.currentDirectory let originalTabOrder = tabs.map(\.id) + // Remember what the user was focused on before grouping. When we don't + // explicitly focus the new anchor (interactive ⌘⇧G / context menu pass + // selectAnchor: false), keep focus on that workspace instead of jumping + // to the freshly-created, empty group-pivot anchor. + let previousSelectedId = selectedTabId + + // Animate the fresh-anchor grouping (multi-select "New Group from + // Selection" / 2+ ⌘⇧G): the new header row fades in at the top and the + // selected workspaces indent in under it. Same animation as the + // single-workspace promote so both grouping paths feel identical. + return withAnimation(SidebarGroupAnimation.structure) { + let anchor = addWorkspace( + title: resolvedName, + workingDirectory: inferredCwd, + inheritWorkingDirectory: inferredCwd == nil, + select: selectAnchor, + placementOverride: .top, + autoWelcomeIfNeeded: false, + normalizeWorkspaceGroupsAfterInsert: false + ) - let anchor = addWorkspace( - title: resolvedName, - workingDirectory: inferredCwd, - inheritWorkingDirectory: inferredCwd == nil, - select: selectAnchor, - placementOverride: .top, - autoWelcomeIfNeeded: false, - normalizeWorkspaceGroupsAfterInsert: false - ) - - let group = WorkspaceGroup( - id: UUID(), - name: resolvedName, - isCollapsed: false, - isPinned: false, - anchorWorkspaceId: anchor.id, - customColor: nil, - iconSymbol: nil - ) - workspaceGroups.append(group) - anchor.groupId = group.id - for id in eligibleChildren { - assignGroup(workspaceId: id, groupId: group.id) - } - placeNewWorkspaceGroupAtCreationPosition( - groupId: group.id, - anchorId: anchor.id, - childWorkspaceIds: eligibleChildren, - originalTabOrder: originalTabOrder - ) - // Collapse the sidebar multi-selection so a second ⌘⇧G press doesn't - // immediately reuse the same child ids and create a duplicate group - // around them. The new anchor is the only sensible "current" - // selection at this point. Posts the hide notification so the - // SwiftUI sidebar binding follows. - // - // Skipped for the non-focus socket/CLI path (caller passes - // collapseSidebarSelection: false): per the socket focus policy in - // CLAUDE.md, those entrypoints must not mutate the user's active - // sidebar selection. - if collapseSidebarSelection, - !sidebarSelectedWorkspaceIds.isDisjoint(with: Set(eligibleChildren)) || sidebarSelectedWorkspaceIds.count > 1 { - let hiddenIds = sidebarSelectedWorkspaceIds - sidebarSelectedWorkspaceIds = [anchor.id] - NotificationCenter.default.post( - name: .sidebarMultiSelectionDidHide, - object: self, - userInfo: [ - SidebarMultiSelectionHideKey.hiddenWorkspaceIds: hiddenIds, - SidebarMultiSelectionHideKey.focusedWorkspaceId: anchor.id, - ] + let group = WorkspaceGroup( + id: UUID(), + name: resolvedName, + isCollapsed: false, + isPinned: false, + anchorWorkspaceId: anchor.id, + customColor: nil, + iconSymbol: nil ) + workspaceGroups.append(group) + anchor.groupId = group.id + for id in eligibleChildren { + assignGroup(workspaceId: id, groupId: group.id) + } + placeNewWorkspaceGroupAtCreationPosition( + groupId: group.id, + anchorId: anchor.id, + childWorkspaceIds: eligibleChildren, + originalTabOrder: originalTabOrder + ) + // Collapse the sidebar multi-selection so a second ⌘⇧G press doesn't + // immediately reuse the same child ids and create a duplicate group + // around them. The new anchor is the only sensible "current" + // selection at this point. Posts the hide notification so the + // SwiftUI sidebar binding follows. + // + // Skipped for the non-focus socket/CLI path (caller passes + // collapseSidebarSelection: false): per the socket focus policy in + // CLAUDE.md, those entrypoints must not mutate the user's active + // sidebar selection. + if collapseSidebarSelection, + !sidebarSelectedWorkspaceIds.isDisjoint(with: Set(eligibleChildren)) || sidebarSelectedWorkspaceIds.count > 1 { + let hiddenIds = sidebarSelectedWorkspaceIds + // Collapse the multi-selection to a single row. Prefer the + // workspace the user was already focused on (now a member) over + // the new empty anchor, so grouping doesn't yank them into the + // group-pivot workspace. Falls back to the anchor when the + // caller did want the anchor focused (selectAnchor: true) or the + // prior selection isn't one of the grouped workspaces. + let focusId: UUID = { + if !selectAnchor, + let previousSelectedId, + eligibleChildren.contains(previousSelectedId) { + return previousSelectedId + } + return anchor.id + }() + sidebarSelectedWorkspaceIds = [focusId] + NotificationCenter.default.post( + name: .sidebarMultiSelectionDidHide, + object: self, + userInfo: [ + SidebarMultiSelectionHideKey.hiddenWorkspaceIds: hiddenIds, + SidebarMultiSelectionHideKey.focusedWorkspaceId: focusId, + ] + ) + } + postWorkspaceOrderDidChange(movedWorkspaceIds: [anchor.id] + eligibleChildren) + return group.id } - postWorkspaceOrderDidChange(movedWorkspaceIds: [anchor.id] + eligibleChildren) - return group.id } /// Turn an existing workspace into a group by promoting it to be the @@ -4285,14 +4310,21 @@ class TabManager: ObservableObject { customColor: nil, iconSymbol: nil ) - workspaceGroups.append(group) - assignGroup(workspaceId: anchorWorkspaceId, groupId: group.id) - // The anchor is already at its sidebar position; normalize keeps it - // there (`sidebarTopLevelWorkspaceIds` maps the now-grouped workspace - // back to its anchor's slot) while syncing the workspaceGroups order - // to the tabs order. - normalizeWorkspaceGroupContiguity() - postWorkspaceOrderDidChange(movedWorkspaceIds: [anchorWorkspaceId]) + // Animate the workspace row morphing into its group header in place. + // The anchor keeps its ForEach identity (see + // `SidebarWorkspaceRenderItem.id`), so this crossfades rather than + // teleports. Shared path: every entrypoint (⌘⇧G, context menu, socket) + // routes here, so they all animate identically. + withAnimation(SidebarGroupAnimation.structure) { + workspaceGroups.append(group) + assignGroup(workspaceId: anchorWorkspaceId, groupId: group.id) + // The anchor is already at its sidebar position; normalize keeps it + // there (`sidebarTopLevelWorkspaceIds` maps the now-grouped + // workspace back to its anchor's slot) while syncing the + // workspaceGroups order to the tabs order. + normalizeWorkspaceGroupContiguity() + postWorkspaceOrderDidChange(movedWorkspaceIds: [anchorWorkspaceId]) + } return group.id } @@ -4418,28 +4450,32 @@ class TabManager: ObservableObject { } if isAnchorOfOtherGroup { return } let originalTopLevelIds = sidebarTopLevelWorkspaceIds() - assignGroup(workspaceId: workspaceId, groupId: groupId) - // selectedTabId may not change here (the workspace was already - // selected), so the existing didSet hook won't fire. Expand manually - // when the added workspace is the focused one so it doesn't end up - // hidden inside a collapsed section. - if selectedTabId == workspaceId, - let groupIndex = workspaceGroups.firstIndex(where: { $0.id == groupId }), - workspaceGroups[groupIndex].isCollapsed { - workspaceGroups[groupIndex].isCollapsed = false - } - normalizeWorkspaceGroupContiguity( - preservingTopLevelIds: originalTopLevelIds.filter { $0 != workspaceId } - ) - if let placement { - placeWithinGroup( - workspaceId: workspaceId, - groupId: groupId, - placement: placement, - referenceWorkspaceId: referenceWorkspaceId + // Animate the workspace sliding under the header and indenting as a + // member. Covers the drag-into-group drop and the socket/CLI add path. + withAnimation(SidebarGroupAnimation.structure) { + assignGroup(workspaceId: workspaceId, groupId: groupId) + // selectedTabId may not change here (the workspace was already + // selected), so the existing didSet hook won't fire. Expand + // manually when the added workspace is the focused one so it + // doesn't end up hidden inside a collapsed section. + if selectedTabId == workspaceId, + let groupIndex = workspaceGroups.firstIndex(where: { $0.id == groupId }), + workspaceGroups[groupIndex].isCollapsed { + workspaceGroups[groupIndex].isCollapsed = false + } + normalizeWorkspaceGroupContiguity( + preservingTopLevelIds: originalTopLevelIds.filter { $0 != workspaceId } ) + if let placement { + placeWithinGroup( + workspaceId: workspaceId, + groupId: groupId, + placement: placement, + referenceWorkspaceId: referenceWorkspaceId + ) + } + postWorkspaceOrderDidChange(movedWorkspaceIds: [workspaceId]) } - postWorkspaceOrderDidChange(movedWorkspaceIds: [workspaceId]) } /// Remove a non-anchor workspace from its group. If the workspace is its @@ -4453,9 +4489,11 @@ class TabManager: ObservableObject { ungroupWorkspaceGroup(groupId: groupId) return } - assignGroup(workspaceId: workspaceId, groupId: nil) - normalizeWorkspaceGroupContiguity() - postWorkspaceOrderDidChange(movedWorkspaceIds: [workspaceId]) + withAnimation(SidebarGroupAnimation.structure) { + assignGroup(workspaceId: workspaceId, groupId: nil) + normalizeWorkspaceGroupContiguity() + postWorkspaceOrderDidChange(movedWorkspaceIds: [workspaceId]) + } } /// Dissolve a group while preserving every member workspace (including its @@ -4471,11 +4509,16 @@ class TabManager: ObservableObject { func ungroupWorkspaceGroup(groupId: UUID) { let memberIds = tabs.filter { $0.groupId == groupId }.map(\.id) guard !memberIds.isEmpty || workspaceGroups.contains(where: { $0.id == groupId }) else { return } - for id in memberIds { - assignGroup(workspaceId: id, groupId: nil) + // Reverse of promote-in-place: the header morphs back into the anchor's + // workspace row at the same slot, and any members un-indent. Animated + // for the round-trip to read cleanly. + withAnimation(SidebarGroupAnimation.structure) { + for id in memberIds { + assignGroup(workspaceId: id, groupId: nil) + } + workspaceGroups.removeAll { $0.id == groupId } + postWorkspaceOrderDidChange(movedWorkspaceIds: memberIds) } - workspaceGroups.removeAll { $0.id == groupId } - postWorkspaceOrderDidChange(movedWorkspaceIds: memberIds) } /// Delete a group and close every workspace inside it (anchor + all @@ -4574,7 +4617,12 @@ class TabManager: ObservableObject { ) } } - setWorkspaceGroupCollapsed(groupId: groupId, isCollapsed: nextCollapsed) + // Animate the disclosure: member rows slide+fade and the chevron spins. + // Only the UI toggle animates; the pure-data `setWorkspaceGroupCollapsed` + // socket/CLI path stays instant (no view transaction). + withAnimation(SidebarGroupAnimation.collapse) { + setWorkspaceGroupCollapsed(groupId: groupId, isCollapsed: nextCollapsed) + } } /// Pure data mutation — flips the collapse flag without touching diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index e11fb6b8f6b4..d5d1f465c419 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -20,14 +20,15 @@ extension VerticalTabsSidebar { ) let cwdContextMenuItems = resolvedConfig?.contextMenuItems ?? [] let newWorkspacePlacement = resolvedConfig?.newWorkspacePlacement - let anchorUnreadCount: Int = { - if group.isCollapsed { - return memberWorkspaceIds.reduce(0) { partial, workspaceId in - partial + notificationStore.unreadCount(forTabId: workspaceId) - } - } - return notificationStore.unreadCount(forTabId: group.anchorWorkspaceId) - }() + // The group header badge is always a rollup of every member's unread + // (anchor included — `memberWorkspaceIds` contains the anchor), whether + // the group is collapsed or expanded. Expanded members still show their + // own per-row badges; the header total tells you the group has unread + // activity without expanding it. (Members hidden under a collapsed + // group have no row of their own, so the rollup is the only signal.) + let groupUnreadCount: Int = memberWorkspaceIds.reduce(0) { partial, workspaceId in + partial + notificationStore.unreadCount(forTabId: workspaceId) + } let anchorIndex = renderContext.tabIndexById[group.anchorWorkspaceId] ?? 0 let shortcutDigit = WorkspaceShortcutMapper.digitForWorkspace( at: anchorIndex, @@ -84,7 +85,7 @@ extension VerticalTabsSidebar { isPinned: group.isPinned, isAnchorActive: isAnchorActive, memberCount: memberWorkspaceIds.count, - anchorUnreadCount: anchorUnreadCount, + groupUnreadCount: groupUnreadCount, shortcutDigit: shortcutDigit, shortcutModifierSymbol: modifierSymbol, showsShortcutHint: showsHintForAnchor, @@ -154,7 +155,9 @@ extension VerticalTabsSidebar { } ) .equatable() - .id(group.anchorWorkspaceId) + // No `.id(group.anchorWorkspaceId)` here: identity comes from the + // ForEach (`id: \.scrollAnchorWorkspaceId`, which equals the anchor id), + // so promote/ungroup keeps the same slot and the morph transition runs. .accessibilityIdentifier("sidebarWorkspaceGroup.\(group.id.uuidString)") .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([group.anchorWorkspaceId])) diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 556c9f286450..400c37f843ff 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -197,6 +197,49 @@ struct WorkspaceGroupTests { #expect(!visibleWorkspaceIds.contains(originalIds[2])) } + /// Promote-in-place must keep the anchor's sidebar slot identity: the group + /// header's render-item `id` has to equal the render-item `id` the same + /// workspace's row had before it became a group. That stable identity is + /// what lets SwiftUI animate the morph and stops the LazyVStack from + /// dropping the row (the bug that previously needed a whole-list + /// `.id(groupAnchorSignature)` rebuild). Round-trips back to the workspace + /// id after ungroup. + @Test func promoteInPlaceKeepsAnchorRenderIdentity() throws { + let manager = makeTabManager() + let anchorId = try #require(manager.tabs.first?.id) + + func renderItemId(forWorkspace workspaceId: UUID) -> String? { + let items = SidebarWorkspaceRenderItem.renderItems( + tabs: manager.tabs, + groupsById: Dictionary( + uniqueKeysWithValues: manager.workspaceGroups.map { ($0.id, $0) } + ) + ) + for item in items { + switch item { + case .groupHeader(let group, _) where group.anchorWorkspaceId == workspaceId: + return item.id + case .workspace(let workspace) where workspace.id == workspaceId: + return item.id + default: + continue + } + } + return nil + } + + let workspaceRowId = try #require(renderItemId(forWorkspace: anchorId)) + + let groupId = try #require(manager.makeWorkspaceGroupFromWorkspace(anchorWorkspaceId: anchorId)) + let headerRowId = try #require(renderItemId(forWorkspace: anchorId)) + // Same sidebar slot identity before and after promotion. + #expect(headerRowId == workspaceRowId) + + manager.ungroupWorkspaceGroup(groupId: groupId) + let restoredRowId = try #require(renderItemId(forWorkspace: anchorId)) + #expect(restoredRowId == workspaceRowId) + } + @Test func groupHeaderEdgeDropUsesTopLevelIndicatorScope() throws { let manager = makeTabManager() manager.addWorkspace(autoWelcomeIfNeeded: false) @@ -706,6 +749,54 @@ struct WorkspaceGroupTests { #expect(manager.tabs.allSatisfy { $0.groupId == nil }) } + /// Deleting a group must remove the header row *and* every member row from + /// the sidebar render items, not just the model arrays. The stable-identity + /// refactor keys the header on its anchor workspace's id, so this guards + /// that the header doesn't linger as a phantom row after its anchor (and + /// members) are closed. + @Test func deleteRemovesGroupHeaderAndMemberRowsFromRenderItems() throws { + let manager = makeTabManager() + // Outsider so closeWorkspace's `tabs.count <= 1` guard never fires and + // the whole group is genuinely closed. + manager.addWorkspace(autoWelcomeIfNeeded: false) + let outsiderId = try #require(manager.tabs.last?.id) + let groupChildren = Array(manager.tabs.prefix(2)).map(\.id) + let groupId = try #require(manager.createWorkspaceGroup(name: "Doomed", childWorkspaceIds: groupChildren)) + let group = try #require(manager.workspaceGroups.first { $0.id == groupId }) + let anchorId = group.anchorWorkspaceId + let memberIds = Set(manager.tabs.filter { $0.groupId == groupId }.map(\.id)) + + func renderItems() -> [SidebarWorkspaceRenderItem] { + SidebarWorkspaceRenderItem.renderItems( + tabs: manager.tabs, + groupsById: Dictionary(uniqueKeysWithValues: manager.workspaceGroups.map { ($0.id, $0) }) + ) + } + + // Sanity: before delete the header renders. + #expect(renderItems().contains { item in + if case .groupHeader(let g, _) = item, g.id == groupId { return true } + return false + }) + + manager.deleteWorkspaceGroup(groupId: groupId) + + let items = renderItems() + // No header for the deleted group. + #expect(!items.contains { item in + if case .groupHeader = item { return true } + return false + }) + // No row carries the deleted group's identity (header or member). + let deletedRowIds = memberIds.union([anchorId]).map { "workspace.\($0.uuidString)" } + #expect(items.allSatisfy { !deletedRowIds.contains($0.id) }) + // The unrelated outsider survives as a plain workspace row. + #expect(items.contains { item in + if case .workspace(let ws) = item, ws.id == outsiderId { return true } + return false + }) + } + @Test func pinnedWorkspaceCannotJoinGroupViaCreate() { let manager = makeTabManager() let pinnedWs = manager.tabs[0] From d5757a2252b44d333f735a64b33218694cfd48eb Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 10 Jun 2026 02:38:46 -0700 Subject: [PATCH 04/36] Sidebar drag: Escape-cancel via HID poll + remove end-of-list drop line - Escape now cancels an in-progress sidebar drag. The existing escape_cancel handler used a local keyDown monitor, which never fires inside the native NSDraggingSession modal loop. Poll CGEventSource.keyState for Escape instead (same HID-read trick the mouse-button failsafe already uses via buttonState), readable inside the drag loop. Bounded/cancellable task scoped to the live drag. - Removed the end-of-list (empty-area) blue drop-indicator line too, matching the per-row indicator removal. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 0a1815e3ca25..45a646d2414b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13273,6 +13273,7 @@ private final class SidebarDragFailsafeMonitor: ObservableObject { private var keyDownMonitor: Any? private var localMouseMonitor: Any? private var globalMouseMonitor: Any? + private var escapePollTask: Task? private var onRequestClear: ((String) -> Void)? func start(onRequestClear: @escaping (String) -> Void) { @@ -13304,6 +13305,26 @@ private final class SidebarDragFailsafeMonitor: ObservableObject { return event } } + // The local keyDown monitor above cannot see Escape during a native + // NSDraggingSession: the drag runs a nested modal event-tracking loop + // that never routes keyDown to app monitors, so "Escape cancels the + // drag" silently did nothing. Poll the Escape key's HID state directly + // instead (the same trick the mouse-button failsafe already uses via + // CGEventSource.buttonState), which is readable inside the drag loop. + // Bounded and cancellable: the task is scoped to a live drag and torn + // down in stop() when the drag ends. One detection is enough — macOS + // also cancels the native session on Escape, so no drop is committed. + if escapePollTask == nil { + escapePollTask = Task { @MainActor [weak self] in + while !Task.isCancelled { + if CGEventSource.keyState(.combinedSessionState, key: Self.escapeKeyCode) { + self?.requestClearSoon(reason: "escape_cancel") + return + } + try? await Task.sleep(for: .milliseconds(20)) + } + } + } if localMouseMonitor == nil { localMouseMonitor = NSEvent.addLocalMonitorForEvents(matching: .leftMouseUp) { [weak self] event in if SidebarDragFailsafePolicy.shouldRequestClear(forMouseEventType: event.type) { @@ -13333,6 +13354,8 @@ private final class SidebarDragFailsafeMonitor: ObservableObject { NSEvent.removeMonitor(keyDownMonitor) self.keyDownMonitor = nil } + escapePollTask?.cancel() + escapePollTask = nil if let localMouseMonitor { NSEvent.removeMonitor(localMouseMonitor) self.localMouseMonitor = nil @@ -14940,15 +14963,10 @@ private struct SidebarEmptyArea: View { ) .frame(maxWidth: .infinity, maxHeight: .infinity) } - .overlay(alignment: .top) { - if topDropIndicatorVisible { - Rectangle() - .fill(cmuxAccentColor()) - .frame(height: 2) - .padding(.horizontal, 8) - .offset(y: -(rowSpacing / 2)) - } - } + // The end-of-list blue drop line was removed per dogfood feedback, + // matching the per-row indicator removal. `topDropIndicatorVisible` + // is kept as a stored property so the drop plumbing and Equatable + // conformance stay unchanged. } } From 44910a1ee5b0c0ad9f1f38722f447f59bca7d8d3 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 10 Jun 2026 02:57:10 -0700 Subject: [PATCH 05/36] Sidebar drag: animated drop gap (rows shift apart) instead of an indicator When a drag would insert above a row, that row opens a row-tall animated gap so the list visibly shifts apart to preview the drop slot, replacing the removed blue insertion line. Purely a layout animation driven by the existing topDropIndicatorVisible signal: the model is only reordered once on drop, so there's no during-drag @Published reorder thrash (#2586) or hover oscillation from live model mutation. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 13 ++++++------- Sources/SidebarWorkspaceGroupHeaderView.swift | 11 ++++------- Sources/SidebarWorkspaceGroupingMetrics.swift | 7 +++++++ 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 45a646d2414b..92fe2da726c4 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -15869,13 +15869,12 @@ struct TabItemView: View, Equatable { tabManager.closeWorkspaceWithConfirmation(tab) } } - .overlay(alignment: .top) { - SidebarWorkspaceTopDropIndicator( - isVisible: topDropIndicatorVisible, - isFirstRow: index == 0, - rowSpacing: rowSpacing - ) - } + // Animated drop gap: when a drag would insert above this row, open a + // row-tall space so the list visibly shifts apart to preview where the + // workspace lands. Replaces the old blue insertion line. The model is + // not reordered until drop, so this is purely a layout animation. + .padding(.top, topDropIndicatorVisible ? SidebarWorkspaceGroupingMetrics.dropGapHeight : 0) + .animation(SidebarGroupAnimation.collapse, value: topDropIndicatorVisible) .onAppear { refreshWorkspaceSnapshot(force: true) } diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index bafd2b2b9504..33d61dc4d8e5 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -236,13 +236,10 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) .opacity(isBeingDragged ? 0.6 : 1) - .overlay(alignment: .top) { - SidebarWorkspaceTopDropIndicator( - isVisible: topDropIndicatorVisible, - isFirstRow: isFirstRow, - rowSpacing: rowSpacing - ) - } + // Animated drop gap above the header (see TabItemView): the list shifts + // apart to preview the drop slot, replacing the old blue line. + .padding(.top, topDropIndicatorVisible ? SidebarWorkspaceGroupingMetrics.dropGapHeight : 0) + .animation(SidebarGroupAnimation.collapse, value: topDropIndicatorVisible) .onDrag(onDragStart) .internalOnlyTabDrag() .onDrop(of: SidebarTabDragPayload.dropContentTypes, delegate: tabDropDelegateFactory(rowHeight)) diff --git a/Sources/SidebarWorkspaceGroupingMetrics.swift b/Sources/SidebarWorkspaceGroupingMetrics.swift index 5d28e7d96654..98148b3eb295 100644 --- a/Sources/SidebarWorkspaceGroupingMetrics.swift +++ b/Sources/SidebarWorkspaceGroupingMetrics.swift @@ -3,6 +3,13 @@ import SwiftUI enum SidebarWorkspaceGroupingMetrics { /// Leading inset applied to workspace rows that visually nest under a group header. static let memberIndent: CGFloat = 12 + + /// Height of the animated gap that opens above the row a drag would drop + /// into, replacing the old blue insertion line. Roughly one row tall so the + /// opening reads as "the dropped row goes here". Purely visual — it does not + /// reorder the model (commit still happens once on drop), so there's no + /// during-drag @Published thrash (issue #2586) or hover oscillation. + static let dropGapHeight: CGFloat = 30 } /// Shared animation timings for workspace-group structure changes in the From 79798c14783595aee0e4f0f69a2aed4de2229f6d Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 10 Jun 2026 15:26:30 -0700 Subject: [PATCH 06/36] Sidebar drag: true live reorder (row travels through the list) Replace the greyed-ghost + gap preview with real live reorder: as the drag moves over rows, the dragged workspace is immediately moved to the hovered drop slot (within withAnimation), so the row physically travels through the list and the others reorder around it. The drop commit then no-ops because the order is already correct. - commitLiveReorder reuses the exact drop-commit planner (targetIndex from the freshly-set indicator with the same pinned/group/legal-range inputs), so constraints hold on every step. Only fires when the resolved index changes (once per row crossed), intra-window only. Logs sidebar.liveReorder for diagnosing jank. - Dragged row no longer dims in place (it moves instead). - Escape restores the order captured at drag start (live reorder is undone); a normal release commits via performDrop and keeps the new order. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 94 +++++++++++++++++-- Sources/SidebarWorkspaceGroupHeaderView.swift | 7 +- 2 files changed, 89 insertions(+), 12 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 92fe2da726c4..de82d66137c1 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10577,6 +10577,10 @@ struct VerticalTabsSidebar: View { @State var modifierKeyMonitor = WindowScopedShortcutHintModifierMonitor(activation: .commandOnly) @StateObject var dragAutoScrollController = SidebarDragAutoScrollController() @StateObject private var dragFailsafeMonitor = SidebarDragFailsafeMonitor() + /// Workspace order captured when a sidebar drag begins, so an Escape-cancel + /// can undo the live reorder and put the row back where it started. Nil when + /// no drag is in flight. + @State private var dragReorderSnapshot: [UUID]? @StateObject private var tabItemSettingsStore = SidebarTabItemSettingsStore( initialSidebarFontSize: GhosttyConfig.load().sidebarFontSize ) @@ -11056,6 +11060,9 @@ struct VerticalTabsSidebar: View { cmuxDebugLog("sidebar.dragState.sidebar tab=\(debugShortSidebarTabId(newDraggedTabId))") #endif if newDraggedTabId != nil { + // Snapshot the order at drag start so an Escape-cancel can undo + // the live reorder. Captured before any drop hover mutates it. + dragReorderSnapshot = tabManager.tabs.map(\.id) // The failsafe monitor probes the real mouse-button state and // posts `mouse_up_failsafe` if no mouse is held down. That's // correct for HID-driven drags, but `debug.sidebar.simulate_drag` @@ -11071,6 +11078,8 @@ struct VerticalTabsSidebar: View { dragFailsafeMonitor.stop() dragAutoScrollController.stop() dragState.clearDropIndicator() + // Drag ended (committed via drop); discard the undo snapshot. + dragReorderSnapshot = nil } .onReceive(NotificationCenter.default.publisher(for: SidebarDragLifecycleNotification.requestClear)) { notification in guard dragState.draggedTabId != nil || dragState.dropIndicator != nil else { return } @@ -11078,6 +11087,21 @@ struct VerticalTabsSidebar: View { #if DEBUG cmuxDebugLog("sidebar.dragClear tab=\(debugShortSidebarTabId(dragState.draggedTabId)) reason=\(reason)") #endif + // Escape undoes the live reorder by restoring the order captured at + // drag start, then clears. A normal mouse release commits via + // performDrop (keeping the live order), so only the explicit + // escape_cancel reason restores. + if reason == "escape_cancel", + let snapshot = dragReorderSnapshot, + snapshot != tabManager.tabs.map(\.id) { +#if DEBUG + cmuxDebugLog("sidebar.dragCancel.restoreOrder reason=\(reason)") +#endif + _ = withAnimation(SidebarGroupAnimation.structure) { + tabManager.reorderWorkspaces(orderedWorkspaceIds: snapshot) + } + } + dragReorderSnapshot = nil dragState.clearDrag() } .onChange(of: tabManager.tabs.map(\.id)) { tabIds in @@ -15857,7 +15881,8 @@ struct TabItemView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .contentShape(Rectangle()) - .opacity(isBeingDragged ? 0.6 : 1) + // Live reorder relocates the dragged row through the list as you drag, + // so it no longer sits greyed-out in place. .overlay { SidebarWorkspaceRowHoverTracker(rowInteractionState: $rowInteractionState) } @@ -15869,12 +15894,6 @@ struct TabItemView: View, Equatable { tabManager.closeWorkspaceWithConfirmation(tab) } } - // Animated drop gap: when a drag would insert above this row, open a - // row-tall space so the list visibly shifts apart to preview where the - // workspace lands. Replaces the old blue insertion line. The model is - // not reordered until drop, so this is purely a layout animation. - .padding(.top, topDropIndicatorVisible ? SidebarWorkspaceGroupingMetrics.dropGapHeight : 0) - .animation(SidebarGroupAnimation.collapse, value: topDropIndicatorVisible) .onAppear { refreshWorkspaceSnapshot(force: true) } @@ -17913,6 +17932,7 @@ struct SidebarTabDropDelegate: DropDelegate { activateForeignDragIfNeeded() dragAutoScrollController.updateFromDragLocation() updateDropIndicator(for: info) + commitLiveReorder(for: info) } func dropExited(info: DropInfo) { @@ -17928,6 +17948,7 @@ struct SidebarTabDropDelegate: DropDelegate { activateForeignDragIfNeeded() dragAutoScrollController.updateFromDragLocation() updateDropIndicator(for: info) + commitLiveReorder(for: info) #if DEBUG cmuxDebugLog( "sidebar.dropUpdated target=\(targetTabId?.uuidString.prefix(5) ?? "end") " + @@ -18160,6 +18181,65 @@ struct SidebarTabDropDelegate: DropDelegate { dragState.setDropIndicator(nextIndicator, usesTopLevelRows: usesTopLevelRows) } + /// Live intra-window reorder: as the drag moves over rows, immediately move + /// the dragged workspace to the hovered drop slot (within `withAnimation`) + /// instead of only previewing with an indicator and committing on drop. The + /// dragged row physically travels through the list; the actual commit on + /// `performDrop` then no-ops because the order is already correct. + /// + /// Reuses the exact planner the drop commit uses (`targetIndex` from the + /// freshly-set indicator, with the same pinned/group/legal-range inputs), so + /// pinned tiers and group boundaries are respected on every step. Only fires + /// when the resolved index actually changes, so it runs once per row crossed + /// rather than on every pointer move. Cross-window drags are skipped (the + /// workspace isn't in this window yet). + private func commitLiveReorder(for info: DropInfo) { + guard let draggedTabId = effectiveDraggedTabId, + !isCrossWindowDrag(draggedTabId) else { return } + let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( + forDraggedWorkspaceId: draggedTabId, + targetWorkspaceId: targetTabId + ) + let reorderTabIds = tabManager.sidebarReorderWorkspaceIds( + forDraggedWorkspaceId: draggedTabId, + targetWorkspaceId: targetTabId + ) + let pinnedTabIds = tabManager.sidebarReorderPinnedWorkspaceIds( + forDraggedWorkspaceId: draggedTabId, + targetWorkspaceId: targetTabId + ) + let legalInsertionRange = tabManager.sidebarReorderLegalInsertionRange( + forDraggedWorkspaceId: draggedTabId, + targetWorkspaceId: targetTabId, + usesTopLevelRows: usesTopLevelRows + ) + guard let fromIndex = reorderTabIds.firstIndex(of: draggedTabId), + let targetIndex = SidebarDropPlanner.targetIndex( + draggedTabId: draggedTabId, + targetTabId: targetTabId, + indicator: dragState.dropIndicator, + tabIds: reorderTabIds, + pinnedTabIds: pinnedTabIds, + legalInsertionRange: legalInsertionRange + ), + fromIndex != targetIndex else { return } +#if DEBUG + cmuxDebugLog( + "sidebar.liveReorder tab=\(draggedTabId.uuidString.prefix(5)) " + + "from=\(fromIndex) to=\(targetIndex) " + + "target=\(targetTabId?.uuidString.prefix(5) ?? "end") topLevel=\(usesTopLevelRows)" + ) +#endif + _ = withAnimation(SidebarGroupAnimation.structure) { + tabManager.reorderSidebarWorkspace( + tabId: draggedTabId, + toIndex: targetIndex, + isDragOperation: true, + usesTopLevelRows: usesTopLevelRows + ) + } + } + /// Drop indicator for a foreign workspace hovering this window. The dragged /// workspace is not in this window's list, so the reorder planner (which /// removes a source index) does not apply — use the cross-window planner. diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 33d61dc4d8e5..217d8aa5515e 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -235,11 +235,8 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) - .opacity(isBeingDragged ? 0.6 : 1) - // Animated drop gap above the header (see TabItemView): the list shifts - // apart to preview the drop slot, replacing the old blue line. - .padding(.top, topDropIndicatorVisible ? SidebarWorkspaceGroupingMetrics.dropGapHeight : 0) - .animation(SidebarGroupAnimation.collapse, value: topDropIndicatorVisible) + // Live reorder moves the dragged row through the list instead of + // greying it in place, so don't dim during drag. .onDrag(onDragStart) .internalOnlyTabDrag() .onDrop(of: SidebarTabDragPayload.dropContentTypes, delegate: tabDropDelegateFactory(rowHeight)) From 67408932fc54dee18486f029f1312956a302252f Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Wed, 10 Jun 2026 15:37:10 -0700 Subject: [PATCH 07/36] Sidebar live reorder: fix stationary-pointer oscillation The first live-reorder pass ping-ponged the dragged row between two adjacent slots while the pointer was held still: each reorder shifts rows, which re-fires the drop delegate with the pointer unmoved, and the planner's targetIndex (which depends on the dragged row's current index) flips back. The debug log showed from=N to=N+1 then N+1 to=N repeating every ~25ms. Loop-breaker: only commit a live reorder when the global pointer has moved since the last committed reorder (>5pt). Self-induced re-fires arrive at the same location and are skipped; genuine drag movement still reorders. Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index de82d66137c1..d7574e94f95e 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10368,6 +10368,13 @@ final class SidebarDragState { var draggedTabId: UUID? var dropIndicator: SidebarDropIndicator? var dropIndicatorUsesTopLevelRows = false + /// Global pointer location at the last committed live reorder. Used as the + /// loop-breaker: a live reorder shifts rows, which makes a drop delegate + /// re-fire even though the pointer hasn't moved, and the planner's index + /// flips back (observed in sidebar.liveReorder as from=N to=N+1 then back). + /// If the pointer hasn't physically moved since the last reorder, the update + /// was self-induced, so it's ignored. Reset on drag begin/clear. + var lastLiveReorderMouseLocation: CGPoint? /// True while the `debug.sidebar.simulate_drag` debug-only V2 method is /// driving the drag state. The lifecycle observers honor this by not /// starting `SidebarDragFailsafeMonitor` (which would otherwise post a @@ -10394,6 +10401,7 @@ final class SidebarDragState { func beginDragging(tabId: UUID) { draggedTabId = tabId + lastLiveReorderMouseLocation = nil clearDropIndicator() originatedActiveDrag = true SidebarWorkspaceDragRegistry.begin(workspaceId: tabId) @@ -10415,6 +10423,7 @@ final class SidebarDragState { originatedActiveDrag = false foreignDraggedIsPinned = nil draggedTabId = nil + lastLiveReorderMouseLocation = nil clearDropIndicator() } } @@ -18196,6 +18205,20 @@ struct SidebarTabDropDelegate: DropDelegate { private func commitLiveReorder(for info: DropInfo) { guard let draggedTabId = effectiveDraggedTabId, !isCrossWindowDrag(draggedTabId) else { return } + // Hovering the dragged row itself: nothing to move. + guard targetTabId != draggedTabId else { return } + // Loop-breaker: a live reorder shifts rows under the pointer, re-firing + // this drop delegate with the pointer in the same place, and the planner + // flips the index back — an infinite ping-pong while the pointer is held + // still (seen in sidebar.liveReorder as from=N to=N+1 then back). Only + // act when the pointer has physically moved since the last committed + // reorder, so self-induced re-fires are ignored while genuine drag + // movement still reorders. + let mouseLocation = NSEvent.mouseLocation + if let last = dragState.lastLiveReorderMouseLocation, + hypot(mouseLocation.x - last.x, mouseLocation.y - last.y) < 5 { + return + } let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( forDraggedWorkspaceId: draggedTabId, targetWorkspaceId: targetTabId @@ -18230,6 +18253,9 @@ struct SidebarTabDropDelegate: DropDelegate { "target=\(targetTabId?.uuidString.prefix(5) ?? "end") topLevel=\(usesTopLevelRows)" ) #endif + // Anchor the loop-breaker to where the pointer is now: the upcoming + // self-induced re-fires arrive with this same location and are skipped. + dragState.lastLiveReorderMouseLocation = mouseLocation _ = withAnimation(SidebarGroupAnimation.structure) { tabManager.reorderSidebarWorkspace( tabId: draggedTabId, From dc419f0f409fe835a5aaf97afe8c9ff31443b9fe Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 14:13:31 -0700 Subject: [PATCH 08/36] Sidebar drag: restore fully on every non-commit end; fix review findings Review fixes from Cursor Bugbot and Codex on the live-reorder work: - The pre-drag snapshot now restores on EVERY clear request (escape, mouse-up failsafe, app deactivation, outside-sidebar drop, aborted performDrop), not only escape_cancel. The live reorder mutates the model on hover, so any drag end that doesn't commit must roll back. - The snapshot captures group membership alongside row order: reorderSidebarWorkspace(isDragOperation:) can rewrite Workspace.groupId when a row is dragged into or out of an expanded group, so restoring the id order alone left the row in the wrong group. New TabManager.SidebarDragRestoreSnapshot capture/restore API, unit-tested. - commitLiveReorder skips the move when the freshly-updated drop indicator is nil: the planner suppresses the indicator when the dragged row already sits at the pointer's insertion point, and recomputing from preferredEdge bounced the row back across the hovered row. - createWorkspaceGroup(selectAnchor: false) keeps the collapsed sidebar selection on the previously focused workspace even when it isn't a group member, so the sidebar highlight tracks the still-active workspace instead of jumping to the new empty anchor. Co-Authored-By: Claude Fable 5 --- Sources/ContentView.swift | 69 +++++++++++------ Sources/TabManager.swift | 74 ++++++++++++++++-- cmuxTests/WorkspaceGroupTests.swift | 116 ++++++++++++++++++++++++++++ 3 files changed, 230 insertions(+), 29 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index d7574e94f95e..65ad9a400244 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10586,10 +10586,11 @@ struct VerticalTabsSidebar: View { @State var modifierKeyMonitor = WindowScopedShortcutHintModifierMonitor(activation: .commandOnly) @StateObject var dragAutoScrollController = SidebarDragAutoScrollController() @StateObject private var dragFailsafeMonitor = SidebarDragFailsafeMonitor() - /// Workspace order captured when a sidebar drag begins, so an Escape-cancel - /// can undo the live reorder and put the row back where it started. Nil when - /// no drag is in flight. - @State private var dragReorderSnapshot: [UUID]? + /// Workspace order + group membership captured when a sidebar drag begins, + /// so any drag that ends without committing (Escape, mouse-up outside a + /// valid target, app deactivation, aborted drop) undoes the live reorder + /// and puts every row back where it started. Nil when no drag is in flight. + @State private var dragReorderSnapshot: TabManager.SidebarDragRestoreSnapshot? @StateObject private var tabItemSettingsStore = SidebarTabItemSettingsStore( initialSidebarFontSize: GhosttyConfig.load().sidebarFontSize ) @@ -11069,9 +11070,10 @@ struct VerticalTabsSidebar: View { cmuxDebugLog("sidebar.dragState.sidebar tab=\(debugShortSidebarTabId(newDraggedTabId))") #endif if newDraggedTabId != nil { - // Snapshot the order at drag start so an Escape-cancel can undo - // the live reorder. Captured before any drop hover mutates it. - dragReorderSnapshot = tabManager.tabs.map(\.id) + // Snapshot order + group membership at drag start so a + // non-committing drag end can undo the live reorder. Captured + // before any drop hover mutates the model. + dragReorderSnapshot = tabManager.captureSidebarDragRestoreSnapshot() // The failsafe monitor probes the real mouse-button state and // posts `mouse_up_failsafe` if no mouse is held down. That's // correct for HID-driven drags, but `debug.sidebar.simulate_drag` @@ -11096,18 +11098,20 @@ struct VerticalTabsSidebar: View { #if DEBUG cmuxDebugLog("sidebar.dragClear tab=\(debugShortSidebarTabId(dragState.draggedTabId)) reason=\(reason)") #endif - // Escape undoes the live reorder by restoring the order captured at - // drag start, then clears. A normal mouse release commits via - // performDrop (keeping the live order), so only the explicit - // escape_cancel reason restores. - if reason == "escape_cancel", - let snapshot = dragReorderSnapshot, - snapshot != tabManager.tabs.map(\.id) { + // Every clear request means the drag ended WITHOUT performDrop + // committing — Escape, the mouse-up failsafe, app deactivation, a + // drop outside the sidebar, or an aborted drop. The live reorder + // has already mutated the model on hover, so all of them must + // restore the order + group membership captured at drag start. A + // normal in-sidebar release commits via performDrop, which clears + // the drag state synchronously, so its trailing failsafe mouse-up + // never passes the guard above. + if let snapshot = dragReorderSnapshot { #if DEBUG cmuxDebugLog("sidebar.dragCancel.restoreOrder reason=\(reason)") #endif _ = withAnimation(SidebarGroupAnimation.structure) { - tabManager.reorderWorkspaces(orderedWorkspaceIds: snapshot) + tabManager.restoreSidebarDragSnapshot(snapshot) } } dragReorderSnapshot = nil @@ -17967,6 +17971,16 @@ struct SidebarTabDropDelegate: DropDelegate { return DropProposal(operation: .move) } + /// A drop that aborts must roll back the live reorder — the model has + /// already been mutated on hover. Posting the clear request delivers + /// synchronously to the sidebar's lifecycle handler, which restores the + /// pre-drag snapshot (order + group membership) before our `defer` clears + /// the drag state. + private func abortDrop() -> Bool { + SidebarDragLifecycleNotification.postClearRequest(reason: "drop_aborted") + return false + } + func performDrop(info: DropInfo) -> Bool { defer { dragState.clearDrag() @@ -17979,10 +17993,11 @@ struct SidebarTabDropDelegate: DropDelegate { #if DEBUG cmuxDebugLog("sidebar.drop.abort reason=missingDraggedTab") #endif - return false + return abortDrop() } if isCrossWindowDrag(draggedTabId) { - return performCrossWindowDrop(draggedTabId: draggedTabId) + let didMove = performCrossWindowDrop(draggedTabId: draggedTabId) + return didMove ? true : abortDrop() } let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( forDraggedWorkspaceId: draggedTabId, @@ -18005,7 +18020,7 @@ struct SidebarTabDropDelegate: DropDelegate { #if DEBUG cmuxDebugLog("sidebar.drop.abort reason=draggedTabMissing tab=\(draggedTabId.uuidString.prefix(5))") #endif - return false + return abortDrop() } guard let targetIndex = SidebarDropPlanner.targetIndex( draggedTabId: draggedTabId, @@ -18021,7 +18036,7 @@ struct SidebarTabDropDelegate: DropDelegate { "target=\(targetTabId?.uuidString.prefix(5) ?? "end") indicator=\(debugIndicator(dragState.dropIndicator))" ) #endif - return false + return abortDrop() } guard fromIndex != targetIndex else { @@ -18039,10 +18054,11 @@ struct SidebarTabDropDelegate: DropDelegate { existingAnchorIndex: lastSidebarSelectionIndex, liveWorkspaceIds: tabManager.tabs.map(\.id) ) - // Animate the drop settle: rows glide to their new positions instead of - // snapping. The array mutates once here (the live drag only moves a - // visual indicator, not the model), so this is post-drag and safe under - // the LazyVStack — it does not touch the 60fps drag hot path. + // Animate the drop settle: rows glide to their final positions. With + // the live reorder having already moved the row on hover, this commit + // is usually a no-op (caught by the fromIndex == targetIndex guard + // above); it only mutates when the last hover tick and the drop + // disagree, e.g. a fast flick released before the final dropUpdated. let didReorder = withAnimation(SidebarGroupAnimation.structure) { tabManager.reorderSidebarWorkspace( tabId: draggedTabId, @@ -18207,6 +18223,13 @@ struct SidebarTabDropDelegate: DropDelegate { !isCrossWindowDrag(draggedTabId) else { return } // Hovering the dragged row itself: nothing to move. guard targetTabId != draggedTabId else { return } + // `updateDropIndicator` just ran for this hover; a nil indicator means + // the planner resolved "the dragged row already sits at the pointer's + // insertion point" (the indicator is suppressed in that case). + // Recomputing targetIndex below would fall back to preferredEdge — + // which can pick the OTHER side of the hovered row and bounce the row + // back across it on every hover tick. Already in place: nothing to do. + guard dragState.dropIndicator != nil else { return } // Loop-breaker: a live reorder shifts rows under the pointer, re-firing // this drop delegate with the pointer in the same place, and the planner // flips the index back — an infinite ping-pong while the pointer is held diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index e05bb7e5b787..17b135f44a45 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -3951,6 +3951,65 @@ class TabManager: ObservableObject { return .success(plan) } + /// Sidebar order and group membership captured when a sidebar drag begins, + /// so an uncommitted drag can be rolled back. The live drag-reorder mutates + /// the model on every hover — `reorderSidebarWorkspace(isDragOperation:)` + /// moves rows in `tabs[]` AND can rewrite `Workspace.groupId` when a row is + /// dragged into or out of an expanded group — so restoring the id order + /// alone is not enough. + struct SidebarDragRestoreSnapshot { + let orderedWorkspaceIds: [UUID] + let groupIdByWorkspaceId: [UUID: UUID?] + } + + func captureSidebarDragRestoreSnapshot() -> SidebarDragRestoreSnapshot { + SidebarDragRestoreSnapshot( + orderedWorkspaceIds: tabs.map(\.id), + groupIdByWorkspaceId: Dictionary( + uniqueKeysWithValues: tabs.map { ($0.id, $0.groupId) } + ) + ) + } + + /// Roll back everything a cancelled or uncommitted sidebar drag changed: + /// group membership first, then row order. Workspaces created or closed + /// after the capture are left where they are — the restore only covers + /// workspaces present both at capture time and now. + @discardableResult + func restoreSidebarDragSnapshot(_ snapshot: SidebarDragRestoreSnapshot) -> Bool { + let liveGroupIds = Set(workspaceGroups.map(\.id)) + var membershipChangedIds: [UUID] = [] + for tab in tabs { + guard let capturedGroupId = snapshot.groupIdByWorkspaceId[tab.id], + tab.groupId != capturedGroupId else { continue } + // A group deleted mid-drag must not have its dead id restored + // onto former members. + if let restoredGroupId = capturedGroupId, + !liveGroupIds.contains(restoredGroupId) { continue } + tab.groupId = capturedGroupId + membershipChangedIds.append(tab.id) + } + let liveIds = Set(tabs.map(\.id)) + let restoredOrder = snapshot.orderedWorkspaceIds.filter { liveIds.contains($0) } + if restoredOrder != tabs.map(\.id) { + // Renormalizes group contiguity and resyncs `workspaceGroups` + // order from the restored anchor positions, and posts the + // order-change event. + _ = reorderWorkspaces(orderedWorkspaceIds: restoredOrder) + return true + } + guard !membershipChangedIds.isEmpty else { return false } + // Order already matches but a membership flip was rolled back: + // re-establish the group invariants and notify, the same way + // `reorderWorkspaces` would have. + if !workspaceGroups.isEmpty { + syncWorkspaceGroupsOrderToAnchorOrder() + normalizeWorkspaceGroupContiguity() + } + postWorkspaceOrderDidChange(movedWorkspaceIds: membershipChangedIds) + return true + } + @discardableResult func reorderWorkspaces( orderedWorkspaceIds: [UUID], @@ -4230,15 +4289,18 @@ class TabManager: ObservableObject { !sidebarSelectedWorkspaceIds.isDisjoint(with: Set(eligibleChildren)) || sidebarSelectedWorkspaceIds.count > 1 { let hiddenIds = sidebarSelectedWorkspaceIds // Collapse the multi-selection to a single row. Prefer the - // workspace the user was already focused on (now a member) over - // the new empty anchor, so grouping doesn't yank them into the - // group-pivot workspace. Falls back to the anchor when the - // caller did want the anchor focused (selectAnchor: true) or the - // prior selection isn't one of the grouped workspaces. + // workspace the user was already focused on over the new empty + // anchor, so grouping doesn't yank them into the group-pivot + // workspace — whether or not that workspace became a member, + // since the active tab doesn't change when selectAnchor is + // false and the sidebar highlight should keep tracking it. + // Falls back to the anchor when the caller did want the anchor + // focused (selectAnchor: true) or the previously focused + // workspace is gone. let focusId: UUID = { if !selectAnchor, let previousSelectedId, - eligibleChildren.contains(previousSelectedId) { + tabs.contains(where: { $0.id == previousSelectedId }) { return previousSelectedId } return anchor.id diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 400c37f843ff..2bbec96cdc93 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1047,4 +1047,120 @@ struct WorkspaceGroupTests { #expect(headerGroupIds.contains(groupId)) #expect(workspaceRowIds.contains(targetId) == false) } + + // MARK: - Drag restore snapshot (cancelled / uncommitted live reorder) + + @Test func dragRestoreSnapshotRestoresOrderAndGroupMembership() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup(name: "G", childWorkspaceIds: [originalIds[1]])) + let orderBefore = manager.tabs.map(\.id) + let draggedId = originalIds[3] + + let snapshot = manager.captureSidebarDragRestoreSnapshot() + // Live-reorder the last (ungrouped) workspace between the anchor and + // its member: both neighbors share the group, so the drag inference + // absorbs it into the group. + let moved = manager.reorderSidebarWorkspace( + tabId: draggedId, + toIndex: 2, + isDragOperation: true + ) + #expect(moved) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == groupId) + #expect(manager.tabs.map(\.id) != orderBefore) + + let restored = manager.restoreSidebarDragSnapshot(snapshot) + + #expect(restored) + #expect(manager.tabs.map(\.id) == orderBefore) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == nil) + let memberIds = manager.tabs.filter { $0.groupId == groupId }.map(\.id) + #expect(!memberIds.contains(draggedId)) + } + + @Test func dragRestoreSnapshotIsNoOpWhenNothingChanged() throws { + let manager = makeTabManager() + let orderBefore = manager.tabs.map(\.id) + + let snapshot = manager.captureSidebarDragRestoreSnapshot() + let restored = manager.restoreSidebarDragSnapshot(snapshot) + + #expect(!restored) + #expect(manager.tabs.map(\.id) == orderBefore) + } + + @Test func dragRestoreSnapshotRestoresMembershipWhenOrderAlreadyMatches() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup(name: "G", childWorkspaceIds: [originalIds[1]])) + + let snapshot = manager.captureSidebarDragRestoreSnapshot() + // Membership flips while the id order happens to end up unchanged — + // the restore must still roll the membership back. + let lastTab = try #require(manager.tabs.last) + #expect(lastTab.groupId == nil) + lastTab.groupId = groupId + + let restored = manager.restoreSidebarDragSnapshot(snapshot) + + #expect(restored) + #expect(manager.tabs.first { $0.id == lastTab.id }?.groupId == nil) + } + + @Test func dragRestoreSnapshotSkipsWorkspaceClosedMidDrag() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup(name: "G", childWorkspaceIds: [originalIds[1]])) + let draggedId = originalIds[3] + + let snapshot = manager.captureSidebarDragRestoreSnapshot() + let moved = manager.reorderSidebarWorkspace( + tabId: draggedId, + toIndex: 2, + isDragOperation: true + ) + #expect(moved) + let closingTab = try #require(manager.tabs.first { $0.id == originalIds[2] }) + manager.closeWorkspace(closingTab) + + let restored = manager.restoreSidebarDragSnapshot(snapshot) + + #expect(restored) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == nil) + let expectedOrder = snapshot.orderedWorkspaceIds.filter { id in + manager.tabs.contains { $0.id == id } + } + #expect(manager.tabs.map(\.id) == expectedOrder) + } + + // MARK: - Grouping keeps sidebar selection on the focused workspace + + @Test func createGroupKeepsSidebarSelectionOnFocusedNonMember() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let focusedTab = try #require(manager.tabs.first { $0.id == originalIds[3] }) + manager.selectTab(focusedTab) + manager.setSidebarSelectedWorkspaceIds([originalIds[0], originalIds[1]]) + + let groupId = manager.createWorkspaceGroup( + name: "G", + childWorkspaceIds: [originalIds[0], originalIds[1]], + selectAnchor: false + ) + + #expect(groupId != nil) + // The active workspace did not change (selectAnchor: false), so the + // collapsed sidebar selection must keep tracking it instead of + // jumping to the new empty anchor. + #expect(manager.selectedTabId == focusedTab.id) + #expect(manager.sidebarSelectedWorkspaceIds == [focusedTab.id]) + } } From d6fc3f6a7836a8867cfbd3f669a299c7a1b35a0c Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 14:13:56 -0700 Subject: [PATCH 09/36] Move SidebarGroupAnimation into its own file SidebarWorkspaceGroupingMetrics.swift goes back to holding only spatial layout constants (Greptile review note). Also drops the now-dead dropGapHeight: the animated drop gap was replaced by the live reorder. Co-Authored-By: Claude Fable 5 --- Sources/Sidebar/SidebarGroupAnimation.swift | 32 ++++++++++++++++ Sources/SidebarWorkspaceGroupingMetrics.swift | 38 ------------------- cmux.xcodeproj/project.pbxproj | 4 ++ 3 files changed, 36 insertions(+), 38 deletions(-) create mode 100644 Sources/Sidebar/SidebarGroupAnimation.swift diff --git a/Sources/Sidebar/SidebarGroupAnimation.swift b/Sources/Sidebar/SidebarGroupAnimation.swift new file mode 100644 index 000000000000..e923d6db41b6 --- /dev/null +++ b/Sources/Sidebar/SidebarGroupAnimation.swift @@ -0,0 +1,32 @@ +import SwiftUI + +/// Shared animation timings for workspace-group structure changes in the +/// sidebar (promote-in-place, ungroup, collapse/expand, member join/leave, +/// drag-reorder settle). +/// +/// One source of truth so every entrypoint that mutates group structure +/// (keyboard shortcut, context menu, group-header buttons, drag-and-drop, +/// socket/CLI) animates identically. The `TabManager` group mutation methods +/// wrap their structural changes in `withAnimation(SidebarGroupAnimation.)`, +/// and the sidebar rows carry `.transition(.sidebarGroupRow)` so inserted or +/// removed rows fade while their siblings reflow within the same transaction. +enum SidebarGroupAnimation { + /// Workspace row morphs into a group header (and back), member rows join or + /// leave a group, drag-reorder drops settle. + static let structure: Animation = .snappy(duration: 0.26) + + /// Group collapse / expand: member rows slide+fade and the chevron rotates. + static let collapse: Animation = .snappy(duration: 0.24) +} + +extension AnyTransition { + /// Transition for a sidebar row appearing or disappearing because of a + /// group-structure change. A plain opacity fade keeps the morph between a + /// workspace row and a group header (same ForEach identity, swapped + /// `_ConditionalContent` branch) reading as a crossfade, while the + /// surrounding `withAnimation` transaction animates the list reflow so + /// collapse/expand and member join/leave feel like a slide for free. + static var sidebarGroupRow: AnyTransition { + .opacity + } +} diff --git a/Sources/SidebarWorkspaceGroupingMetrics.swift b/Sources/SidebarWorkspaceGroupingMetrics.swift index 98148b3eb295..bfc85aba1d40 100644 --- a/Sources/SidebarWorkspaceGroupingMetrics.swift +++ b/Sources/SidebarWorkspaceGroupingMetrics.swift @@ -3,42 +3,4 @@ import SwiftUI enum SidebarWorkspaceGroupingMetrics { /// Leading inset applied to workspace rows that visually nest under a group header. static let memberIndent: CGFloat = 12 - - /// Height of the animated gap that opens above the row a drag would drop - /// into, replacing the old blue insertion line. Roughly one row tall so the - /// opening reads as "the dropped row goes here". Purely visual — it does not - /// reorder the model (commit still happens once on drop), so there's no - /// during-drag @Published thrash (issue #2586) or hover oscillation. - static let dropGapHeight: CGFloat = 30 -} - -/// Shared animation timings for workspace-group structure changes in the -/// sidebar (promote-in-place, ungroup, collapse/expand, member join/leave, -/// drag-reorder settle). -/// -/// One source of truth so every entrypoint that mutates group structure -/// (keyboard shortcut, context menu, group-header buttons, drag-and-drop, -/// socket/CLI) animates identically. The `TabManager` group mutation methods -/// wrap their structural changes in `withAnimation(SidebarGroupAnimation.)`, -/// and the sidebar rows carry `.transition(.sidebarGroupRow)` so inserted or -/// removed rows fade while their siblings reflow within the same transaction. -enum SidebarGroupAnimation { - /// Workspace row morphs into a group header (and back), member rows join or - /// leave a group, drag-reorder drops settle. - static let structure: Animation = .snappy(duration: 0.26) - - /// Group collapse / expand: member rows slide+fade and the chevron rotates. - static let collapse: Animation = .snappy(duration: 0.24) -} - -extension AnyTransition { - /// Transition for a sidebar row appearing or disappearing because of a - /// group-structure change. A plain opacity fade keeps the morph between a - /// workspace row and a group header (same ForEach identity, swapped - /// `_ConditionalContent` branch) reading as a crossfade, while the - /// surrounding `withAnimation` transaction animates the list reflow so - /// collapse/expand and member join/leave feel like a slide for free. - static var sidebarGroupRow: AnyTransition { - .opacity - } } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index f8a569d5e7a5..6086ea60c4af 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -545,6 +545,7 @@ D7AB34300000000000000003 /* SidebarBonsplitTabWorkspaceDropOverlay.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */; }; EA1F00000000000000000003 /* SidebarDirectoryText.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA1F00000000000000000004 /* SidebarDirectoryText.swift */; }; D7AB34300000000000000001 /* SidebarDropPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000002 /* SidebarDropPlanner.swift */; }; + D7AB34300000000000000007 /* SidebarGroupAnimation.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7AB34300000000000000008 /* SidebarGroupAnimation.swift */; }; B8F266246A1A3D9A45BD840F /* SidebarHelpMenuUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8F266256A1A3D9A45BD840F /* SidebarHelpMenuUITests.swift */; }; 51D800000000000000000001 /* SidebarIdentifierFormattingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51D800000000000000000002 /* SidebarIdentifierFormattingTests.swift */; }; 385C6BA7E78DB87460E5D930 /* SidebarMarkdownRendererTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1C3F1DBF6BF5D7223C4A30C /* SidebarMarkdownRendererTests.swift */; }; @@ -1270,6 +1271,7 @@ D7AB34300000000000000004 /* SidebarBonsplitTabWorkspaceDropOverlay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarBonsplitTabWorkspaceDropOverlay.swift; sourceTree = ""; }; EA1F00000000000000000004 /* SidebarDirectoryText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarDirectoryText.swift; sourceTree = ""; }; D7AB34300000000000000002 /* SidebarDropPlanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarDropPlanner.swift; sourceTree = ""; }; + D7AB34300000000000000008 /* SidebarGroupAnimation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sidebar/SidebarGroupAnimation.swift; sourceTree = ""; }; B8F266256A1A3D9A45BD840F /* SidebarHelpMenuUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarHelpMenuUITests.swift; sourceTree = ""; }; 51D800000000000000000002 /* SidebarIdentifierFormattingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarIdentifierFormattingTests.swift; sourceTree = ""; }; F1C3F1DBF6BF5D7223C4A30C /* SidebarMarkdownRendererTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarMarkdownRendererTests.swift; sourceTree = ""; }; @@ -1686,6 +1688,7 @@ C3408A000000000000000006 /* ContentView+ViewCommandPalette.swift */, C0DEF0A90000000000000002 /* ContentView+ForkAgentConversation.swift */, D7AB00000000000000000004 /* ContentView+MoveTabToNewWorkspace.swift */, + D7AB34300000000000000008 /* SidebarGroupAnimation.swift */, D7AB34300000000000000002 /* SidebarDropPlanner.swift */, EA1F00000000000000000002 /* SidebarPathFormatter.swift */, EA1F00000000000000000004 /* SidebarDirectoryText.swift */, @@ -2948,6 +2951,7 @@ D7AB34300000000000000003 /* SidebarBonsplitTabWorkspaceDropOverlay.swift in Sources */, EA1F00000000000000000003 /* SidebarDirectoryText.swift in Sources */, D7AB34300000000000000001 /* SidebarDropPlanner.swift in Sources */, + D7AB34300000000000000007 /* SidebarGroupAnimation.swift in Sources */, EA1F00000000000000000001 /* SidebarPathFormatter.swift in Sources */, C0DEF0A30000000000000001 /* SidebarPortDisplayText.swift in Sources */, C0DE35010000000000000001 /* SidebarScrim.swift in Sources */, From 2ef6b60c82b2912122bc4c48823b3b3cfdfb1cce Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 14:13:56 -0700 Subject: [PATCH 10/36] Refresh Swift file length budgets for the drag-restore work Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 920952672f09..b9443a8bb461 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,12 +4,12 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19072 Sources/ContentView.swift -17919 Sources/AppDelegate.swift +19239 Sources/ContentView.swift +17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift 11756 cmuxTests/AppDelegateShortcutRoutingTests.swift -9995 Sources/TabManager.swift +10105 Sources/TabManager.swift 8494 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift 7737 Sources/Panels/BrowserPanelView.swift 7214 cmuxTests/WorkspaceUnitTests.swift @@ -71,6 +71,7 @@ 1313 cmuxTests/MobileHostAuthorizationTests.swift 1285 cmuxUITests/SidebarHelpMenuUITests.swift 1197 cmuxTests/CodexAppServerSessionTests.swift +1166 cmuxTests/WorkspaceGroupTests.swift 1156 cmuxTests/SidebarOrderingTests.swift 1144 Sources/VaultAgentProcessScanner.swift 1139 cmuxTests/PiVaultAgentPersistenceTests.swift @@ -82,7 +83,6 @@ 1006 cmuxTests/CmuxSSHURLRequestTests.swift 1000 cmuxTests/CmuxTopSnapshotScopeTests.swift 969 cmuxUITests/TerminalCmdClickUITests.swift -959 cmuxTests/WorkspaceGroupTests.swift 949 Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalInputTextView.swift 947 Sources/TerminalNotificationPolicy.swift 945 Sources/SessionIndexRegisteredAgents.swift From c4c6513eefce490a5cd9ab4a9e89c28e349efd63 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 14:58:32 -0700 Subject: [PATCH 11/36] Sidebar live reorder: let autoscroll reorder under a stationary pointer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex review P2: the loop-breaker keyed on pointer movement alone, but autoscroll moves new rows under a held pointer, so the dragged row stopped following once the drag sat in the top/bottom autoscroll zone. The breaker now ignores a hover update only when the pointer is unmoved AND the hovered row is unchanged — the self-induced re-fire signature. A new row arriving under a stationary pointer reorders normally. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 26 +++++++++++++++++++------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index b9443a8bb461..2e1d05f9e637 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19239 Sources/ContentView.swift +19251 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 65ad9a400244..186ba3edb1a8 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10375,6 +10375,12 @@ final class SidebarDragState { /// If the pointer hasn't physically moved since the last reorder, the update /// was self-induced, so it's ignored. Reset on drag begin/clear. var lastLiveReorderMouseLocation: CGPoint? + /// The hovered row at the last committed live reorder, paired with + /// ``lastLiveReorderMouseLocation``. Autoscroll moves new rows under a + /// stationary pointer, so a stationary pointer alone cannot mean + /// "self-induced re-fire" — only a stationary pointer over the SAME + /// target row is. Reset on drag begin/clear. + var lastLiveReorderTargetTabId: UUID? /// True while the `debug.sidebar.simulate_drag` debug-only V2 method is /// driving the drag state. The lifecycle observers honor this by not /// starting `SidebarDragFailsafeMonitor` (which would otherwise post a @@ -10402,6 +10408,7 @@ final class SidebarDragState { func beginDragging(tabId: UUID) { draggedTabId = tabId lastLiveReorderMouseLocation = nil + lastLiveReorderTargetTabId = nil clearDropIndicator() originatedActiveDrag = true SidebarWorkspaceDragRegistry.begin(workspaceId: tabId) @@ -10424,6 +10431,7 @@ final class SidebarDragState { foreignDraggedIsPinned = nil draggedTabId = nil lastLiveReorderMouseLocation = nil + lastLiveReorderTargetTabId = nil clearDropIndicator() } } @@ -18233,13 +18241,15 @@ struct SidebarTabDropDelegate: DropDelegate { // Loop-breaker: a live reorder shifts rows under the pointer, re-firing // this drop delegate with the pointer in the same place, and the planner // flips the index back — an infinite ping-pong while the pointer is held - // still (seen in sidebar.liveReorder as from=N to=N+1 then back). Only - // act when the pointer has physically moved since the last committed - // reorder, so self-induced re-fires are ignored while genuine drag - // movement still reorders. + // still (seen in sidebar.liveReorder as from=N to=N+1 then back). A + // self-induced re-fire arrives with the pointer unmoved AND the same + // hovered row, so only that combination is ignored. A stationary + // pointer over a DIFFERENT row is genuine: autoscroll moves new rows + // under a held pointer, and the dragged row must keep following them. let mouseLocation = NSEvent.mouseLocation if let last = dragState.lastLiveReorderMouseLocation, - hypot(mouseLocation.x - last.x, mouseLocation.y - last.y) < 5 { + hypot(mouseLocation.x - last.x, mouseLocation.y - last.y) < 5, + targetTabId == dragState.lastLiveReorderTargetTabId { return } let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( @@ -18276,9 +18286,11 @@ struct SidebarTabDropDelegate: DropDelegate { "target=\(targetTabId?.uuidString.prefix(5) ?? "end") topLevel=\(usesTopLevelRows)" ) #endif - // Anchor the loop-breaker to where the pointer is now: the upcoming - // self-induced re-fires arrive with this same location and are skipped. + // Anchor the loop-breaker to where the pointer is now and what it + // hovers: the upcoming self-induced re-fires arrive with this same + // location + target and are skipped. dragState.lastLiveReorderMouseLocation = mouseLocation + dragState.lastLiveReorderTargetTabId = targetTabId _ = withAnimation(SidebarGroupAnimation.structure) { tabManager.reorderSidebarWorkspace( tabId: draggedTabId, From 99ca472adb2e9f394ed8220ba2e8d1832942d90d Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 15:26:05 -0700 Subject: [PATCH 12/36] Sidebar drop: nil indicator over a row commits as a no-op MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex review P2, the drop-time sibling of the hover fix: performDrop recomputed targetIndex from a nil indicator, falling back to preferredEdge — releasing over the same row half after the live reorder had already placed the row moved it back across the target. The hover path's nil-indicator rule ("planner says already at the pointer's insertion point") now applies before the final commit too. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 2e1d05f9e637..a4b0deededa2 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19251 Sources/ContentView.swift +19263 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 186ba3edb1a8..94e8110f188b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -18007,6 +18007,18 @@ struct SidebarTabDropDelegate: DropDelegate { let didMove = performCrossWindowDrop(draggedTabId: draggedTabId) return didMove ? true : abortDrop() } + // Same rule as the live-reorder hover path: a nil indicator over a row + // means the planner resolved "the dragged row already sits at the + // pointer's insertion point", i.e. the live reorder has already + // produced the final order. Recomputing targetIndex below would fall + // back to preferredEdge and move the row back across the target at + // drop time. Commit as a no-op instead. + if targetTabId != nil, dragState.dropIndicator == nil { +#if DEBUG + cmuxDebugLog("sidebar.drop.noop reason=nilIndicatorAlreadyPlaced") +#endif + return true + } let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( forDraggedWorkspaceId: draggedTabId, targetWorkspaceId: targetTabId From beed2dd1fc7f9c3186f1a8e199e055e6e1d57ca1 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 15:53:38 -0700 Subject: [PATCH 13/36] Sidebar drag: capture the rollback snapshot synchronously; arm the loop-breaker only on real moves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review findings on the previous round: - Codex P2: the rollback snapshot was captured in `.onChange` of the dragged tab, which SwiftUI delivers on a later view update — a native drag can hover (and live-reorder the model) first, leaving the snapshot nil or post-mutation so cancel couldn't restore. The snapshot now lives on SidebarDragState and commitLiveReorder captures it synchronously right before this drag's first mutation. A drop that ends with a clamped final nudge also no longer fails once the model was mutated, so the failsafe can't roll back an order the user saw land. - Bugbot medium: the loop-breaker armed (pointer + target recorded) even when reorderSidebarWorkspace clamped to a no-op, suppressing later genuine hovers over the same row. It now arms only when the reorder actually moved. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 60 ++++++++++++++++++---------- 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index a4b0deededa2..c42cde919ec3 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19263 Sources/ContentView.swift +19283 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 94e8110f188b..daaee7a392d9 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10403,12 +10403,22 @@ final class SidebarDragState { /// pointer-move. `nil` when no foreign drag is mirrored here. var foreignDraggedIsPinned: Bool? + /// Pre-drag order + group membership, captured synchronously by + /// `commitLiveReorder` right before this drag's FIRST model mutation — + /// not in a view-update callback, because a native drag can hover (and + /// mutate) before SwiftUI delivers `.onChange`. Restored by the sidebar's + /// clear-request handler when the drag ends without committing; a + /// successful drop clears it via ``clearDrag()``. Nil while nothing has + /// been mutated, so a no-mutation drag restores nothing. + var dragRestoreSnapshot: TabManager.SidebarDragRestoreSnapshot? + init() {} func beginDragging(tabId: UUID) { draggedTabId = tabId lastLiveReorderMouseLocation = nil lastLiveReorderTargetTabId = nil + dragRestoreSnapshot = nil clearDropIndicator() originatedActiveDrag = true SidebarWorkspaceDragRegistry.begin(workspaceId: tabId) @@ -10432,6 +10442,7 @@ final class SidebarDragState { draggedTabId = nil lastLiveReorderMouseLocation = nil lastLiveReorderTargetTabId = nil + dragRestoreSnapshot = nil clearDropIndicator() } } @@ -10594,11 +10605,6 @@ struct VerticalTabsSidebar: View { @State var modifierKeyMonitor = WindowScopedShortcutHintModifierMonitor(activation: .commandOnly) @StateObject var dragAutoScrollController = SidebarDragAutoScrollController() @StateObject private var dragFailsafeMonitor = SidebarDragFailsafeMonitor() - /// Workspace order + group membership captured when a sidebar drag begins, - /// so any drag that ends without committing (Escape, mouse-up outside a - /// valid target, app deactivation, aborted drop) undoes the live reorder - /// and puts every row back where it started. Nil when no drag is in flight. - @State private var dragReorderSnapshot: TabManager.SidebarDragRestoreSnapshot? @StateObject private var tabItemSettingsStore = SidebarTabItemSettingsStore( initialSidebarFontSize: GhosttyConfig.load().sidebarFontSize ) @@ -11078,10 +11084,11 @@ struct VerticalTabsSidebar: View { cmuxDebugLog("sidebar.dragState.sidebar tab=\(debugShortSidebarTabId(newDraggedTabId))") #endif if newDraggedTabId != nil { - // Snapshot order + group membership at drag start so a - // non-committing drag end can undo the live reorder. Captured - // before any drop hover mutates the model. - dragReorderSnapshot = tabManager.captureSidebarDragRestoreSnapshot() + // The undo snapshot is NOT captured here: this onChange runs + // on a later view update, and a native drag can hover (and + // live-reorder the model) before that. The drop delegate + // captures `dragState.dragRestoreSnapshot` synchronously + // before this drag's first mutation instead. // The failsafe monitor probes the real mouse-button state and // posts `mouse_up_failsafe` if no mouse is held down. That's // correct for HID-driven drags, but `debug.sidebar.simulate_drag` @@ -11097,8 +11104,6 @@ struct VerticalTabsSidebar: View { dragFailsafeMonitor.stop() dragAutoScrollController.stop() dragState.clearDropIndicator() - // Drag ended (committed via drop); discard the undo snapshot. - dragReorderSnapshot = nil } .onReceive(NotificationCenter.default.publisher(for: SidebarDragLifecycleNotification.requestClear)) { notification in guard dragState.draggedTabId != nil || dragState.dropIndicator != nil else { return } @@ -11114,7 +11119,7 @@ struct VerticalTabsSidebar: View { // normal in-sidebar release commits via performDrop, which clears // the drag state synchronously, so its trailing failsafe mouse-up // never passes the guard above. - if let snapshot = dragReorderSnapshot { + if let snapshot = dragState.dragRestoreSnapshot { #if DEBUG cmuxDebugLog("sidebar.dragCancel.restoreOrder reason=\(reason)") #endif @@ -11122,7 +11127,7 @@ struct VerticalTabsSidebar: View { tabManager.restoreSidebarDragSnapshot(snapshot) } } - dragReorderSnapshot = nil + // Also clears the restore snapshot. dragState.clearDrag() } .onChange(of: tabManager.tabs.map(\.id)) { tabIds in @@ -18091,7 +18096,11 @@ struct SidebarTabDropDelegate: DropDelegate { preserving: selectionBeforeReorder, preferredAnchorWorkspaceId: anchorWorkspaceIdBeforeReorder ) - return didReorder + // A clamped final nudge must not fail the drop once the live reorder + // has already mutated the model (snapshot captured): the row sits + // where the user saw it land, and returning false would let the + // failsafe roll the whole drag back. + return didReorder || dragState.dragRestoreSnapshot != nil } /// Move a workspace dragged in from another window into this window at the @@ -18298,12 +18307,14 @@ struct SidebarTabDropDelegate: DropDelegate { "target=\(targetTabId?.uuidString.prefix(5) ?? "end") topLevel=\(usesTopLevelRows)" ) #endif - // Anchor the loop-breaker to where the pointer is now and what it - // hovers: the upcoming self-induced re-fires arrive with this same - // location + target and are skipped. - dragState.lastLiveReorderMouseLocation = mouseLocation - dragState.lastLiveReorderTargetTabId = targetTabId - _ = withAnimation(SidebarGroupAnimation.structure) { + // Capture the rollback snapshot synchronously before this drag's + // FIRST mutation. Drag start can't capture it: `.onChange` of the + // dragged tab runs on a later view update, and a native drag can + // reach this hover first. + if dragState.dragRestoreSnapshot == nil { + dragState.dragRestoreSnapshot = tabManager.captureSidebarDragRestoreSnapshot() + } + let didReorder = withAnimation(SidebarGroupAnimation.structure) { tabManager.reorderSidebarWorkspace( tabId: draggedTabId, toIndex: targetIndex, @@ -18311,6 +18322,15 @@ struct SidebarTabDropDelegate: DropDelegate { usesTopLevelRows: usesTopLevelRows ) } + // Anchor the loop-breaker to where the pointer is now and what it + // hovers: the upcoming self-induced re-fires arrive with this same + // location + target and are skipped. Only a reorder that actually + // moved can self-induce re-fires — a clamped no-op must not arm the + // breaker, or later genuine hovers over the same row get suppressed. + if didReorder { + dragState.lastLiveReorderMouseLocation = mouseLocation + dragState.lastLiveReorderTargetTabId = targetTabId + } } /// Drop indicator for a foreign workspace hovering this window. The dragged From ad1f7b6a4f9416d249dcd64f5c511ddf87a8a904 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 16:32:00 -0700 Subject: [PATCH 14/36] Sidebar drag: stop scroll-follow fighting the live reorder; tighter mid-drag animation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: dragging felt laggy. Two causes: - Scroll-follow (keep the selected row visible after a reorder) was designed for one-shot keyboard/socket moves, but the live reorder mutates the order on every row crossing — each crossing could fire an animated scrollTo(selectedWorkspace) that fights the pointer and the edge autoscroll. Both scroll-follow entry points (the workspaceIds onChange and the workspaceOrderDidChange observer) are now suppressed while a sidebar drag is in flight; the pointer owns the viewport. - Mid-drag crossings animated with the 0.26s structural spring, so the row trailed the cursor by a quarter second per crossing. New SidebarGroupAnimation.liveReorder (0.15s, no bounce) for the crossing itself; promote/collapse morphs, drop settle, and cancel restore keep the slower structural timing. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 15 ++++++++++++++- Sources/Sidebar/SidebarGroupAnimation.swift | 6 ++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index c42cde919ec3..f7a7b8302685 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19283 Sources/ContentView.swift +19296 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index daaee7a392d9..5ee6eaddf10f 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10939,6 +10939,11 @@ struct VerticalTabsSidebar: View { guard let manager = notification.object as? TabManager, manager === tabManager else { return } + // The pointer owns the viewport while a sidebar drag is in flight: + // the live reorder posts an order change per row crossing, and + // queueing a scroll-to-selected for each one fights the drag (see the + // matching guard in the workspaceIds onChange). + guard dragState.draggedTabId == nil else { return } guard let selectedWorkspaceId = tabManager.selectedTabId else { return } let movedWorkspaceIds = notification.userInfo?[WorkspaceOrderChangeNotificationKey.movedWorkspaceIds] as? [UUID] ?? [] guard movedWorkspaceIds.contains(selectedWorkspaceId) else { return } @@ -11236,6 +11241,14 @@ struct VerticalTabsSidebar: View { requestSelectedWorkspaceScroll(scrollProxy, workspaceIds: renderContext.workspaceIds) } .onChange(of: renderContext.workspaceIds) { oldWorkspaceIds, newWorkspaceIds in + // Scroll-follow exists for one-shot reorders (keyboard, + // socket "move up/down") that should keep the selected row + // visible. The live drag-reorder mutates the order on + // every row crossing — firing an animated scrollTo per + // crossing fights the pointer and the edge autoscroll and + // makes the whole drag stutter. The pointer owns the + // viewport while a drag is in flight. + guard dragState.draggedTabId == nil else { return } guard shouldRequestSelectedWorkspaceScrollAfterWorkspaceIdsChange( from: oldWorkspaceIds, to: newWorkspaceIds @@ -18314,7 +18327,7 @@ struct SidebarTabDropDelegate: DropDelegate { if dragState.dragRestoreSnapshot == nil { dragState.dragRestoreSnapshot = tabManager.captureSidebarDragRestoreSnapshot() } - let didReorder = withAnimation(SidebarGroupAnimation.structure) { + let didReorder = withAnimation(SidebarGroupAnimation.liveReorder) { tabManager.reorderSidebarWorkspace( tabId: draggedTabId, toIndex: targetIndex, diff --git a/Sources/Sidebar/SidebarGroupAnimation.swift b/Sources/Sidebar/SidebarGroupAnimation.swift index e923d6db41b6..7e5779ac23ba 100644 --- a/Sources/Sidebar/SidebarGroupAnimation.swift +++ b/Sources/Sidebar/SidebarGroupAnimation.swift @@ -17,6 +17,12 @@ enum SidebarGroupAnimation { /// Group collapse / expand: member rows slide+fade and the chevron rotates. static let collapse: Animation = .snappy(duration: 0.24) + + /// Mid-drag row crossing during the live reorder. Deliberately faster + /// than `structure`: the row is chasing the pointer, and a 0.26s spring + /// reads as input lag when crossings come several per second. No bounce — + /// overshoot under a moving pointer looks like jitter. + static let liveReorder: Animation = .snappy(duration: 0.15, extraBounce: 0) } extension AnyTransition { From 534c21c43b0266d2d32c677d982369f8192d93af Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 16:59:07 -0700 Subject: [PATCH 15/36] Sidebar live reorder: arm the loop-breaker on an actual order change, not the reorder Bool Bugbot: reorderWorkspace returns true for clamped no-ops (planner index differs but clamping lands on fromIndex), so the breaker could still arm without a row shift and suppress later genuine hovers. Compare the id order before/after instead. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index f7a7b8302685..839fedd23db7 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19296 Sources/ContentView.swift +19300 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 5ee6eaddf10f..25d354052651 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -18327,7 +18327,8 @@ struct SidebarTabDropDelegate: DropDelegate { if dragState.dragRestoreSnapshot == nil { dragState.dragRestoreSnapshot = tabManager.captureSidebarDragRestoreSnapshot() } - let didReorder = withAnimation(SidebarGroupAnimation.liveReorder) { + let orderBeforeReorder = tabManager.tabs.map(\.id) + _ = withAnimation(SidebarGroupAnimation.liveReorder) { tabManager.reorderSidebarWorkspace( tabId: draggedTabId, toIndex: targetIndex, @@ -18337,10 +18338,13 @@ struct SidebarTabDropDelegate: DropDelegate { } // Anchor the loop-breaker to where the pointer is now and what it // hovers: the upcoming self-induced re-fires arrive with this same - // location + target and are skipped. Only a reorder that actually - // moved can self-induce re-fires — a clamped no-op must not arm the - // breaker, or later genuine hovers over the same row get suppressed. - if didReorder { + // location + target and are skipped. Only an actual row shift can + // self-induce re-fires, and the reorder's Bool is not that proof — + // `reorderWorkspace` reports true for clamped no-ops (the planner + // index differs but clamping lands on fromIndex). Compare the order + // itself so a no-op never arms the breaker and suppresses later + // genuine hovers over the same row. + if tabManager.tabs.map(\.id) != orderBeforeReorder { dragState.lastLiveReorderMouseLocation = mouseLocation dragState.lastLiveReorderTargetTabId = targetTabId } From 651dd4d04c4fef4f12ae96aca58ddb9afa4a021a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 17:11:40 -0700 Subject: [PATCH 16/36] Sidebar live reorder: kill the animation-feedback cascade MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood logs showed the dragged row "walking" on its own: one reorder's 0.15s animation slides other rows under the pointer, SwiftUI's drop tracking hit-tests those in-flight rows, each re-fire reordered again and restarted the animations — a self-sustaining cascade (10 reorders/s across a band of rows in the captured log). The "hovered row changed" loop-breaker exemption enabled it: rows animating past the pointer change the hovered row by definition. The breaker is now strictly pointer-driven: a live reorder only fires after >= 8pt of genuine VERTICAL pointer travel since the last committed reorder (horizontal jitter never re-arms). Autoscroll — the one legitimate way rows move under a held pointer — re-arms the breaker explicitly via a new SidebarDragAutoScrollController.onDidScroll callback fired only when the controller actually scrolled content, so edge-follow keeps working without re-opening the loop. The per-target exemption state is removed. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 64 ++++++++++++++++------------ 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 839fedd23db7..6a67317153fc 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19300 Sources/ContentView.swift +19308 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 25d354052651..99f09d157af5 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10375,12 +10375,6 @@ final class SidebarDragState { /// If the pointer hasn't physically moved since the last reorder, the update /// was self-induced, so it's ignored. Reset on drag begin/clear. var lastLiveReorderMouseLocation: CGPoint? - /// The hovered row at the last committed live reorder, paired with - /// ``lastLiveReorderMouseLocation``. Autoscroll moves new rows under a - /// stationary pointer, so a stationary pointer alone cannot mean - /// "self-induced re-fire" — only a stationary pointer over the SAME - /// target row is. Reset on drag begin/clear. - var lastLiveReorderTargetTabId: UUID? /// True while the `debug.sidebar.simulate_drag` debug-only V2 method is /// driving the drag state. The lifecycle observers honor this by not /// starting `SidebarDragFailsafeMonitor` (which would otherwise post a @@ -10417,7 +10411,6 @@ final class SidebarDragState { func beginDragging(tabId: UUID) { draggedTabId = tabId lastLiveReorderMouseLocation = nil - lastLiveReorderTargetTabId = nil dragRestoreSnapshot = nil clearDropIndicator() originatedActiveDrag = true @@ -10441,7 +10434,6 @@ final class SidebarDragState { foreignDraggedIsPinned = nil draggedTabId = nil lastLiveReorderMouseLocation = nil - lastLiveReorderTargetTabId = nil dragRestoreSnapshot = nil clearDropIndicator() } @@ -11050,6 +11042,13 @@ struct VerticalTabsSidebar: View { modifierKeyMonitor.start() dragState.clearDrag() isBonsplitWorkspaceDropTargetCollectionActive = false + // Autoscroll moves new rows under a stationary pointer; re-arm + // the live-reorder loop-breaker on every real scroll so the + // dragged row keeps following at the edges without re-opening + // the stationary-pointer feedback loop. + dragAutoScrollController.onDidScroll = { [weak dragState] in + dragState?.lastLiveReorderMouseLocation = nil + } // Defensive reset: if a prior simulation died without running // its teardown (sidebar unmounted mid-loop, app crash, etc.) the // @State SidebarDragState could carry isSimulated=true into a @@ -17452,6 +17451,11 @@ final class SidebarDragAutoScrollController: ObservableObject { private weak var scrollView: NSScrollView? private var timer: Timer? private var activePlan: SidebarAutoScrollPlan? + /// Fired after every tick that actually moved the scroll content. The + /// sidebar uses it to re-arm the live-reorder loop-breaker: autoscroll + /// moves new rows under a stationary pointer, and only the controller + /// knows a scroll really happened (pointer movement does not). + var onDidScroll: (() -> Void)? func attach(scrollView: NSScrollView?) { self.scrollView = scrollView @@ -17500,6 +17504,7 @@ final class SidebarDragAutoScrollController: ObservableObject { // AppKit drag/drop autoscroll guidance recommends autoscroll(with:) // when periodic drag updates are available; use it first. if applyNativeAutoscroll(to: scrollView) { + onDidScroll?() activePlan = plan(for: scrollView) if activePlan == nil { stop() @@ -17512,7 +17517,9 @@ final class SidebarDragAutoScrollController: ObservableObject { stop() return } - _ = apply(plan: plan, to: scrollView) + if apply(plan: plan, to: scrollView) { + onDidScroll?() + } } private func applyNativeAutoscroll(to scrollView: NSScrollView) -> Bool { @@ -18272,18 +18279,21 @@ struct SidebarTabDropDelegate: DropDelegate { // which can pick the OTHER side of the hovered row and bounce the row // back across it on every hover tick. Already in place: nothing to do. guard dragState.dropIndicator != nil else { return } - // Loop-breaker: a live reorder shifts rows under the pointer, re-firing - // this drop delegate with the pointer in the same place, and the planner - // flips the index back — an infinite ping-pong while the pointer is held - // still (seen in sidebar.liveReorder as from=N to=N+1 then back). A - // self-induced re-fire arrives with the pointer unmoved AND the same - // hovered row, so only that combination is ignored. A stationary - // pointer over a DIFFERENT row is genuine: autoscroll moves new rows - // under a held pointer, and the dragged row must keep following them. + // Loop-breaker: a live reorder animates rows under the pointer, and + // SwiftUI's drop tracking hit-tests those in-flight rows — each one + // re-fires this delegate and, left unchecked, re-reorders, which + // restarts the animations and sustains the loop (dogfooded as the + // dragged row "walking" across whole bands of rows on its own). Only + // genuine VERTICAL pointer travel since the last committed reorder + // may reorder again; reordering is a vertical axis, so horizontal + // hand jitter must not re-arm. An earlier "hovered row changed" + // exemption here re-opened the loop — rows animating past the + // pointer change the hovered row by definition. Autoscroll (the one + // legitimate way rows move under a held pointer) re-arms explicitly + // via SidebarDragAutoScrollController.onDidScroll instead. let mouseLocation = NSEvent.mouseLocation if let last = dragState.lastLiveReorderMouseLocation, - hypot(mouseLocation.x - last.x, mouseLocation.y - last.y) < 5, - targetTabId == dragState.lastLiveReorderTargetTabId { + abs(mouseLocation.y - last.y) < 8 { return } let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( @@ -18336,17 +18346,15 @@ struct SidebarTabDropDelegate: DropDelegate { usesTopLevelRows: usesTopLevelRows ) } - // Anchor the loop-breaker to where the pointer is now and what it - // hovers: the upcoming self-induced re-fires arrive with this same - // location + target and are skipped. Only an actual row shift can - // self-induce re-fires, and the reorder's Bool is not that proof — - // `reorderWorkspace` reports true for clamped no-ops (the planner - // index differs but clamping lands on fromIndex). Compare the order - // itself so a no-op never arms the breaker and suppresses later - // genuine hovers over the same row. + // Anchor the loop-breaker to where the pointer is now: re-fires from + // rows animating under an (almost) unmoved pointer are skipped. Only + // an actual row shift can self-induce re-fires, and the reorder's + // Bool is not that proof — `reorderWorkspace` reports true for + // clamped no-ops (the planner index differs but clamping lands on + // fromIndex). Compare the order itself so a no-op never arms the + // breaker and suppresses later genuine hovers over the same row. if tabManager.tabs.map(\.id) != orderBeforeReorder { dragState.lastLiveReorderMouseLocation = mouseLocation - dragState.lastLiveReorderTargetTabId = targetTabId } } From 003fb27c338db502059ae144f35eb373839382a9 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 19:08:52 -0700 Subject: [PATCH 17/36] Sidebar gesture reorder: stop the drop-target gate from killing the drag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood log evidence: both drags logged sidebar.reorder.begin and never reached sidebar.reorder.end — the mouse-up failsafe did the cleanup. The gesture was dying at its first event: shouldCollectWorkspaceDropTargets flipped on draggedTabId != nil (a leftover from the NSDraggingSession world), and rowsWithGatedDropTargetReader's if/else branch switch re-identities the entire row subtree, tearing down the row that hosts the in-flight DragGesture. An AppKit drag session survived that; a SwiftUI gesture does not. The gate now flips only for bonsplit tab drags (the overlay that actually consumes those frames); the gesture reorder hit-tests on SidebarReorderRowFrameKey frames and needs no drop targets. Also adds a DEBUG every-60th-event tick log so drag health is measurable from the log on the next dogfood pass. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 27 +++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index c7698ec99dea..6de0214e5b8f 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19372 Sources/ContentView.swift +19391 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 347e0d3ee66e..9de09c83ac70 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10510,10 +10510,23 @@ final class SidebarDragState { /// Updates the follower position and landing slot for a moved cursor. func updateReorder(cursorY: CGFloat) { +#if DEBUG + reorderTickCount += 1 + if reorderTickCount % 60 == 0 { + cmuxDebugLog("sidebar.reorder.tick n=\(reorderTickCount) cursorY=\(Int(cursorY))") + } +#endif followerCursorY = cursorY recomputeIndicator(cursorY: cursorY) } +#if DEBUG + /// Gesture event counter, logged every 60th tick as drag-health evidence + /// (a healthy drag streams events at pointer rate; a torn-down gesture + /// stops ticking). + @ObservationIgnored private var reorderTickCount = 0 +#endif + /// Advances the reorder by the distance the auto-scroll tick just moved /// the content. The gesture's cursor Y lives in list (content) space, so /// when content scrolls `delta` points under a stationary pointer, the @@ -12555,10 +12568,16 @@ struct VerticalTabsSidebar: View { tabs: renderContext.tabs, groupsById: renderContext.workspaceGroupById ) - let shouldCollectWorkspaceDropTargets = SidebarDropPlanner.shouldCollectWorkspaceDropTargets( - draggedTabId: dragState.draggedTabId, - isBonsplitWorkspaceDropActive: isBonsplitWorkspaceDropTargetCollectionActive - ) + // Collect row frames for the bonsplit drop overlay ONLY while a + // bonsplit tab drag is active. The legacy gate also flipped on for + // workspace drags (draggedTabId != nil), which in the gesture world + // killed the drag at its first event: flipping + // `rowsWithGatedDropTargetReader`'s if/else re-identities the whole + // row subtree, tearing down the row hosting the in-flight reorder + // `DragGesture` (begin logged, end never fired, follower frozen). The + // gesture reorder needs no drop targets — its hit-testing runs on + // `SidebarReorderRowFrameKey` frames. + let shouldCollectWorkspaceDropTargets = isBonsplitWorkspaceDropTargetCollectionActive // During a gesture-driven reorder the list reflows to `previewItems` // (the dragged row moved to its landing slot) so the gap animates open. // `dropIndicator` is discrete — it changes only when the landing slot From d405d1b60ce33fdfe36c5977b1e3632fc88d4193 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 19:27:02 -0700 Subject: [PATCH 18/36] Fix test patterns for the workspace render item's effectiveGroupId payload The tests job (the only place the test bundle compiles) caught three .workspace patterns still binding the old single-value payload. Co-Authored-By: Claude Fable 5 --- cmuxTests/WorkspaceGroupTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index d80b9f35768c..c7bcc926db8f 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -219,7 +219,7 @@ struct WorkspaceGroupTests { switch item { case .groupHeader(let group, _) where group.anchorWorkspaceId == workspaceId: return item.id - case .workspace(let workspace) where workspace.id == workspaceId: + case .workspace(let workspace, _) where workspace.id == workspaceId: return item.id default: continue @@ -792,7 +792,7 @@ struct WorkspaceGroupTests { #expect(items.allSatisfy { !deletedRowIds.contains($0.id) }) // The unrelated outsider survives as a plain workspace row. #expect(items.contains { item in - if case .workspace(let ws) = item, ws.id == outsiderId { return true } + if case .workspace(let ws, _) = item, ws.id == outsiderId { return true } return false }) } @@ -1041,7 +1041,7 @@ struct WorkspaceGroupTests { return nil } let workspaceRowIds: [UUID] = items.compactMap { - if case let .workspace(workspace) = $0 { return workspace.id } + if case let .workspace(workspace, _) = $0 { return workspace.id } return nil } #expect(headerGroupIds.contains(groupId)) From 26446268c9ee1056253045d132dbd6ab1e79baac Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 19:49:59 -0700 Subject: [PATCH 19/36] Sidebar gesture reorder: derive the cursor from translation, not location MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In-group reorders did not work, and synthetic-drag repro showed why: a steady 50pt drag produced list-space cursor positions jumping 561 -> 439 -> 540. DragGesture converts its locations through the host row's CURRENT geometry, and the preview moves that row to the landing slot mid-drag — so every preview reflow shifted the reported location by the row's displacement, moving the indicator, moving the row again. The frozen row frames guarded hit-testing against this feedback, but the gesture's own coordinates were never guarded. The cursor is now derived from the gesture's translation (pure pointer delta, immune to host movement) anchored at the begin-time location (geometry-consistent: the preview has not moved yet), plus the accumulated autoscroll delta. Verified end to end with synthetic CGEvent drags on the tagged build: single-slot and multi-row in-group moves commit to the exact slot, cursor trace is monotonic, group member order changes correctly. Also extends the begin/tick debug logs with frames/scope/indicator diagnostics (these are what localized the bug). Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 33 ++++++++++--- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 47 ++++++++++++++----- Sources/SidebarWorkspaceGroupHeaderView.swift | 4 +- .../VerticalTabsSidebar+WorkspaceGroups.swift | 6 +-- 5 files changed, 67 insertions(+), 25 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 6de0214e5b8f..0e376f2aaa96 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19391 Sources/ContentView.swift +19412 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 9de09c83ac70..b75e3a150df9 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10429,6 +10429,15 @@ final class SidebarDragState { /// members when dragging a group anchor at top level). @ObservationIgnored private var scopeBandComposition: [UUID: [UUID]] = [:] + /// The begin-time gesture location in list space. Later cursor positions + /// are derived as base + translation + autoscroll delta, because the + /// gesture's location re-converts through the host row's CURRENT geometry + /// and jumps when the preview moves that row. + @ObservationIgnored var reorderTranslationBaseY: CGFloat = 0 + /// Total content distance autoscroll has moved during this drag; folded + /// into every translation-derived cursor position. + @ObservationIgnored var autoScrollAccumulatedDelta: CGFloat = 0 + /// Dead-zone half-width around a row midpoint within which the landing edge /// is held, so the gap does not flicker on sub-pixel jitter. static let hysteresisMargin: CGFloat = 6 @@ -10478,6 +10487,8 @@ final class SidebarDragState { followerCursorY = nil draggedRowFrame = nil grabOffsetY = 0 + reorderTranslationBaseY = 0 + autoScrollAccumulatedDelta = 0 reorderIds = [] pinnedIds = [] scopeBandComposition = [:] @@ -10495,6 +10506,7 @@ final class SidebarDragState { scopeBandComposition: [UUID: [UUID]], draggedRowFrame: CGRect?, grabOffsetY: CGFloat, + translationBaseY: CGFloat, cursorY: CGFloat ) { self.draggedTabId = tabId @@ -10504,6 +10516,8 @@ final class SidebarDragState { self.scopeBandComposition = scopeBandComposition self.draggedRowFrame = draggedRowFrame self.grabOffsetY = grabOffsetY + self.reorderTranslationBaseY = translationBaseY + self.autoScrollAccumulatedDelta = 0 self.followerCursorY = cursorY recomputeIndicator(cursorY: cursorY) } @@ -10513,7 +10527,13 @@ final class SidebarDragState { #if DEBUG reorderTickCount += 1 if reorderTickCount % 60 == 0 { - cmuxDebugLog("sidebar.reorder.tick n=\(reorderTickCount) cursorY=\(Int(cursorY))") + let indicatorDescription = dropIndicator.map { + "\($0.tabId?.uuidString.prefix(5) ?? "end").\($0.edge == .top ? "top" : "bottom")" + } ?? "nil" + cmuxDebugLog( + "sidebar.reorder.tick n=\(reorderTickCount) cursorY=\(Int(cursorY)) " + + "frames=\(rowFramesInList.count) indicator=\(indicatorDescription)" + ) } #endif followerCursorY = cursorY @@ -10535,6 +10555,7 @@ final class SidebarDragState { /// the pointer sits still at a list edge. func applyAutoScrollDelta(_ delta: CGFloat) { guard draggedTabId != nil, delta != 0, let cursorY = followerCursorY else { return } + autoScrollAccumulatedDelta += delta updateReorder(cursorY: cursorY + delta) } @@ -12834,15 +12855,15 @@ struct VerticalTabsSidebar: View { // into `TabItemView` so it lives below `.equatable()` and survives the // parent body re-evaluations that the discrete drop-indicator changes // trigger, instead of being torn down mid-drag. - let onReorderChanged: (CGPoint, CGPoint) -> Void = { [tabId = tab.id, renderContext] startLocation, location in + let onReorderChanged: (CGPoint, CGFloat) -> Void = { [tabId = tab.id, renderContext] startLocation, translationHeight in sidebarReorderGestureChanged( draggedId: tabId, startLocationY: startLocation.y, - cursorY: location.y, + translationHeight: translationHeight, renderContext: renderContext ) } - let onReorderEnded: (CGPoint, CGPoint) -> Void = { [tabId = tab.id] _, _ in + let onReorderEnded: (CGPoint, CGFloat) -> Void = { [tabId = tab.id] _, _ in sidebarReorderGestureEnded(draggedId: tabId) } @@ -15440,8 +15461,8 @@ struct TabItemView: View, Equatable { /// Reorder gesture callbacks (start location, current location), dispatched /// into the shared `VerticalTabsSidebar` reorder helpers via closures so the /// row never holds an `@Observable` store reference (snapshot-boundary rule). - let onReorderChanged: (CGPoint, CGPoint) -> Void - let onReorderEnded: (CGPoint, CGPoint) -> Void + let onReorderChanged: (CGPoint, CGFloat) -> Void + let onReorderEnded: (CGPoint, CGFloat) -> Void /// False for the floating follower copy, which is non-interactive and must /// not report a row frame. let isReorderEnabled: Bool diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index 108ae1e8c36e..b9d886febe4c 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -24,24 +24,36 @@ extension VerticalTabsSidebar { /// Handles a reorder drag tick: begins the drag on the first event, then /// updates the follower position and landing slot. /// + /// The cursor is derived from the gesture's TRANSLATION, not its location: + /// `DragGesture` converts locations through the host row's current + /// geometry, and the preview moves that row to the landing slot mid-drag, + /// so location jumps by the row's displacement on every preview reflow — + /// a feedback loop (cursor jump → indicator jump → preview move → cursor + /// jump) seen in the dogfood log as ±row-band cursorY oscillation. + /// Translation is a pure pointer delta and is immune to host movement; it + /// is anchored to the begin-time location (geometry-consistent, the + /// preview has not moved yet) plus the accumulated autoscroll delta. + /// /// - Parameters: /// - draggedId: the workspace (or group anchor) being dragged. /// - startLocationY: the gesture's start Y in the reorder list space. - /// - cursorY: the gesture's current Y in the reorder list space. + /// Trustworthy only on the begin event (it re-converts with current + /// geometry on later events). + /// - translationHeight: the gesture's vertical pointer travel. func sidebarReorderGestureChanged( draggedId: UUID, startLocationY: CGFloat, - cursorY: CGFloat, + translationHeight: CGFloat, renderContext: WorkspaceListRenderContext ) { // Escape cancelled this drag mid-gesture. The DragGesture itself stays // alive until the mouse releases and keeps streaming onChanged; without // this latch the next event would re-begin the cancelled drag. guard dragState.cancelledReorderTabId != draggedId else { return } + let cursorY = (dragState.draggedTabId == draggedId) + ? dragState.reorderTranslationBaseY + translationHeight + dragState.autoScrollAccumulatedDelta + : startLocationY + translationHeight if dragState.draggedTabId != draggedId { - #if DEBUG - cmuxDebugLog("sidebar.reorder.begin id=\(draggedId.uuidString.prefix(5)) startY=\(Int(startLocationY)) cursorY=\(Int(cursorY))") - #endif let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( forDraggedWorkspaceId: draggedId, targetWorkspaceId: nil @@ -60,6 +72,14 @@ extension VerticalTabsSidebar { ) let frame = dragState.rowFramesInList[draggedId] let grabOffsetY = frame.map { startLocationY - $0.minY } ?? 0 + #if DEBUG + cmuxDebugLog( + "sidebar.reorder.begin id=\(draggedId.uuidString.prefix(5)) " + + "startY=\(Int(startLocationY)) cursorY=\(Int(cursorY)) " + + "topLevel=\(usesTopLevelRows) scope=\(reorderIds.count) " + + "frames=\(dragState.rowFramesInList.count) ownFrame=\(frame.map { "\(Int($0.minY))..\(Int($0.maxY))" } ?? "nil")" + ) + #endif dragState.beginReorder( tabId: draggedId, usesTopLevelRows: usesTopLevelRows, @@ -68,6 +88,7 @@ extension VerticalTabsSidebar { scopeBandComposition: composition, draggedRowFrame: frame, grabOffsetY: grabOffsetY, + translationBaseY: startLocationY, cursorY: cursorY ) } else { @@ -129,22 +150,22 @@ extension VerticalTabsSidebar { /// `"sidebarReorderList"` space so its location aligns with the measured row /// frames. A non-zero `minimumDistance` lets a plain click still select the row. struct SidebarReorderDragModifier: ViewModifier { - let onChanged: (_ startLocation: CGPoint, _ location: CGPoint) -> Void - let onEnded: (_ startLocation: CGPoint, _ location: CGPoint) -> Void + let onChanged: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void + let onEnded: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void func body(content: Content) -> some View { content.gesture( DragGesture(minimumDistance: 6, coordinateSpace: .named(SidebarReorderListCoordinateSpace.name)) - .onChanged { value in onChanged(value.startLocation, value.location) } - .onEnded { value in onEnded(value.startLocation, value.location) } + .onChanged { value in onChanged(value.startLocation, value.translation.height) } + .onEnded { value in onEnded(value.startLocation, value.translation.height) } ) } } extension View { func sidebarReorderDrag( - onChanged: @escaping (_ startLocation: CGPoint, _ location: CGPoint) -> Void, - onEnded: @escaping (_ startLocation: CGPoint, _ location: CGPoint) -> Void + onChanged: @escaping (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void, + onEnded: @escaping (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void ) -> some View { modifier(SidebarReorderDragModifier(onChanged: onChanged, onEnded: onEnded)) } @@ -157,8 +178,8 @@ extension View { struct SidebarReorderRowModifier: ViewModifier { let enabled: Bool let workspaceId: UUID - let onChanged: (_ startLocation: CGPoint, _ location: CGPoint) -> Void - let onEnded: (_ startLocation: CGPoint, _ location: CGPoint) -> Void + let onChanged: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void + let onEnded: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void @ViewBuilder func body(content: Content) -> some View { diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index bd5eaeb3fb77..72ce6aecbec2 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -53,8 +53,8 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isFirstRow: Bool let topDropIndicatorVisible: Bool /// Reorder gesture callbacks dispatched into the shared reorder helpers. - let onReorderChanged: (CGPoint, CGPoint) -> Void - let onReorderEnded: (CGPoint, CGPoint) -> Void + let onReorderChanged: (CGPoint, CGFloat) -> Void + let onReorderEnded: (CGPoint, CGFloat) -> Void /// False for the floating follower copy. let isReorderEnabled: Bool let onToggleCollapsed: () -> Void diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index d01f8450c452..8834289085c4 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -39,15 +39,15 @@ extension VerticalTabsSidebar { let showsHintForAnchor = modifierKeyMonitor.isModifierPressed // Dragging a group header reorders the whole group at top level; the // shared reorder helpers handle the anchor/top-level scope. - let onReorderChanged: (CGPoint, CGPoint) -> Void = { [anchorId = group.anchorWorkspaceId, renderContext] startLocation, location in + let onReorderChanged: (CGPoint, CGFloat) -> Void = { [anchorId = group.anchorWorkspaceId, renderContext] startLocation, translationHeight in sidebarReorderGestureChanged( draggedId: anchorId, startLocationY: startLocation.y, - cursorY: location.y, + translationHeight: translationHeight, renderContext: renderContext ) } - let onReorderEnded: (CGPoint, CGPoint) -> Void = { [anchorId = group.anchorWorkspaceId] _, _ in + let onReorderEnded: (CGPoint, CGFloat) -> Void = { [anchorId = group.anchorWorkspaceId] _, _ in sidebarReorderGestureEnded(draggedId: anchorId) } // Computed in the parent and applied as opacity below (not passed into From c8502da4c4ccc4019d3f8790ba5a0d11b02976af Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 20:30:02 -0700 Subject: [PATCH 20/36] Sidebar gesture reorder: clamp members to their group, drop-into headers, honest edge preview MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three review findings on the gesture port: - Bugbot: the gesture resolved indicators and commit indices without sidebarReorderLegalInsertionRange, while the commit-side clampedGroupedMemberReorderIndex still clamps grouped members inside their group's run — so a member aimed outside its group previewed one slot and snapped back to another on release. The range is now captured at drag begin and passed to the commit's targetIndex, and the live hit-test cursor is clamped to the group's rendered run so the gap never shows a slot the drop would reject. Matches main's model: members reorder within their group; leaving a group stays a context menu action. - Codex: dropping a workspace onto a group header used to add it to the group (the old drop delegate) and the gesture lost that — the only drag path INTO a collapsed group. Parking over a header's center third now highlights the header and releasing runs addWorkspaceToGroup. Available for non-anchor rows over any group they are not already in. - Codex: the preview unindented a member at its group's first/last slot while the commit kept it grouped (ambiguous-neighbor case). The preview now mirrors the commit rule exactly: ambiguous keeps the committed membership. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 3 +- Sources/ContentView.swift | 72 ++++++++++++++++++- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 51 ++++++++++++- Sources/SidebarWorkspaceGroupHeaderView.swift | 10 +++ Sources/SidebarWorkspaceRenderItem.swift | 11 ++- .../VerticalTabsSidebar+WorkspaceGroups.swift | 1 + 6 files changed, 142 insertions(+), 6 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 0e376f2aaa96..73eb8bd0934f 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19412 Sources/ContentView.swift +19480 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -181,5 +181,6 @@ 506 Sources/App/MainWindowVisibilityController.swift 505 cmuxUITests/DisplayResolutionRegressionUITests.swift 504 cmuxTests/TerminalNotificationSocketActionTests.swift +503 Sources/SidebarWorkspaceGroupHeaderView.swift 502 Sources/CmuxEventPublishing.swift 502 Sources/Settings/ConfigSource.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index b75e3a150df9..71a714f8be24 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10429,6 +10429,29 @@ final class SidebarDragState { /// members when dragging a group anchor at top level). @ObservationIgnored private var scopeBandComposition: [UUID: [UUID]] = [:] + /// The group header (anchor id) the cursor is currently parked over in + /// its center drop-into zone, observed so the header can highlight. + /// Releasing here adds the dragged workspace to that group instead of + /// reordering — the only drag path INTO a collapsed group, whose members + /// have no rows to sandwich between. + var dropIntoGroupAnchorId: UUID? + + /// Insertion clamp for the commit, in full reorder-scope index space + /// (grouped members may only land inside their group's run; pinned + /// members inside the group's pinned sub-tier). Mirrors the clamp + /// `TabManager.reorderWorkspace` applies at commit so the landing slot + /// the preview shows is the slot the drop produces. + @ObservationIgnored private var legalInsertionRange: ClosedRange? + /// When dragging a grouped member, the rendered band ids of its group's + /// member rows. The hit-test cursor is clamped to this run so the live + /// gap also stays inside the group (the visual mirror of + /// `legalInsertionRange`). + @ObservationIgnored private var memberClampBandIds: Set? + /// Anchor ids of groups the dragged workspace could be dropped INTO via + /// a header's center zone (every group except the one it is already in; + /// empty when dragging an anchor). + @ObservationIgnored private var dropIntoGroupCandidateAnchorIds: Set = [] + /// The begin-time gesture location in list space. Later cursor positions /// are derived as base + translation + autoscroll delta, because the /// gesture's location re-converts through the host row's CURRENT geometry @@ -10492,6 +10515,10 @@ final class SidebarDragState { reorderIds = [] pinnedIds = [] scopeBandComposition = [:] + legalInsertionRange = nil + memberClampBandIds = nil + dropIntoGroupCandidateAnchorIds = [] + dropIntoGroupAnchorId = nil clearDropIndicator() } @@ -10504,6 +10531,9 @@ final class SidebarDragState { reorderIds: [UUID], pinnedIds: Set, scopeBandComposition: [UUID: [UUID]], + legalInsertionRange: ClosedRange?, + memberClampBandIds: Set?, + dropIntoGroupCandidateAnchorIds: Set, draggedRowFrame: CGRect?, grabOffsetY: CGFloat, translationBaseY: CGFloat, @@ -10514,6 +10544,9 @@ final class SidebarDragState { self.reorderIds = reorderIds self.pinnedIds = pinnedIds self.scopeBandComposition = scopeBandComposition + self.legalInsertionRange = legalInsertionRange + self.memberClampBandIds = memberClampBandIds + self.dropIntoGroupCandidateAnchorIds = dropIntoGroupCandidateAnchorIds self.draggedRowFrame = draggedRowFrame self.grabOffsetY = grabOffsetY self.reorderTranslationBaseY = translationBaseY @@ -10569,15 +10602,50 @@ final class SidebarDragState { targetTabId: dropIndicator?.tabId, indicator: dropIndicator, tabIds: reorderIds, - pinnedTabIds: pinnedIds + pinnedTabIds: pinnedIds, + legalInsertionRange: legalInsertionRange ) } private func recomputeIndicator(cursorY: CGFloat) { guard let draggedTabId else { return } let bands = buildBands() + + // Center drop-into zone: parking over the middle of another group's + // header adds the dragged row to that group on release. Checked + // against the raw cursor (a grouped member's clamp below would never + // reach a header outside its group anyway). + let hoveredBand = bands.first(where: { cursorY >= $0.minY && cursorY < $0.maxY }) + let intoGroupAnchorId: UUID? = hoveredBand.flatMap { band in + guard dropIntoGroupCandidateAnchorIds.contains(band.id) else { return nil } + let inset = band.height / 3 + let isCenter = cursorY >= band.minY + inset && cursorY <= band.maxY - inset + return isCenter ? band.id : nil + } + if intoGroupAnchorId != dropIntoGroupAnchorId { + dropIntoGroupAnchorId = intoGroupAnchorId + } + if intoGroupAnchorId != nil { + if dropIndicator != nil { + dropIndicator = nil + } + return + } + + // A grouped member's hit-test cursor is clamped to its group's + // rendered run, mirroring the commit-side clamp so the live gap never + // shows a landing slot the drop would reject. + var effectiveCursorY = cursorY + if let memberClampBandIds { + let runBands = bands.filter { memberClampBandIds.contains($0.id) } + if let runMinY = runBands.map(\.minY).min(), + let runMaxY = runBands.map(\.maxY).max() { + effectiveCursorY = min(max(cursorY, runMinY + 1), runMaxY - 1) + } + } + let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: cursorY, + cursorY: effectiveCursorY, bands: bands, draggedId: draggedTabId, pinnedIds: pinnedIds, diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index b9d886febe4c..d44bfc8bd614 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -70,6 +70,32 @@ extension VerticalTabsSidebar { usesTopLevelRows: usesTopLevelRows, renderContext: renderContext ) + // Commit-side clamp (grouped members stay inside their group's + // run) plus its visual mirror for the live gap, and the headers a + // non-anchor row could be dropped INTO via their center zone. + let legalInsertionRange = tabManager.sidebarReorderLegalInsertionRange( + forDraggedWorkspaceId: draggedId, + usesTopLevelRows: usesTopLevelRows + ) + let draggedWorkspace = renderContext.workspaceById[draggedId] + let draggedGroupId = draggedWorkspace?.groupId + let memberClampBandIds: Set? = legalInsertionRange.flatMap { _ in + guard let draggedGroupId else { return nil } + return Set( + renderContext.tabs + .filter { $0.groupId == draggedGroupId } + .map(\.id) + ) + } + let draggedIsAnchor = renderContext.workspaceGroups + .contains { $0.anchorWorkspaceId == draggedId } + let dropIntoCandidates: Set = draggedIsAnchor + ? [] + : Set( + renderContext.workspaceGroups + .filter { $0.id != draggedGroupId } + .map(\.anchorWorkspaceId) + ) let frame = dragState.rowFramesInList[draggedId] let grabOffsetY = frame.map { startLocationY - $0.minY } ?? 0 #if DEBUG @@ -86,6 +112,9 @@ extension VerticalTabsSidebar { reorderIds: reorderIds, pinnedIds: pinnedIds, scopeBandComposition: composition, + legalInsertionRange: legalInsertionRange, + memberClampBandIds: memberClampBandIds, + dropIntoGroupCandidateAnchorIds: dropIntoCandidates, draggedRowFrame: frame, grabOffsetY: grabOffsetY, translationBaseY: startLocationY, @@ -105,8 +134,26 @@ extension VerticalTabsSidebar { dragState.clearDrag() dragAutoScrollController.stop() } - guard dragState.draggedTabId == draggedId, - let targetIndex = dragState.gestureReorderTargetIndex() else { + guard dragState.draggedTabId == draggedId else { + #if DEBUG + cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=nil (noop)") + #endif + return + } + // Released over a group header's center zone: join that group. The + // only drag path INTO a collapsed group, whose members have no rows + // to land between. + if let anchorId = dragState.dropIntoGroupAnchorId, + let group = tabManager.workspaceGroups.first(where: { $0.anchorWorkspaceId == anchorId }) { + #if DEBUG + cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) intoGroup=\(group.id.uuidString.prefix(5))") + #endif + withAnimation(SidebarGroupAnimation.structure) { + tabManager.addWorkspaceToGroup(workspaceId: draggedId, groupId: group.id) + } + return + } + guard let targetIndex = dragState.gestureReorderTargetIndex() else { #if DEBUG cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=nil (noop)") #endif diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 72ce6aecbec2..99d038c8bf86 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -15,6 +15,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.isCollapsed == rhs.isCollapsed && lhs.isPinned == rhs.isPinned && lhs.isAnchorActive == rhs.isAnchorActive && + lhs.isReorderDropTarget == rhs.isReorderDropTarget && lhs.memberCount == rhs.memberCount && lhs.groupUnreadCount == rhs.groupUnreadCount && lhs.shortcutDigit == rhs.shortcutDigit && @@ -39,6 +40,9 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isCollapsed: Bool let isPinned: Bool let isAnchorActive: Bool + /// True while a gesture-reorder drag is parked over this header's center + /// drop-into zone (releasing adds the dragged workspace to the group). + let isReorderDropTarget: Bool let memberCount: Int let groupUnreadCount: Int let shortcutDigit: Int? @@ -237,6 +241,12 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) + .overlay { + if isReorderDropTarget { + RoundedRectangle(cornerRadius: 6) + .strokeBorder(Color.accentColor, lineWidth: 1.5) + } + } .modifier(SidebarReorderRowModifier( enabled: isReorderEnabled, workspaceId: anchorWorkspaceId, diff --git a/Sources/SidebarWorkspaceRenderItem.swift b/Sources/SidebarWorkspaceRenderItem.swift index fec19e5e9709..0f0590711e49 100644 --- a/Sources/SidebarWorkspaceRenderItem.swift +++ b/Sources/SidebarWorkspaceRenderItem.swift @@ -184,7 +184,16 @@ enum SidebarWorkspaceRenderItem { let afterGroup = draggedIndex < renderItems.index(before: renderItems.endIndex) ? groupIdentity(renderItems[draggedIndex + 1]) : nil - let membership: UUID? = (beforeGroup == afterGroup) ? beforeGroup : nil + // Mirror the commit rule exactly: matching neighbors decide the + // membership; the AMBIGUOUS case (one neighbor in, one out — the + // first/last in-group slot) keeps the COMMITTED membership, the same + // bias `applyDragInferredGroupMembership` applies. Forcing nil here + // made the preview unindent at group-edge slots and snap back on drop. + let committedGroupId: UUID? = { + if case .workspace(let workspace, _) = renderItems[draggedIndex] { return workspace.groupId } + return nil + }() + let membership: UUID? = (beforeGroup == afterGroup) ? beforeGroup : committedGroupId guard renderItems[draggedIndex].effectiveGroupId != membership else { return renderItems } var result = renderItems result[draggedIndex] = result[draggedIndex].withEffectiveGroupId(membership) diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 8834289085c4..cd2f38ae9d04 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -64,6 +64,7 @@ extension VerticalTabsSidebar { isCollapsed: group.isCollapsed, isPinned: group.isPinned, isAnchorActive: isAnchorActive, + isReorderDropTarget: role == .list && dragState.dropIntoGroupAnchorId == group.anchorWorkspaceId, memberCount: memberWorkspaceIds.count, groupUnreadCount: groupUnreadCount, shortcutDigit: shortcutDigit, From 58e9614ae213f15c2296a94054a274afac284348 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 20:37:45 -0700 Subject: [PATCH 21/36] Sidebar gesture reorder: animate the follower's indent across group boundaries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: dragging into/out of a group should read as a horizontal slide. The follower previously kept its committed indent for the whole drag and snapped on release. The parent now derives the previewed membership from the preview items (member indent when the landing slot sits inside a group the row is not yet in, also while parked over a header's drop-into zone) and the follower animates just that leading indent on its own 0.15s axis — the row slides right and narrows crossing into a group and back out, while Y tracking stays animation-free. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 22 +++++++++++++++++++ .../Sidebar/SidebarReorderFollowerView.swift | 19 +++++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 73eb8bd0934f..b3dee64fa494 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19480 Sources/ContentView.swift +19502 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 71a714f8be24..b72ed3f9d4e5 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12745,6 +12745,10 @@ struct VerticalTabsSidebar: View { SidebarReorderFollowerView( dragState: dragState, sourceItems: baseRenderItems, + previewExtraIndent: followerPreviewExtraIndent( + baseRenderItems: baseRenderItems, + previewItems: previewItems + ), rowContent: { item in switch item { case .groupHeader(let group, let memberWorkspaceIds): @@ -12800,6 +12804,24 @@ struct VerticalTabsSidebar: View { } } + /// Extra leading indent the follower previews for the dragged row: the + /// member indent when the current landing slot is inside a group the row + /// is not yet a member of, 0 otherwise. Members are clamped to their own + /// group, so only ungrouped rows ever gain preview indent. + private func followerPreviewExtraIndent( + baseRenderItems: [SidebarWorkspaceRenderItem], + previewItems: [SidebarWorkspaceRenderItem] + ) -> CGFloat { + guard let draggedId = dragState.draggedTabId, + let committed = baseRenderItems.first(where: { $0.representedWorkspaceId == draggedId }), + committed.effectiveGroupId == nil, + let previewed = previewItems.first(where: { $0.representedWorkspaceId == draggedId }), + previewed.effectiveGroupId != nil else { + return 0 + } + return SidebarWorkspaceGroupingMetrics.memberIndent + } + private func bonsplitWorkspaceDropOverlay() -> some View { SidebarBonsplitTabWorkspaceDropOverlay( currentSelectedTabId: { diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift index 8bf667e54eb5..390f83bab98e 100644 --- a/Sources/Sidebar/SidebarReorderFollowerView.swift +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -9,11 +9,17 @@ import SwiftUI /// this one view and never invalidate the list body — the property that keeps /// the drag off the https://github.com/manaflow-ai/cmux/issues/2586 thrash path. /// Implicit animations are disabled so the follower snaps to the cursor with -/// zero lag while the list rows animate the gap open underneath it. +/// zero lag while the list rows animate the gap open underneath it — except the +/// group-membership indent, which animates on its own axis (see below). struct SidebarReorderFollowerView: View { let dragState: SidebarDragState /// The committed render list, used to find the picked-up row's content. let sourceItems: [SidebarWorkspaceRenderItem] + /// Extra leading indent previewed for the dragged row at its current + /// landing slot (member indent when the slot is inside a group the row is + /// not yet a member of, 0 otherwise). Derived by the parent from the + /// preview items, so it only changes when the landing slot does. + let previewExtraIndent: CGFloat let rowContent: (SidebarWorkspaceRenderItem) -> AnyView var body: some View { @@ -24,7 +30,18 @@ struct SidebarReorderFollowerView: View { frame.height > 0, let item = sourceItems.first(where: { $0.representedWorkspaceId == draggedId }) { let topY = cursorY - dragState.grabOffsetY + // Parking over a header's drop-into zone also previews membership. + let extraIndent = dragState.dropIntoGroupAnchorId != nil + ? SidebarWorkspaceGroupingMetrics.memberIndent + : previewExtraIndent + // The indent is applied INSIDE the fixed-size, position-tracked + // container, on its own animation keyed to the indent value: the + // row slides right and narrows when the landing slot crosses into + // a group (and back out), while Y stays glued to the cursor with + // animations disabled. rowContent(item) + .padding(.leading, extraIndent) + .animation(.snappy(duration: 0.15, extraBounce: 0), value: extraIndent) .frame(width: frame.width, height: frame.height, alignment: .topLeading) .position(x: frame.midX, y: topY + frame.height / 2) .shadow(color: Color.black.opacity(0.18), radius: 11, x: 0, y: 5) From 9bb032504e2382ef21b0bf73dbd5d57cf1e86bb9 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 20:54:36 -0700 Subject: [PATCH 22/36] Sidebar gesture reorder: one-step drag into and out of groups, X axis decides membership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: moving a workspace into a group and positioning it (or pulling a member out) should be ONE continuous drag, not reorder-then-add. The previous round's member clamp made drag-out impossible and joining required interior slots only. Membership is now resolved live during the drag, outliner-style: - Interior slots of a group force membership — drop between two members and the row slots straight in. - Boundary slots (first/last slot of a run, the slot under a memberless or collapsed header) follow the pointer's X axis with hysteresis around the half-indent threshold: drag right to tuck the row in, left to keep it (or pull it) out, in the same motion as the vertical reorder. The follower and preview indent animate to match, so the X feedback is visible before release. - The commit writes membership EXPLICITLY (new TabManager.applyGestureDragReorder) instead of re-inferring from neighbors — boundary cases ("last slot inside" vs "first slot after") share an array position, so inference cannot express them. Writing membership before the move lets members leave their group while the member-run clamp still snaps joins into the target group's run, and a membership flip at an unchanged index renormalizes group contiguity. The previous round's legalInsertionRange/member cursor clamp is removed (superseded), and the preview's neighbor inference is replaced by the resolved membership so preview, follower, and commit always agree. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +- Sources/ContentView.swift | 194 +++++++++++++----- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 83 +++++--- Sources/SidebarWorkspaceGroupHeaderView.swift | 4 +- Sources/SidebarWorkspaceRenderItem.swift | 47 ++--- Sources/TabManager.swift | 42 ++++ .../VerticalTabsSidebar+WorkspaceGroups.swift | 6 +- 7 files changed, 249 insertions(+), 131 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index b3dee64fa494..034e9bab6d16 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,12 +4,12 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19502 Sources/ContentView.swift +19586 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift 11756 cmuxTests/AppDelegateShortcutRoutingTests.swift -10046 Sources/TabManager.swift +10088 Sources/TabManager.swift 8494 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift 7737 Sources/Panels/BrowserPanelView.swift 7214 cmuxTests/WorkspaceUnitTests.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index b72ed3f9d4e5..4ba060a2327c 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10436,21 +10436,31 @@ final class SidebarDragState { /// have no rows to sandwich between. var dropIntoGroupAnchorId: UUID? - /// Insertion clamp for the commit, in full reorder-scope index space - /// (grouped members may only land inside their group's run; pinned - /// members inside the group's pinned sub-tier). Mirrors the clamp - /// `TabManager.reorderWorkspace` applies at commit so the landing slot - /// the preview shows is the slot the drop produces. - @ObservationIgnored private var legalInsertionRange: ClosedRange? - /// When dragging a grouped member, the rendered band ids of its group's - /// member rows. The hit-test cursor is clamped to this run so the live - /// gap also stays inside the group (the visual mirror of - /// `legalInsertionRange`). - @ObservationIgnored private var memberClampBandIds: Set? + /// The group membership the dragged row will COMMIT with at the current + /// landing slot, resolved live during the drag: interior slots of a group + /// force membership; boundary slots (first/last slot of a run, the slot + /// under a memberless header) are decided by the pointer's X axis with + /// hysteresis, the outliner interaction. Drives the preview indent, the + /// follower indent, and the explicit-membership commit, so all three + /// always agree. Observed; changes only when the slot or the X side flips. + var previewMembershipGroupId: UUID? + /// Anchor ids of groups the dragged workspace could be dropped INTO via /// a header's center zone (every group except the one it is already in; /// empty when dragging an anchor). @ObservationIgnored private var dropIntoGroupCandidateAnchorIds: Set = [] + /// Per-band group identity (a member row's group, a header's group, nil + /// for ungrouped rows), used to resolve the landing slot's membership. + @ObservationIgnored private var bandGroupIdById: [UUID: UUID?] = [:] + /// Band ids that are group headers (insertion ABOVE a header is outside + /// its group, so headers never donate a boundary candidate to the slot + /// above them). + @ObservationIgnored private var headerBandIds: Set = [] + /// Dragged row's committed membership and leading indent at drag begin. + @ObservationIgnored private var draggedCommittedGroupId: UUID? + @ObservationIgnored private var draggedCommittedIndent: CGFloat = 0 + /// True while dragging an anchor (membership never changes for anchors). + @ObservationIgnored private var draggedIsAnchor = false /// The begin-time gesture location in list space. Later cursor positions /// are derived as base + translation + autoscroll delta, because the @@ -10515,10 +10525,15 @@ final class SidebarDragState { reorderIds = [] pinnedIds = [] scopeBandComposition = [:] - legalInsertionRange = nil - memberClampBandIds = nil dropIntoGroupCandidateAnchorIds = [] dropIntoGroupAnchorId = nil + bandGroupIdById = [:] + headerBandIds = [] + draggedCommittedGroupId = nil + draggedCommittedIndent = 0 + draggedIsAnchor = false + previewMembershipGroupId = nil + lastTranslationWidth = 0 clearDropIndicator() } @@ -10531,9 +10546,11 @@ final class SidebarDragState { reorderIds: [UUID], pinnedIds: Set, scopeBandComposition: [UUID: [UUID]], - legalInsertionRange: ClosedRange?, - memberClampBandIds: Set?, dropIntoGroupCandidateAnchorIds: Set, + bandGroupIdById: [UUID: UUID?], + headerBandIds: Set, + draggedCommittedGroupId: UUID?, + draggedIsAnchor: Bool, draggedRowFrame: CGRect?, grabOffsetY: CGFloat, translationBaseY: CGFloat, @@ -10544,19 +10561,30 @@ final class SidebarDragState { self.reorderIds = reorderIds self.pinnedIds = pinnedIds self.scopeBandComposition = scopeBandComposition - self.legalInsertionRange = legalInsertionRange - self.memberClampBandIds = memberClampBandIds self.dropIntoGroupCandidateAnchorIds = dropIntoGroupCandidateAnchorIds + self.bandGroupIdById = bandGroupIdById + self.headerBandIds = headerBandIds + self.draggedCommittedGroupId = draggedCommittedGroupId + self.draggedCommittedIndent = draggedCommittedGroupId != nil + ? SidebarWorkspaceGroupingMetrics.memberIndent + : 0 + self.draggedIsAnchor = draggedIsAnchor + self.previewMembershipGroupId = draggedCommittedGroupId self.draggedRowFrame = draggedRowFrame self.grabOffsetY = grabOffsetY self.reorderTranslationBaseY = translationBaseY self.autoScrollAccumulatedDelta = 0 self.followerCursorY = cursorY - recomputeIndicator(cursorY: cursorY) + recomputeIndicator(cursorY: cursorY, translationWidth: 0) } + /// Last translation width seen, reused by the autoscroll tick (which + /// moves content, not the pointer). + @ObservationIgnored private var lastTranslationWidth: CGFloat = 0 + /// Updates the follower position and landing slot for a moved cursor. - func updateReorder(cursorY: CGFloat) { + func updateReorder(cursorY: CGFloat, translationWidth: CGFloat) { + lastTranslationWidth = translationWidth #if DEBUG reorderTickCount += 1 if reorderTickCount % 60 == 0 { @@ -10570,7 +10598,7 @@ final class SidebarDragState { } #endif followerCursorY = cursorY - recomputeIndicator(cursorY: cursorY) + recomputeIndicator(cursorY: cursorY, translationWidth: translationWidth) } #if DEBUG @@ -10589,7 +10617,7 @@ final class SidebarDragState { func applyAutoScrollDelta(_ delta: CGFloat) { guard draggedTabId != nil, delta != 0, let cursorY = followerCursorY else { return } autoScrollAccumulatedDelta += delta - updateReorder(cursorY: cursorY + delta) + updateReorder(cursorY: cursorY + delta, translationWidth: lastTranslationWidth) } /// The committed index the dragged workspace should move to on drop, or nil @@ -10602,19 +10630,16 @@ final class SidebarDragState { targetTabId: dropIndicator?.tabId, indicator: dropIndicator, tabIds: reorderIds, - pinnedTabIds: pinnedIds, - legalInsertionRange: legalInsertionRange + pinnedTabIds: pinnedIds ) } - private func recomputeIndicator(cursorY: CGFloat) { + private func recomputeIndicator(cursorY: CGFloat, translationWidth: CGFloat) { guard let draggedTabId else { return } let bands = buildBands() // Center drop-into zone: parking over the middle of another group's - // header adds the dragged row to that group on release. Checked - // against the raw cursor (a grouped member's clamp below would never - // reach a header outside its group anyway). + // header adds the dragged row to that group (appended) on release. let hoveredBand = bands.first(where: { cursorY >= $0.minY && cursorY < $0.maxY }) let intoGroupAnchorId: UUID? = hoveredBand.flatMap { band in guard dropIntoGroupCandidateAnchorIds.contains(band.id) else { return nil } @@ -10632,20 +10657,8 @@ final class SidebarDragState { return } - // A grouped member's hit-test cursor is clamped to its group's - // rendered run, mirroring the commit-side clamp so the live gap never - // shows a landing slot the drop would reject. - var effectiveCursorY = cursorY - if let memberClampBandIds { - let runBands = bands.filter { memberClampBandIds.contains($0.id) } - if let runMinY = runBands.map(\.minY).min(), - let runMaxY = runBands.map(\.maxY).max() { - effectiveCursorY = min(max(cursorY, runMinY + 1), runMaxY - 1) - } - } - let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: effectiveCursorY, + cursorY: cursorY, bands: bands, draggedId: draggedTabId, pinnedIds: pinnedIds, @@ -10655,6 +10668,73 @@ final class SidebarDragState { if indicator != dropIndicator { dropIndicator = indicator } + resolveMembership(bands: bands, translationWidth: translationWidth) + } + + /// Resolves the membership the dragged row will commit with at the + /// current landing slot. Interior slots of a group force membership; + /// boundary slots (first/last slot of a run, the slot under a memberless + /// header) follow the pointer's X axis with hysteresis — drag right to + /// tuck the row into the group, left to keep it (or pull it) out, in the + /// same motion as the vertical reorder. + private func resolveMembership( + bands: [SidebarReorderIndicatorResolver.Band], + translationWidth: CGFloat + ) { + guard let draggedTabId, !draggedIsAnchor, !dropIndicatorUsesTopLevelRows else { return } + // Indicator nil means "already at the committed slot": membership + // follows the committed neighbors, i.e. the committed membership. + guard let dropIndicator else { + setPreviewMembership(draggedCommittedGroupId) + return + } + + // The slot's visual neighbors, skipping the dragged row's own + // (frozen) band: insertion is canonicalized to "above row X" or the + // end sentinel. + let neighborBands = bands.filter { $0.id != draggedTabId } + var prevBand: SidebarReorderIndicatorResolver.Band? + var nextBand: SidebarReorderIndicatorResolver.Band? + if let targetId = dropIndicator.tabId, + let targetIndex = neighborBands.firstIndex(where: { $0.id == targetId }) { + nextBand = neighborBands[targetIndex] + prevBand = targetIndex > 0 ? neighborBands[targetIndex - 1] : nil + } else { + prevBand = neighborBands.last + nextBand = nil + } + + // A header donates its group to the slot BELOW it (prev side) but + // never to the slot above it (next side). + let prevGroup: UUID? = prevBand.flatMap { bandGroupIdById[$0.id] ?? nil } + let nextGroup: UUID? = nextBand.flatMap { band in + headerBandIds.contains(band.id) ? nil : (bandGroupIdById[band.id] ?? nil) + } + + if let prevGroup, prevGroup == nextGroup { + // Interior slot: sandwiched inside a group, membership is forced. + setPreviewMembership(prevGroup) + return + } + guard let candidate = prevGroup ?? nextGroup else { + setPreviewMembership(nil) + return + } + // Boundary slot: the X axis decides, with hysteresis around the + // half-indent threshold so jitter does not flicker the indent. + let effectiveLeadingX = draggedCommittedIndent + translationWidth + let half = SidebarWorkspaceGroupingMetrics.memberIndent / 2 + let currentlyIn = previewMembershipGroupId == candidate + let isIn = currentlyIn + ? effectiveLeadingX > half - 3 + : effectiveLeadingX >= half + 3 + setPreviewMembership(isIn ? candidate : nil) + } + + private func setPreviewMembership(_ groupId: UUID?) { + if previewMembershipGroupId != groupId { + previewMembershipGroupId = groupId + } } private func buildBands() -> [SidebarReorderIndicatorResolver.Band] { @@ -12680,7 +12760,8 @@ struct VerticalTabsSidebar: View { baseRenderItems, draggedWorkspaceId: dragState.draggedTabId, dropIndicator: dragState.dropIndicator, - reorderWorkspaceIds: renderContext.sidebarReorderIds + reorderWorkspaceIds: renderContext.sidebarReorderIds, + draggedMembershipGroupId: dragState.previewMembershipGroupId ) // No `.id(groupAnchorSignature)` rebuild hack here: a group header now // shares ForEach identity with its anchor workspace's row (see @@ -12804,22 +12885,25 @@ struct VerticalTabsSidebar: View { } } - /// Extra leading indent the follower previews for the dragged row: the - /// member indent when the current landing slot is inside a group the row - /// is not yet a member of, 0 otherwise. Members are clamped to their own - /// group, so only ungrouped rows ever gain preview indent. + /// Extra leading indent the follower previews for the dragged row, + /// relative to its committed indent: positive when the resolved landing + /// membership tucks an ungrouped row into a group, negative when a member + /// is being pulled out, 0 when membership is unchanged. private func followerPreviewExtraIndent( baseRenderItems: [SidebarWorkspaceRenderItem], previewItems: [SidebarWorkspaceRenderItem] ) -> CGFloat { guard let draggedId = dragState.draggedTabId, - let committed = baseRenderItems.first(where: { $0.representedWorkspaceId == draggedId }), - committed.effectiveGroupId == nil, - let previewed = previewItems.first(where: { $0.representedWorkspaceId == draggedId }), - previewed.effectiveGroupId != nil else { + let committed = baseRenderItems.first(where: { $0.representedWorkspaceId == draggedId }) else { return 0 } - return SidebarWorkspaceGroupingMetrics.memberIndent + let committedIndent: CGFloat = committed.effectiveGroupId != nil + ? SidebarWorkspaceGroupingMetrics.memberIndent + : 0 + let previewIndent: CGFloat = dragState.previewMembershipGroupId != nil + ? SidebarWorkspaceGroupingMetrics.memberIndent + : 0 + return previewIndent - committedIndent } private func bonsplitWorkspaceDropOverlay() -> some View { @@ -12945,15 +13029,15 @@ struct VerticalTabsSidebar: View { // into `TabItemView` so it lives below `.equatable()` and survives the // parent body re-evaluations that the discrete drop-indicator changes // trigger, instead of being torn down mid-drag. - let onReorderChanged: (CGPoint, CGFloat) -> Void = { [tabId = tab.id, renderContext] startLocation, translationHeight in + let onReorderChanged: (CGPoint, CGSize) -> Void = { [tabId = tab.id, renderContext] startLocation, translation in sidebarReorderGestureChanged( draggedId: tabId, startLocationY: startLocation.y, - translationHeight: translationHeight, + translation: translation, renderContext: renderContext ) } - let onReorderEnded: (CGPoint, CGFloat) -> Void = { [tabId = tab.id] _, _ in + let onReorderEnded: (CGPoint, CGSize) -> Void = { [tabId = tab.id] _, _ in sidebarReorderGestureEnded(draggedId: tabId) } @@ -15551,8 +15635,8 @@ struct TabItemView: View, Equatable { /// Reorder gesture callbacks (start location, current location), dispatched /// into the shared `VerticalTabsSidebar` reorder helpers via closures so the /// row never holds an `@Observable` store reference (snapshot-boundary rule). - let onReorderChanged: (CGPoint, CGFloat) -> Void - let onReorderEnded: (CGPoint, CGFloat) -> Void + let onReorderChanged: (CGPoint, CGSize) -> Void + let onReorderEnded: (CGPoint, CGSize) -> Void /// False for the floating follower copy, which is non-interactive and must /// not report a row frame. let isReorderEnabled: Bool diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index d44bfc8bd614..9a48745d0ac0 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -39,11 +39,12 @@ extension VerticalTabsSidebar { /// - startLocationY: the gesture's start Y in the reorder list space. /// Trustworthy only on the begin event (it re-converts with current /// geometry on later events). - /// - translationHeight: the gesture's vertical pointer travel. + /// - translation: the gesture's pointer travel. Height drives the slot, + /// width drives boundary-slot group membership (the outliner X axis). func sidebarReorderGestureChanged( draggedId: UUID, startLocationY: CGFloat, - translationHeight: CGFloat, + translation: CGSize, renderContext: WorkspaceListRenderContext ) { // Escape cancelled this drag mid-gesture. The DragGesture itself stays @@ -51,8 +52,8 @@ extension VerticalTabsSidebar { // this latch the next event would re-begin the cancelled drag. guard dragState.cancelledReorderTabId != draggedId else { return } let cursorY = (dragState.draggedTabId == draggedId) - ? dragState.reorderTranslationBaseY + translationHeight + dragState.autoScrollAccumulatedDelta - : startLocationY + translationHeight + ? dragState.reorderTranslationBaseY + translation.height + dragState.autoScrollAccumulatedDelta + : startLocationY + translation.height if dragState.draggedTabId != draggedId { let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( forDraggedWorkspaceId: draggedId, @@ -70,23 +71,11 @@ extension VerticalTabsSidebar { usesTopLevelRows: usesTopLevelRows, renderContext: renderContext ) - // Commit-side clamp (grouped members stay inside their group's - // run) plus its visual mirror for the live gap, and the headers a - // non-anchor row could be dropped INTO via their center zone. - let legalInsertionRange = tabManager.sidebarReorderLegalInsertionRange( - forDraggedWorkspaceId: draggedId, - usesTopLevelRows: usesTopLevelRows - ) + // Membership-resolution inputs: each band's group identity, which + // bands are headers, and the headers a non-anchor row could be + // dropped INTO via their center zone. let draggedWorkspace = renderContext.workspaceById[draggedId] let draggedGroupId = draggedWorkspace?.groupId - let memberClampBandIds: Set? = legalInsertionRange.flatMap { _ in - guard let draggedGroupId else { return nil } - return Set( - renderContext.tabs - .filter { $0.groupId == draggedGroupId } - .map(\.id) - ) - } let draggedIsAnchor = renderContext.workspaceGroups .contains { $0.anchorWorkspaceId == draggedId } let dropIntoCandidates: Set = draggedIsAnchor @@ -96,6 +85,10 @@ extension VerticalTabsSidebar { .filter { $0.id != draggedGroupId } .map(\.anchorWorkspaceId) ) + let bandGroupIdById: [UUID: UUID?] = Dictionary( + uniqueKeysWithValues: renderContext.tabs.map { ($0.id, $0.groupId) } + ) + let headerBandIds = Set(renderContext.workspaceGroups.map(\.anchorWorkspaceId)) let frame = dragState.rowFramesInList[draggedId] let grabOffsetY = frame.map { startLocationY - $0.minY } ?? 0 #if DEBUG @@ -112,16 +105,18 @@ extension VerticalTabsSidebar { reorderIds: reorderIds, pinnedIds: pinnedIds, scopeBandComposition: composition, - legalInsertionRange: legalInsertionRange, - memberClampBandIds: memberClampBandIds, dropIntoGroupCandidateAnchorIds: dropIntoCandidates, + bandGroupIdById: bandGroupIdById, + headerBandIds: headerBandIds, + draggedCommittedGroupId: draggedGroupId, + draggedIsAnchor: draggedIsAnchor, draggedRowFrame: frame, grabOffsetY: grabOffsetY, translationBaseY: startLocationY, cursorY: cursorY ) } else { - dragState.updateReorder(cursorY: cursorY) + dragState.updateReorder(cursorY: cursorY, translationWidth: translation.width) } dragAutoScrollController.updateFromDragLocation() } @@ -160,15 +155,35 @@ extension VerticalTabsSidebar { return } let usesTopLevelRows = dragState.dropIndicatorUsesTopLevelRows + if usesTopLevelRows { + #if DEBUG + cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=\(targetIndex) topLevel=true") + #endif + withAnimation(Self.sidebarReorderAnimation) { + _ = tabManager.reorderSidebarWorkspace( + tabId: draggedId, + toIndex: targetIndex, + isDragOperation: true, + usesTopLevelRows: true + ) + } + return + } + // Membership was resolved live (interior slots force it, boundary + // slots followed the pointer's X) and is committed explicitly so the + // drop lands exactly what the preview showed. + let membership = dragState.previewMembershipGroupId #if DEBUG - cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=\(targetIndex) topLevel=\(usesTopLevelRows)") + cmuxDebugLog( + "sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=\(targetIndex) " + + "membership=\(membership?.uuidString.prefix(5) ?? "nil")" + ) #endif withAnimation(Self.sidebarReorderAnimation) { - _ = tabManager.reorderSidebarWorkspace( + _ = tabManager.applyGestureDragReorder( tabId: draggedId, toIndex: targetIndex, - isDragOperation: true, - usesTopLevelRows: usesTopLevelRows + desiredGroupId: membership ) } } @@ -197,22 +212,22 @@ extension VerticalTabsSidebar { /// `"sidebarReorderList"` space so its location aligns with the measured row /// frames. A non-zero `minimumDistance` lets a plain click still select the row. struct SidebarReorderDragModifier: ViewModifier { - let onChanged: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void - let onEnded: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void + let onChanged: (_ startLocation: CGPoint, _ translation: CGSize) -> Void + let onEnded: (_ startLocation: CGPoint, _ translation: CGSize) -> Void func body(content: Content) -> some View { content.gesture( DragGesture(minimumDistance: 6, coordinateSpace: .named(SidebarReorderListCoordinateSpace.name)) - .onChanged { value in onChanged(value.startLocation, value.translation.height) } - .onEnded { value in onEnded(value.startLocation, value.translation.height) } + .onChanged { value in onChanged(value.startLocation, value.translation) } + .onEnded { value in onEnded(value.startLocation, value.translation) } ) } } extension View { func sidebarReorderDrag( - onChanged: @escaping (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void, - onEnded: @escaping (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void + onChanged: @escaping (_ startLocation: CGPoint, _ translation: CGSize) -> Void, + onEnded: @escaping (_ startLocation: CGPoint, _ translation: CGSize) -> Void ) -> some View { modifier(SidebarReorderDragModifier(onChanged: onChanged, onEnded: onEnded)) } @@ -225,8 +240,8 @@ extension View { struct SidebarReorderRowModifier: ViewModifier { let enabled: Bool let workspaceId: UUID - let onChanged: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void - let onEnded: (_ startLocation: CGPoint, _ translationHeight: CGFloat) -> Void + let onChanged: (_ startLocation: CGPoint, _ translation: CGSize) -> Void + let onEnded: (_ startLocation: CGPoint, _ translation: CGSize) -> Void @ViewBuilder func body(content: Content) -> some View { diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 99d038c8bf86..253faa0e6de6 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -57,8 +57,8 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isFirstRow: Bool let topDropIndicatorVisible: Bool /// Reorder gesture callbacks dispatched into the shared reorder helpers. - let onReorderChanged: (CGPoint, CGFloat) -> Void - let onReorderEnded: (CGPoint, CGFloat) -> Void + let onReorderChanged: (CGPoint, CGSize) -> Void + let onReorderEnded: (CGPoint, CGSize) -> Void /// False for the floating follower copy. let isReorderEnabled: Bool let onToggleCollapsed: () -> Void diff --git a/Sources/SidebarWorkspaceRenderItem.swift b/Sources/SidebarWorkspaceRenderItem.swift index 0f0590711e49..63656c4c15f9 100644 --- a/Sources/SidebarWorkspaceRenderItem.swift +++ b/Sources/SidebarWorkspaceRenderItem.swift @@ -122,7 +122,8 @@ enum SidebarWorkspaceRenderItem { _ items: [SidebarWorkspaceRenderItem], draggedWorkspaceId: UUID?, dropIndicator: SidebarDropIndicator?, - reorderWorkspaceIds: [UUID] + reorderWorkspaceIds: [UUID], + draggedMembershipGroupId: UUID? = nil ) -> [SidebarWorkspaceRenderItem] { guard let draggedWorkspaceId, let dropIndicator, @@ -160,17 +161,20 @@ enum SidebarWorkspaceRenderItem { blocksById[block.workspaceId] = block.items } let reordered = nextReorderIds.flatMap { blocksById[$0] ?? [] } - return applyingDraggedMembership(reordered, draggedWorkspaceId: draggedWorkspaceId) + return applyingDraggedMembership( + reordered, + draggedWorkspaceId: draggedWorkspaceId, + membership: draggedMembershipGroupId + ) } - /// Recomputes the dragged workspace's effective group membership from its - /// new neighbors in the preview list, matching the vertical-position rule - /// used at commit (`TabManager.applyDragInferredGroupMembership`): a member - /// only when sandwiched between two rows of the SAME group. Keeps the live - /// indent preview in sync with where the drop will actually land. + /// Applies the membership the drag RESOLVED for the dragged row (interior + /// slots force it, boundary slots follow the pointer's X axis) so the + /// preview indent always matches what the drop will commit. private static func applyingDraggedMembership( _ renderItems: [SidebarWorkspaceRenderItem], - draggedWorkspaceId: UUID + draggedWorkspaceId: UUID, + membership: UUID? ) -> [SidebarWorkspaceRenderItem] { guard let draggedIndex = renderItems.firstIndex(where: { item in if case .workspace(let workspace, _) = item { return workspace.id == draggedWorkspaceId } @@ -178,39 +182,12 @@ enum SidebarWorkspaceRenderItem { }) else { return renderItems } - let beforeGroup = draggedIndex > renderItems.startIndex - ? groupIdentity(renderItems[draggedIndex - 1]) - : nil - let afterGroup = draggedIndex < renderItems.index(before: renderItems.endIndex) - ? groupIdentity(renderItems[draggedIndex + 1]) - : nil - // Mirror the commit rule exactly: matching neighbors decide the - // membership; the AMBIGUOUS case (one neighbor in, one out — the - // first/last in-group slot) keeps the COMMITTED membership, the same - // bias `applyDragInferredGroupMembership` applies. Forcing nil here - // made the preview unindent at group-edge slots and snap back on drop. - let committedGroupId: UUID? = { - if case .workspace(let workspace, _) = renderItems[draggedIndex] { return workspace.groupId } - return nil - }() - let membership: UUID? = (beforeGroup == afterGroup) ? beforeGroup : committedGroupId guard renderItems[draggedIndex].effectiveGroupId != membership else { return renderItems } var result = renderItems result[draggedIndex] = result[draggedIndex].withEffectiveGroupId(membership) return result } - /// The group a render item counts as for neighbor-membership purposes: the - /// group a header anchors, or a workspace row's effective group. - private static func groupIdentity(_ item: SidebarWorkspaceRenderItem) -> UUID? { - switch item { - case .groupHeader(let group, _): - return group.id - case .workspace(_, let effectiveGroupId): - return effectiveGroupId - } - } - /// The id order after moving the dragged workspace to the indicator slot, /// or nil when the move is a no-op. private static func dragPreviewWorkspaceIds( diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 57a9f2cf4e1b..6ed2e2489328 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -3750,6 +3750,48 @@ class TabManager: ObservableObject { return min(lower, upper)...max(lower, upper) } + /// Commits a gesture-driven drag of a NON-ANCHOR workspace row: the slot + /// (`toIndex`) and the group membership (`desiredGroupId`) were both + /// resolved live during the drag (position by Y, membership by X at + /// boundary slots), so membership is written EXPLICITLY instead of being + /// re-inferred from neighbors — the inference cannot express the + /// boundary-slot cases ("last slot but outside the group" vs "last slot + /// inside" share an array position). Writing membership before the move + /// also lets a member leave its group: the member-run clamp consults the + /// (already updated) groupId, so a row leaving is unclamped and a row + /// joining is clamped into its NEW group's run. + @discardableResult + func applyGestureDragReorder( + tabId: UUID, + toIndex targetIndex: Int, + desiredGroupId: UUID? + ) -> Bool { + guard let tab = tabs.first(where: { $0.id == tabId }), + !isWorkspaceGroupAnchor(tabId) else { return false } + let resolvedGroupId = desiredGroupId.flatMap { gid in + workspaceGroups.contains(where: { $0.id == gid }) ? gid : nil + } + let membershipChanged = tab.groupId != resolvedGroupId + if membershipChanged { + tab.groupId = resolvedGroupId + } + let moved = reorderWorkspace(tabId: tabId, toIndex: targetIndex, isDragOperation: false) + if membershipChanged { + // The reorder's own normalize is skipped on clamped no-op moves + // (early `return true`), and a membership flip at an unchanged + // index still needs the group invariants re-established — + // otherwise a row that just left its group would sit ungrouped + // INSIDE the group's contiguous run. Idempotent when the reorder + // already normalized. + if !workspaceGroups.isEmpty { + syncWorkspaceGroupsOrderToAnchorOrder() + normalizeWorkspaceGroupContiguity() + } + postWorkspaceOrderDidChange(movedWorkspaceIds: [tabId]) + } + return moved || membershipChanged + } + @discardableResult func reorderSidebarWorkspace( tabId: UUID, diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index cd2f38ae9d04..71a4204aa224 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -39,15 +39,15 @@ extension VerticalTabsSidebar { let showsHintForAnchor = modifierKeyMonitor.isModifierPressed // Dragging a group header reorders the whole group at top level; the // shared reorder helpers handle the anchor/top-level scope. - let onReorderChanged: (CGPoint, CGFloat) -> Void = { [anchorId = group.anchorWorkspaceId, renderContext] startLocation, translationHeight in + let onReorderChanged: (CGPoint, CGSize) -> Void = { [anchorId = group.anchorWorkspaceId, renderContext] startLocation, translation in sidebarReorderGestureChanged( draggedId: anchorId, startLocationY: startLocation.y, - translationHeight: translationHeight, + translation: translation, renderContext: renderContext ) } - let onReorderEnded: (CGPoint, CGFloat) -> Void = { [anchorId = group.anchorWorkspaceId] _, _ in + let onReorderEnded: (CGPoint, CGSize) -> Void = { [anchorId = group.anchorWorkspaceId] _, _ in sidebarReorderGestureEnded(draggedId: anchorId) } // Computed in the parent and applied as opacity below (not passed into From 796a9c458d94738b4704612019531fb6081678ed Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 22:13:39 -0700 Subject: [PATCH 23/36] Sidebar gesture reorder: fix the full edge-case audit (ultracode sweep) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 42-agent adversarial audit of the gesture reorder + groups feature confirmed 23 findings (several verified line-by-line). The fixes: - B3 root cause: dragPreviewItems inferred top-level mode from set equality of scope ids vs visible ids, which is wrongly true whenever ANY collapsed group has members — every member/ungrouped drag lost its in-group slot preview. The mode is now the caller's reorder-scope mode pinned at drag begin (dragState.gestureScopeUsesTopLevelRows), passed explicitly. - B2: the anchor-drag commit was already correct (children move via normalizeWorkspaceGroupRunsPreservingOrder); what the user saw was the follower carrying only the bare header while a headless group body reflowed in the list. The follower now lifts the whole visible block (header + members, capped at 7 rows) and the in-list member rows of the dragged group hide alongside their header. - B1: the header center drop-into zone caused five distinct bugs (transit arming with zero hysteresis, indicator-nil gap collapse and whole-list churn on every pass-through, ring drawn 12pt outside the header pill at the wrong radius, transient frozen-vs-live geometry misalignment, absolute-vs-relative follower indent override). It is removed entirely: X-axis membership at the slot under a header now covers joining collapsed groups, with the indent preview as the affordance. - X membership is measured RELATIVE to boundary-slot entry (re-anchored on each flip) instead of cumulative translation since mouse-down: horizontal drift no longer silently biases joins, and a grouped member crossing a foreign group's boundary no longer auto-joins it on a purely vertical drag. Sticky default keeps the carried membership. - Membership-only drops now commit: at the dragged row's own slot (indicator nil) the boundary is resolved from the row's own neighbors, and gestureEnded commits a membership flip at the unchanged index — "drag right to tuck in / left to pull out in place" works without vertical movement. - clampedGroupedMemberReorderIndex computed the group run WITH the moving row already re-labeled at its old index, corrupting the clamp for cross-position joins; the run now excludes the moving row. - A drag that changes membership unpins the row: keeping the pin let the pinned-tier clamp teleport it to the top of the sidebar, far from the slot the preview showed. - The group-header follower no longer renders a spurious +12pt indent (anchor preview membership starts nil), and grouped-member followers no longer double-indent (the captured frame already encodes the committed indent; the dragFollower branch padding is removed). Documented known bounded inaccuracy: rows first materialized mid-drag during autoscroll report preview-space frames (error bounded by the dragged block height, edges unaffected). Known remaining preview/commit divergence around PINNED GROUP tiers (planner pinned set undercounts the global tier) is unchanged from before this branch. New tests: gesture commit (interior join, empty-group join, in-place membership-only leave, unpin on membership change, anchor/dead-group rejection) and the collapsed-group preview regression. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 7 +- Sources/ContentView.swift | 171 +++++++++++------- .../Sidebar/SidebarReorderFollowerView.swift | 83 ++++++--- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 49 ++--- Sources/SidebarWorkspaceGroupHeaderView.swift | 10 - Sources/SidebarWorkspaceRenderItem.swift | 7 +- Sources/TabManager.swift | 25 ++- .../VerticalTabsSidebar+WorkspaceGroups.swift | 1 - cmuxTests/WorkspaceGroupTests.swift | 150 +++++++++++++++ 9 files changed, 361 insertions(+), 142 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 034e9bab6d16..5ddad8a864da 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,12 +4,12 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19586 Sources/ContentView.swift +19617 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift 11756 cmuxTests/AppDelegateShortcutRoutingTests.swift -10088 Sources/TabManager.swift +10105 Sources/TabManager.swift 8494 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift 7737 Sources/Panels/BrowserPanelView.swift 7214 cmuxTests/WorkspaceUnitTests.swift @@ -69,11 +69,11 @@ 1365 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift 1313 cmuxTests/MobileHostAuthorizationTests.swift +1293 cmuxTests/WorkspaceGroupTests.swift 1285 cmuxUITests/SidebarHelpMenuUITests.swift 1197 cmuxTests/CodexAppServerSessionTests.swift 1156 cmuxTests/SidebarOrderingTests.swift 1144 Sources/VaultAgentProcessScanner.swift -1143 cmuxTests/WorkspaceGroupTests.swift 1139 cmuxTests/PiVaultAgentPersistenceTests.swift 1107 Sources/AppDelegate+CmuxSSHURL.swift 1084 cmuxTests/AgentHibernationTests.swift @@ -181,6 +181,5 @@ 506 Sources/App/MainWindowVisibilityController.swift 505 cmuxUITests/DisplayResolutionRegressionUITests.swift 504 cmuxTests/TerminalNotificationSocketActionTests.swift -503 Sources/SidebarWorkspaceGroupHeaderView.swift 502 Sources/CmuxEventPublishing.swift 502 Sources/Settings/ConfigSource.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 4ba060a2327c..2558dcc987fa 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10429,13 +10429,6 @@ final class SidebarDragState { /// members when dragging a group anchor at top level). @ObservationIgnored private var scopeBandComposition: [UUID: [UUID]] = [:] - /// The group header (anchor id) the cursor is currently parked over in - /// its center drop-into zone, observed so the header can highlight. - /// Releasing here adds the dragged workspace to that group instead of - /// reordering — the only drag path INTO a collapsed group, whose members - /// have no rows to sandwich between. - var dropIntoGroupAnchorId: UUID? - /// The group membership the dragged row will COMMIT with at the current /// landing slot, resolved live during the drag: interior slots of a group /// force membership; boundary slots (first/last slot of a run, the slot @@ -10445,10 +10438,6 @@ final class SidebarDragState { /// always agree. Observed; changes only when the slot or the X side flips. var previewMembershipGroupId: UUID? - /// Anchor ids of groups the dragged workspace could be dropped INTO via - /// a header's center zone (every group except the one it is already in; - /// empty when dragging an anchor). - @ObservationIgnored private var dropIntoGroupCandidateAnchorIds: Set = [] /// Per-band group identity (a member row's group, a header's group, nil /// for ungrouped rows), used to resolve the landing slot's membership. @ObservationIgnored private var bandGroupIdById: [UUID: UUID?] = [:] @@ -10456,11 +10445,20 @@ final class SidebarDragState { /// its group, so headers never donate a boundary candidate to the slot /// above them). @ObservationIgnored private var headerBandIds: Set = [] - /// Dragged row's committed membership and leading indent at drag begin. + /// Dragged row's committed membership at drag begin. @ObservationIgnored private var draggedCommittedGroupId: UUID? - @ObservationIgnored private var draggedCommittedIndent: CGFloat = 0 /// True while dragging an anchor (membership never changes for anchors). @ObservationIgnored private var draggedIsAnchor = false + /// The reorder scope mode pinned at drag begin (anchors reorder in + /// top-level space). Read by the preview builder; safe non-observed + /// because it only changes together with `draggedTabId`. + @ObservationIgnored var gestureScopeUsesTopLevelRows = false + /// Identity of the boundary slot the drag currently hovers plus the + /// translation width when it was entered. The X membership gesture is + /// measured RELATIVE to slot entry, so horizontal drift accumulated + /// earlier in the drag cannot silently bias joins. + @ObservationIgnored private var boundarySlotKey: String? + @ObservationIgnored private var translationWidthAtBoundaryEntry: CGFloat = 0 /// The begin-time gesture location in list space. Later cursor positions /// are derived as base + translation + autoscroll delta, because the @@ -10482,6 +10480,13 @@ final class SidebarDragState { /// ones are not overwritten): the list reflows to preview the gap, but /// hit-testing stays against the committed layout so the landing slot does /// not feed back on its own preview and oscillate. + /// + /// Known bounded inaccuracy: a row first materialized MID-drag (long-list + /// autoscroll) reports its preview-space frame; for rows outside the + /// preview's displaced span (the common case at the list edges) that + /// equals committed space, and for rows inside it the error is at most + /// the dragged block's height and only affects slot targeting on those + /// rows until the drag ends. func updateRowFrames(_ frames: [UUID: CGRect]) { guard draggedTabId != nil else { rowFramesInList = frames @@ -10525,14 +10530,14 @@ final class SidebarDragState { reorderIds = [] pinnedIds = [] scopeBandComposition = [:] - dropIntoGroupCandidateAnchorIds = [] - dropIntoGroupAnchorId = nil bandGroupIdById = [:] headerBandIds = [] draggedCommittedGroupId = nil - draggedCommittedIndent = 0 draggedIsAnchor = false + gestureScopeUsesTopLevelRows = false previewMembershipGroupId = nil + boundarySlotKey = nil + translationWidthAtBoundaryEntry = 0 lastTranslationWidth = 0 clearDropIndicator() } @@ -10546,7 +10551,6 @@ final class SidebarDragState { reorderIds: [UUID], pinnedIds: Set, scopeBandComposition: [UUID: [UUID]], - dropIntoGroupCandidateAnchorIds: Set, bandGroupIdById: [UUID: UUID?], headerBandIds: Set, draggedCommittedGroupId: UUID?, @@ -10561,15 +10565,17 @@ final class SidebarDragState { self.reorderIds = reorderIds self.pinnedIds = pinnedIds self.scopeBandComposition = scopeBandComposition - self.dropIntoGroupCandidateAnchorIds = dropIntoGroupCandidateAnchorIds self.bandGroupIdById = bandGroupIdById self.headerBandIds = headerBandIds self.draggedCommittedGroupId = draggedCommittedGroupId - self.draggedCommittedIndent = draggedCommittedGroupId != nil - ? SidebarWorkspaceGroupingMetrics.memberIndent - : 0 self.draggedIsAnchor = draggedIsAnchor - self.previewMembershipGroupId = draggedCommittedGroupId + self.gestureScopeUsesTopLevelRows = usesTopLevelRows + // Anchors never change membership; their committed groupId is the + // group they HEAD, not one they could join, so the preview membership + // (which drives follower indent) must stay nil for them. + self.previewMembershipGroupId = draggedIsAnchor ? nil : draggedCommittedGroupId + self.boundarySlotKey = nil + self.translationWidthAtBoundaryEntry = 0 self.draggedRowFrame = draggedRowFrame self.grabOffsetY = grabOffsetY self.reorderTranslationBaseY = translationBaseY @@ -10637,26 +10643,6 @@ final class SidebarDragState { private func recomputeIndicator(cursorY: CGFloat, translationWidth: CGFloat) { guard let draggedTabId else { return } let bands = buildBands() - - // Center drop-into zone: parking over the middle of another group's - // header adds the dragged row to that group (appended) on release. - let hoveredBand = bands.first(where: { cursorY >= $0.minY && cursorY < $0.maxY }) - let intoGroupAnchorId: UUID? = hoveredBand.flatMap { band in - guard dropIntoGroupCandidateAnchorIds.contains(band.id) else { return nil } - let inset = band.height / 3 - let isCenter = cursorY >= band.minY + inset && cursorY <= band.maxY - inset - return isCenter ? band.id : nil - } - if intoGroupAnchorId != dropIntoGroupAnchorId { - dropIntoGroupAnchorId = intoGroupAnchorId - } - if intoGroupAnchorId != nil { - if dropIndicator != nil { - dropIndicator = nil - } - return - } - let indicator = SidebarReorderIndicatorResolver.resolve( cursorY: cursorY, bands: bands, @@ -10674,34 +10660,43 @@ final class SidebarDragState { /// Resolves the membership the dragged row will commit with at the /// current landing slot. Interior slots of a group force membership; /// boundary slots (first/last slot of a run, the slot under a memberless - /// header) follow the pointer's X axis with hysteresis — drag right to - /// tuck the row into the group, left to keep it (or pull it) out, in the - /// same motion as the vertical reorder. + /// or collapsed header) follow the pointer's X axis — drag right to tuck + /// the row into the group, left to keep it (or pull it) out, in the same + /// motion as the vertical reorder. The X gesture is measured RELATIVE to + /// when the current boundary slot was entered, so horizontal drift + /// accumulated earlier in the drag never silently flips membership, and + /// a grouped member crossing a foreign group's boundary never auto-joins + /// it on a purely vertical drag. private func resolveMembership( bands: [SidebarReorderIndicatorResolver.Band], translationWidth: CGFloat ) { guard let draggedTabId, !draggedIsAnchor, !dropIndicatorUsesTopLevelRows else { return } - // Indicator nil means "already at the committed slot": membership - // follows the committed neighbors, i.e. the committed membership. - guard let dropIndicator else { - setPreviewMembership(draggedCommittedGroupId) - return - } // The slot's visual neighbors, skipping the dragged row's own - // (frozen) band: insertion is canonicalized to "above row X" or the - // end sentinel. + // (frozen) band. With an indicator, the slot is canonicalized to + // "above row X" or the end sentinel; with a nil indicator the row + // sits at its own committed slot — whose neighbors still define a + // boundary, so "drag right/left in place" can flip membership + // without moving (the membership-only drop). let neighborBands = bands.filter { $0.id != draggedTabId } var prevBand: SidebarReorderIndicatorResolver.Band? var nextBand: SidebarReorderIndicatorResolver.Band? - if let targetId = dropIndicator.tabId, - let targetIndex = neighborBands.firstIndex(where: { $0.id == targetId }) { - nextBand = neighborBands[targetIndex] - prevBand = targetIndex > 0 ? neighborBands[targetIndex - 1] : nil + if let dropIndicator { + if let targetId = dropIndicator.tabId, + let targetIndex = neighborBands.firstIndex(where: { $0.id == targetId }) { + nextBand = neighborBands[targetIndex] + prevBand = targetIndex > 0 ? neighborBands[targetIndex - 1] : nil + } else { + prevBand = neighborBands.last + nextBand = nil + } + } else if let ownIndex = bands.firstIndex(where: { $0.id == draggedTabId }) { + prevBand = ownIndex > 0 ? bands[ownIndex - 1] : nil + nextBand = ownIndex + 1 < bands.count ? bands[ownIndex + 1] : nil } else { - prevBand = neighborBands.last - nextBand = nil + setPreviewMembership(draggedIsAnchor ? nil : draggedCommittedGroupId) + return } // A header donates its group to the slot BELOW it (prev side) but @@ -10713,21 +10708,42 @@ final class SidebarDragState { if let prevGroup, prevGroup == nextGroup { // Interior slot: sandwiched inside a group, membership is forced. + boundarySlotKey = nil setPreviewMembership(prevGroup) return } guard let candidate = prevGroup ?? nextGroup else { + boundarySlotKey = nil setPreviewMembership(nil) return } - // Boundary slot: the X axis decides, with hysteresis around the - // half-indent threshold so jitter does not flicker the indent. - let effectiveLeadingX = draggedCommittedIndent + translationWidth - let half = SidebarWorkspaceGroupingMetrics.memberIndent / 2 - let currentlyIn = previewMembershipGroupId == candidate - let isIn = currentlyIn - ? effectiveLeadingX > half - 3 - : effectiveLeadingX >= half + 3 + + // Boundary slot. Re-anchor the X measurement whenever the slot (or + // its candidate group) changes. + let slotKey = "\(dropIndicator?.tabId?.uuidString ?? "own").\(dropIndicator?.edge == .top ? "t" : "b").\(candidate.uuidString)" + if boundarySlotKey != slotKey { + boundarySlotKey = slotKey + translationWidthAtBoundaryEntry = translationWidth + } + let deltaSinceEntry = translationWidth - translationWidthAtBoundaryEntry + // Sticky default: whatever membership the drag already resolved + // carries into the boundary (a member at its own group's edge stays + // in; a foreign row stays out) until a deliberate ~8pt horizontal + // nudge flips it. + let stickyIn = previewMembershipGroupId == candidate + let isIn: Bool + if deltaSinceEntry >= 8 { + isIn = true + } else if deltaSinceEntry <= -8 { + isIn = false + } else { + isIn = stickyIn + } + if isIn != stickyIn { + // Re-anchor on each flip so flipping back needs the same ~8pt + // nudge from here, not double the distance from slot entry. + translationWidthAtBoundaryEntry = translationWidth + } setPreviewMembership(isIn ? candidate : nil) } @@ -12761,6 +12777,7 @@ struct VerticalTabsSidebar: View { draggedWorkspaceId: dragState.draggedTabId, dropIndicator: dragState.dropIndicator, reorderWorkspaceIds: renderContext.sidebarReorderIds, + topLevelMode: dragState.gestureScopeUsesTopLevelRows, draggedMembershipGroupId: dragState.previewMembershipGroupId ) // No `.id(groupAnchorSignature)` rebuild hack here: a group header now @@ -12792,7 +12809,10 @@ struct VerticalTabsSidebar: View { workspaceRow( tab, renderContext: renderContext, - shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets + shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets, + isHiddenInDraggedGroupBlock: tab.groupId != nil + && dragState.draggedTabId != nil + && tab.groupId.flatMap { renderContext.workspaceGroupById[$0]?.anchorWorkspaceId } == dragState.draggedTabId ) .transition(.sidebarGroupRow) } @@ -12826,6 +12846,7 @@ struct VerticalTabsSidebar: View { SidebarReorderFollowerView( dragState: dragState, sourceItems: baseRenderItems, + rowSpacing: tabRowSpacing, previewExtraIndent: followerPreviewExtraIndent( baseRenderItems: baseRenderItems, previewItems: previewItems @@ -12962,6 +12983,7 @@ struct VerticalTabsSidebar: View { _ tab: Workspace, renderContext: WorkspaceListRenderContext, shouldCollectWorkspaceDropTargets: Bool, + isHiddenInDraggedGroupBlock: Bool = false, role: SidebarWorkspaceRowRenderRole = .list ) -> some View { let index = renderContext.tabIndexById[tab.id] ?? 0 @@ -13084,13 +13106,22 @@ struct VerticalTabsSidebar: View { // row's inputs constant during a drag, so `.equatable()` skips its body // and the in-flight `DragGesture` is not torn down when the drag starts. if role == .dragFollower { + // No committed-indent padding here: the captured drag frame the + // follower is sized/positioned with ALREADY encodes the row's + // committed indent (the frame is measured inside TabItemView, + // after the parent applies the indent). Re-applying it shifted + // grouped members +12pt and made pull-out previews land at 12 + // instead of 0. The follower's only indent input is the RELATIVE + // previewExtraIndent. row .allowsHitTesting(false) .accessibilityHidden(true) - .padding(.leading, indent) } else { + // Members of a dragged group hide alongside their header: the + // whole block lifts into the follower, and the (invisible) rows + // still reflow with the preview so the gap matches the block. row - .opacity(isBeingDragged ? 0 : 1) + .opacity(isBeingDragged || isHiddenInDraggedGroupBlock ? 0 : 1) // No `.id(tab.id)` here: the row identity is set by the ForEach // (`id: \.representedWorkspaceId`), which also serves // scroll-to. An inner `.id` would re-pin identity and suppress diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift index 390f83bab98e..572b2ff41e5c 100644 --- a/Sources/Sidebar/SidebarReorderFollowerView.swift +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -1,7 +1,9 @@ import SwiftUI /// The floating copy of the picked-up workspace row that tracks the cursor -/// during a gesture-driven reorder. +/// during a gesture-driven reorder. For a group-header drag the follower +/// carries the WHOLE visible block (header + member rows) so the group reads +/// as one object traveling with the cursor. /// /// This is the ONLY view that reads `SidebarDragState.followerCursorY`, the /// per-frame cursor position. Because it is a sibling overlay over the list (not @@ -13,12 +15,17 @@ import SwiftUI /// group-membership indent, which animates on its own axis (see below). struct SidebarReorderFollowerView: View { let dragState: SidebarDragState - /// The committed render list, used to find the picked-up row's content. + /// The committed render list, used to find the picked-up row's content + /// (and, for a header drag, the member rows that follow it). let sourceItems: [SidebarWorkspaceRenderItem] + /// Spacing between the header and member rows in a group-block follower, + /// matching the list's row spacing. + let rowSpacing: CGFloat /// Extra leading indent previewed for the dragged row at its current - /// landing slot (member indent when the slot is inside a group the row is - /// not yet a member of, 0 otherwise). Derived by the parent from the - /// preview items, so it only changes when the landing slot does. + /// landing slot, RELATIVE to its committed indent (positive tucking into + /// a group, negative pulling out, 0 unchanged). Derived by the parent + /// from the resolved membership, so it only changes when the resolved + /// membership does. let previewExtraIndent: CGFloat let rowContent: (SidebarWorkspaceRenderItem) -> AnyView @@ -28,31 +35,51 @@ struct SidebarReorderFollowerView: View { let frame = dragState.draggedRowFrame, frame.width > 0, frame.height > 0, - let item = sourceItems.first(where: { $0.representedWorkspaceId == draggedId }) { + let itemIndex = sourceItems.firstIndex(where: { $0.representedWorkspaceId == draggedId }) { let topY = cursorY - dragState.grabOffsetY - // Parking over a header's drop-into zone also previews membership. - let extraIndent = dragState.dropIntoGroupAnchorId != nil - ? SidebarWorkspaceGroupingMetrics.memberIndent - : previewExtraIndent - // The indent is applied INSIDE the fixed-size, position-tracked - // container, on its own animation keyed to the indent value: the - // row slides right and narrows when the landing slot crosses into - // a group (and back out), while Y stays glued to the cursor with - // animations disabled. - rowContent(item) - .padding(.leading, extraIndent) - .animation(.snappy(duration: 0.15, extraBounce: 0), value: extraIndent) - .frame(width: frame.width, height: frame.height, alignment: .topLeading) - .position(x: frame.midX, y: topY + frame.height / 2) - .shadow(color: Color.black.opacity(0.18), radius: 11, x: 0, y: 5) - .opacity(0.97) - .allowsHitTesting(false) - .accessibilityHidden(true) - .zIndex(1000) - .transaction { transaction in - transaction.disablesAnimations = true - transaction.animation = nil + let blockItems = followerBlockItems(startingAt: itemIndex) + // The indent is applied INSIDE the position-tracked container, on + // its own animation keyed to the indent value: the row slides + // right and narrows when the landing slot crosses into a group + // (and back out), while Y stays glued to the cursor with + // animations disabled. The container is sized to the picked-up + // row's frame and top-aligned, so a group block overflows below + // it without disturbing the cursor anchor math. + VStack(alignment: .leading, spacing: rowSpacing) { + ForEach(blockItems, id: \.representedWorkspaceId) { item in + rowContent(item) } + } + .padding(.leading, previewExtraIndent) + .animation(.snappy(duration: 0.15, extraBounce: 0), value: previewExtraIndent) + .frame(width: frame.width, height: frame.height, alignment: .topLeading) + .position(x: frame.midX, y: topY + frame.height / 2) + .shadow(color: Color.black.opacity(0.18), radius: 11, x: 0, y: 5) + .opacity(0.97) + .allowsHitTesting(false) + .accessibilityHidden(true) + .zIndex(1000) + .transaction { transaction in + transaction.disablesAnimations = true + transaction.animation = nil + } } } + + /// The dragged item plus, for a group header, the visible member rows + /// that follow it in the committed list (capped so enormous groups don't + /// turn the per-frame follower into a wall of rows). + private func followerBlockItems(startingAt itemIndex: Int) -> [SidebarWorkspaceRenderItem] { + let item = sourceItems[itemIndex] + guard case .groupHeader(let group, _) = item else { return [item] } + var block: [SidebarWorkspaceRenderItem] = [item] + var index = itemIndex + 1 + while index < sourceItems.count, block.count < 7 { + guard case .workspace(let workspace, _) = sourceItems[index], + workspace.groupId == group.id else { break } + block.append(sourceItems[index]) + index += 1 + } + return block + } } diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index 9a48745d0ac0..4cbbe114b011 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -71,20 +71,12 @@ extension VerticalTabsSidebar { usesTopLevelRows: usesTopLevelRows, renderContext: renderContext ) - // Membership-resolution inputs: each band's group identity, which - // bands are headers, and the headers a non-anchor row could be - // dropped INTO via their center zone. + // Membership-resolution inputs: each band's group identity and + // which bands are headers. let draggedWorkspace = renderContext.workspaceById[draggedId] let draggedGroupId = draggedWorkspace?.groupId let draggedIsAnchor = renderContext.workspaceGroups .contains { $0.anchorWorkspaceId == draggedId } - let dropIntoCandidates: Set = draggedIsAnchor - ? [] - : Set( - renderContext.workspaceGroups - .filter { $0.id != draggedGroupId } - .map(\.anchorWorkspaceId) - ) let bandGroupIdById: [UUID: UUID?] = Dictionary( uniqueKeysWithValues: renderContext.tabs.map { ($0.id, $0.groupId) } ) @@ -105,7 +97,6 @@ extension VerticalTabsSidebar { reorderIds: reorderIds, pinnedIds: pinnedIds, scopeBandComposition: composition, - dropIntoGroupCandidateAnchorIds: dropIntoCandidates, bandGroupIdById: bandGroupIdById, headerBandIds: headerBandIds, draggedCommittedGroupId: draggedGroupId, @@ -135,20 +126,30 @@ extension VerticalTabsSidebar { #endif return } - // Released over a group header's center zone: join that group. The - // only drag path INTO a collapsed group, whose members have no rows - // to land between. - if let anchorId = dragState.dropIntoGroupAnchorId, - let group = tabManager.workspaceGroups.first(where: { $0.anchorWorkspaceId == anchorId }) { - #if DEBUG - cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) intoGroup=\(group.id.uuidString.prefix(5))") - #endif - withAnimation(SidebarGroupAnimation.structure) { - tabManager.addWorkspaceToGroup(workspaceId: draggedId, groupId: group.id) - } - return - } guard let targetIndex = dragState.gestureReorderTargetIndex() else { + // No positional move — but the X axis may have flipped membership + // in place (tuck into the group directly above / pull out at the + // group's edge without moving). Commit the membership-only drop + // at the row's current index. + let membership = dragState.previewMembershipGroupId + if !dragState.dropIndicatorUsesTopLevelRows, + let currentIndex = tabManager.tabs.firstIndex(where: { $0.id == draggedId }), + membership != tabManager.tabs[currentIndex].groupId { + #if DEBUG + cmuxDebugLog( + "sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=inPlace " + + "membership=\(membership?.uuidString.prefix(5) ?? "nil")" + ) + #endif + withAnimation(Self.sidebarReorderAnimation) { + _ = tabManager.applyGestureDragReorder( + tabId: draggedId, + toIndex: currentIndex, + desiredGroupId: membership + ) + } + return + } #if DEBUG cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=nil (noop)") #endif diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 253faa0e6de6..27fbf9fd7a9a 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -15,7 +15,6 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.isCollapsed == rhs.isCollapsed && lhs.isPinned == rhs.isPinned && lhs.isAnchorActive == rhs.isAnchorActive && - lhs.isReorderDropTarget == rhs.isReorderDropTarget && lhs.memberCount == rhs.memberCount && lhs.groupUnreadCount == rhs.groupUnreadCount && lhs.shortcutDigit == rhs.shortcutDigit && @@ -40,9 +39,6 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isCollapsed: Bool let isPinned: Bool let isAnchorActive: Bool - /// True while a gesture-reorder drag is parked over this header's center - /// drop-into zone (releasing adds the dragged workspace to the group). - let isReorderDropTarget: Bool let memberCount: Int let groupUnreadCount: Int let shortcutDigit: Int? @@ -241,12 +237,6 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) - .overlay { - if isReorderDropTarget { - RoundedRectangle(cornerRadius: 6) - .strokeBorder(Color.accentColor, lineWidth: 1.5) - } - } .modifier(SidebarReorderRowModifier( enabled: isReorderEnabled, workspaceId: anchorWorkspaceId, diff --git a/Sources/SidebarWorkspaceRenderItem.swift b/Sources/SidebarWorkspaceRenderItem.swift index 63656c4c15f9..c7ecd95a1ac0 100644 --- a/Sources/SidebarWorkspaceRenderItem.swift +++ b/Sources/SidebarWorkspaceRenderItem.swift @@ -123,6 +123,7 @@ enum SidebarWorkspaceRenderItem { draggedWorkspaceId: UUID?, dropIndicator: SidebarDropIndicator?, reorderWorkspaceIds: [UUID], + topLevelMode: Bool, draggedMembershipGroupId: UUID? = nil ) -> [SidebarWorkspaceRenderItem] { guard let draggedWorkspaceId, @@ -132,7 +133,11 @@ enum SidebarWorkspaceRenderItem { return items } - let topLevelMode = Set(reorderWorkspaceIds) != Set(items.map(\.representedWorkspaceId)) + // The mode is the caller's reorder-scope mode, pinned at drag begin. + // It must NOT be inferred from set equality of scope vs visible ids: + // a member drag's scope contains members hidden under collapsed + // groups, so any collapsed group used to flip the inference to + // top-level and the whole in-group slot preview silently died. let blocks = dragPreviewBlocks( items, reorderWorkspaceIds: reorderWorkspaceIds, diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 6ed2e2489328..d734d0639145 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -3774,6 +3774,13 @@ class TabManager: ObservableObject { let membershipChanged = tab.groupId != resolvedGroupId if membershipChanged { tab.groupId = resolvedGroupId + // A drag that changes membership expresses a spatial intent that + // overrides pinning: keeping the pin would let the pinned-tier + // clamp teleport the row to the top of the sidebar (or into the + // group's pinned sub-tier) far from the slot the preview showed. + if tab.isPinned { + tab.isPinned = false + } } let moved = reorderWorkspace(tabId: tabId, toIndex: targetIndex, isDragOperation: false) if membershipChanged { @@ -5181,7 +5188,14 @@ class TabManager: ObservableObject { workspace.id != group.anchorWorkspaceId else { return nil } - let memberIndices = tabs.indices.filter { tabs[$0].groupId == groupId } + // Exclude the moving row itself from the run bounds: a gesture join + // writes the NEW groupId before the move, so the row still sits at + // its OLD index — including it would stretch the run toward wherever + // the row happened to be and corrupt the clamp for cross-position + // joins. The anchor and the OTHER members define the run. + let memberIndices = tabs.indices.filter { + tabs[$0].groupId == groupId && tabs[$0].id != workspace.id + } guard let firstIndex = memberIndices.first, let lastIndex = memberIndices.last else { return nil @@ -5192,12 +5206,15 @@ class TabManager: ObservableObject { count += 1 } } + // Bounds are insertion-style around the remaining run: a row moving + // up from below the run targets indices relative to the array WITH + // itself removed first, which `workspaceReorderPlan` accounts for. let lowerBound = workspace.isPinned - ? min(firstIndex + 1, lastIndex) - : min(firstIndex + 1 + pinnedMemberCount, lastIndex) + ? min(firstIndex + 1, lastIndex + 1) + : min(firstIndex + 1 + pinnedMemberCount, lastIndex + 1) let upperBound = workspace.isPinned ? max(firstIndex + pinnedMemberCount, lowerBound) - : lastIndex + : lastIndex + 1 return min(max(clampedTargetIndex, lowerBound), upperBound) } diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 71a4204aa224..e3a1c0f9e681 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -64,7 +64,6 @@ extension VerticalTabsSidebar { isCollapsed: group.isCollapsed, isPinned: group.isPinned, isAnchorActive: isAnchorActive, - isReorderDropTarget: role == .list && dragState.dropIntoGroupAnchorId == group.anchorWorkspaceId, memberCount: memberWorkspaceIds.count, groupUnreadCount: groupUnreadCount, shortcutDigit: shortcutDigit, diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index c7bcc926db8f..71f1d3ba9159 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1072,6 +1072,156 @@ struct WorkspaceGroupTests { #expect(manager.selectedTabId == focusedTab.id) #expect(manager.sidebarSelectedWorkspaceIds == [focusedTab.id]) } + + // MARK: - Gesture drag commit (explicit membership) + + @Test func gestureDragJoinsGroupAtInteriorSlot() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup( + name: "G", + childWorkspaceIds: [originalIds[0], originalIds[1]] + )) + // tabs: [anchor, m0, m1, w2, w3] + let draggedId = manager.tabs[4].id + let anchorId = try #require(manager.workspaceGroups.first { $0.id == groupId }).anchorWorkspaceId + + // Join between m0 and m1 (interior slot, index 2 after removal shift). + let moved = manager.applyGestureDragReorder(tabId: draggedId, toIndex: 2, desiredGroupId: groupId) + + #expect(moved) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == groupId) + let order = manager.tabs.map(\.id) + #expect(order[0] == anchorId) + #expect(order[1] == originalIds[0]) + #expect(order[2] == draggedId) + #expect(order[3] == originalIds[1]) + } + + @Test func gestureDragJoinsEmptyGroupFromBelow() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.makeWorkspaceGroupFromWorkspace(anchorWorkspaceId: originalIds[0])) + // tabs: [anchor(=w0), w1, w2] + let draggedId = originalIds[2] + + let moved = manager.applyGestureDragReorder(tabId: draggedId, toIndex: 1, desiredGroupId: groupId) + + #expect(moved) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == groupId) + #expect(manager.tabs.map(\.id)[1] == draggedId) + } + + @Test func gestureDragMembershipOnlyLeaveAtUnchangedIndex() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup( + name: "G", + childWorkspaceIds: [originalIds[0], originalIds[1]] + )) + // tabs: [anchor, m0, m1, w2]; pull m1 out in place (last member slot). + let draggedId = originalIds[1] + let index = try #require(manager.tabs.firstIndex { $0.id == draggedId }) + + let changed = manager.applyGestureDragReorder(tabId: draggedId, toIndex: index, desiredGroupId: nil) + + #expect(changed) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == nil) + // Contiguity holds: the row sits right after the group's run. + let memberIds = manager.tabs.filter { $0.groupId == groupId }.map(\.id) + #expect(!memberIds.contains(draggedId)) + let lastMemberIndex = try #require(manager.tabs.lastIndex { $0.groupId == groupId }) + let draggedIndex = try #require(manager.tabs.firstIndex { $0.id == draggedId }) + #expect(draggedIndex > lastMemberIndex) + } + + @Test func gestureDragMembershipChangeUnpins() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup( + name: "G", + childWorkspaceIds: [originalIds[0]] + )) + // Pin the member, then drag it out: the pin must not survive and the + // row must land where aimed instead of teleporting to the pinned tier. + let memberId = originalIds[0] + let member = try #require(manager.tabs.first { $0.id == memberId }) + manager.setPinned(member, pinned: true) + let lastIndex = manager.tabs.count - 1 + + let changed = manager.applyGestureDragReorder(tabId: memberId, toIndex: lastIndex, desiredGroupId: nil) + + #expect(changed) + let moved = try #require(manager.tabs.first { $0.id == memberId }) + #expect(moved.groupId == nil) + #expect(!moved.isPinned) + #expect(manager.tabs.firstIndex { $0.id == memberId } == lastIndex) + } + + @Test func gestureDragRejectsAnchorsAndDeadGroups() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.makeWorkspaceGroupFromWorkspace(anchorWorkspaceId: originalIds[0])) + let anchorId = try #require(manager.workspaceGroups.first { $0.id == groupId }).anchorWorkspaceId + + #expect(manager.applyGestureDragReorder(tabId: anchorId, toIndex: 2, desiredGroupId: nil) == false) + // A stale group id resolves to no membership instead of corrupting state. + let draggedId = originalIds[2] + _ = manager.applyGestureDragReorder(tabId: draggedId, toIndex: 1, desiredGroupId: UUID()) + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == nil) + } + + @Test func dragPreviewItemsKeepsInGroupSlotsWhenCollapsedGroupsExist() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + manager.addWorkspace(autoWelcomeIfNeeded: false) + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + // One EXPANDED group (m0, m1) and one COLLAPSED group (m2) — the + // collapsed group's hidden member used to flip the preview into + // top-level mode and kill the in-group slot preview entirely. + let expandedGroupId = try #require(manager.createWorkspaceGroup( + name: "Open", + childWorkspaceIds: [originalIds[0], originalIds[1]] + )) + let collapsedGroupId = try #require(manager.createWorkspaceGroup( + name: "Closed", + childWorkspaceIds: [originalIds[2]] + )) + manager.toggleWorkspaceGroupCollapsed(groupId: collapsedGroupId) + _ = expandedGroupId + + let items = SidebarWorkspaceRenderItem.renderItems( + tabs: manager.tabs, + groupsById: Dictionary(uniqueKeysWithValues: manager.workspaceGroups.map { ($0.id, $0) }) + ) + let draggedId = try #require(manager.tabs.last).id + let targetMemberId = originalIds[1] + let reorderIds = manager.sidebarReorderWorkspaceIds(forDraggedWorkspaceId: draggedId) + + let preview = SidebarWorkspaceRenderItem.dragPreviewItems( + items, + draggedWorkspaceId: draggedId, + dropIndicator: SidebarDropIndicator(tabId: targetMemberId, edge: .top), + reorderWorkspaceIds: reorderIds, + topLevelMode: false, + draggedMembershipGroupId: expandedGroupId + ) + + let previewIds = preview.map(\.representedWorkspaceId) + let itemIds = items.map(\.representedWorkspaceId) + #expect(previewIds != itemIds) + let draggedIndex = try #require(previewIds.firstIndex(of: draggedId)) + let targetIndex = try #require(previewIds.firstIndex(of: targetMemberId)) + #expect(draggedIndex == targetIndex - 1) + #expect(preview[draggedIndex].effectiveGroupId == expandedGroupId) + } } /// Covers the gesture-driven reorder hit-testing + hysteresis that From 214e22fecc78e24a0ceda4b05b6dfbbadf562f1a Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Thu, 11 Jun 2026 22:41:37 -0700 Subject: [PATCH 24/36] Sidebar gesture reorder: expand collapsed groups on join, unpin on leaving the pinned tier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round on the audit fixes: - Bugbot: joining a collapsed group via the X-tuck made the row vanish under the closed header. applyGestureDragReorder now expands the target group on join, matching the addWorkspaceToGroup path. - Codex: the pinned-tier clamp applied to the dragged row BEFORE membership resolved, so a pinned row could not be dragged into a group (or anywhere below the tier) — the indicator stuck at the top. The dragged row is now excluded from the preview's pinned set, and the commit treats landing outside the tier as unpin intent (same spatial-intent rule as the membership-change unpin), so preview and commit agree. - Declined (replied): in-place membership flips show no in-list gap — the follower indent is the feedback, and the committed row is the invisible placeholder, so there is nothing visible to preview. Tests: collapsed-join expands; tier-exit unpins and lands at the slot. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +-- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 11 ++++++- Sources/TabManager.swift | 19 ++++++++++++ cmuxTests/WorkspaceGroupTests.swift | 31 +++++++++++++++++++ 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 5ddad8a864da..d0d630f79565 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -9,7 +9,7 @@ 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift 11756 cmuxTests/AppDelegateShortcutRoutingTests.swift -10105 Sources/TabManager.swift +10124 Sources/TabManager.swift 8494 cmuxTests/CLINotifyProcessIntegrationRegressionTests.swift 7737 Sources/Panels/BrowserPanelView.swift 7214 cmuxTests/WorkspaceUnitTests.swift @@ -68,8 +68,8 @@ 1372 cmuxTests/AppDelegateIssue2907RoutingTests.swift 1365 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift +1324 cmuxTests/WorkspaceGroupTests.swift 1313 cmuxTests/MobileHostAuthorizationTests.swift -1293 cmuxTests/WorkspaceGroupTests.swift 1285 cmuxUITests/SidebarHelpMenuUITests.swift 1197 cmuxTests/CodexAppServerSessionTests.swift 1156 cmuxTests/SidebarOrderingTests.swift diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index 4cbbe114b011..582ccc6b3437 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -63,10 +63,19 @@ extension VerticalTabsSidebar { forDraggedWorkspaceId: draggedId, usesTopLevelRows: usesTopLevelRows ) - let pinnedIds = tabManager.sidebarReorderPinnedWorkspaceIds( + // The dragged row itself is excluded from the pinned-tier clamp: + // its slots must not be pre-clamped to the tier before membership + // resolves (dragging a pinned row into a group, or out of the + // tier, unpins it at commit — the preview must be able to show + // those slots). Anchor/top-level drags keep the full set, since + // group pinning is positional, not membership-driven. + var pinnedIds = tabManager.sidebarReorderPinnedWorkspaceIds( forDraggedWorkspaceId: draggedId, usesTopLevelRows: usesTopLevelRows ) + if !usesTopLevelRows { + pinnedIds.remove(draggedId) + } let composition = sidebarReorderScopeBandComposition( usesTopLevelRows: usesTopLevelRows, renderContext: renderContext diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index d734d0639145..fdc066c1d5e2 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -3781,6 +3781,25 @@ class TabManager: ObservableObject { if tab.isPinned { tab.isPinned = false } + // Joining a collapsed group expands it (matching the + // addWorkspaceToGroup path) so the dropped row stays visible + // instead of vanishing under the closed header. + if let resolvedGroupId, + let groupIndex = workspaceGroups.firstIndex(where: { $0.id == resolvedGroupId }), + workspaceGroups[groupIndex].isCollapsed { + workspaceGroups[groupIndex].isCollapsed = false + } + } else if tab.isPinned { + // No membership change, but landing OUTSIDE the pinned tier also + // expresses unpin intent — otherwise the commit-side tier clamp + // would snap the row back to the top, away from the slot the + // preview showed. The tier is counted without the moving row. + let tierCountExcludingSelf = tabs.prefix(while: { isGlobalPinnedRow($0) }) + .filter { $0.id != tabId } + .count + if targetIndex >= tierCountExcludingSelf + 1 { + tab.isPinned = false + } } let moved = reorderWorkspace(tabId: tabId, toIndex: targetIndex, isDragOperation: false) if membershipChanged { diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 71f1d3ba9159..a3696a7cb70d 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1163,6 +1163,37 @@ struct WorkspaceGroupTests { #expect(manager.tabs.firstIndex { $0.id == memberId } == lastIndex) } + @Test func gestureDragJoiningCollapsedGroupExpandsIt() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let groupId = try #require(manager.createWorkspaceGroup(name: "C", childWorkspaceIds: [originalIds[0]])) + manager.toggleWorkspaceGroupCollapsed(groupId: groupId) + #expect(try #require(manager.workspaceGroups.first { $0.id == groupId }).isCollapsed) + let draggedId = originalIds[2] + + _ = manager.applyGestureDragReorder(tabId: draggedId, toIndex: 2, desiredGroupId: groupId) + + #expect(manager.tabs.first { $0.id == draggedId }?.groupId == groupId) + #expect(try #require(manager.workspaceGroups.first { $0.id == groupId }).isCollapsed == false) + } + + @Test func gestureDragLeavingPinnedTierUnpins() throws { + let manager = makeTabManager() + manager.addWorkspace(autoWelcomeIfNeeded: false) + let originalIds = manager.tabs.map(\.id) + let pinnedTab = try #require(manager.tabs.first { $0.id == originalIds[0] }) + manager.setPinned(pinnedTab, pinned: true) + let lastIndex = manager.tabs.count - 1 + + let moved = manager.applyGestureDragReorder(tabId: originalIds[0], toIndex: lastIndex, desiredGroupId: nil) + + #expect(moved) + let tab = try #require(manager.tabs.first { $0.id == originalIds[0] }) + #expect(!tab.isPinned) + #expect(manager.tabs.firstIndex { $0.id == originalIds[0] } == lastIndex) + } + @Test func gestureDragRejectsAnchorsAndDeadGroups() throws { let manager = makeTabManager() manager.addWorkspace(autoWelcomeIfNeeded: false) From 834fbfef2cb0ce54483cd8ba82e75518a24bf0eb Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 12 Jun 2026 00:15:43 -0700 Subject: [PATCH 25/36] Sidebar gesture reorder: stacked hitboxes at group bottoms; animate follower width explicitly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: dropping as the LAST member of a group was not reachable, and the follower's width change was not visibly animated when crossing into a group. - Every group bottom edge now has TWO stacked hitboxes sharing one insertion position: hovering the boundary row's lower half drops INSIDE the group (last member; for a header that means tucked under it, covering collapsed groups), and hovering past that row's bottom edge (the gap / next row's top half) drops OUTSIDE as the first row after the group. Deterministic from the pointer's Y — no horizontal nudge needed — with a 2pt hysteresis band at the edge. The X-axis flip remains only for the in-place membership change at the row's own slot. - The follower's width is now an explicit animated function of the previewed indent (trailing edge fixed, narrows by the indent), in the same 0.15s transaction as the X slide. Test: boundaryHitboxesResolveLastOfGroupVsFirstAfterGroup drives SidebarDragState with synthetic frames and asserts the in/out zones and the header-tuck zone. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +- Sources/ContentView.swift | 71 +++++++++++++------ .../Sidebar/SidebarReorderFollowerView.swift | 6 ++ cmuxTests/WorkspaceGroupTests.swift | 48 +++++++++++++ 4 files changed, 104 insertions(+), 25 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index d0d630f79565..56d312815fc9 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19617 Sources/ContentView.swift +19642 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -66,9 +66,9 @@ 1380 cmuxUITests/MenuKeyEquivalentRoutingUITests.swift 1376 cmuxTests/KeyboardShortcutSettingsFileStoreStartupTests.swift 1372 cmuxTests/AppDelegateIssue2907RoutingTests.swift +1372 cmuxTests/WorkspaceGroupTests.swift 1365 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift -1324 cmuxTests/WorkspaceGroupTests.swift 1313 cmuxTests/MobileHostAuthorizationTests.swift 1285 cmuxUITests/SidebarHelpMenuUITests.swift 1197 cmuxTests/CodexAppServerSessionTests.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 2558dcc987fa..d9bfa5d14746 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10654,7 +10654,7 @@ final class SidebarDragState { if indicator != dropIndicator { dropIndicator = indicator } - resolveMembership(bands: bands, translationWidth: translationWidth) + resolveMembership(bands: bands, cursorY: cursorY, translationWidth: translationWidth) } /// Resolves the membership the dragged row will commit with at the @@ -10669,6 +10669,7 @@ final class SidebarDragState { /// it on a purely vertical drag. private func resolveMembership( bands: [SidebarReorderIndicatorResolver.Band], + cursorY: CGFloat, translationWidth: CGFloat ) { guard let draggedTabId, !draggedIsAnchor, !dropIndicatorUsesTopLevelRows else { return } @@ -10718,31 +10719,55 @@ final class SidebarDragState { return } - // Boundary slot. Re-anchor the X measurement whenever the slot (or - // its candidate group) changes. - let slotKey = "\(dropIndicator?.tabId?.uuidString ?? "own").\(dropIndicator?.edge == .top ? "t" : "b").\(candidate.uuidString)" - if boundarySlotKey != slotKey { - boundarySlotKey = slotKey - translationWidthAtBoundaryEntry = translationWidth + if dropIndicator == nil { + // Own-slot boundary (no vertical movement): the X axis flips + // membership in place — drag right to tuck into the adjacent + // group, left to pull out, without moving vertically. Measured + // relative to slot entry so earlier drift never biases it. + let slotKey = "own.\(candidate.uuidString)" + if boundarySlotKey != slotKey { + boundarySlotKey = slotKey + translationWidthAtBoundaryEntry = translationWidth + } + let deltaSinceEntry = translationWidth - translationWidthAtBoundaryEntry + let stickyIn = previewMembershipGroupId == candidate + let isIn: Bool + if deltaSinceEntry >= 8 { + isIn = true + } else if deltaSinceEntry <= -8 { + isIn = false + } else { + isIn = stickyIn + } + if isIn != stickyIn { + translationWidthAtBoundaryEntry = translationWidth + } + setPreviewMembership(isIn ? candidate : nil) + return } - let deltaSinceEntry = translationWidth - translationWidthAtBoundaryEntry - // Sticky default: whatever membership the drag already resolved - // carries into the boundary (a member at its own group's edge stays - // in; a foreign row stays out) until a deliberate ~8pt horizontal - // nudge flips it. - let stickyIn = previewMembershipGroupId == candidate + + // Moving boundary slot: TWO stacked hitboxes share this insertion + // position. While the cursor is still over the boundary-adjacent row + // that donated the candidate (its lower half resolved this slot) the + // drop is INSIDE the group ("last member" / "tucked under the + // header"); once the cursor passes that row's bottom edge into the + // gap or the next row's top half, the drop is OUTSIDE ("first row + // after the group"). Deterministic from Y — no horizontal nudge + // needed — with a small hysteresis band at the edge so jitter does + // not flicker the indent. + boundarySlotKey = nil + let currentlyIn = previewMembershipGroupId == candidate let isIn: Bool - if deltaSinceEntry >= 8 { - isIn = true - } else if deltaSinceEntry <= -8 { - isIn = false + if prevGroup != nil, let prevBand { + let edgeY = prevBand.maxY + isIn = currentlyIn ? cursorY <= edgeY + 2 : cursorY <= edgeY - 2 + } else if let nextBand { + // Candidate donated by the row BELOW the slot — mirror the rule + // on that row's top edge. + let edgeY = nextBand.minY + isIn = currentlyIn ? cursorY >= edgeY - 2 : cursorY >= edgeY + 2 } else { - isIn = stickyIn - } - if isIn != stickyIn { - // Re-anchor on each flip so flipping back needs the same ~8pt - // nudge from here, not double the distance from slot entry. - translationWidthAtBoundaryEntry = translationWidth + isIn = currentlyIn } setPreviewMembership(isIn ? candidate : nil) } diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift index 572b2ff41e5c..5ab08dc72151 100644 --- a/Sources/Sidebar/SidebarReorderFollowerView.swift +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -50,6 +50,12 @@ struct SidebarReorderFollowerView: View { rowContent(item) } } + // Width and X are BOTH explicit functions of the previewed + // indent: tucking into a group slides the row right by the + // indent AND narrows it by the same amount (the trailing edge + // stays fixed), animated together on the indent's own axis while + // Y tracking below stays animation-free. + .frame(width: max(frame.width - previewExtraIndent, 0), height: frame.height, alignment: .topLeading) .padding(.leading, previewExtraIndent) .animation(.snappy(duration: 0.15, extraBounce: 0), value: previewExtraIndent) .frame(width: frame.width, height: frame.height, alignment: .topLeading) diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index a3696a7cb70d..275c33e439ea 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1194,6 +1194,54 @@ struct WorkspaceGroupTests { #expect(manager.tabs.firstIndex { $0.id == originalIds[0] } == lastIndex) } + @Test func boundaryHitboxesResolveLastOfGroupVsFirstAfterGroup() throws { + // Layout (list space): header H(0..30, group G), member M(30..80, G), + // ungrouped U(80..130), dragged row D(200..250, ungrouped). + let drag = SidebarDragState() + let g = UUID() + let h = UUID(), m = UUID(), u = UUID(), d = UUID() + let frames: [UUID: CGRect] = [ + h: CGRect(x: 0, y: 0, width: 200, height: 30), + m: CGRect(x: 12, y: 30, width: 188, height: 50), + u: CGRect(x: 0, y: 80, width: 200, height: 50), + d: CGRect(x: 0, y: 200, width: 200, height: 50), + ] + drag.updateRowFrames(frames) + drag.beginReorder( + tabId: d, + usesTopLevelRows: false, + reorderIds: [h, m, u, d], + pinnedIds: [], + scopeBandComposition: [:], + bandGroupIdById: [h: g, m: g, u: nil, d: nil], + headerBandIds: [h], + draggedCommittedGroupId: nil, + draggedIsAnchor: false, + draggedRowFrame: frames[d], + grabOffsetY: 25, + translationBaseY: 225, + cursorY: 225 + ) + + // Hover the last member's LOWER half: the slot is "after M" and the + // membership hitbox says INSIDE the group (last member). + drag.updateReorder(cursorY: 70, translationWidth: 0) + #expect(drag.dropIndicator != nil) + #expect(drag.previewMembershipGroupId == g) + + // Slide just past M's bottom edge (over U's top half): SAME insertion + // position, but the second hitbox — first row AFTER the group. + drag.updateReorder(cursorY: 95, translationWidth: 0) + #expect(drag.previewMembershipGroupId == nil) + + // The header's lower half tucks INTO the group as its first slot. + drag.updateReorder(cursorY: 28, translationWidth: 0) + #expect(drag.previewMembershipGroupId == g) + + drag.clearDrag() + #expect(drag.previewMembershipGroupId == nil) + } + @Test func gestureDragRejectsAnchorsAndDeadGroups() throws { let manager = makeTabManager() manager.addWorkspace(autoWelcomeIfNeeded: false) From 6efee48e66fe3f80b854bf7324133f3608d58230 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 12 Jun 2026 14:12:34 -0700 Subject: [PATCH 26/36] Sidebar gesture reorder: actually animate the follower indent and width MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: the indent/width animation never played. The follower's blanket .transaction { disablesAnimations = true } (inherited from the original engine to keep cursor tracking snap-instant) suppresses ALL downstream animations — disablesAnimations kills .animation(_:value:) too — so the indent keyed inside it could never run. The blanket is removed. Cursor tracking stays animation-free by construction: .position sits OUTSIDE the indent's .animation scope, no other animation modifier covers it, and followerCursorY writes are never wrapped in withAnimation. The indent/width now animate on their 0.15s axis. Co-Authored-By: Claude Fable 5 --- Sources/Sidebar/SidebarReorderFollowerView.swift | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift index 5ab08dc72151..66d5fbdc4a69 100644 --- a/Sources/Sidebar/SidebarReorderFollowerView.swift +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -10,9 +10,14 @@ import SwiftUI /// a row inside the `LazyVStack`/`ForEach`), its per-frame updates repaint just /// this one view and never invalidate the list body — the property that keeps /// the drag off the https://github.com/manaflow-ai/cmux/issues/2586 thrash path. -/// Implicit animations are disabled so the follower snaps to the cursor with -/// zero lag while the list rows animate the gap open underneath it — except the -/// group-membership indent, which animates on its own axis (see below). +/// The cursor tracking stays animation-free by construction: `.position` sits +/// OUTSIDE the indent's `.animation(_:value:)` scope, no other animation +/// modifier covers it, and `followerCursorY` writes are never wrapped in +/// `withAnimation` — so the follower snaps to the cursor with zero lag while +/// the indent/width animate on their own axis. (A blanket +/// `.transaction { disablesAnimations = true }` used to enforce this, but it +/// also suppressed the indent animation — disablesAnimations kills +/// `.animation(_:value:)` downstream — so it must not come back.) struct SidebarReorderFollowerView: View { let dragState: SidebarDragState /// The committed render list, used to find the picked-up row's content @@ -65,10 +70,6 @@ struct SidebarReorderFollowerView: View { .allowsHitTesting(false) .accessibilityHidden(true) .zIndex(1000) - .transaction { transaction in - transaction.disablesAnimations = true - transaction.animation = nil - } } } From 3bf119633f980d001120d168a6469dc8a607eff1 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 12 Jun 2026 14:27:12 -0700 Subject: [PATCH 27/36] Sidebar gesture reorder: deterministic indent animation + midpoint boundary hitboxes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: the indent/width animation still did not play after removing the transaction blanket, and the in/out boundary at a group's end felt wrong. - The follower's indent is now follower-local @State driven by an explicit withAnimation in onChange(of: previewExtraIndent) — the most deterministic animation mechanism available, with no dependence on .animation(_:value:) transaction semantics. Width and X both derive from the animated value. - The in/out boundary at a group's bottom edge moved from the boundary row's bottom pixel to the MIDPOINT of the space between it and the next row: the "last member" hitbox covers the row's lower half plus half the gap, the "first after group" hitbox the other half plus the next row's top half — two comparably-sized zones with 3pt hysteresis. Co-Authored-By: Claude Fable 5 --- Sources/ContentView.swift | 19 +++++++++++--- .../Sidebar/SidebarReorderFollowerView.swift | 26 ++++++++++++++----- cmuxTests/WorkspaceGroupTests.swift | 5 ++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index d9bfa5d14746..c114ffe9ed8b 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10759,13 +10759,24 @@ final class SidebarDragState { let currentlyIn = previewMembershipGroupId == candidate let isIn: Bool if prevGroup != nil, let prevBand { - let edgeY = prevBand.maxY - isIn = currentlyIn ? cursorY <= edgeY + 2 : cursorY <= edgeY - 2 + // Split at the MIDPOINT of the space between the boundary row's + // bottom and the next row's top: the IN hitbox covers the + // boundary row's lower half PLUS half the gap, the OUT hitbox the + // other half of the gap plus the next row's top half — two + // comparably-sized zones instead of a knife edge at the row's + // bottom pixel. + let edgeY: CGFloat + if let nextBand { + edgeY = (prevBand.maxY + nextBand.minY) / 2 + } else { + edgeY = prevBand.maxY + } + isIn = currentlyIn ? cursorY <= edgeY + 3 : cursorY <= edgeY - 3 } else if let nextBand { // Candidate donated by the row BELOW the slot — mirror the rule // on that row's top edge. - let edgeY = nextBand.minY - isIn = currentlyIn ? cursorY >= edgeY - 2 : cursorY >= edgeY + 2 + let edgeY = prevBand.map { ($0.maxY + nextBand.minY) / 2 } ?? nextBand.minY + isIn = currentlyIn ? cursorY >= edgeY - 3 : cursorY >= edgeY + 3 } else { isIn = currentlyIn } diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift index 66d5fbdc4a69..70afa2443a71 100644 --- a/Sources/Sidebar/SidebarReorderFollowerView.swift +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -34,6 +34,13 @@ struct SidebarReorderFollowerView: View { let previewExtraIndent: CGFloat let rowContent: (SidebarWorkspaceRenderItem) -> AnyView + /// The rendered indent, animated toward `previewExtraIndent` with an + /// EXPLICIT `withAnimation` transaction in `onChange` — the most + /// deterministic animation mechanism available, immune to the + /// transaction-semantics subtleties that kept `.animation(_:value:)` + /// from firing here. + @State private var animatedExtraIndent: CGFloat = 0 + var body: some View { if let draggedId = dragState.draggedTabId, let cursorY = dragState.followerCursorY, @@ -55,16 +62,23 @@ struct SidebarReorderFollowerView: View { rowContent(item) } } - // Width and X are BOTH explicit functions of the previewed + // Width and X are BOTH explicit functions of the animated // indent: tucking into a group slides the row right by the // indent AND narrows it by the same amount (the trailing edge - // stays fixed), animated together on the indent's own axis while - // Y tracking below stays animation-free. - .frame(width: max(frame.width - previewExtraIndent, 0), height: frame.height, alignment: .topLeading) - .padding(.leading, previewExtraIndent) - .animation(.snappy(duration: 0.15, extraBounce: 0), value: previewExtraIndent) + // stays fixed), in one motion, while Y tracking below stays + // animation-free. + .frame(width: max(frame.width - animatedExtraIndent, 0), height: frame.height, alignment: .topLeading) + .padding(.leading, animatedExtraIndent) .frame(width: frame.width, height: frame.height, alignment: .topLeading) .position(x: frame.midX, y: topY + frame.height / 2) + .onAppear { + animatedExtraIndent = previewExtraIndent + } + .onChange(of: previewExtraIndent) { _, newValue in + withAnimation(.snappy(duration: 0.15, extraBounce: 0)) { + animatedExtraIndent = newValue + } + } .shadow(color: Color.black.opacity(0.18), radius: 11, x: 0, y: 5) .opacity(0.97) .allowsHitTesting(false) diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 275c33e439ea..73dbb5e79830 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1234,8 +1234,9 @@ struct WorkspaceGroupTests { drag.updateReorder(cursorY: 95, translationWidth: 0) #expect(drag.previewMembershipGroupId == nil) - // The header's lower half tucks INTO the group as its first slot. - drag.updateReorder(cursorY: 28, translationWidth: 0) + // The header's lower half tucks INTO the group as its first slot + // (clear of the 3pt hysteresis band around the zone edge at y=30). + drag.updateReorder(cursorY: 26, translationWidth: 0) #expect(drag.previewMembershipGroupId == g) drag.clearDrag() From 954d39c581a0e613b18826b63b7d15d0e3432f4c Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 12 Jun 2026 14:51:42 -0700 Subject: [PATCH 28/36] Sidebar gesture reorder: animate the follower indent at its single mutation site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood pinned an asymmetry: the in-place X nudge animated the indent but a vertical drag into a group snapped instantly — the two flips took different view-update paths and the onChange+@State mechanism only survived one of them. The rendered indent is now a SidebarDragState property (followerRenderedIndent) written ONLY by setPreviewMembership, wrapped in an explicit withAnimation there — the same mutation-site pattern the TabManager group morphs use. Every flip path (slot crossing, X nudge) funnels through that one write, so both animate identically by construction. The follower just renders the value; the @State/onChange plumbing and the parent's indent computation are removed. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +- Sources/ContentView.swift | 51 ++++++++-------- .../Sidebar/SidebarReorderFollowerView.swift | 59 +++++-------------- 3 files changed, 44 insertions(+), 70 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 56d312815fc9..f060ae2a5de8 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19642 Sources/ContentView.swift +19654 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -65,8 +65,8 @@ 1410 Sources/CommandPalette/CommandPaletteSearch.swift 1380 cmuxUITests/MenuKeyEquivalentRoutingUITests.swift 1376 cmuxTests/KeyboardShortcutSettingsFileStoreStartupTests.swift +1373 cmuxTests/WorkspaceGroupTests.swift 1372 cmuxTests/AppDelegateIssue2907RoutingTests.swift -1372 cmuxTests/WorkspaceGroupTests.swift 1365 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift 1313 cmuxTests/MobileHostAuthorizationTests.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index c114ffe9ed8b..18b6d623b828 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10445,8 +10445,20 @@ final class SidebarDragState { /// its group, so headers never donate a boundary candidate to the slot /// above them). @ObservationIgnored private var headerBandIds: Set = [] + /// The follower's rendered extra leading indent, RELATIVE to the dragged + /// row's committed indent (+12 tucking into a group, -12 pulling out, 0 + /// unchanged). Driven exclusively by ``setPreviewMembership(_:)`` with an + /// explicit `withAnimation` at that single mutation site, so every way a + /// membership flip can happen (vertical slot crossing, in-place X nudge) + /// animates identically by construction. Read only by the follower + /// overlay. + var followerRenderedIndent: CGFloat = 0 + /// Dragged row's committed membership at drag begin. @ObservationIgnored private var draggedCommittedGroupId: UUID? + /// The committed leading indent matching that membership (member rows + /// are indented); the baseline the rendered indent is relative to. + @ObservationIgnored private var draggedCommittedIndent: CGFloat = 0 /// True while dragging an anchor (membership never changes for anchors). @ObservationIgnored private var draggedIsAnchor = false /// The reorder scope mode pinned at drag begin (anchors reorder in @@ -10533,6 +10545,8 @@ final class SidebarDragState { bandGroupIdById = [:] headerBandIds = [] draggedCommittedGroupId = nil + draggedCommittedIndent = 0 + followerRenderedIndent = 0 draggedIsAnchor = false gestureScopeUsesTopLevelRows = false previewMembershipGroupId = nil @@ -10568,6 +10582,10 @@ final class SidebarDragState { self.bandGroupIdById = bandGroupIdById self.headerBandIds = headerBandIds self.draggedCommittedGroupId = draggedCommittedGroupId + self.draggedCommittedIndent = (draggedCommittedGroupId != nil && !draggedIsAnchor) + ? SidebarWorkspaceGroupingMetrics.memberIndent + : 0 + self.followerRenderedIndent = 0 self.draggedIsAnchor = draggedIsAnchor self.gestureScopeUsesTopLevelRows = usesTopLevelRows // Anchors never change membership; their committed groupId is the @@ -10787,6 +10805,14 @@ final class SidebarDragState { if previewMembershipGroupId != groupId { previewMembershipGroupId = groupId } + let targetIndent: CGFloat = draggedIsAnchor + ? 0 + : (groupId != nil ? SidebarWorkspaceGroupingMetrics.memberIndent : 0) - draggedCommittedIndent + if followerRenderedIndent != targetIndent { + withAnimation(.snappy(duration: 0.15, extraBounce: 0)) { + followerRenderedIndent = targetIndent + } + } } private func buildBands() -> [SidebarReorderIndicatorResolver.Band] { @@ -12883,10 +12909,6 @@ struct VerticalTabsSidebar: View { dragState: dragState, sourceItems: baseRenderItems, rowSpacing: tabRowSpacing, - previewExtraIndent: followerPreviewExtraIndent( - baseRenderItems: baseRenderItems, - previewItems: previewItems - ), rowContent: { item in switch item { case .groupHeader(let group, let memberWorkspaceIds): @@ -12942,27 +12964,6 @@ struct VerticalTabsSidebar: View { } } - /// Extra leading indent the follower previews for the dragged row, - /// relative to its committed indent: positive when the resolved landing - /// membership tucks an ungrouped row into a group, negative when a member - /// is being pulled out, 0 when membership is unchanged. - private func followerPreviewExtraIndent( - baseRenderItems: [SidebarWorkspaceRenderItem], - previewItems: [SidebarWorkspaceRenderItem] - ) -> CGFloat { - guard let draggedId = dragState.draggedTabId, - let committed = baseRenderItems.first(where: { $0.representedWorkspaceId == draggedId }) else { - return 0 - } - let committedIndent: CGFloat = committed.effectiveGroupId != nil - ? SidebarWorkspaceGroupingMetrics.memberIndent - : 0 - let previewIndent: CGFloat = dragState.previewMembershipGroupId != nil - ? SidebarWorkspaceGroupingMetrics.memberIndent - : 0 - return previewIndent - committedIndent - } - private func bonsplitWorkspaceDropOverlay() -> some View { SidebarBonsplitTabWorkspaceDropOverlay( currentSelectedTabId: { diff --git a/Sources/Sidebar/SidebarReorderFollowerView.swift b/Sources/Sidebar/SidebarReorderFollowerView.swift index 70afa2443a71..095d7b7d1b94 100644 --- a/Sources/Sidebar/SidebarReorderFollowerView.swift +++ b/Sources/Sidebar/SidebarReorderFollowerView.swift @@ -10,14 +10,14 @@ import SwiftUI /// a row inside the `LazyVStack`/`ForEach`), its per-frame updates repaint just /// this one view and never invalidate the list body — the property that keeps /// the drag off the https://github.com/manaflow-ai/cmux/issues/2586 thrash path. -/// The cursor tracking stays animation-free by construction: `.position` sits -/// OUTSIDE the indent's `.animation(_:value:)` scope, no other animation -/// modifier covers it, and `followerCursorY` writes are never wrapped in -/// `withAnimation` — so the follower snaps to the cursor with zero lag while -/// the indent/width animate on their own axis. (A blanket -/// `.transaction { disablesAnimations = true }` used to enforce this, but it -/// also suppressed the indent animation — disablesAnimations kills -/// `.animation(_:value:)` downstream — so it must not come back.) +/// +/// The membership indent is NOT animated here: `followerRenderedIndent` is +/// animated at its single mutation site (`SidebarDragState.setPreviewMembership` +/// wraps the write in `withAnimation`), so every way a flip can happen — +/// vertical slot crossing, in-place X nudge — animates identically. This view +/// just renders the value. Cursor tracking stays animation-free because the +/// `followerCursorY` writes are never wrapped in `withAnimation` and no +/// animation modifier covers `.position`. struct SidebarReorderFollowerView: View { let dragState: SidebarDragState /// The committed render list, used to find the picked-up row's content @@ -26,21 +26,8 @@ struct SidebarReorderFollowerView: View { /// Spacing between the header and member rows in a group-block follower, /// matching the list's row spacing. let rowSpacing: CGFloat - /// Extra leading indent previewed for the dragged row at its current - /// landing slot, RELATIVE to its committed indent (positive tucking into - /// a group, negative pulling out, 0 unchanged). Derived by the parent - /// from the resolved membership, so it only changes when the resolved - /// membership does. - let previewExtraIndent: CGFloat let rowContent: (SidebarWorkspaceRenderItem) -> AnyView - /// The rendered indent, animated toward `previewExtraIndent` with an - /// EXPLICIT `withAnimation` transaction in `onChange` — the most - /// deterministic animation mechanism available, immune to the - /// transaction-semantics subtleties that kept `.animation(_:value:)` - /// from firing here. - @State private var animatedExtraIndent: CGFloat = 0 - var body: some View { if let draggedId = dragState.draggedTabId, let cursorY = dragState.followerCursorY, @@ -49,36 +36,22 @@ struct SidebarReorderFollowerView: View { frame.height > 0, let itemIndex = sourceItems.firstIndex(where: { $0.representedWorkspaceId == draggedId }) { let topY = cursorY - dragState.grabOffsetY + let indent = dragState.followerRenderedIndent let blockItems = followerBlockItems(startingAt: itemIndex) - // The indent is applied INSIDE the position-tracked container, on - // its own animation keyed to the indent value: the row slides - // right and narrows when the landing slot crosses into a group - // (and back out), while Y stays glued to the cursor with - // animations disabled. The container is sized to the picked-up - // row's frame and top-aligned, so a group block overflows below - // it without disturbing the cursor anchor math. + // Width and X are BOTH functions of the rendered indent: tucking + // into a group slides the row right by the indent AND narrows it + // by the same amount (the trailing edge stays fixed). The outer + // fixed-size container keeps the cursor anchor math stable; a + // group block overflows below it without clipping. VStack(alignment: .leading, spacing: rowSpacing) { ForEach(blockItems, id: \.representedWorkspaceId) { item in rowContent(item) } } - // Width and X are BOTH explicit functions of the animated - // indent: tucking into a group slides the row right by the - // indent AND narrows it by the same amount (the trailing edge - // stays fixed), in one motion, while Y tracking below stays - // animation-free. - .frame(width: max(frame.width - animatedExtraIndent, 0), height: frame.height, alignment: .topLeading) - .padding(.leading, animatedExtraIndent) + .frame(width: max(frame.width - indent, 0), height: frame.height, alignment: .topLeading) + .padding(.leading, indent) .frame(width: frame.width, height: frame.height, alignment: .topLeading) .position(x: frame.midX, y: topY + frame.height / 2) - .onAppear { - animatedExtraIndent = previewExtraIndent - } - .onChange(of: previewExtraIndent) { _, newValue in - withAnimation(.snappy(duration: 0.15, extraBounce: 0)) { - animatedExtraIndent = newValue - } - } .shadow(color: Color.black.opacity(0.18), radius: 11, x: 0, y: 5) .opacity(0.97) .allowsHitTesting(false) From 013577052c32af158f48fc67b1b4fe9bc1bed632 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 12 Jun 2026 15:20:33 -0700 Subject: [PATCH 29/36] Sidebar gesture reorder: touch-triggered slots, spring-loaded collapsed groups Dogfood asks: - The reorder now triggers the moment the dragged row TOUCHES a neighbor instead of when the cursor crosses row midpoints. The slot probe is the follower's leading edge for the current drag direction (top edge moving up, bottom edge moving down) with ~6pt penetration; moving up claims the slot above the touched row, moving down the slot below it. Gaps and the dragged row's own frozen band keep the current slot, which doubles as hysteresis. Still built through SidebarDropPlanner so pinned-tier legality and canonicalization hold, and still hit-tested against frozen frames so there is no feedback. - Spring-loaded collapsed groups: parking the cursor over a collapsed group's header for 600ms mid-drag expands the group (cancellable Task; cancelled when the cursor leaves or the drag ends) so the row can be placed at a specific slot inside, Finder-style. After the expand, the indicator clears and the frozen frame map re-baselines from the expanded committed layout. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 139 +++++++++++++++++- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 4 + cmuxTests/WorkspaceGroupTests.swift | 14 +- 4 files changed, 143 insertions(+), 16 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index f060ae2a5de8..286edbd0bbc7 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19654 Sources/ContentView.swift +19777 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 18b6d623b828..4a6c7812ba4a 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10471,6 +10471,19 @@ final class SidebarDragState { /// earlier in the drag cannot silently bias joins. @ObservationIgnored private var boundarySlotKey: String? @ObservationIgnored private var translationWidthAtBoundaryEntry: CGFloat = 0 + /// Last cursor Y and the persisted vertical drag direction. The reorder + /// probe is the follower's LEADING edge for the current direction, so a + /// touch triggers the swap; direction persists while stationary. + @ObservationIgnored private var lastReorderCursorY: CGFloat? + @ObservationIgnored private var dragDirectionIsUp = false + /// Anchor ids of currently-collapsed groups, for spring-loading: parking + /// the cursor over one mid-drag expands the group so the row can be + /// placed at a specific slot inside (Finder-style spring-loaded folders). + @ObservationIgnored private var collapsedAnchorBandIds: Set = [] + @ObservationIgnored private var springLoadArmedAnchorId: UUID? + @ObservationIgnored private var springLoadTask: Task? + /// Set by the sidebar; performs the model-side expand for a spring-load. + @ObservationIgnored var onSpringLoadExpand: ((UUID) -> Void)? /// The begin-time gesture location in list space. Later cursor positions /// are derived as base + translation + autoscroll delta, because the @@ -10553,6 +10566,12 @@ final class SidebarDragState { boundarySlotKey = nil translationWidthAtBoundaryEntry = 0 lastTranslationWidth = 0 + lastReorderCursorY = nil + dragDirectionIsUp = false + collapsedAnchorBandIds = [] + springLoadArmedAnchorId = nil + springLoadTask?.cancel() + springLoadTask = nil clearDropIndicator() } @@ -10567,6 +10586,7 @@ final class SidebarDragState { scopeBandComposition: [UUID: [UUID]], bandGroupIdById: [UUID: UUID?], headerBandIds: Set, + collapsedAnchorBandIds: Set, draggedCommittedGroupId: UUID?, draggedIsAnchor: Bool, draggedRowFrame: CGRect?, @@ -10581,6 +10601,9 @@ final class SidebarDragState { self.scopeBandComposition = scopeBandComposition self.bandGroupIdById = bandGroupIdById self.headerBandIds = headerBandIds + self.collapsedAnchorBandIds = collapsedAnchorBandIds + self.lastReorderCursorY = nil + self.dragDirectionIsUp = false self.draggedCommittedGroupId = draggedCommittedGroupId self.draggedCommittedIndent = (draggedCommittedGroupId != nil && !draggedIsAnchor) ? SidebarWorkspaceGroupingMetrics.memberIndent @@ -10661,20 +10684,109 @@ final class SidebarDragState { private func recomputeIndicator(cursorY: CGFloat, translationWidth: CGFloat) { guard let draggedTabId else { return } let bands = buildBands() - let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: cursorY, - bands: bands, - draggedId: draggedTabId, - pinnedIds: pinnedIds, - current: dropIndicator, - hysteresisMargin: Self.hysteresisMargin - ) + + // Persisted vertical direction (kept while stationary). + if let last = lastReorderCursorY { + if cursorY < last - 0.5 { + dragDirectionIsUp = true + } else if cursorY > last + 0.5 { + dragDirectionIsUp = false + } + } + lastReorderCursorY = cursorY + + // The reorder probe is the FOLLOWER'S leading edge, not the cursor: + // the swap triggers as soon as the dragged row visually penetrates + // ~6pt into a neighbor, instead of waiting for the cursor to cross + // row midpoints. Moving up claims the slot ABOVE the touched row, + // moving down the slot BELOW it; while the probe sits in a gap (or + // the dragged row's own frozen band) the current slot is kept, which + // is also the hysteresis. + let draggedHeight = draggedRowFrame?.height ?? 0 + let followerTop = cursorY - grabOffsetY + let touchInset: CGFloat = 6 + let probeY = dragDirectionIsUp + ? followerTop + touchInset + : followerTop + draggedHeight - touchInset + + let neighborBands = bands.filter { $0.id != draggedTabId } + let scopeIds = bands.map(\.id) + var indicator = dropIndicator + if let probeBand = neighborBands.first(where: { probeY >= $0.minY && probeY < $0.maxY }) { + // Built through the planner so pinned-tier legality and slot + // canonicalization still apply. + let forcedPointerY: CGFloat = dragDirectionIsUp ? 1 : max(probeBand.height - 1, 1) + indicator = SidebarDropPlanner.indicator( + draggedTabId: draggedTabId, + targetTabId: probeBand.id, + tabIds: scopeIds, + pinnedTabIds: pinnedIds, + pointerY: forcedPointerY, + targetHeight: probeBand.height + ) + } else if let lastBand = neighborBands.last, probeY >= lastBand.maxY { + indicator = SidebarDropPlanner.indicator( + draggedTabId: draggedTabId, + targetTabId: nil, + tabIds: scopeIds, + pinnedTabIds: pinnedIds + ) + } else if let firstBand = neighborBands.first, probeY < firstBand.minY { + indicator = SidebarDropPlanner.indicator( + draggedTabId: draggedTabId, + targetTabId: firstBand.id, + tabIds: scopeIds, + pinnedTabIds: pinnedIds, + pointerY: 1, + targetHeight: firstBand.height + ) + } if indicator != dropIndicator { dropIndicator = indicator } + + updateSpringLoad(bands: bands, cursorY: cursorY) resolveMembership(bands: bands, cursorY: cursorY, translationWidth: translationWidth) } + /// Spring-loaded collapsed groups: parking the CURSOR over a collapsed + /// group's header for a short dwell expands the group mid-drag so the + /// row can be placed at a specific slot inside. The dwell is a + /// cancellable Task (cancelled when the cursor leaves the header or the + /// drag ends), per the no-asyncAfter policy. + private func updateSpringLoad( + bands: [SidebarReorderIndicatorResolver.Band], + cursorY: CGFloat + ) { + let hoveredCollapsedAnchorId = bands.first(where: { + collapsedAnchorBandIds.contains($0.id) && cursorY >= $0.minY && cursorY < $0.maxY + })?.id + guard hoveredCollapsedAnchorId != springLoadArmedAnchorId else { return } + springLoadTask?.cancel() + springLoadTask = nil + springLoadArmedAnchorId = hoveredCollapsedAnchorId + guard let anchorId = hoveredCollapsedAnchorId else { return } + springLoadTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .milliseconds(600)) + guard !Task.isCancelled, let self, self.draggedTabId != nil else { return } + self.onSpringLoadExpand?(anchorId) + } + } + + /// Called by the sidebar after a spring-load expanded the group in the + /// model: re-baselines the frozen geometry against the expanded layout. + /// The indicator is cleared first so the next layout pass renders the + /// committed (gapless) order, and the frame map refills from it. + func noteSpringLoadExpanded(anchorId: UUID) { + collapsedAnchorBandIds.remove(anchorId) + springLoadArmedAnchorId = nil + springLoadTask = nil + if dropIndicator != nil { + dropIndicator = nil + } + rowFramesInList = [:] + } + /// Resolves the membership the dragged row will commit with at the /// current landing slot. Interior slots of a group force membership; /// boundary slots (first/last slot of a run, the slot under a memberless @@ -11444,6 +11556,17 @@ struct VerticalTabsSidebar: View { dragAutoScrollController.onDidScroll = { [weak dragState] delta in dragState?.applyAutoScrollDelta(delta) } + // Spring-loaded collapsed groups: a dwell over a collapsed + // header mid-drag expands the group so the row can be placed at + // a specific slot inside. + dragState.onSpringLoadExpand = { [weak tabManager, weak dragState] anchorId in + guard let tabManager, + let group = tabManager.workspaceGroups.first(where: { $0.anchorWorkspaceId == anchorId }) else { return } + withAnimation(SidebarGroupAnimation.collapse) { + tabManager.setWorkspaceGroupCollapsed(groupId: group.id, isCollapsed: false) + } + dragState?.noteSpringLoadExpanded(anchorId: anchorId) + } // Defensive reset: if a prior simulation died without running // its teardown (sidebar unmounted mid-loop, app crash, etc.) the // @State SidebarDragState could carry isSimulated=true into a diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index 582ccc6b3437..4ba90fa54dd8 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -90,6 +90,9 @@ extension VerticalTabsSidebar { uniqueKeysWithValues: renderContext.tabs.map { ($0.id, $0.groupId) } ) let headerBandIds = Set(renderContext.workspaceGroups.map(\.anchorWorkspaceId)) + let collapsedAnchorIds = Set( + renderContext.workspaceGroups.filter(\.isCollapsed).map(\.anchorWorkspaceId) + ) let frame = dragState.rowFramesInList[draggedId] let grabOffsetY = frame.map { startLocationY - $0.minY } ?? 0 #if DEBUG @@ -108,6 +111,7 @@ extension VerticalTabsSidebar { scopeBandComposition: composition, bandGroupIdById: bandGroupIdById, headerBandIds: headerBandIds, + collapsedAnchorBandIds: collapsedAnchorIds, draggedCommittedGroupId: draggedGroupId, draggedIsAnchor: draggedIsAnchor, draggedRowFrame: frame, diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 73dbb5e79830..1613ff620c67 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1223,20 +1223,20 @@ struct WorkspaceGroupTests { cursorY: 225 ) - // Hover the last member's LOWER half: the slot is "after M" and the - // membership hitbox says INSIDE the group (last member). + // Drag UP until the follower's top edge penetrates the member M + // (touch-probe): the slot flips immediately to "before M" — an + // interior slot of the group, so membership is forced IN. drag.updateReorder(cursorY: 70, translationWidth: 0) #expect(drag.dropIndicator != nil) #expect(drag.previewMembershipGroupId == g) - // Slide just past M's bottom edge (over U's top half): SAME insertion - // position, but the second hitbox — first row AFTER the group. + // Reverse DOWN until the follower's bottom edge penetrates the + // ungrouped row U: the slot flips below it — outside the group. drag.updateReorder(cursorY: 95, translationWidth: 0) #expect(drag.previewMembershipGroupId == nil) - // The header's lower half tucks INTO the group as its first slot - // (clear of the 3pt hysteresis band around the zone edge at y=30). - drag.updateReorder(cursorY: 26, translationWidth: 0) + // Back UP into M again: in-group once touched. + drag.updateReorder(cursorY: 60, translationWidth: 0) #expect(drag.previewMembershipGroupId == g) drag.clearDrag() From 256728d768395e026f33aca6adbe8841a3e137fa Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Fri, 12 Jun 2026 15:30:48 -0700 Subject: [PATCH 30/36] Sidebar gesture reorder: one reference point for slot + membership, header join tint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: dragging into a group still felt non-intuitive. Root cause: the slot flipped on the follower's leading edge (touch probe) while the in/out membership zones still measured the CURSOR — two reference points, so the gap moved before the indent did and the row looked like it would not join even when it would. - The membership zones now use the SAME follower-edge probe as the slots: touching a group's interior indents immediately together with the gap, and the boundary sub-zones flip in lockstep with what the user sees. - New affordance: while the resolved landing membership is a group, that group's header shows a soft accent tint (geometry matched to the header pill — radius 4 inside the 6pt gutter, unlike the removed oversized ring), making "release joins this group" unmistakable. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 3 +- Sources/ContentView.swift | 30 ++++++++----------- Sources/SidebarWorkspaceGroupHeaderView.swift | 13 ++++++++ .../VerticalTabsSidebar+WorkspaceGroups.swift | 3 ++ 4 files changed, 30 insertions(+), 19 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 286edbd0bbc7..f25ee775f145 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19777 Sources/ContentView.swift +19771 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -179,6 +179,7 @@ 507 Sources/TerminalControllerTopSupport.swift 506 Packages/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/KeyboardShortcutsSection.swift 506 Sources/App/MainWindowVisibilityController.swift +506 Sources/SidebarWorkspaceGroupHeaderView.swift 505 cmuxUITests/DisplayResolutionRegressionUITests.swift 504 cmuxTests/TerminalNotificationSocketActionTests.swift 502 Sources/CmuxEventPublishing.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 4a6c7812ba4a..8f1d2f15116c 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10746,7 +10746,7 @@ final class SidebarDragState { } updateSpringLoad(bands: bands, cursorY: cursorY) - resolveMembership(bands: bands, cursorY: cursorY, translationWidth: translationWidth) + resolveMembership(bands: bands, probeY: probeY, translationWidth: translationWidth) } /// Spring-loaded collapsed groups: parking the CURSOR over a collapsed @@ -10799,7 +10799,7 @@ final class SidebarDragState { /// it on a purely vertical drag. private func resolveMembership( bands: [SidebarReorderIndicatorResolver.Band], - cursorY: CGFloat, + probeY: CGFloat, translationWidth: CGFloat ) { guard let draggedTabId, !draggedIsAnchor, !dropIndicatorUsesTopLevelRows else { return } @@ -10877,36 +10877,30 @@ final class SidebarDragState { } // Moving boundary slot: TWO stacked hitboxes share this insertion - // position. While the cursor is still over the boundary-adjacent row - // that donated the candidate (its lower half resolved this slot) the - // drop is INSIDE the group ("last member" / "tucked under the - // header"); once the cursor passes that row's bottom edge into the - // gap or the next row's top half, the drop is OUTSIDE ("first row - // after the group"). Deterministic from Y — no horizontal nudge - // needed — with a small hysteresis band at the edge so jitter does - // not flicker the indent. + // position, measured with the SAME probe (the follower's leading + // edge) that drives the slot — one reference point for both, so the + // gap and the indent always flip together. While the probe is still + // over the boundary-adjacent row's run (its lower half plus half the + // gap) the drop is INSIDE the group ("last member" / "tucked under + // the header"); past the gap midpoint it is OUTSIDE ("first row + // after the group"). A small hysteresis band keeps jitter from + // flickering the indent. boundarySlotKey = nil let currentlyIn = previewMembershipGroupId == candidate let isIn: Bool if prevGroup != nil, let prevBand { - // Split at the MIDPOINT of the space between the boundary row's - // bottom and the next row's top: the IN hitbox covers the - // boundary row's lower half PLUS half the gap, the OUT hitbox the - // other half of the gap plus the next row's top half — two - // comparably-sized zones instead of a knife edge at the row's - // bottom pixel. let edgeY: CGFloat if let nextBand { edgeY = (prevBand.maxY + nextBand.minY) / 2 } else { edgeY = prevBand.maxY } - isIn = currentlyIn ? cursorY <= edgeY + 3 : cursorY <= edgeY - 3 + isIn = currentlyIn ? probeY <= edgeY + 3 : probeY <= edgeY - 3 } else if let nextBand { // Candidate donated by the row BELOW the slot — mirror the rule // on that row's top edge. let edgeY = prevBand.map { ($0.maxY + nextBand.minY) / 2 } ?? nextBand.minY - isIn = currentlyIn ? cursorY >= edgeY - 3 : cursorY >= edgeY + 3 + isIn = currentlyIn ? probeY >= edgeY - 3 : probeY >= edgeY + 3 } else { isIn = currentlyIn } diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 27fbf9fd7a9a..21e3808b6d4a 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -15,6 +15,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.isCollapsed == rhs.isCollapsed && lhs.isPinned == rhs.isPinned && lhs.isAnchorActive == rhs.isAnchorActive && + lhs.isMembershipPreviewTarget == rhs.isMembershipPreviewTarget && lhs.memberCount == rhs.memberCount && lhs.groupUnreadCount == rhs.groupUnreadCount && lhs.shortcutDigit == rhs.shortcutDigit && @@ -39,6 +40,11 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isCollapsed: Bool let isPinned: Bool let isAnchorActive: Bool + /// True while a gesture-reorder drag's resolved landing membership is + /// THIS group: releasing now drops the dragged row into it. Rendered as + /// a soft background tint so "you are inside this group" is unmistakable + /// during the drag. + let isMembershipPreviewTarget: Bool let memberCount: Int let groupUnreadCount: Int let shortcutDigit: Int? @@ -237,6 +243,13 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) + .background { + if isMembershipPreviewTarget { + RoundedRectangle(cornerRadius: 4) + .fill(Color.accentColor.opacity(0.14)) + .padding(.horizontal, 6) + } + } .modifier(SidebarReorderRowModifier( enabled: isReorderEnabled, workspaceId: anchorWorkspaceId, diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index e3a1c0f9e681..35da45aba55c 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -64,6 +64,9 @@ extension VerticalTabsSidebar { isCollapsed: group.isCollapsed, isPinned: group.isPinned, isAnchorActive: isAnchorActive, + isMembershipPreviewTarget: role == .list + && dragState.draggedTabId != nil + && dragState.previewMembershipGroupId == group.id, memberCount: memberWorkspaceIds.count, groupUnreadCount: groupUnreadCount, shortcutDigit: shortcutDigit, From a831f017bd691781b9a4b5ed4175d54ac56ba6ea Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 13 Jun 2026 18:34:39 -0700 Subject: [PATCH 31/36] Sidebar reorder: replace the direction-flag probe with a continuous control law MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dogfood: "too sensitive, sometimes two workspaces reorder and jump at once". An ultracode design pass traced it to a discontinuous control function: the probe was the follower's TOP edge when dragging up and the BOTTOM edge when dragging down, so a 0.6pt hand reversal flipped the direction bit and teleported the probe ~38pt (a row height), jumping the slot 2-3 positions in one event. The group in/out boundary used the same teleporting probe, which is why it also felt bistable. The whole slot+membership map is now a monotone step function of ONE scalar against ONE strictly-increasing threshold sequence: - probeY = follower CENTER + a slew-limited velocity lean (EMA, capped at ±(H/2 - 6), moved at most 3pt/event). At rest it is the center (classic iOS reference); at drag speed it leans 6pt inside the leading edge so a row still triggers the swap on contact — with no binary direction state, so a jitter moves the probe ≤ |dY|+3pt instead of a row height. - slot = Schmitt-clamped staircase over neighbor midpoints (4pt dead band): clamp(prev, lo, hi). At most one threshold crosses per event, so two rows can never reorder at once; the memory is consulted only inside a dead band, never as sticky state. - membership = Schmitt around the gap midpoint M, read off the SAME probeY, with M strictly interleaved between the two neighbor midpoints, so descending a group bottom crosses prevMid → M → nextMid as three distinct single steps. The in-place X flip survives as an override only at the dragged row's own slot, keyed on the legalized slot so indicator flicker can't erase accumulated X intent. The pure control math moves into SidebarReorderIndicatorResolver (probe / slot / membershipIn) so the live path is exactly what the tests exercise (the old midpoint+sticky resolver was dead, referenced only by tests). A new SidebarDropPlanner.plan(neighborSlot:) overload feeds the staircase slot through the existing pinned-tier legalization. Spring-load resets the velocity/bias/slot memory so the expansion doesn't blink. Tests: monotone staircase, dead-band hold, jitter-never-moves-slot, per-event single-step sweep, slew bound, rest decay, membership Schmitt, and the planner neighbor-slot mapping. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +- Sources/ContentView.swift | 312 +++++++++--------- Sources/Sidebar/SidebarDropPlanner.swift | 47 +++ .../SidebarReorderIndicatorResolver.swift | 177 +++++----- cmuxTests/WorkspaceGroupTests.swift | 142 +++++--- 5 files changed, 373 insertions(+), 309 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index f25ee775f145..eef731ffdaba 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19771 Sources/ContentView.swift +19759 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -63,9 +63,9 @@ 1496 cmuxUITests/MultiWindowNotificationsUITests.swift 1450 Sources/FileExplorerStore.swift 1410 Sources/CommandPalette/CommandPaletteSearch.swift +1405 cmuxTests/WorkspaceGroupTests.swift 1380 cmuxUITests/MenuKeyEquivalentRoutingUITests.swift 1376 cmuxTests/KeyboardShortcutSettingsFileStoreStartupTests.swift -1373 cmuxTests/WorkspaceGroupTests.swift 1372 cmuxTests/AppDelegateIssue2907RoutingTests.swift 1365 Sources/Feed/FeedButtonStyleDebugWindowController.swift 1362 Sources/CMUXInstalledExtensionSidebarHostView.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 8f1d2f15116c..b2becf4713f1 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10465,17 +10465,25 @@ final class SidebarDragState { /// top-level space). Read by the preview builder; safe non-observed /// because it only changes together with `draggedTabId`. @ObservationIgnored var gestureScopeUsesTopLevelRows = false - /// Identity of the boundary slot the drag currently hovers plus the - /// translation width when it was entered. The X membership gesture is - /// measured RELATIVE to slot entry, so horizontal drift accumulated - /// earlier in the drag cannot silently bias joins. - @ObservationIgnored private var boundarySlotKey: String? + /// Translation width captured when the current legalized slot was entered; + /// the in-place X membership flip is measured relative to it so horizontal + /// drift accumulated in an earlier slot cannot silently bias a join. @ObservationIgnored private var translationWidthAtBoundaryEntry: CGFloat = 0 - /// Last cursor Y and the persisted vertical drag direction. The reorder - /// probe is the follower's LEADING edge for the current direction, so a - /// touch triggers the swap; direction persists while stationary. + /// Previous cursor Y, used only to derive the per-event vertical delta `dY` + /// that feeds the velocity estimate. @ObservationIgnored private var lastReorderCursorY: CGFloat? - @ObservationIgnored private var dragDirectionIsUp = false + /// Low-passed vertical velocity and the slew-limited probe bias. Together + /// they lean the probe toward the follower's leading edge at drag speed and + /// back to the center at rest, CONTINUOUSLY — there is no binary direction + /// flag, which is what removes the old ~38pt jitter teleport. + @ObservationIgnored private var velocityEMA: CGFloat = 0 + @ObservationIgnored private var probeBias: CGFloat = 0 + /// Raw Schmitt memory for the slot staircase (neighbor-space). Consulted + /// only inside a threshold dead band; nil seeds from the committed slot. + @ObservationIgnored private var schmittSlot: Int? + /// The legalized neighbor slot the membership rule last saw; the X-flip + /// baseline re-anchors whenever it changes. + @ObservationIgnored private var lastLegalSlot: Int? /// Anchor ids of currently-collapsed groups, for spring-loading: parking /// the cursor over one mid-drag expands the group so the row can be /// placed at a specific slot inside (Finder-style spring-loaded folders). @@ -10494,10 +10502,6 @@ final class SidebarDragState { /// into every translation-derived cursor position. @ObservationIgnored var autoScrollAccumulatedDelta: CGFloat = 0 - /// Dead-zone half-width around a row midpoint within which the landing edge - /// is held, so the gap does not flicker on sub-pixel jitter. - static let hysteresisMargin: CGFloat = 6 - init() {} /// Pushes the latest rendered row frames. While a drag is active the @@ -10563,11 +10567,13 @@ final class SidebarDragState { draggedIsAnchor = false gestureScopeUsesTopLevelRows = false previewMembershipGroupId = nil - boundarySlotKey = nil translationWidthAtBoundaryEntry = 0 lastTranslationWidth = 0 lastReorderCursorY = nil - dragDirectionIsUp = false + velocityEMA = 0 + probeBias = 0 + schmittSlot = nil + lastLegalSlot = nil collapsedAnchorBandIds = [] springLoadArmedAnchorId = nil springLoadTask?.cancel() @@ -10603,7 +10609,10 @@ final class SidebarDragState { self.headerBandIds = headerBandIds self.collapsedAnchorBandIds = collapsedAnchorBandIds self.lastReorderCursorY = nil - self.dragDirectionIsUp = false + self.velocityEMA = 0 + self.probeBias = 0 + self.schmittSlot = nil + self.lastLegalSlot = nil self.draggedCommittedGroupId = draggedCommittedGroupId self.draggedCommittedIndent = (draggedCommittedGroupId != nil && !draggedIsAnchor) ? SidebarWorkspaceGroupingMetrics.memberIndent @@ -10615,7 +10624,6 @@ final class SidebarDragState { // group they HEAD, not one they could join, so the preview membership // (which drives follower indent) must stay nil for them. self.previewMembershipGroupId = draggedIsAnchor ? nil : draggedCommittedGroupId - self.boundarySlotKey = nil self.translationWidthAtBoundaryEntry = 0 self.draggedRowFrame = draggedRowFrame self.grabOffsetY = grabOffsetY @@ -10684,69 +10692,72 @@ final class SidebarDragState { private func recomputeIndicator(cursorY: CGFloat, translationWidth: CGFloat) { guard let draggedTabId else { return } let bands = buildBands() - - // Persisted vertical direction (kept while stationary). - if let last = lastReorderCursorY { - if cursorY < last - 0.5 { - dragDirectionIsUp = true - } else if cursorY > last + 0.5 { - dragDirectionIsUp = false - } + // One frame after a spring-load expansion the frozen frame map is + // empty; HOLD the current indicator + membership rather than snapping + // to the committed order, and only track cursorY so the next dY is sane. + guard !bands.isEmpty else { + lastReorderCursorY = cursorY + return } - lastReorderCursorY = cursorY - // The reorder probe is the FOLLOWER'S leading edge, not the cursor: - // the swap triggers as soon as the dragged row visually penetrates - // ~6pt into a neighbor, instead of waiting for the cursor to cross - // row midpoints. Moving up claims the slot ABOVE the touched row, - // moving down the slot BELOW it; while the probe sits in a gap (or - // the dragged row's own frozen band) the current slot is kept, which - // is also the hysteresis. + // ONE continuous scalar drives everything. The probe is the follower + // CENTER plus a slew-limited velocity lean: at rest it is the center + // (classic iOS reference), at drag speed it leans `probeInset` inside + // the leading edge so the ROW touches a neighbor rather than the + // cursor — with no binary direction flag, so a jitter reversal moves + // the probe by at most |dY| + biasSlew (~3.6pt) instead of teleporting + // a row height. + let dY = cursorY - (lastReorderCursorY ?? cursorY) + lastReorderCursorY = cursorY let draggedHeight = draggedRowFrame?.height ?? 0 - let followerTop = cursorY - grabOffsetY - let touchInset: CGFloat = 6 - let probeY = dragDirectionIsUp - ? followerTop + touchInset - : followerTop + draggedHeight - touchInset + let followerCenter = cursorY - grabOffsetY + draggedHeight / 2 + let probed = SidebarReorderIndicatorResolver.probe( + followerCenter: followerCenter, + dY: dY, + height: draggedHeight, + ema: velocityEMA, + bias: probeBias + ) + velocityEMA = probed.ema + probeBias = probed.bias + let probeY = probed.probeY let neighborBands = bands.filter { $0.id != draggedTabId } - let scopeIds = bands.map(\.id) - var indicator = dropIndicator - if let probeBand = neighborBands.first(where: { probeY >= $0.minY && probeY < $0.maxY }) { - // Built through the planner so pinned-tier legality and slot - // canonicalization still apply. - let forcedPointerY: CGFloat = dragDirectionIsUp ? 1 : max(probeBand.height - 1, 1) - indicator = SidebarDropPlanner.indicator( - draggedTabId: draggedTabId, - targetTabId: probeBand.id, - tabIds: scopeIds, - pinnedTabIds: pinnedIds, - pointerY: forcedPointerY, - targetHeight: probeBand.height - ) - } else if let lastBand = neighborBands.last, probeY >= lastBand.maxY { - indicator = SidebarDropPlanner.indicator( - draggedTabId: draggedTabId, - targetTabId: nil, - tabIds: scopeIds, - pinnedTabIds: pinnedIds - ) - } else if let firstBand = neighborBands.first, probeY < firstBand.minY { - indicator = SidebarDropPlanner.indicator( - draggedTabId: draggedTabId, - targetTabId: firstBand.id, - tabIds: scopeIds, - pinnedTabIds: pinnedIds, - pointerY: 1, - targetHeight: firstBand.height - ) - } - if indicator != dropIndicator { - dropIndicator = indicator + let midYs = neighborBands.map(\.midY) + // Committed neighbor slot = number of neighbors above the dragged row's + // frozen band; seeds the staircase so the first event (probe at the own + // center) yields the committed slot with zero motion. + let committedSlot: Int + if let draggedBand = bands.first(where: { $0.id == draggedTabId }) { + committedSlot = neighborBands.prefix(while: { $0.minY < draggedBand.minY }).count + } else { + committedSlot = min(reorderIds.firstIndex(of: draggedTabId) ?? 0, neighborBands.count) + } + let s = SidebarReorderIndicatorResolver.slot( + probeY: probeY, + midYs: midYs, + previous: schmittSlot ?? committedSlot + ) + schmittSlot = s + + let planned = SidebarDropPlanner.plan( + draggedTabId: draggedTabId, + neighborSlot: s, + tabIds: bands.map(\.id), + pinnedTabIds: pinnedIds + ) + if planned.indicator != dropIndicator { + dropIndicator = planned.indicator } updateSpringLoad(bands: bands, cursorY: cursorY) - resolveMembership(bands: bands, probeY: probeY, translationWidth: translationWidth) + resolveMembership( + neighborBands: neighborBands, + probeY: probeY, + legalNeighborSlot: planned.legalNeighborSlot, + isOwnSlot: planned.indicator == nil, + translationWidth: translationWidth + ) } /// Spring-loaded collapsed groups: parking the CURSOR over a collapsed @@ -10785,51 +10796,48 @@ final class SidebarDragState { dropIndicator = nil } rowFramesInList = [:] + // The frozen geometry is about to be rebuilt against the expanded + // layout; reset the velocity/bias/slot memory so the staircase + // re-seeds from the new committed slot instead of carrying a stale + // lean across the discontinuity. previewMembership is deliberately + // held (membership rule 5) so the indent does not blink. + velocityEMA = 0 + probeBias = 0 + schmittSlot = nil + lastLegalSlot = nil + lastReorderCursorY = nil } - /// Resolves the membership the dragged row will commit with at the - /// current landing slot. Interior slots of a group force membership; - /// boundary slots (first/last slot of a run, the slot under a memberless - /// or collapsed header) follow the pointer's X axis — drag right to tuck - /// the row into the group, left to keep it (or pull it) out, in the same - /// motion as the vertical reorder. The X gesture is measured RELATIVE to - /// when the current boundary slot was entered, so horizontal drift - /// accumulated earlier in the drag never silently flips membership, and - /// a grouped member crossing a foreign group's boundary never auto-joins - /// it on a purely vertical drag. + /// Resolves the membership the dragged row will commit with at the current + /// landing slot, off the SAME velocity-biased probe that picks the slot — + /// one reference point, one strictly-increasing threshold sequence, so the + /// gap and the indent flip in lockstep and a single threshold crosses per + /// event. Interior slots of a group force membership; boundary slots use a + /// Schmitt around the gap midpoint `M`. The only horizontal input is the + /// in-place X-flip override at the dragged row's OWN slot (drag right to + /// tuck in / left to pull out without moving vertically), measured relative + /// to the slot the legalized planner reports so indicator flicker can never + /// erase accumulated X intent. private func resolveMembership( - bands: [SidebarReorderIndicatorResolver.Band], + neighborBands: [SidebarReorderIndicatorResolver.Band], probeY: CGFloat, + legalNeighborSlot p: Int, + isOwnSlot: Bool, translationWidth: CGFloat ) { - guard let draggedTabId, !draggedIsAnchor, !dropIndicatorUsesTopLevelRows else { return } - - // The slot's visual neighbors, skipping the dragged row's own - // (frozen) band. With an indicator, the slot is canonicalized to - // "above row X" or the end sentinel; with a nil indicator the row - // sits at its own committed slot — whose neighbors still define a - // boundary, so "drag right/left in place" can flip membership - // without moving (the membership-only drop). - let neighborBands = bands.filter { $0.id != draggedTabId } - var prevBand: SidebarReorderIndicatorResolver.Band? - var nextBand: SidebarReorderIndicatorResolver.Band? - if let dropIndicator { - if let targetId = dropIndicator.tabId, - let targetIndex = neighborBands.firstIndex(where: { $0.id == targetId }) { - nextBand = neighborBands[targetIndex] - prevBand = targetIndex > 0 ? neighborBands[targetIndex - 1] : nil - } else { - prevBand = neighborBands.last - nextBand = nil - } - } else if let ownIndex = bands.firstIndex(where: { $0.id == draggedTabId }) { - prevBand = ownIndex > 0 ? bands[ownIndex - 1] : nil - nextBand = ownIndex + 1 < bands.count ? bands[ownIndex + 1] : nil - } else { - setPreviewMembership(draggedIsAnchor ? nil : draggedCommittedGroupId) - return + guard !draggedIsAnchor, !dropIndicatorUsesTopLevelRows else { return } + + // Re-anchor the X baseline whenever the legalized slot changes (X + // intent is per-slot). Keyed on `p`, not indicator nil-ness, so a + // vertical jiggle that flickers the indicator does not reset it. + if lastLegalSlot != p { + lastLegalSlot = p + translationWidthAtBoundaryEntry = translationWidth } + let prevBand = p > 0 ? neighborBands[p - 1] : nil + let nextBand = p < neighborBands.count ? neighborBands[p] : nil + // A header donates its group to the slot BELOW it (prev side) but // never to the slot above it (next side). let prevGroup: UUID? = prevBand.flatMap { bandGroupIdById[$0.id] ?? nil } @@ -10839,70 +10847,50 @@ final class SidebarDragState { if let prevGroup, prevGroup == nextGroup { // Interior slot: sandwiched inside a group, membership is forced. - boundarySlotKey = nil setPreviewMembership(prevGroup) return } guard let candidate = prevGroup ?? nextGroup else { - boundarySlotKey = nil setPreviewMembership(nil) return } - if dropIndicator == nil { - // Own-slot boundary (no vertical movement): the X axis flips - // membership in place — drag right to tuck into the adjacent - // group, left to pull out, without moving vertically. Measured - // relative to slot entry so earlier drift never biases it. - let slotKey = "own.\(candidate.uuidString)" - if boundarySlotKey != slotKey { - boundarySlotKey = slotKey - translationWidthAtBoundaryEntry = translationWidth - } - let deltaSinceEntry = translationWidth - translationWidthAtBoundaryEntry - let stickyIn = previewMembershipGroupId == candidate - let isIn: Bool - if deltaSinceEntry >= 8 { + // Boundary slot. `M` = midpoint of the physical gap the slot occupies; + // it sits strictly between the two neighbor midpoints, so descending a + // group's bottom edge crosses prevMid (slot advances, still IN), then M + // (membership flips OUT), then nextMid (slot advances) — three single + // steps, the two group-bottom drops as adjacent Y intervals. + let candidateFromAbove = (prevGroup != nil) + let threshold: CGFloat + if let prevBand, let nextBand { + threshold = (prevBand.maxY + nextBand.minY) / 2 + } else if let prevBand { + threshold = prevBand.maxY + } else if let nextBand { + threshold = nextBand.minY + } else { + threshold = probeY + } + var isIn = SidebarReorderIndicatorResolver.membershipIn( + probeY: probeY, + threshold: threshold, + candidateFromAbove: candidateFromAbove, + currentlyIn: previewMembershipGroupId == candidate + ) + + // In-place X override: only at the dragged row's own slot, where there + // is no vertical signal. Re-baselines on each flip so reversing needs a + // fresh nudge. Leaving the own slot vertically is continuous because + // the forced bit becomes the Schmitt seed above. + if isOwnSlot { + let deltaX = translationWidth - translationWidthAtBoundaryEntry + if deltaX >= SidebarReorderIndicatorResolver.Tuning.xFlipThreshold { + if !isIn { translationWidthAtBoundaryEntry = translationWidth } isIn = true - } else if deltaSinceEntry <= -8 { + } else if deltaX <= -SidebarReorderIndicatorResolver.Tuning.xFlipThreshold { + if isIn { translationWidthAtBoundaryEntry = translationWidth } isIn = false - } else { - isIn = stickyIn } - if isIn != stickyIn { - translationWidthAtBoundaryEntry = translationWidth - } - setPreviewMembership(isIn ? candidate : nil) - return - } - - // Moving boundary slot: TWO stacked hitboxes share this insertion - // position, measured with the SAME probe (the follower's leading - // edge) that drives the slot — one reference point for both, so the - // gap and the indent always flip together. While the probe is still - // over the boundary-adjacent row's run (its lower half plus half the - // gap) the drop is INSIDE the group ("last member" / "tucked under - // the header"); past the gap midpoint it is OUTSIDE ("first row - // after the group"). A small hysteresis band keeps jitter from - // flickering the indent. - boundarySlotKey = nil - let currentlyIn = previewMembershipGroupId == candidate - let isIn: Bool - if prevGroup != nil, let prevBand { - let edgeY: CGFloat - if let nextBand { - edgeY = (prevBand.maxY + nextBand.minY) / 2 - } else { - edgeY = prevBand.maxY - } - isIn = currentlyIn ? probeY <= edgeY + 3 : probeY <= edgeY - 3 - } else if let nextBand { - // Candidate donated by the row BELOW the slot — mirror the rule - // on that row's top edge. - let edgeY = prevBand.map { ($0.maxY + nextBand.minY) / 2 } ?? nextBand.minY - isIn = currentlyIn ? probeY >= edgeY - 3 : probeY >= edgeY + 3 - } else { - isIn = currentlyIn } setPreviewMembership(isIn ? candidate : nil) } diff --git a/Sources/Sidebar/SidebarDropPlanner.swift b/Sources/Sidebar/SidebarDropPlanner.swift index d0fa4dfdf26c..81c7390cae14 100644 --- a/Sources/Sidebar/SidebarDropPlanner.swift +++ b/Sources/Sidebar/SidebarDropPlanner.swift @@ -54,6 +54,53 @@ enum SidebarDropPlanner { return indicatorForInsertionPosition(legalInsertionPosition, tabIds: tabIds) } + /// Continuous-control entry for the gesture reorder. Takes a NEIGHBOR-space + /// insertion slot `s` (0...neighborCount, "above neighbor s", s == count is + /// the end sentinel) already chosen by the stable staircase, and returns + /// the legalized drop indicator (nil for a no-op at the dragged row's own + /// slot) plus the legalized neighbor-space slot `p` the membership rule + /// derives its neighbors from. Reuses the SAME legalization + + /// canonicalization chain as ``indicator(...)`` so pinned-tier rules hold; + /// it just skips the pointer/edge derivation, which is what the staircase + /// has already replaced upstream. + /// + /// Neighbor space ↔ tabIds: with the dragged row at `fromIndex`, neighbor + /// `i` is `tabIds[i]` for `i < fromIndex` and `tabIds[i + 1]` after, so a + /// neighbor slot `s` maps to the full-list insertion position `s` (when + /// `s <= fromIndex`) or `s + 1` (after), and the legalized target index + /// equals the legalized neighbor slot. + static func plan( + draggedTabId: UUID, + neighborSlot s: Int, + tabIds: [UUID], + pinnedTabIds: Set, + legalInsertionRange: ClosedRange? = nil + ) -> (indicator: SidebarDropIndicator?, legalNeighborSlot: Int) { + guard tabIds.count > 1, let fromIndex = tabIds.firstIndex(of: draggedTabId) else { + return (nil, max(0, min(s, max(0, tabIds.count - 1)))) + } + let proposed = (s <= fromIndex) ? s : s + 1 + let legalInsertion = legalInsertionPosition( + draggedTabId: draggedTabId, + proposedInsertionPosition: proposed, + tabIds: tabIds, + pinnedTabIds: pinnedTabIds, + legalInsertionRange: legalInsertionRange + ) + let target = resolvedTargetIndex( + from: fromIndex, + insertionPosition: legalInsertion, + totalCount: tabIds.count + ) + // target == fromIndex means the dragged row stays put (no-op): nil + // indicator, but `p` still names the own slot so membership keeps a + // valid neighbor pair. + let indicator: SidebarDropIndicator? = (target == fromIndex) + ? nil + : indicatorForInsertionPosition(legalInsertion, tabIds: tabIds) + return (indicator, target) + } + static func targetIndex( draggedTabId: UUID, targetTabId: UUID?, diff --git a/Sources/Sidebar/SidebarReorderIndicatorResolver.swift b/Sources/Sidebar/SidebarReorderIndicatorResolver.swift index 513bc82cb5a3..c9b414cdc16c 100644 --- a/Sources/Sidebar/SidebarReorderIndicatorResolver.swift +++ b/Sources/Sidebar/SidebarReorderIndicatorResolver.swift @@ -1,15 +1,20 @@ import CoreGraphics import Foundation -/// Maps a drag cursor position to a ``SidebarDropIndicator`` for the gesture -/// driven workspace reorder, with hysteresis so the gap does not flicker when -/// the cursor hovers exactly on a row's midpoint. +/// Pure, unit-testable control math for the gesture-driven workspace reorder. /// -/// Pure and self-contained so it is unit-testable without a running app: the -/// caller passes the reorder-scope rows as vertical bands (already resolved -/// from the live row frames) plus the current cursor Y, all in one coordinate -/// space. Edge/insertion/pinned-tier legality is delegated to -/// ``SidebarDropPlanner``; this type only adds hit-testing and stickiness. +/// The live drag maps two inputs — the follower's vertical position and the +/// horizontal translation — to two outputs: the insertion slot and the group +/// membership the dragged row will commit with. The whole map is a MONOTONE +/// step function of a single scalar (the velocity-biased follower probe `Y`) +/// against one strictly-increasing threshold sequence, so an infinitesimal +/// input change moves at most one decision boundary and two rows can never +/// reorder in the same event. Every persistent decision sits behind a fixed +/// dead band, never sticky state that survives large motion. The slot is fed +/// to ``SidebarDropPlanner`` for pinned-tier legality; this type owns only the +/// stable numeric mapping. (Replaces the old direction-flag probe whose +/// ~38pt teleport on a sub-pixel reversal caused the "two workspaces jump at +/// once" instability.) enum SidebarReorderIndicatorResolver { /// One reorder-scope item's vertical extent in list space. For a top-level /// group drag, a band spans the group header plus all its member rows so @@ -23,93 +28,85 @@ enum SidebarReorderIndicatorResolver { var height: CGFloat { max(maxY - minY, 0) } } - /// Resolves the drop indicator for `cursorY`. - /// - /// - Parameters: - /// - cursorY: cursor Y in the same list space as the band extents. - /// - bands: reorder-scope bands in scope order, contiguous and sorted. - /// - draggedId: the workspace being dragged. - /// - pinnedIds: pinned ids within the scope (tier constraint). - /// - current: the indicator currently shown, used for hysteresis. - /// - hysteresisMargin: half-width of the dead-zone around a band midpoint - /// within which the current edge is kept (points). - /// - Returns: the indicator to show, or nil for a no-op move. - static func resolve( - cursorY: CGFloat, - bands: [Band], - draggedId: UUID, - pinnedIds: Set, - current: SidebarDropIndicator?, - hysteresisMargin: CGFloat - ) -> SidebarDropIndicator? { - guard !bands.isEmpty else { return nil } - let scopeIds = bands.map(\.id) - - // Below every row: append to the end of the scope. - guard let lastBand = bands.last, cursorY <= lastBand.maxY else { - return SidebarDropPlanner.indicator( - draggedTabId: draggedId, - targetTabId: nil, - tabIds: scopeIds, - pinnedTabIds: pinnedIds - ) - } - - // First band whose bottom edge is below the cursor is the target; this - // also assigns the inter-row spacing gap to the lower band. - let targetBand = bands.first(where: { cursorY < $0.maxY }) ?? lastBand - let pointerY = cursorY - targetBand.minY - - let effectivePointerY = stickyPointerY( - pointerY: pointerY, - band: targetBand, - scopeIds: scopeIds, - current: current, - margin: hysteresisMargin - ) + /// Tuning constants for the control law, centralized so the live path and + /// the tests share one source of truth. + enum Tuning { + /// How far inside the follower's leading edge the saturated probe sits. + static let probeInset: CGFloat = 6 + /// Low-pass factor for the velocity estimate (0 = frozen, 1 = raw). + static let emaAlpha: CGFloat = 0.25 + /// Velocity → bias gain before clamping to ±B. + static let biasGain: CGFloat = 1.5 + /// HARD per-event cap on how far the bias may move, the proof that + /// velocity-derived state can never teleport the probe. + static let biasSlew: CGFloat = 3 + /// Half-width of the dead band around each slot threshold. + static let slotDeadBand: CGFloat = 4 + /// Half-width of the dead band around the membership threshold. + static let membershipDeadBand: CGFloat = 4 + /// Horizontal translation needed to force an in-place membership flip. + static let xFlipThreshold: CGFloat = 8 + } - return SidebarDropPlanner.indicator( - draggedTabId: draggedId, - targetTabId: targetBand.id, - tabIds: scopeIds, - pinnedTabIds: pinnedIds, - pointerY: effectivePointerY, - targetHeight: targetBand.height - ) + /// Updates the velocity estimate and slew-limited bias, returning the probe + /// Y. At rest the probe is the follower CENTER (the classic iOS reference); + /// at deliberate drag speed the bias saturates so the probe sits + /// `probeInset` inside the follower's leading edge, giving "the row touches, + /// not the cursor" responsiveness WITHOUT any binary direction state. The + /// bias gets there continuously through the EMA + per-event slew cap, so a + /// jitter reversal moves the probe by at most `|dY| + biasSlew`. + static func probe( + followerCenter: CGFloat, + dY: CGFloat, + height: CGFloat, + ema: CGFloat, + bias: CGFloat + ) -> (probeY: CGFloat, ema: CGFloat, bias: CGFloat) { + let newEMA = ema + Tuning.emaAlpha * (dY - ema) + let maxBias = max(0, height / 2 - Tuning.probeInset) + let biasTarget = min(max(Tuning.biasGain * newEMA, -maxBias), maxBias) + let newBias = min(max(biasTarget, bias - Tuning.biasSlew), bias + Tuning.biasSlew) + return (followerCenter + newBias, newEMA, newBias) } - /// Biases `pointerY` toward the current edge while the cursor sits within - /// `margin` of the band midpoint, so the indicator does not oscillate on - /// sub-pixel jitter at the 50% split. - private static func stickyPointerY( - pointerY: CGFloat, - band: Band, - scopeIds: [UUID], - current: SidebarDropIndicator?, - margin: CGFloat - ) -> CGFloat { - let mid = band.height / 2 - guard margin > 0, abs(pointerY - mid) < margin else { return pointerY } - guard let edge = currentEdge(for: band, scopeIds: scopeIds, current: current) else { - return pointerY + /// Schmitt-clamped staircase slot. `midYs` is the strictly-increasing + /// sequence of neighbor band midpoints; the returned slot is in + /// `0...midYs.count` ("above neighbor s", `count` = end sentinel). `lo`/`hi` + /// are the threshold counts at the two edges of the dead band; clamping the + /// previous slot into `[lo, hi]` means the slot only changes once `probeY` + /// is unambiguously past a threshold (by `deadBand`), and `previous` is + /// consulted ONLY inside a dead band, never as state surviving real motion. + static func slot( + probeY: CGFloat, + midYs: [CGFloat], + previous: Int, + deadBand: CGFloat = Tuning.slotDeadBand + ) -> Int { + var lo = 0 + var hi = 0 + for m in midYs { + if m + deadBand < probeY { lo += 1 } + if m - deadBand < probeY { hi += 1 } } - return edge == .top ? mid - margin : mid + margin + return min(max(previous, lo), hi) } - /// The edge of `band` that the current indicator represents, if any. The - /// planner canonicalizes "after row i" to "top of row i+1" (or the end - /// sentinel), so both forms are matched here. - private static func currentEdge( - for band: Band, - scopeIds: [UUID], - current: SidebarDropIndicator? - ) -> SidebarDropEdge? { - guard let current else { return nil } - if current.tabId == band.id, current.edge == .top { return .top } - guard let index = scopeIds.firstIndex(of: band.id) else { return nil } - let afterId: UUID? = index + 1 < scopeIds.count ? scopeIds[index + 1] : nil - if let afterId, current.tabId == afterId, current.edge == .top { return .bottom } - if afterId == nil, current.tabId == nil, current.edge == .bottom { return .bottom } - return nil + /// Schmitt membership bit at a boundary slot. `threshold` is the midpoint of + /// the physical gap the slot occupies; the bit only flips once `probeY` is + /// past it by `deadBand`. `candidateFromAbove` is true when the candidate + /// group is donated by the row ABOVE the slot (the common case at a group's + /// bottom edge); false when donated from below (a slot directly above a + /// group's first member). + static func membershipIn( + probeY: CGFloat, + threshold: CGFloat, + candidateFromAbove: Bool, + currentlyIn: Bool, + deadBand: CGFloat = Tuning.membershipDeadBand + ) -> Bool { + if candidateFromAbove { + return currentlyIn ? probeY <= threshold + deadBand : probeY <= threshold - deadBand + } + return currentlyIn ? probeY >= threshold - deadBand : probeY >= threshold + deadBand } } diff --git a/cmuxTests/WorkspaceGroupTests.swift b/cmuxTests/WorkspaceGroupTests.swift index 1613ff620c67..a906ce65c57e 100644 --- a/cmuxTests/WorkspaceGroupTests.swift +++ b/cmuxTests/WorkspaceGroupTests.swift @@ -1215,6 +1215,7 @@ struct WorkspaceGroupTests { scopeBandComposition: [:], bandGroupIdById: [h: g, m: g, u: nil, d: nil], headerBandIds: [h], + collapsedAnchorBandIds: [], draggedCommittedGroupId: nil, draggedIsAnchor: false, draggedRowFrame: frames[d], @@ -1304,70 +1305,101 @@ struct WorkspaceGroupTests { } } -/// Covers the gesture-driven reorder hit-testing + hysteresis that -/// `SidebarReorderIndicatorResolver` adds on top of `SidebarDropPlanner`. -@Suite("Sidebar reorder indicator resolver") -struct SidebarReorderIndicatorResolverTests { - private func band(_ id: UUID, _ minY: CGFloat, _ maxY: CGFloat) -> SidebarReorderIndicatorResolver.Band { - .init(id: id, minY: minY, maxY: maxY) +/// Covers the stable control law (`SidebarReorderIndicatorResolver` pure +/// functions + the `SidebarDropPlanner.plan` neighbor-slot overload) that the +/// live gesture reorder runs on. These are the invariants that kill the +/// "two workspaces jump at once" instability: a single threshold sequence, a +/// dead band at every decision, and a slew-limited probe. +@Suite("Sidebar reorder control law") +struct SidebarReorderControlLawTests { + private typealias R = SidebarReorderIndicatorResolver + + @Test func slotIsMonotoneStaircase() { + let midYs: [CGFloat] = [15, 55, 105] + #expect(R.slot(probeY: -50, midYs: midYs, previous: 1) == 0) // above all + #expect(R.slot(probeY: 500, midYs: midYs, previous: 1) == 3) // below all (end) + #expect(R.slot(probeY: 35, midYs: midYs, previous: 0) == 1) // between mid0/mid1 + #expect(R.slot(probeY: 35, midYs: midYs, previous: 3) == 1) // same regardless of memory } - @Test func cursorBelowAllRowsAppendsToEnd() { - let a = UUID(); let b = UUID(); let c = UUID() - let bands = [band(a, 0, 20), band(b, 22, 42), band(c, 44, 64)] - let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: 200, bands: bands, draggedId: a, pinnedIds: [], current: nil, hysteresisMargin: 6 - ) - #expect(indicator?.tabId == nil) - #expect(indicator?.edge == .bottom) + @Test func slotDeadBandHoldsPreviousNearThreshold() { + let midYs: [CGFloat] = [15, 55, 105] + // Within ±4 of mid1 (55): the previous slot is preserved (no flicker). + #expect(R.slot(probeY: 54, midYs: midYs, previous: 1) == 1) + #expect(R.slot(probeY: 54, midYs: midYs, previous: 2) == 2) + // Clearly past the dead band: the memory is overridden. + #expect(R.slot(probeY: 60, midYs: midYs, previous: 1) == 2) + #expect(R.slot(probeY: 50, midYs: midYs, previous: 2) == 1) } - @Test func cursorInTopHalfOfFirstRowTargetsItsTop() { - let a = UUID(); let b = UUID(); let c = UUID() - let bands = [band(a, 0, 20), band(b, 22, 42), band(c, 44, 64)] - // Dragging C; hovering the top half of A should land it before A. - let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: 3, bands: bands, draggedId: c, pinnedIds: [], current: nil, hysteresisMargin: 6 - ) - #expect(indicator?.tabId == a) - #expect(indicator?.edge == .top) + @Test func jitterAroundAThresholdNeverMovesTheSlot() { + // A stationary hand wobbling ±0.6pt across a threshold used to teleport + // the slot by a row height via the direction flag; now the dead band + // freezes it entirely. + let midYs: [CGFloat] = (0..<8).map { CGFloat($0) * 50 + 25 } // 25,75,...,375 + var prev = R.slot(probeY: 175, midYs: midYs, previous: 4) // sit on mid3 + for y in [CGFloat(174.4), 175.6, 174.4, 175.6, 175] { + let s = R.slot(probeY: y, midYs: midYs, previous: prev) + #expect(s == prev) + prev = s + } } - @Test func hysteresisHoldsCurrentEdgeNearMidpoint() { - let a = UUID(); let b = UUID(); let c = UUID() - let bands = [band(a, 0, 20), band(b, 20, 40), band(c, 40, 60)] - // Dragging A. Current landing slot is "after B" (canonicalized to top of C). - let current = SidebarDropIndicator(tabId: c, edge: .top) - // Cursor just above B's midpoint (30) and within the 6pt dead-zone: the - // raw decision flips to "before B", but stickiness keeps the current slot. - let held = SidebarReorderIndicatorResolver.resolve( - cursorY: 29, bands: bands, draggedId: a, pinnedIds: [], current: current, hysteresisMargin: 6 - ) - #expect(held == current) - // With no hysteresis the same cursor flips the slot. - let flipped = SidebarReorderIndicatorResolver.resolve( - cursorY: 29, bands: bands, draggedId: a, pinnedIds: [], current: current, hysteresisMargin: 0 - ) - #expect(flipped != current) + @Test func perEventSweepNeverSkipsASlot() { + let midYs: [CGFloat] = (0..<8).map { CGFloat($0) * 50 + 25 } + var prev = 0 + var y: CGFloat = -20 + while y < 420 { + let s = R.slot(probeY: y, midYs: midYs, previous: prev) + #expect(abs(s - prev) <= 1) // ≤ one position per 10pt step + prev = s + y += 10 + } } - @Test func clearMidpointCrossingFlipsEdge() { - let a = UUID(); let b = UUID(); let c = UUID() - let bands = [band(a, 0, 20), band(b, 20, 40), band(c, 40, 60)] - let current = SidebarDropIndicator(tabId: c, edge: .top) // after B - // Dragging C; cursor well into the top of B (far outside the dead-zone) - // lands before B. - let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: 22, bands: bands, draggedId: c, pinnedIds: [], current: current, hysteresisMargin: 6 - ) - #expect(indicator?.tabId == b) - #expect(indicator?.edge == .top) + @Test func probeBiasIsSlewLimited() { + // A huge dY cannot move the bias more than biasSlew in one event, so the + // probe stays within slew of the follower center on first contact. + let r = R.probe(followerCenter: 100, dY: -200, height: 50, ema: 0, bias: 0) + #expect(abs(r.bias) <= R.Tuning.biasSlew + 0.001) + #expect(abs(r.probeY - 100) <= R.Tuning.biasSlew + 0.001) } - @Test func emptyBandsResolveToNil() { - let indicator = SidebarReorderIndicatorResolver.resolve( - cursorY: 10, bands: [], draggedId: UUID(), pinnedIds: [], current: nil, hysteresisMargin: 6 - ) - #expect(indicator == nil) + @Test func probeBiasDecaysToCenterAtRest() { + var ema: CGFloat = -30 + var bias: CGFloat = -19 + for _ in 0..<25 { + let r = R.probe(followerCenter: 100, dY: 0, height: 50, ema: ema, bias: bias) + ema = r.ema + bias = r.bias + } + #expect(abs(bias) < 0.5) + } + + @Test func membershipSchmittFlipsOnlyPastThreshold() { + // Candidate donated from above (a group's bottom edge), M = 80. + #expect(R.membershipIn(probeY: 70, threshold: 80, candidateFromAbove: true, currentlyIn: false)) + #expect(!R.membershipIn(probeY: 90, threshold: 80, candidateFromAbove: true, currentlyIn: true)) + // Inside the ±4 dead band, the current state holds either way. + #expect(R.membershipIn(probeY: 82, threshold: 80, candidateFromAbove: true, currentlyIn: true)) + #expect(!R.membershipIn(probeY: 82, threshold: 80, candidateFromAbove: true, currentlyIn: false)) + } + + @Test func planMapsNeighborSlotsThroughLegalization() { + let a = UUID(); let b = UUID(); let c = UUID() // dragged = b (fromIndex 1) + let ids = [a, b, c] + let p0 = SidebarDropPlanner.plan(draggedTabId: b, neighborSlot: 0, tabIds: ids, pinnedTabIds: []) + #expect(p0.indicator?.tabId == a) + #expect(p0.indicator?.edge == .top) + #expect(p0.legalNeighborSlot == 0) + + let p1 = SidebarDropPlanner.plan(draggedTabId: b, neighborSlot: 1, tabIds: ids, pinnedTabIds: []) + #expect(p1.indicator == nil) // own slot, no-op + #expect(p1.legalNeighborSlot == 1) + + let p2 = SidebarDropPlanner.plan(draggedTabId: b, neighborSlot: 2, tabIds: ids, pinnedTabIds: []) + #expect(p2.indicator?.tabId == nil) // end sentinel + #expect(p2.indicator?.edge == .bottom) + #expect(p2.legalNeighborSlot == 2) } } From ce61759be9a223b453c484a6b7fae9a3ff21e5cf Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 13 Jun 2026 21:19:01 -0700 Subject: [PATCH 32/36] Sidebar: group header hover background; spring-load auto-collapses on leave Two dogfood asks: - Group headers now show a subtle hover background (primary.opacity(0.05)), matching how workspace rows highlight, so hovering a group reads as interactive. - Spring-loaded collapsed groups now COLLAPSE BACK when the drag leaves them, if they were collapsed at drag begin (Finder spring-loaded folder behavior). Dragging onto a collapsed group's header still expands it after a short dwell (450ms, down from 600); the group's live span (header + now-visible members) is tracked, and once the cursor leaves that span the group re-collapses and re-arms. On drop, the group stays expanded only if the row landed inside it; otherwise it collapses. gestureEnded returns the landed group so the caller can decide. Geometry/velocity state re-baselines on every collapse toggle so the indicator never blinks. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 87 +++++++++++++++---- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 33 +++++-- Sources/SidebarWorkspaceGroupHeaderView.swift | 2 +- 4 files changed, 95 insertions(+), 29 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index eef731ffdaba..1ec79f0007eb 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19759 Sources/ContentView.swift +19810 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index b2becf4713f1..fdf340655f27 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10490,8 +10490,14 @@ final class SidebarDragState { @ObservationIgnored private var collapsedAnchorBandIds: Set = [] @ObservationIgnored private var springLoadArmedAnchorId: UUID? @ObservationIgnored private var springLoadTask: Task? - /// Set by the sidebar; performs the model-side expand for a spring-load. + /// The group THIS drag spring-expanded (it was collapsed at drag begin). + /// Tracked so it can be auto-collapsed again when the cursor leaves it + /// without dropping inside — Finder spring-loaded folder behavior. + @ObservationIgnored private var springAutoExpandedAnchorId: UUID? + @ObservationIgnored var springAutoExpandedGroupId: UUID? + /// Set by the sidebar; expand / collapse the group model-side. @ObservationIgnored var onSpringLoadExpand: ((UUID) -> Void)? + @ObservationIgnored var onSpringLoadCollapse: ((UUID) -> Void)? /// The begin-time gesture location in list space. Later cursor positions /// are derived as base + translation + autoscroll delta, because the @@ -10576,6 +10582,8 @@ final class SidebarDragState { lastLegalSlot = nil collapsedAnchorBandIds = [] springLoadArmedAnchorId = nil + springAutoExpandedAnchorId = nil + springAutoExpandedGroupId = nil springLoadTask?.cancel() springLoadTask = nil clearDropIndicator() @@ -10760,15 +10768,33 @@ final class SidebarDragState { ) } - /// Spring-loaded collapsed groups: parking the CURSOR over a collapsed - /// group's header for a short dwell expands the group mid-drag so the - /// row can be placed at a specific slot inside. The dwell is a - /// cancellable Task (cancelled when the cursor leaves the header or the - /// drag ends), per the no-asyncAfter policy. + /// Spring-loaded collapsed groups. Two halves: (1) if THIS drag has already + /// spring-expanded a group and the cursor has now LEFT that group's span, + /// collapse it again (it was collapsed at drag begin); (2) otherwise, arm a + /// short dwell over a collapsed group's header to expand it so the row can + /// be placed at a specific slot inside (Finder-style). The dwell is a + /// cancellable Task per the no-asyncAfter policy. private func updateSpringLoad( bands: [SidebarReorderIndicatorResolver.Band], cursorY: CGFloat ) { + if let anchorId = springAutoExpandedAnchorId, let groupId = springAutoExpandedGroupId { + // Span of the expanded group = its header band plus its member + // bands (now visible). Collapse once the cursor leaves it. + let groupBands = bands.filter { + $0.id == anchorId || (bandGroupIdById[$0.id] ?? nil) == groupId + } + if let minY = groupBands.map(\.minY).min(), + let maxY = groupBands.map(\.maxY).max() { + let pad: CGFloat = 10 + if cursorY < minY - pad || cursorY > maxY + pad { + onSpringLoadCollapse?(anchorId) + } + } + // While a group is auto-expanded, never arm another expansion. + return + } + let hoveredCollapsedAnchorId = bands.first(where: { collapsedAnchorBandIds.contains($0.id) && cursorY >= $0.minY && cursorY < $0.maxY })?.id @@ -10778,29 +10804,46 @@ final class SidebarDragState { springLoadArmedAnchorId = hoveredCollapsedAnchorId guard let anchorId = hoveredCollapsedAnchorId else { return } springLoadTask = Task { @MainActor [weak self] in - try? await Task.sleep(for: .milliseconds(600)) + try? await Task.sleep(for: .milliseconds(450)) guard !Task.isCancelled, let self, self.draggedTabId != nil else { return } self.onSpringLoadExpand?(anchorId) } } /// Called by the sidebar after a spring-load expanded the group in the - /// model: re-baselines the frozen geometry against the expanded layout. - /// The indicator is cleared first so the next layout pass renders the - /// committed (gapless) order, and the frame map refills from it. - func noteSpringLoadExpanded(anchorId: UUID) { + /// model: re-baselines the frozen geometry against the expanded layout and + /// records the group as auto-expanded so it can be collapsed again on + /// leave. The indicator is cleared first so the next layout pass renders + /// the committed (gapless) order, and the frame map refills from it. + func noteSpringLoadExpanded(anchorId: UUID, groupId: UUID) { collapsedAnchorBandIds.remove(anchorId) springLoadArmedAnchorId = nil springLoadTask = nil + springAutoExpandedAnchorId = anchorId + springAutoExpandedGroupId = groupId + rebaselineFrozenGeometryAfterCollapseChange() + } + + /// Called after an auto-expanded group is collapsed back (the cursor left + /// it mid-drag): re-arm spring-loading for it and re-baseline geometry. + func noteSpringLoadCollapsed(anchorId: UUID) { + collapsedAnchorBandIds.insert(anchorId) + springAutoExpandedAnchorId = nil + springAutoExpandedGroupId = nil + springLoadArmedAnchorId = nil + springLoadTask?.cancel() + springLoadTask = nil + rebaselineFrozenGeometryAfterCollapseChange() + } + + /// Drops the frozen frame map and the velocity/bias/slot memory so the + /// staircase re-seeds from the new committed layout after a collapse + /// toggle, without blinking the membership indent (rule 5: held). + private func rebaselineFrozenGeometryAfterCollapseChange() { if dropIndicator != nil { dropIndicator = nil } rowFramesInList = [:] - // The frozen geometry is about to be rebuilt against the expanded - // layout; reset the velocity/bias/slot memory so the staircase - // re-seeds from the new committed slot instead of carrying a stale - // lean across the discontinuity. previewMembership is deliberately - // held (membership rule 5) so the indent does not blink. velocityEMA = 0 probeBias = 0 schmittSlot = nil @@ -11540,14 +11583,22 @@ struct VerticalTabsSidebar: View { } // Spring-loaded collapsed groups: a dwell over a collapsed // header mid-drag expands the group so the row can be placed at - // a specific slot inside. + // a specific slot inside; leaving it again collapses it back. dragState.onSpringLoadExpand = { [weak tabManager, weak dragState] anchorId in guard let tabManager, let group = tabManager.workspaceGroups.first(where: { $0.anchorWorkspaceId == anchorId }) else { return } withAnimation(SidebarGroupAnimation.collapse) { tabManager.setWorkspaceGroupCollapsed(groupId: group.id, isCollapsed: false) } - dragState?.noteSpringLoadExpanded(anchorId: anchorId) + dragState?.noteSpringLoadExpanded(anchorId: anchorId, groupId: group.id) + } + dragState.onSpringLoadCollapse = { [weak tabManager, weak dragState] anchorId in + guard let tabManager, + let group = tabManager.workspaceGroups.first(where: { $0.anchorWorkspaceId == anchorId }) else { return } + withAnimation(SidebarGroupAnimation.collapse) { + tabManager.setWorkspaceGroupCollapsed(groupId: group.id, isCollapsed: true) + } + dragState?.noteSpringLoadCollapsed(anchorId: anchorId) } // Defensive reset: if a prior simulation died without running // its teardown (sidebar unmounted mid-loop, app crash, etc.) the diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index 4ba90fa54dd8..cad12a194173 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -126,18 +126,32 @@ extension VerticalTabsSidebar { } /// Commits the reorder on drag end, animating the list into the landing - /// slot, then clears the drag state. + /// slot, then clears the drag state. A group that THIS drag spring-expanded + /// is collapsed again unless the dragged row landed inside it. func sidebarReorderGestureEnded(draggedId: UUID) { - defer { - dragState.cancelledReorderTabId = nil - dragState.clearDrag() - dragAutoScrollController.stop() + let autoExpandedGroupId = dragState.springAutoExpandedGroupId + let landedGroupId = commitGestureReorder(draggedId: draggedId) + if let autoExpandedGroupId, landedGroupId != autoExpandedGroupId, + let group = tabManager.workspaceGroups.first(where: { $0.id == autoExpandedGroupId }), + !group.isCollapsed { + withAnimation(SidebarGroupAnimation.collapse) { + tabManager.setWorkspaceGroupCollapsed(groupId: autoExpandedGroupId, isCollapsed: true) + } } + dragState.cancelledReorderTabId = nil + dragState.clearDrag() + dragAutoScrollController.stop() + } + + /// Applies the drop and returns the group the dragged row landed inside + /// (nil for a top-level/anchor move, a no-op, or a drop outside any group). + @discardableResult + private func commitGestureReorder(draggedId: UUID) -> UUID? { guard dragState.draggedTabId == draggedId else { #if DEBUG cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=nil (noop)") #endif - return + return nil } guard let targetIndex = dragState.gestureReorderTargetIndex() else { // No positional move — but the X axis may have flipped membership @@ -161,12 +175,12 @@ extension VerticalTabsSidebar { desiredGroupId: membership ) } - return + return membership } #if DEBUG cmuxDebugLog("sidebar.reorder.end id=\(draggedId.uuidString.prefix(5)) target=nil (noop)") #endif - return + return tabManager.tabs.first(where: { $0.id == draggedId })?.groupId } let usesTopLevelRows = dragState.dropIndicatorUsesTopLevelRows if usesTopLevelRows { @@ -181,7 +195,7 @@ extension VerticalTabsSidebar { usesTopLevelRows: true ) } - return + return nil } // Membership was resolved live (interior slots force it, boundary // slots followed the pointer's X) and is committed explicitly so the @@ -200,6 +214,7 @@ extension VerticalTabsSidebar { desiredGroupId: membership ) } + return membership } /// Maps each reorder-scope id to the rendered rows that compose its hit-test diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 21e3808b6d4a..774aa91753e5 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -231,7 +231,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .background( isAnchorActive ? Color.primary.opacity(0.08) - : Color.clear + : (isHovered ? Color.primary.opacity(0.05) : Color.clear) ) .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) .sidebarShortcutHintOverlay( From 615bfe77a9b8301fa54308ea38ac464b501b06c8 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 13 Jun 2026 21:50:58 -0700 Subject: [PATCH 33/36] Sidebar: highlight the whole group region (header + member rows), not just the header The hover/drop highlight now covers the entire group area. A shared highlightedGroupId drives it: during a drag it is the membership the dragged row would commit to (drop-into target), otherwise the hovered group's id (header hover reports up to the parent). The header and every member row draw a matching full-width accent tint (applied after the member indent so it spans the full width, bled past the 2pt inter-row gap so the group reads as one continuous block). Renames the header's isMembershipPreviewTarget to isGroupHighlighted since it is now hover- or drag-driven. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +-- Sources/ContentView.swift | 26 ++++++++++++++++++- Sources/SidebarWorkspaceGroupHeaderView.swift | 23 +++++++++------- .../VerticalTabsSidebar+WorkspaceGroups.swift | 11 +++++--- 4 files changed, 49 insertions(+), 15 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 1ec79f0007eb..85053e399646 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19810 Sources/ContentView.swift +19834 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -175,11 +175,11 @@ 518 Packages/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift 516 Sources/CmuxConfigExecutor.swift 514 cmuxUITests/UpdatePillUITests.swift +511 Sources/SidebarWorkspaceGroupHeaderView.swift 509 Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerAdditionalPolicies.swift 507 Sources/TerminalControllerTopSupport.swift 506 Packages/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/KeyboardShortcutsSection.swift 506 Sources/App/MainWindowVisibilityController.swift -506 Sources/SidebarWorkspaceGroupHeaderView.swift 505 cmuxUITests/DisplayResolutionRegressionUITests.swift 504 cmuxTests/TerminalNotificationSocketActionTests.swift 502 Sources/CmuxEventPublishing.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index fdf340655f27..a9225ba17ecb 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -11134,6 +11134,10 @@ struct VerticalTabsSidebar: View { ) @ObservedObject private var keyboardShortcutSettingsObserver = KeyboardShortcutSettingsObserver.shared @State var dragState = SidebarDragState() + /// The group whose header the cursor is currently hovering (no drag). + /// Highlights the whole group region; cleared on leave. Not `private`: + /// the group-header builder lives in a sibling file. + @State var hoveredGroupId: UUID? // Bonsplit tab drags arrive through AppKit pasteboard callbacks, not // `SidebarDragState`, so they need a separate transient collection flag. @State private var isBonsplitWorkspaceDropTargetCollectionActive = false @@ -12965,6 +12969,13 @@ struct VerticalTabsSidebar: View { .frame(minHeight: minHeight, alignment: .top) } + /// The group whose entire region (header + member rows) is currently + /// highlighted: during a drag it is the membership the dragged row would + /// commit to (the drop-into target); otherwise the hovered group's id. + var highlightedGroupId: UUID? { + dragState.draggedTabId != nil ? dragState.previewMembershipGroupId : hoveredGroupId + } + @ViewBuilder private func workspaceRows(renderContext: WorkspaceListRenderContext) -> some View { let baseRenderItems = SidebarWorkspaceRenderItem.renderItems( @@ -13030,7 +13041,8 @@ struct VerticalTabsSidebar: View { shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets, isHiddenInDraggedGroupBlock: tab.groupId != nil && dragState.draggedTabId != nil - && tab.groupId.flatMap { renderContext.workspaceGroupById[$0]?.anchorWorkspaceId } == dragState.draggedTabId + && tab.groupId.flatMap { renderContext.workspaceGroupById[$0]?.anchorWorkspaceId } == dragState.draggedTabId, + isInHighlightedGroup: tab.groupId != nil && tab.groupId == highlightedGroupId ) .transition(.sidebarGroupRow) } @@ -13177,6 +13189,7 @@ struct VerticalTabsSidebar: View { renderContext: WorkspaceListRenderContext, shouldCollectWorkspaceDropTargets: Bool, isHiddenInDraggedGroupBlock: Bool = false, + isInHighlightedGroup: Bool = false, role: SidebarWorkspaceRowRenderRole = .list ) -> some View { let index = renderContext.tabIndexById[tab.id] ?? 0 @@ -13323,6 +13336,17 @@ struct VerticalTabsSidebar: View { .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([tab.id])) .sidebarWorkspaceFrameAnchor(id: tab.id, isEnabled: shouldCollectWorkspaceDropTargets) .padding(.leading, indent) + // Whole-group highlight: a full-width tint behind every member + // of the highlighted group (applied AFTER the indent so it + // spans the full row width, and bled 1pt past each edge to + // close the 2pt inter-row gap so the group reads as one block). + .background { + if isInHighlightedGroup { + Color.accentColor.opacity(0.10) + .padding(.horizontal, 6) + .padding(.vertical, -tabRowSpacing / 2) + } + } } } diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 774aa91753e5..a7d48d526307 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -15,7 +15,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { lhs.isCollapsed == rhs.isCollapsed && lhs.isPinned == rhs.isPinned && lhs.isAnchorActive == rhs.isAnchorActive && - lhs.isMembershipPreviewTarget == rhs.isMembershipPreviewTarget && + lhs.isGroupHighlighted == rhs.isGroupHighlighted && lhs.memberCount == rhs.memberCount && lhs.groupUnreadCount == rhs.groupUnreadCount && lhs.shortcutDigit == rhs.shortcutDigit && @@ -40,11 +40,15 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { let isCollapsed: Bool let isPinned: Bool let isAnchorActive: Bool - /// True while a gesture-reorder drag's resolved landing membership is - /// THIS group: releasing now drops the dragged row into it. Rendered as - /// a soft background tint so "you are inside this group" is unmistakable - /// during the drag. - let isMembershipPreviewTarget: Bool + /// True while the WHOLE group region (this header plus its member rows) + /// should read as highlighted: either a gesture drag's resolved landing + /// membership is THIS group (drop-into target), or the cursor is hovering + /// the group. The member rows draw the matching tint themselves so the + /// area reads as one block. + let isGroupHighlighted: Bool + /// Reports header hover up to the parent so it can highlight the whole + /// group region (header + members), not just this row. + let onHoverChanged: (Bool) -> Void let memberCount: Int let groupUnreadCount: Int let shortcutDigit: Int? @@ -244,10 +248,10 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) .background { - if isMembershipPreviewTarget { - RoundedRectangle(cornerRadius: 4) - .fill(Color.accentColor.opacity(0.14)) + if isGroupHighlighted { + Color.accentColor.opacity(0.10) .padding(.horizontal, 6) + .padding(.bottom, -rowSpacing / 2) } } .modifier(SidebarReorderRowModifier( @@ -258,6 +262,7 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { )) .onHover { hovering in isHovered = hovering + onHoverChanged(hovering) } .contextMenu { Button( diff --git a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift index 35da45aba55c..eb1fa0ae2b46 100644 --- a/Sources/VerticalTabsSidebar+WorkspaceGroups.swift +++ b/Sources/VerticalTabsSidebar+WorkspaceGroups.swift @@ -64,9 +64,14 @@ extension VerticalTabsSidebar { isCollapsed: group.isCollapsed, isPinned: group.isPinned, isAnchorActive: isAnchorActive, - isMembershipPreviewTarget: role == .list - && dragState.draggedTabId != nil - && dragState.previewMembershipGroupId == group.id, + isGroupHighlighted: role == .list && highlightedGroupId == group.id, + onHoverChanged: { [groupId = group.id] hovering in + if hovering { + hoveredGroupId = groupId + } else if hoveredGroupId == groupId { + hoveredGroupId = nil + } + }, memberCount: memberWorkspaceIds.count, groupUnreadCount: groupUnreadCount, shortcutDigit: shortcutDigit, From e968159baf240b1857c3cf5ed2becd90c9b0c264 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 13 Jun 2026 22:12:45 -0700 Subject: [PATCH 34/36] Sidebar: hovering a nested member also highlights its whole group The whole-group highlight previously only triggered from the header's hover. Member workspace rows now report hover up to hoveredGroupId too (guarded so passing ungrouped rows writes nothing), so hovering any row inside a group lights the entire group region. Drag membership still takes precedence over hover. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 2 +- Sources/ContentView.swift | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 85053e399646..ac5675e0ec66 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -4,7 +4,7 @@ 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift 19875 Sources/Workspace.swift -19834 Sources/ContentView.swift +19845 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index a9225ba17ecb..862893fd8bd8 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -13347,6 +13347,17 @@ struct VerticalTabsSidebar: View { .padding(.vertical, -tabRowSpacing / 2) } } + // Hovering a nested member highlights its whole group too (not + // just the header). Guarded so passing ungrouped rows writes + // nothing. Drag takes precedence over hover in highlightedGroupId. + .onHover { [groupId = tab.groupId] hovering in + let target: UUID? = hovering + ? groupId + : (hoveredGroupId == groupId ? nil : hoveredGroupId) + if hoveredGroupId != target { + hoveredGroupId = target + } + } } } From fc4bc75fcbb093abf60b91bd5a48ef8b4d532e53 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 13 Jun 2026 22:23:07 -0700 Subject: [PATCH 35/36] Sidebar: draw the group highlight as one backdrop behind the rows, not a per-row tint The whole-group highlight was a background tint on each row/header, so it traveled with each workspace during a reorder (gray fragments moving with the dragged/reflowing rows). It is now ONE rounded backdrop drawn behind the rows: each row of the highlighted group emits its bounds under the group id (only when highlighted, so no virtualization cost otherwise), the sidebar unions them into a single rect via backgroundPreferenceValue, and the rows (and the dragged-row follower) sit on top of that fixed region. Reordering moves rows over a stable backdrop instead of dragging tint around. Co-Authored-By: Claude Fable 5 --- .github/swift-file-length-budget.tsv | 4 +- Sources/ContentView.swift | 65 +++++++++++++++---- Sources/SidebarWorkspaceGroupHeaderView.swift | 10 +-- 3 files changed, 59 insertions(+), 20 deletions(-) diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index ac5675e0ec66..273412da144f 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -3,8 +3,8 @@ # Reduce counts as files shrink. CI fails if tracked files exceed this budget. 32576 CLI/cmux.swift 22034 Sources/TerminalController.swift +19888 Sources/ContentView.swift 19875 Sources/Workspace.swift -19845 Sources/ContentView.swift 17920 Sources/AppDelegate.swift 16503 Sources/GhosttyTerminalView.swift 13589 Sources/Panels/BrowserPanel.swift @@ -175,8 +175,8 @@ 518 Packages/CmuxSwiftRender/Tests/CmuxSwiftRenderTests/Corpus/stress-git-review-queue-command-deck.swift 516 Sources/CmuxConfigExecutor.swift 514 cmuxUITests/UpdatePillUITests.swift -511 Sources/SidebarWorkspaceGroupHeaderView.swift 509 Packages/CMUXAgentLaunch/Sources/CMUXAgentLaunch/AgentLaunchSanitizerAdditionalPolicies.swift +507 Sources/SidebarWorkspaceGroupHeaderView.swift 507 Sources/TerminalControllerTopSupport.swift 506 Packages/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/KeyboardShortcutsSection.swift 506 Sources/App/MainWindowVisibilityController.swift diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 862893fd8bd8..6d71ed76a7d4 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -12976,6 +12976,26 @@ struct VerticalTabsSidebar: View { dragState.draggedTabId != nil ? dragState.previewMembershipGroupId : hoveredGroupId } + /// The single rounded backdrop behind the highlighted group, unioned from + /// the bounds its rows emitted. + @ViewBuilder + private func groupHighlightBackdrop(prefs: [UUID: [Anchor]]) -> some View { + GeometryReader { proxy in + if let groupId = highlightedGroupId, + let anchors = prefs[groupId], !anchors.isEmpty { + let rects = anchors.map { proxy[$0] } + let minX = rects.map(\.minX).min() ?? 0 + let maxX = rects.map(\.maxX).max() ?? 0 + let minY = rects.map(\.minY).min() ?? 0 + let maxY = rects.map(\.maxY).max() ?? 0 + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(Color.accentColor.opacity(0.10)) + .frame(width: max(0, (maxX - minX) - 12), height: max(0, maxY - minY)) + .position(x: (minX + maxX) / 2, y: (minY + maxY) / 2) + } + } + } + @ViewBuilder private func workspaceRows(renderContext: WorkspaceListRenderContext) -> some View { let baseRenderItems = SidebarWorkspaceRenderItem.renderItems( @@ -13051,6 +13071,13 @@ struct VerticalTabsSidebar: View { .animation(Self.sidebarReorderAnimation, value: previewItems.map(\.id)) .padding(.vertical, SidebarWorkspaceListMetrics.rowVerticalPadding) .frame(maxWidth: .infinity, alignment: .leading) + // ONE backdrop behind the highlighted group's rows, unioned from the + // member/header bounds the rows emit. Drawn as a background so rows + // (and the dragged-row follower) sit on top of a fixed region instead + // of each carrying its own tint. + .backgroundPreferenceValue(SidebarGroupHighlightBoundsKey.self) { prefs in + groupHighlightBackdrop(prefs: prefs) + } // Gate ONLY the per-row frame-anchor *reader* (the virtualization-defeating // work) behind the drag-active check, and keep the Bonsplit drop-capture @@ -13336,17 +13363,10 @@ struct VerticalTabsSidebar: View { .preference(key: SidebarWorkspaceRowIdsPreferenceKey.self, value: Set([tab.id])) .sidebarWorkspaceFrameAnchor(id: tab.id, isEnabled: shouldCollectWorkspaceDropTargets) .padding(.leading, indent) - // Whole-group highlight: a full-width tint behind every member - // of the highlighted group (applied AFTER the indent so it - // spans the full row width, and bled 1pt past each edge to - // close the 2pt inter-row gap so the group reads as one block). - .background { - if isInHighlightedGroup { - Color.accentColor.opacity(0.10) - .padding(.horizontal, 6) - .padding(.vertical, -tabRowSpacing / 2) - } - } + // Emit this member's bounds for the whole-group backdrop drawn + // behind the rows (not a per-row tint, so it does not travel + // with the row during a reorder). + .sidebarGroupHighlightBounds(groupId: tab.groupId, isHighlighted: isInHighlightedGroup) // Hovering a nested member highlights its whole group too (not // just the header). Guarded so passing ungrouped rows writes // nothing. Drag takes precedence over hover in highlightedGroupId. @@ -13405,6 +13425,29 @@ struct SidebarWorkspaceRowFramePreferenceKey: PreferenceKey { } } +/// Bounds of the rows (header + members) that belong to the currently +/// highlighted group, keyed by group id. The sidebar unions them into ONE +/// backdrop rectangle drawn BEHIND the rows, so the highlight is a fixed +/// region the rows sit on top of rather than a per-row tint that travels with +/// each workspace during a reorder. +struct SidebarGroupHighlightBoundsKey: PreferenceKey { + static let defaultValue: [UUID: [Anchor]] = [:] + + static func reduce(value: inout [UUID: [Anchor]], nextValue: () -> [UUID: [Anchor]]) { + value.merge(nextValue()) { $0 + $1 } + } +} + +extension View { + /// Emits this row's bounds under `groupId` for the whole-group backdrop, + /// only when the row is part of the highlighted group. + func sidebarGroupHighlightBounds(groupId: UUID?, isHighlighted: Bool) -> some View { + anchorPreference(key: SidebarGroupHighlightBoundsKey.self, value: .bounds) { anchor in + (isHighlighted && groupId != nil) ? [groupId!: [anchor]] : [:] + } + } +} + enum ShortcutHintModifierPolicy { static let intentionalHoldDelay: TimeInterval = 0.30 diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index a7d48d526307..1502f9b6f072 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -247,13 +247,9 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { .padding(.horizontal, 6) .background { rowHeightProbe } .shortcutHintVisibilityAnimation(value: showsShortcutHint) - .background { - if isGroupHighlighted { - Color.accentColor.opacity(0.10) - .padding(.horizontal, 6) - .padding(.bottom, -rowSpacing / 2) - } - } + // Emit the header bounds for the whole-group backdrop (drawn behind the + // rows by the sidebar), instead of tinting the header itself. + .sidebarGroupHighlightBounds(groupId: groupId, isHighlighted: isGroupHighlighted) .modifier(SidebarReorderRowModifier( enabled: isReorderEnabled, workspaceId: anchorWorkspaceId, From ccb582b8679eee89125cb7aa58f7f80c4b5339c9 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sun, 14 Jun 2026 19:18:36 -0700 Subject: [PATCH 36/36] WIP: isolated animated group backdrop + sooner last-member catch Backdrop geometry funneled through dragState and read only by the isolated SidebarGroupHighlightBackdropView (sibling background), so per-frame union frames never re-run the sidebar body / LazyVStack (issue #2586). Sooner catch margin when joining a group from outside. Diagnostic grab/membership logs still present (temporary). Co-Authored-By: Claude Opus 4.8 (1M context) --- Sources/ContentView.swift | 181 ++++++++++++++---- .../Sidebar/VerticalTabsSidebar+Reorder.swift | 50 +++-- Sources/SidebarWorkspaceGroupHeaderView.swift | 5 +- 3 files changed, 185 insertions(+), 51 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 6d71ed76a7d4..8ebda1abb6a6 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10438,6 +10438,25 @@ final class SidebarDragState { /// always agree. Observed; changes only when the slot or the X side flips. var previewMembershipGroupId: UUID? + /// Live frames (in the reorder list's named space) of the rows that belong + /// to the currently highlighted group, keyed by group id. Written every + /// layout pass from `SidebarGroupHighlightBoundsKey`, including the + /// intermediate frames of the reflow animation. Read ONLY by the isolated + /// `SidebarGroupHighlightBackdropView`, exactly like `followerCursorY` is + /// read only by the follower: keeping it off the parent body and the rows + /// means the per-frame churn cannot re-run the `LazyVStack` and reintroduce + /// the https://github.com/manaflow-ai/cmux/issues/2586 layout-thrash loop. + var groupHighlightRects: [UUID: [CGRect]] = [:] + + /// Replace the highlighted-group frame map, skipping the observation + /// notification when nothing changed so a static hover/drag does not wake + /// the backdrop view every layout pass. + func updateGroupHighlightRects(_ rects: [UUID: [CGRect]]) { + if groupHighlightRects != rects { + groupHighlightRects = rects + } + } + /// Per-band group identity (a member row's group, a header's group, nil /// for ungrouped rows), used to resolve the landing slot's membership. @ObservationIgnored private var bandGroupIdById: [UUID: UUID?] = [:] @@ -10741,12 +10760,27 @@ final class SidebarDragState { } else { committedSlot = min(reorderIds.firstIndex(of: draggedTabId) ?? 0, neighborBands.count) } + let isFirstEvent = schmittSlot == nil let s = SidebarReorderIndicatorResolver.slot( probeY: probeY, midYs: midYs, previous: schmittSlot ?? committedSlot ) schmittSlot = s +#if DEBUG + if isFirstEvent { + // First event after grab: `s != committedSlot` means the list + // reflows immediately on grab (rows jump). `probeY` far from the + // dragged band's own center means the grab offset / probe is off + // (the follower snaps away from the pointer). + let ownCenter = draggedRowFrame.map { Int($0.midY) } ?? -1 + cmuxDebugLog( + "sidebar.reorder.first cursorY=\(Int(cursorY)) grabOff=\(Int(grabOffsetY)) " + + "probeY=\(Int(probeY)) ownCenter=\(ownCenter) " + + "committedSlot=\(committedSlot) s=\(s) reflowOnGrab=\(s != committedSlot) bands=\(bands.count)" + ) + } +#endif let planned = SidebarDropPlanner.plan( draggedTabId: draggedTabId, @@ -10914,9 +10948,22 @@ final class SidebarDragState { } else { threshold = probeY } + // Joining a group FROM OUTSIDE catches sooner: extend the "in" zone + // toward the approach side by a margin so the membership (and the + // backdrop that follows it) flips while the dragged row is still + // approaching the group's edge, instead of waiting until its center + // reaches the gap. Reordering WITHIN the group keeps the plain + // gap-midpoint threshold. + let joiningFromOutside = draggedCommittedGroupId != candidate + let catchMargin: CGFloat = joiningFromOutside + ? min((draggedRowFrame?.height ?? 0) / 2, 16) + : 0 + let effectiveThreshold = candidateFromAbove + ? threshold + catchMargin + : threshold - catchMargin var isIn = SidebarReorderIndicatorResolver.membershipIn( probeY: probeY, - threshold: threshold, + threshold: effectiveThreshold, candidateFromAbove: candidateFromAbove, currentlyIn: previewMembershipGroupId == candidate ) @@ -12976,26 +13023,6 @@ struct VerticalTabsSidebar: View { dragState.draggedTabId != nil ? dragState.previewMembershipGroupId : hoveredGroupId } - /// The single rounded backdrop behind the highlighted group, unioned from - /// the bounds its rows emitted. - @ViewBuilder - private func groupHighlightBackdrop(prefs: [UUID: [Anchor]]) -> some View { - GeometryReader { proxy in - if let groupId = highlightedGroupId, - let anchors = prefs[groupId], !anchors.isEmpty { - let rects = anchors.map { proxy[$0] } - let minX = rects.map(\.minX).min() ?? 0 - let maxX = rects.map(\.maxX).max() ?? 0 - let minY = rects.map(\.minY).min() ?? 0 - let maxY = rects.map(\.maxY).max() ?? 0 - RoundedRectangle(cornerRadius: 6, style: .continuous) - .fill(Color.accentColor.opacity(0.10)) - .frame(width: max(0, (maxX - minX) - 12), height: max(0, maxY - minY)) - .position(x: (minX + maxX) / 2, y: (minY + maxY) / 2) - } - } - } - @ViewBuilder private func workspaceRows(renderContext: WorkspaceListRenderContext) -> some View { let baseRenderItems = SidebarWorkspaceRenderItem.renderItems( @@ -13054,7 +13081,7 @@ struct VerticalTabsSidebar: View { shouldCollectWorkspaceDropTargets: shouldCollectWorkspaceDropTargets ) .transition(.sidebarGroupRow) - case .workspace(let tab, _): + case .workspace(let tab, let effectiveGroupId): workspaceRow( tab, renderContext: renderContext, @@ -13062,7 +13089,13 @@ struct VerticalTabsSidebar: View { isHiddenInDraggedGroupBlock: tab.groupId != nil && dragState.draggedTabId != nil && tab.groupId.flatMap { renderContext.workspaceGroupById[$0]?.anchorWorkspaceId } == dragState.draggedTabId, - isInHighlightedGroup: tab.groupId != nil && tab.groupId == highlightedGroupId + // Use the preview's EFFECTIVE group, not the committed + // one: the dragged row's placeholder reflows to its + // landing slot with the target group's effectiveGroupId, + // so the backdrop extends to cover where it will land — + // including the LAST slot of the group, which committed + // membership could never reach. + isInHighlightedGroup: effectiveGroupId != nil && effectiveGroupId == highlightedGroupId ) .transition(.sidebarGroupRow) } @@ -13071,13 +13104,6 @@ struct VerticalTabsSidebar: View { .animation(Self.sidebarReorderAnimation, value: previewItems.map(\.id)) .padding(.vertical, SidebarWorkspaceListMetrics.rowVerticalPadding) .frame(maxWidth: .infinity, alignment: .leading) - // ONE backdrop behind the highlighted group's rows, unioned from the - // member/header bounds the rows emit. Drawn as a background so rows - // (and the dragged-row follower) sit on top of a fixed region instead - // of each carrying its own tint. - .backgroundPreferenceValue(SidebarGroupHighlightBoundsKey.self) { prefs in - groupHighlightBackdrop(prefs: prefs) - } // Gate ONLY the per-row frame-anchor *reader* (the virtualization-defeating // work) behind the drag-active check, and keep the Bonsplit drop-capture @@ -13096,6 +13122,24 @@ struct VerticalTabsSidebar: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } .coordinateSpace(.named(SidebarReorderListCoordinateSpace.name)) + // ONE backdrop behind the highlighted group, unioned from the member / + // header frames the rows report in this named space. Drawn as a + // background on the coordinate-space view (so its local origin matches + // the reported frames). The frames are funneled through `dragState` + // (NOT parent @State) and read only by the isolated + // `SidebarGroupHighlightBackdropView`, so the per-frame geometry never + // re-runs the sidebar body / LazyVStack (issue #2586), exactly like the + // follower overlay. The union interpolates as rows join or leave, so the + // height animates without an explicit animation modifier. + .background( + SidebarGroupHighlightBackdropView( + dragState: dragState, + groupId: highlightedGroupId + ) + ) + .onPreferenceChange(SidebarGroupHighlightBoundsKey.self) { rects in + dragState.updateGroupHighlightRects(rects) + } .onPreferenceChange(SidebarReorderRowFrameKey.self) { frames in dragState.updateRowFrames(frames) } @@ -13366,7 +13410,15 @@ struct VerticalTabsSidebar: View { // Emit this member's bounds for the whole-group backdrop drawn // behind the rows (not a per-row tint, so it does not travel // with the row during a reorder). - .sidebarGroupHighlightBounds(groupId: tab.groupId, isHighlighted: isInHighlightedGroup) + // Key by the HIGHLIGHTED group, not the committed one: the + // dragged placeholder's committed group differs from where it + // will land, so keying by committed group would file its bounds + // under the wrong group and the backdrop would not stretch to + // contain its landing slot. + .sidebarGroupHighlightBounds( + groupId: isInHighlightedGroup ? highlightedGroupId : nil, + isHighlighted: isInHighlightedGroup + ) // Hovering a nested member highlights its whole group too (not // just the header). Guarded so passing ungrouped rows writes // nothing. Drag takes precedence over hover in highlightedGroupId. @@ -13431,20 +13483,73 @@ struct SidebarWorkspaceRowFramePreferenceKey: PreferenceKey { /// region the rows sit on top of rather than a per-row tint that travels with /// each workspace during a reorder. struct SidebarGroupHighlightBoundsKey: PreferenceKey { - static let defaultValue: [UUID: [Anchor]] = [:] + static let defaultValue: [UUID: [CGRect]] = [:] - static func reduce(value: inout [UUID: [Anchor]], nextValue: () -> [UUID: [Anchor]]) { + static func reduce(value: inout [UUID: [CGRect]], nextValue: () -> [UUID: [CGRect]]) { value.merge(nextValue()) { $0 + $1 } } } +/// The single rounded backdrop drawn behind the currently highlighted group +/// (header + member rows, and during a drag the dragged row's landing slot). +/// +/// This is the ONLY view that reads `SidebarDragState.groupHighlightRects`, the +/// per-layout-frame union geometry. Like `SidebarReorderFollowerView` and +/// `followerCursorY`, it is a sibling background over the list rather than a row +/// inside the `LazyVStack`/`ForEach`, so its per-frame repaints never invalidate +/// the list body. Lifting these frames into the parent's `@State` instead would +/// re-run the whole sidebar body every animation frame and reintroduce the +/// https://github.com/manaflow-ai/cmux/issues/2586 layout-thrash loop. +/// +/// No explicit `.animation` is needed: the highlighted rows report their frames +/// with a `GeometryReader`, which re-reports the intermediate frames of the +/// list's reflow animation, so the union rect already interpolates as a row +/// joins or leaves the group. The backdrop simply renders the current union +/// every frame, exactly like the follower renders the current cursor. +struct SidebarGroupHighlightBackdropView: View { + let dragState: SidebarDragState + /// The group whose region is highlighted right now (drop-into target during + /// a drag, hovered group otherwise), or nil when nothing is highlighted. + let groupId: UUID? + + var body: some View { + if let groupId, + let rects = dragState.groupHighlightRects[groupId], + !rects.isEmpty { + let minX = rects.map(\.minX).min() ?? 0 + let maxX = rects.map(\.maxX).max() ?? 0 + let minY = rects.map(\.minY).min() ?? 0 + let maxY = rects.map(\.maxY).max() ?? 0 + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(Color.primary.opacity(0.06)) + .frame(width: max(0, (maxX - minX) - 12), height: max(0, maxY - minY)) + .position(x: (minX + maxX) / 2, y: (minY + maxY) / 2) + .allowsHitTesting(false) + .accessibilityHidden(true) + } + } +} + extension View { - /// Emits this row's bounds under `groupId` for the whole-group backdrop, - /// only when the row is part of the highlighted group. + /// Emits this row's frame (in the reorder list's named coordinate space) + /// under `groupId` for the whole-group backdrop, only when the row is part + /// of the highlighted group. A `GeometryReader` (not `anchorPreference`) is + /// used on purpose: it re-reports the row's frame on every layout pass, + /// including the intermediate frames of the reflow animation, so the + /// state-driven backdrop can interpolate its height as a row joins or + /// leaves the group instead of snapping to the final geometry the way an + /// `Anchor` resolves. func sidebarGroupHighlightBounds(groupId: UUID?, isHighlighted: Bool) -> some View { - anchorPreference(key: SidebarGroupHighlightBoundsKey.self, value: .bounds) { anchor in - (isHighlighted && groupId != nil) ? [groupId!: [anchor]] : [:] - } + background( + GeometryReader { proxy in + Color.clear.preference( + key: SidebarGroupHighlightBoundsKey.self, + value: (isHighlighted && groupId != nil) + ? [groupId!: [proxy.frame(in: .named(SidebarReorderListCoordinateSpace.name))]] + : [:] + ) + } + ) } } diff --git a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift index cad12a194173..3620419dee87 100644 --- a/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift +++ b/Sources/Sidebar/VerticalTabsSidebar+Reorder.swift @@ -36,9 +36,9 @@ extension VerticalTabsSidebar { /// /// - Parameters: /// - draggedId: the workspace (or group anchor) being dragged. - /// - startLocationY: the gesture's start Y in the reorder list space. - /// Trustworthy only on the begin event (it re-converts with current - /// geometry on later events). + /// - startLocationY: the gesture's start Y in the named list space. No + /// longer used to anchor the drag (it is viewport-wrong under scroll); + /// the anchor is the row's frozen-frame center. Kept for the API shape. /// - translation: the gesture's pointer travel. Height drives the slot, /// width drives boundary-slot group membership (the outliner X axis). func sidebarReorderGestureChanged( @@ -51,9 +51,14 @@ extension VerticalTabsSidebar { // alive until the mouse releases and keeps streaming onChanged; without // this latch the next event would re-begin the cancelled drag. guard dragState.cancelledReorderTabId != draggedId else { return } - let cursorY = (dragState.draggedTabId == draggedId) - ? dragState.reorderTranslationBaseY + translation.height + dragState.autoScrollAccumulatedDelta - : startLocationY + translation.height + // The cursor's CONTENT-space Y = the grab point (frozen frame top + + // within-row offset) + the pure translation + any autoscroll. The + // grab point is captured once at begin into reorderTranslationBaseY, + // so this formula is identical for begin and update and never touches + // the unreliable absolute gesture location. + let updateCursorY = dragState.reorderTranslationBaseY + + translation.height + + dragState.autoScrollAccumulatedDelta if dragState.draggedTabId != draggedId { let usesTopLevelRows = tabManager.sidebarReorderUsesTopLevelRows( forDraggedWorkspaceId: draggedId, @@ -94,13 +99,26 @@ extension VerticalTabsSidebar { renderContext.workspaceGroups.filter(\.isCollapsed).map(\.anchorWorkspaceId) ) let frame = dragState.rowFramesInList[draggedId] - let grabOffsetY = frame.map { startLocationY - $0.minY } ?? 0 + // Anchor to the row's frozen-frame CENTER plus the stable + // translation. With grabOffsetY = height/2 the follower top works + // out to rowMinY + translation, so the row sits at its committed + // spot at grab (no jump) and moves by exactly the drag delta (the + // grabbed point stays under the pointer), and the probe is the + // item center + translation. Nothing here depends on the absolute + // gesture location (viewport-wrong under scroll) or a per-grab + // offset, so it is fully scroll-independent. + let rowCenterY = frame?.midY ?? 0 + let grabOffsetY = (frame?.height ?? 0) / 2 + let beginCursorY = rowCenterY + translation.height #if DEBUG cmuxDebugLog( "sidebar.reorder.begin id=\(draggedId.uuidString.prefix(5)) " + - "startY=\(Int(startLocationY)) cursorY=\(Int(cursorY)) " + + "rowCenterY=\(Int(rowCenterY)) grabOff=\(Int(grabOffsetY)) " + + "cursorY=\(Int(beginCursorY)) followerTop=\(Int(beginCursorY - grabOffsetY)) " + + "transY=\(Int(translation.height)) " + "topLevel=\(usesTopLevelRows) scope=\(reorderIds.count) " + - "frames=\(dragState.rowFramesInList.count) ownFrame=\(frame.map { "\(Int($0.minY))..\(Int($0.maxY))" } ?? "nil")" + "frames=\(dragState.rowFramesInList.count) hasOwnFrame=\(frame != nil) " + + "ownFrame=\(frame.map { "\(Int($0.minY))..\(Int($0.maxY))" } ?? "nil")" ) #endif dragState.beginReorder( @@ -116,11 +134,11 @@ extension VerticalTabsSidebar { draggedIsAnchor: draggedIsAnchor, draggedRowFrame: frame, grabOffsetY: grabOffsetY, - translationBaseY: startLocationY, - cursorY: cursorY + translationBaseY: rowCenterY, + cursorY: beginCursorY ) } else { - dragState.updateReorder(cursorY: cursorY, translationWidth: translation.width) + dragState.updateReorder(cursorY: updateCursorY, translationWidth: translation.width) } dragAutoScrollController.updateFromDragLocation() } @@ -246,6 +264,14 @@ struct SidebarReorderDragModifier: ViewModifier { func body(content: Content) -> some View { content.gesture( + // The named LIST space (not `.local`) so `translation` is measured + // against a FIXED reference and is not corrupted by the dragged + // row's own movement during the drag (which `.local` does — the + // gesture host moves to the preview slot, making `.local` + // translation alternate). The absolute startLocation this space + // reports is unreliable under scroll, so the drag does NOT use it: + // it anchors to the row's frozen-frame center plus this stable + // translation instead. DragGesture(minimumDistance: 6, coordinateSpace: .named(SidebarReorderListCoordinateSpace.name)) .onChanged { value in onChanged(value.startLocation, value.translation) } .onEnded { value in onEnded(value.startLocation, value.translation) } diff --git a/Sources/SidebarWorkspaceGroupHeaderView.swift b/Sources/SidebarWorkspaceGroupHeaderView.swift index 1502f9b6f072..c8ef247c98cc 100644 --- a/Sources/SidebarWorkspaceGroupHeaderView.swift +++ b/Sources/SidebarWorkspaceGroupHeaderView.swift @@ -232,10 +232,13 @@ struct SidebarWorkspaceGroupHeaderView: View, Equatable { } .padding(.vertical, 5) .contentShape(Rectangle()) + // No separate hover tint on the header: hovering anywhere in the group + // (header or a member) draws the single whole-group backdrop behind the + // rows. Only the active-anchor indicator remains here. .background( isAnchorActive ? Color.primary.opacity(0.08) - : (isHovered ? Color.primary.opacity(0.05) : Color.clear) + : Color.clear ) .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) .sidebarShortcutHintOverlay(