Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import CmuxMobileShellModel
import CmuxMobileSupport
import SwiftUI

@MainActor
@Observable
private final class WorkspaceListRefreshPreviewState {
private(set) var generation: UInt64 = 0

func refresh(after delay: Duration) async {
try? await Task.sleep(for: delay)
generation &+= 1
}
}

/// DEBUG-only workspace list fixture for simulator layout screenshots.
///
/// Mounted by the root view when `CMUX_UITEST_WORKSPACE_LIST_PREVIEW=1`.
Expand All @@ -14,6 +25,8 @@ public struct WorkspaceListLayoutPreviewView: View {
@State private var selectedWorkspaceID: MobileWorkspacePreview.ID?
@State private var macSelection: WorkspaceMacSelection = .all
@State private var workspaces: [MobileWorkspacePreview]
@State private var refreshPreviewState = WorkspaceListRefreshPreviewState()
private let refreshDelay: Duration?
// Safety: DEBUG screenshot-only presenter is owned by this preview view and
// only mutates its fired flag from the SwiftUI task that requests the banner.
private let notificationPresenter = ScreenshotNotificationPresenter()
Expand All @@ -23,11 +36,15 @@ public struct WorkspaceListLayoutPreviewView: View {
/// With `CMUX_UITEST_WORKSPACE_LIST_PREVIEW_COUNT=<n>` the fixture seeds
/// `n` deterministic rows (plus `CMUX_UITEST_WORKSPACE_LIST_PREVIEW_GROUPS`
/// leading groups) instead of the static screenshot trio, for scroll
/// measurement.
/// measurement. `CMUX_UITEST_WORKSPACE_LIST_REFRESH_DELAY_MS=<n>` installs
/// a delayed refresh action that toggles the first row's unread state.
public init() {
let environment = ProcessInfo.processInfo.environment
let seedCount = environment["CMUX_UITEST_WORKSPACE_LIST_PREVIEW_COUNT"].flatMap(Int.init) ?? 0
let reorderEnabled = environment["CMUX_UITEST_WORKSPACE_LIST_PREVIEW_REORDER"] == "1"
refreshDelay = environment["CMUX_UITEST_WORKSPACE_LIST_REFRESH_DELAY_MS"]
.flatMap(Int.init)
.map { .milliseconds($0) }
let initialWorkspaces: [MobileWorkspacePreview]
if seedCount > 0 {
let groupCount = environment["CMUX_UITEST_WORKSPACE_LIST_PREVIEW_GROUPS"].flatMap(Int.init) ?? 0
Expand Down Expand Up @@ -74,6 +91,15 @@ public struct WorkspaceListLayoutPreviewView: View {
private let groups: [MobileWorkspaceGroupPreview]
private let reorderEnabled: Bool

private var displayedWorkspaces: [MobileWorkspacePreview] {
guard refreshPreviewState.generation % 2 == 1, !workspaces.isEmpty else {
return workspaces
}
var displayed = workspaces
displayed[0].hasUnread.toggle()
return displayed
}

private static let defaultWorkspaces: [MobileWorkspacePreview] = [
MobileWorkspacePreview(
id: "workspace-main",
Expand Down Expand Up @@ -180,7 +206,7 @@ public struct WorkspaceListLayoutPreviewView: View {
} else {
NavigationStack {
WorkspaceListView(
workspaces: workspaces,
workspaces: displayedWorkspaces,
groups: groups,
selectedWorkspaceID: selectedWorkspaceID,
host: "Visual Mock Mac",
Expand All @@ -199,6 +225,9 @@ public struct WorkspaceListLayoutPreviewView: View {
},
createWorkspace: {},
macSelection: $macSelection,
refresh: refreshDelay.map { delay -> @Sendable () async -> Void in
{ await refreshPreviewState.refresh(after: delay) }
},
renameWorkspace: reorderEnabled ? { id, newName in
if let index = workspaces.firstIndex(where: { $0.id == id }) {
workspaces[index].name = newName
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#if os(iOS)
import Foundation

/// Orders refresh-driven table snapshots ahead of the native refresh collapse.
struct WorkspaceListRefreshLifecycle {
struct RefreshID: Equatable {
fileprivate let rawValue: UInt64
}

struct SnapshotApplyID: Equatable {
fileprivate let rawValue: UInt64
}

private enum Phase: Equatable {
case idle
case refreshing(id: RefreshID, targetGeneration: UInt64)
case awaitingFinalSnapshot(
id: RefreshID,
targetGeneration: UInt64,
latestApplyID: SnapshotApplyID?
)
case collapsing(id: RefreshID)
}

private var phase: Phase = .idle
private var nextRefreshRawValue: UInt64 = 0
private var nextApplyRawValue: UInt64 = 0

var suppressesSnapshotAnimations: Bool {
phase != .idle
}

mutating func begin(currentGeneration: UInt64) -> RefreshID? {
guard phase == .idle else { return nil }
nextRefreshRawValue &+= 1
let id = RefreshID(rawValue: nextRefreshRawValue)
phase = .refreshing(id: id, targetGeneration: currentGeneration &+ 1)
return id
}

mutating func refreshActionCompleted(_ id: RefreshID) -> Bool {
guard case .refreshing(let activeID, let targetGeneration) = phase,
activeID == id else {
return false
}
phase = .awaitingFinalSnapshot(
id: id,
targetGeneration: targetGeneration,
latestApplyID: nil
)
return true
}

mutating func snapshotApplyStarted(
refreshCompletionGeneration: UInt64
) -> SnapshotApplyID? {
guard case .awaitingFinalSnapshot(
let id,
let targetGeneration,
_
) = phase, refreshCompletionGeneration == targetGeneration else {
return nil
}
nextApplyRawValue &+= 1
let applyID = SnapshotApplyID(rawValue: nextApplyRawValue)
phase = .awaitingFinalSnapshot(
id: id,
targetGeneration: targetGeneration,
latestApplyID: applyID
)
return applyID
}

mutating func snapshotApplyCompleted(_ applyID: SnapshotApplyID) -> Bool {
guard case .awaitingFinalSnapshot(
let id,
_,
let latestApplyID
) = phase, latestApplyID == applyID else {
return false
}
phase = .collapsing(id: id)
return true
}

mutating func observeCollapse(
refreshControlIsRefreshing: Bool,
scrollViewIsTracking: Bool,
contentOffsetY: Double,
restingTopY: Double
) {
guard case .collapsing = phase,
!refreshControlIsRefreshing,
!scrollViewIsTracking,
abs(contentOffsetY - restingTopY) <= 0.5
else { return }
phase = .idle
}

mutating func reset() {
phase = .idle
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ struct WorkspaceListTable: UIViewRepresentable {
let showAddDevice: (() -> Void)?
let reconnect: (() -> Void)?
let refresh: (@Sendable () async -> Void)?
let refreshCompletionGeneration: UInt64
let refreshDidComplete: @MainActor () -> Void

func makeCoordinator() -> WorkspaceListTableCoordinator {
WorkspaceListTableCoordinator(configuration: self)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,17 @@ final class WorkspaceListTableCoordinator: NSObject, UITableViewDelegate,
private let sizingCell = UITableViewCell(style: .default, reuseIdentifier: nil)
private var heightCache: [HeightCacheKey: CGFloat] = [:]
private var dropJustCompleted = false
private var refreshLifecycle = WorkspaceListRefreshLifecycle()
private weak var activeRefreshControl: UIRefreshControl?
private weak var tableView: WorkspaceListUITableView?

init(configuration: WorkspaceListTable) {
self.configuration = configuration
super.init()
}

func attach(to tableView: WorkspaceListUITableView) {
self.tableView = tableView
tableView.delegate = self
tableView.dragDelegate = self
tableView.dropDelegate = self
Expand Down Expand Up @@ -95,9 +99,17 @@ final class WorkspaceListTableCoordinator: NSObject, UITableViewDelegate,
snapshot.reconfigureItems(changed)
}
previousConfiguration = next
let animatesSnapshot = tableView.window != nil && !dropJustCompleted
let refreshApplyID = refreshLifecycle.snapshotApplyStarted(
refreshCompletionGeneration: next.refreshCompletionGeneration
)
let animatesSnapshot = tableView.window != nil
&& !dropJustCompleted
&& !refreshLifecycle.suppressesSnapshotAnimations
dropJustCompleted = false
dataSource?.apply(snapshot, animatingDifferences: animatesSnapshot)
dataSource?.apply(snapshot, animatingDifferences: animatesSnapshot) { [weak self] in
guard let refreshApplyID else { return }
self?.refreshSnapshotApplyCompleted(refreshApplyID)
}
}

func tableView(
Expand Down Expand Up @@ -308,9 +320,23 @@ final class WorkspaceListTableCoordinator: NSObject, UITableViewDelegate,
refreshControl.endRefreshing()
return
}
Task { @MainActor in
guard let refreshID = refreshLifecycle.begin(
currentGeneration: configuration.refreshCompletionGeneration
) else { return }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Second pull-to-refresh while collapsing is silently swallowed

If refreshLifecycle.begin() returns nil (phase is anything other than .idle), the method returns early without calling refreshControl.endRefreshing(). During the .collapsing phase isRefreshing is already false so UIKit won't normally let the user initiate a new pull, but if the refresh action is extremely fast (action completes and endRefreshing fires before the user releases their pull gesture), a second UIControlEvents.valueChanged can fire on the same control. In that case the refreshControl is left spinning with no lifecycle entry, no Task, and no future endRefreshing call. Adding refreshControl.endRefreshing() in the else { return } path would prevent the control from hanging.

activeRefreshControl = refreshControl
let refreshDidComplete = configuration.refreshDidComplete
Task { @MainActor [weak self, weak refreshControl] in
await refresh()
refreshControl.endRefreshing()
guard let self else { return }
guard let refreshControl, refreshControl === self.activeRefreshControl else {
self.refreshLifecycle.reset()
self.activeRefreshControl = nil
return
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
guard self.refreshLifecycle.refreshActionCompleted(refreshID) else {
return
}
refreshDidComplete()
}
}

Expand All @@ -325,10 +351,44 @@ final class WorkspaceListTableCoordinator: NSObject, UITableViewDelegate,
)
tableView.refreshControl = refreshControl
} else {
activeRefreshControl?.endRefreshing()
activeRefreshControl = nil
refreshLifecycle.reset()
tableView.refreshControl = nil
}
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
settleRefreshCollapse(in: scrollView)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceListTableCoordinator.swift'

# Map the file structure, then inspect the relevant section.
ast-grep outline "$file" --view expanded || true
echo '---'
sed -n '1,520p' "$file" | cat -n | sed -n '300,430p'

Repository: manaflow-ai/cmux

Length of output: 7419


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceListTableCoordinator.swift'

# Inspect the implementation and nearby delegate methods.
grep -n "settleRefreshCollapse\|scrollViewDid\|endRefreshing\|isTracking\|refresh" "$file" || true
echo '---'
sed -n '1,260p' "$file" | cat -n | sed -n '1,260p'

Repository: manaflow-ai/cmux

Length of output: 15126


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceListTableCoordinator.swift'
nl -ba "$file" | sed -n '320,420p'

Repository: manaflow-ai/cmux

Length of output: 194


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceListTableCoordinator.swift'

echo "[delegate methods]"
grep -nE 'func scrollViewDid|func settleRefreshCollapse|endRefreshing|isTracking' "$file" || true
echo
echo "[context]"
nl -ba "$file" | sed -n '340,390p'

Repository: manaflow-ai/cmux

Length of output: 573


Call settleRefreshCollapse(in:) on drag end too.
scrollViewDidScroll(_:) alone can miss the transition out of isTracking if endRefreshing() happens while the finger is still down and no further offset change occurs, leaving snapshot animation suppression stuck until the next scroll. Add scrollViewDidEndDragging(_:willDecelerate:) here as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceListTableCoordinator.swift`
around lines 361 - 363, Update the scroll-view delegate handling near
scrollViewDidScroll(_:) by adding scrollViewDidEndDragging(_:willDecelerate:)
and call settleRefreshCollapse(in:) with the ending scroll view there,
preserving the existing scrollViewDidScroll behavior.

Source: Coding guidelines

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 collapsing → idle transition has no fallback for animation end

observeCollapse is only invoked from scrollViewDidScroll, which fires on every frame of the UIKit refresh-control collapse animation. If the animation is interrupted mid-flight by a concurrent programmatic setContentOffset (e.g., search-bar appearance, safe-area inset change, or a push navigation triggering a scroll restoration), scrollViewDidEndScrollingAnimation fires for the new scroll but scrollViewDidScroll may not subsequently reach within the 0.5 pt tolerance at the original restingTopY. The lifecycle stays stuck in .collapsing, keeping suppressesSnapshotAnimations = true for all subsequent diffable snapshots until the user manually scrolls. Implementing scrollViewDidEndScrollingAnimation (and scrollViewDidEndDecelerating) to also call settleRefreshCollapse(in:) would cover these interruption paths and make the settlement definitive.


private func refreshSnapshotApplyCompleted(
_ applyID: WorkspaceListRefreshLifecycle.SnapshotApplyID
) {
guard refreshLifecycle.snapshotApplyCompleted(applyID) else { return }
guard let activeRefreshControl else {
refreshLifecycle.reset()
return
}
activeRefreshControl.endRefreshing()
if let tableView {
settleRefreshCollapse(in: tableView)
}
}

private func settleRefreshCollapse(in scrollView: UIScrollView) {
guard refreshLifecycle.suppressesSnapshotAnimations else { return }
refreshLifecycle.observeCollapse(
refreshControlIsRefreshing: activeRefreshControl?.isRefreshing ?? false,
scrollViewIsTracking: scrollView.isTracking,
contentOffsetY: scrollView.contentOffset.y,
restingTopY: -scrollView.adjustedContentInset.top
)
if !refreshLifecycle.suppressesSnapshotAnimations {
activeRefreshControl = nil
}
}

private func workspace(at indexPath: IndexPath) -> MobileWorkspacePreview? {
guard
let item = dataSource?.itemIdentifier(for: indexPath),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,11 @@ extension WorkspaceListView {
retryInitialConnection: initialConnectionTimedOut ? retryInitialConnection : nil,
showAddDevice: initialConnectionTimedOut ? showAddDevice : nil,
reconnect: reconnect,
refresh: refresh
refresh: refresh,
refreshCompletionGeneration: workspaceListRefreshCompletionGeneration,
refreshDidComplete: {
workspaceListRefreshCompletionGeneration &+= 1
}
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ struct WorkspaceListView: View {
@State private var showingShortcutsSettings = false
@State private var showingSettings = false
@State private var showingDeviceTree = false
@State var workspaceListRefreshCompletionGeneration: UInt64 = 0
/// The active row filter (All / Unread), shared-model state behind the
/// toolbar ``WorkspaceListFilterMenu``. Session-transient like a search.
@State var filter: MobileWorkspaceListFilter = .all
Expand Down
Loading