diff --git a/.github/workflows/test-ios.yml b/.github/workflows/test-ios.yml index 7fc640145b66..d5ec652f1be2 100644 --- a/.github/workflows/test-ios.yml +++ b/.github/workflows/test-ios.yml @@ -162,6 +162,10 @@ jobs: run: | swift test --package-path Packages/iOS/CmuxMobilePairedMac + - name: Run CmuxMobileRPC package tests + run: | + swift test --package-path Packages/iOS/CmuxMobileRPC + - name: Run CmuxMobileChanges package tests run: | swift test --package-path Packages/iOS/CmuxMobileChanges diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift index 8347cb2d2c38..3dee9e5b5d5c 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift @@ -104,6 +104,8 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { public let sortIndex: Int /// Terminal rows belonging to this workspace, in spatial order. public let terminals: [Terminal] + /// The workspace's complete pane layout, when the Mac supports pane sync. + public let layout: MobileWorkspaceLayout? /// ``MobileSyncRecord`` identity: the workspace id. public var syncID: String { id } @@ -127,7 +129,8 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { lastActivityAt: Double, hasUnread: Bool, sortIndex: Int, - terminals: [Terminal] + terminals: [Terminal], + layout: MobileWorkspaceLayout? = nil ) { self.id = id self.windowID = windowID @@ -145,6 +148,7 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { self.hasUnread = hasUnread self.sortIndex = sortIndex self.terminals = terminals + self.layout = layout } public init(from decoder: any Decoder) throws { @@ -168,6 +172,7 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { hasUnread = try container.decode(Bool.self, forKey: .hasUnread) sortIndex = try container.decode(Int.self, forKey: .sortIndex) terminals = try container.decode([Terminal].self, forKey: .terminals) + layout = try container.decodeIfPresent(MobileWorkspaceLayout.self, forKey: .layout) } private enum CodingKeys: String, CodingKey { @@ -187,6 +192,7 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { case hasUnread = "has_unread" case sortIndex = "sort_index" case terminals + case layout } } diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift index 244638499c2a..9218cdfb9c83 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift @@ -28,6 +28,61 @@ extension MobileTerminalRenderGridFrame.RowSpan { var gridCellWidth: Int { cellWidth ?? max(1, text.renderGridEstimatedCellWidth) } + + /// Resolves each grapheme to the producer-reported width of this span. + /// + /// Unicode's ambiguous-width characters can occupy one or two terminal + /// cells depending on the producer. The aggregate ``cellWidth`` is the + /// authority; this method distributes that width only when the mapping is + /// unambiguous enough to preserve every grapheme's producer column. + var resolvedCharacterCellWidths: [Int]? { + guard !text.isEmpty, gridCellWidth > 0 else { return nil } + var widths: [Int] = [] + var expandable: [Bool] = [] + var hasUntrustedExpansionCandidate = false + widths.reserveCapacity(text.count) + expandable.reserveCapacity(text.count) + for character in text { + let width = character.renderGridEstimatedCellWidth + let canExpand = character.canExpandForAmbiguousRenderGridWidth + widths.append(width) + expandable.append(canExpand) + if width == 1, + !canExpand, + character.unicodeScalars.contains(where: { + $0.value > 0x7F + && !$0.isRenderGridZeroWidthScalar + }) { + hasUntrustedExpansionCandidate = true + } + } + let total = widths.reduce(0, +) + if total < gridCellWidth { + guard !hasUntrustedExpansionCandidate else { + return nil + } + let expansionCandidates = widths.indices.filter { + widths[$0] < 2 && expandable[$0] + } + let remaining = gridCellWidth - total + guard remaining == expansionCandidates.count else { + return nil + } + for index in expansionCandidates { + widths[index] += 1 + } + } else if total > gridCellWidth { + let contractionCandidates = widths.indices.filter { widths[$0] > 1 } + let excess = total - gridCellWidth + guard excess == contractionCandidates.count else { + return nil + } + for index in contractionCandidates { + widths[index] -= 1 + } + } + return widths + } } extension Character { diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift new file mode 100644 index 000000000000..dc360c5a3f44 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift @@ -0,0 +1,287 @@ +/// A terminal-grid snapshot prepared for a compact pane-map renderer. +public struct MobileTerminalPaneMapPreview: Equatable, Sendable { + /// One terminal column after overlapping spans and wide glyphs are resolved. + public struct Cell: Equatable, Sendable { + /// The grapheme painted at this column, a space for an empty cell, or an + /// empty string when this column continues a wide grapheme. + public let text: String + /// The render-grid style identifier applied to this cell. + public let styleID: Int + /// The number of terminal columns occupied by a glyph-start cell. + /// Continuation cells use zero. + public let columnSpan: Int + + fileprivate init(text: String, styleID: Int, columnSpan: Int) { + self.text = text + self.styleID = styleID + self.columnSpan = columnSpan + } + } + + public let surfaceID: String + public let columns: Int + public let sourceRows: Int + public let firstSourceRow: Int + public let styles: [MobileTerminalRenderGridFrame.Style] + public let stylesByID: [Int: MobileTerminalRenderGridFrame.Style] + public let rows: [[Cell]] + /// Renderer-effective theme captured for this surface, when supplied by + /// the producer. + public let terminalTheme: TerminalTheme? + /// Legacy raw OSC 10 foreground override. + public let terminalForeground: String? + /// Legacy raw OSC 11 background override. + public let terminalBackground: String? + private let usesDECReverseVideo: Bool + + fileprivate init( + surfaceID: String, + columns: Int, + sourceRows: Int, + firstSourceRow: Int, + styles: [MobileTerminalRenderGridFrame.Style], + terminalTheme: TerminalTheme?, + terminalForeground: String?, + terminalBackground: String?, + usesDECReverseVideo: Bool, + rows: [[Cell]] + ) { + self.surfaceID = surfaceID + self.columns = columns + self.sourceRows = sourceRows + self.firstSourceRow = firstSourceRow + self.styles = styles + self.stylesByID = styles.reduce(into: [:]) { result, style in + result[style.id] = style + } + self.terminalTheme = terminalTheme + self.terminalForeground = terminalForeground + self.terminalBackground = terminalBackground + self.usesDECReverseVideo = usesDECReverseVideo + self.rows = rows + } + + /// Plain terminal-width rows retained for text-only consumers and tests. + public var textRows: [String] { + rows.map { $0.map(\.text).joined() } + } + + /// Resolves the terminal theme that painted this preview. + /// + /// Modern producers carry a renderer-effective theme directly. Legacy + /// producers carry raw OSC 10/11 defaults plus DEC reverse-video state, so + /// apply those values to the caller's surface theme before reversing them. + public func resolvedTerminalTheme(fallback: TerminalTheme) -> TerminalTheme { + if let terminalTheme { + return terminalTheme.validatedOrDefault() + } + + var resolved = fallback.validatedOrDefault() + if let foreground = TerminalTheme.canonicalHex(terminalForeground) { + resolved.foreground = foreground + } + if let background = TerminalTheme.canonicalHex(terminalBackground) { + resolved.background = background + } + if usesDECReverseVideo { + swap(&resolved.foreground, &resolved.background) + } + return resolved + } +} + +private struct MutablePaneMapPreviewCell { + var text = " " + var styleID = 0 + var glyphID: Int? + var columnSpan = 1 + + var snapshot: MobileTerminalPaneMapPreview.Cell { + MobileTerminalPaneMapPreview.Cell( + text: text, + styleID: styleID, + columnSpan: columnSpan + ) + } +} + +public extension MobileTerminalRenderGridFrame { + /// Resolves this frame into fixed terminal cells for a compact visual preview. + /// + /// Passing `nil` renders the complete primary-screen history followed by + /// the visible grid. Alternate-screen previews exclude primary scrollback. + /// A finite limit retains the latest history-backed rows, while a preview + /// without history preserves its previous content-aware window. + func paneMapPreview( + maximumRows: Int? = nil + ) -> MobileTerminalPaneMapPreview { + // Resolve mode 5 from its final setting: replay applies modes in order + // (last wins) and theme delivery reads `.last`, so the preview must not + // stay reversed when a later entry disables reverse video. + let usesDECReverseVideo = modes.last { + !$0.ansi && $0.code == 5 + }?.on == true + guard columns > 0, rows > 0 else { + return MobileTerminalPaneMapPreview( + surfaceID: surfaceID, + columns: max(0, columns), + sourceRows: max(0, rows), + firstSourceRow: 0, + styles: styles, + terminalTheme: terminalTheme, + terminalForeground: terminalForeground, + terminalBackground: terminalBackground, + usesDECReverseVideo: usesDECReverseVideo, + rows: [] + ) + } + + let includedScrollbackRows = activeScreen == .primary ? scrollbackRows : 0 + let sourceRows = includedScrollbackRows + rows + var spansByRow: [Int: [RowSpan]] = [:] + var lastSpanRow: Int? + if includedScrollbackRows > 0 { + for span in scrollbackSpans where !span.text.isEmpty { + spansByRow[span.row, default: []].append(span) + lastSpanRow = max(lastSpanRow ?? span.row, span.row) + } + } + for span in rowSpans where !span.text.isEmpty { + let sourceRow = includedScrollbackRows + span.row + spansByRow[sourceRow, default: []].append(span) + lastSpanRow = max(lastSpanRow ?? sourceRow, sourceRow) + } + + let rowRange: Range + if let maximumRows { + guard maximumRows > 0 else { + return MobileTerminalPaneMapPreview( + surfaceID: surfaceID, + columns: columns, + sourceRows: sourceRows, + firstSourceRow: 0, + styles: styles, + terminalTheme: terminalTheme, + terminalForeground: terminalForeground, + terminalBackground: terminalBackground, + usesDECReverseVideo: usesDECReverseVideo, + rows: [] + ) + } + let boundedMaximumRows = min(sourceRows, maximumRows) + if includedScrollbackRows > 0 { + let firstRow = sourceRows - boundedMaximumRows + rowRange = firstRow.. [String] { + paneMapPreview(maximumRows: maximumRows).textRows + } + + private func paneMapPreviewCells( + spans: [RowSpan] + ) -> [MobileTerminalPaneMapPreview.Cell] { + var cells = Array(repeating: MutablePaneMapPreviewCell(), count: columns) + var glyphRanges: [Int: Range] = [:] + var nextGlyphID = 0 + + func clearGlyph(_ glyphID: Int) { + guard let range = glyphRanges.removeValue(forKey: glyphID) else { return } + for column in range where cells[column].glyphID == glyphID { + cells[column] = MutablePaneMapPreviewCell() + } + } + + func place(_ text: String, at column: Int, width: Int, styleID: Int) { + guard width > 0, column >= 0, column < columns else { return } + let endColumn = min(columns, column + width) + let range = column.. 0, + let glyphID = cells[column - 1].glyphID, + let glyphRange = glyphRanges[glyphID] { + cells[glyphRange.lowerBound].text.append(contentsOf: String(character)) + } + continue + } + place(String(character), at: column, width: width, styleID: span.styleID) + column += width + } + } + + return cells.map(\.snapshot) + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift index f569cdf5e984..4f5a66a4597d 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift @@ -387,7 +387,7 @@ public struct MobileTerminalRenderGridReplay: Sendable { return } - guard let widths = sourceCellWidths(for: span.text, targetWidth: span.gridCellWidth) else { + guard let widths = span.resolvedCharacterCellWidths else { appendCursor(row: row, column: span.column, to: &bytes) if let style { bytes.append(sgrBytes(for: style)) @@ -420,59 +420,6 @@ public struct MobileTerminalRenderGridReplay: Sendable { return true } - private func sourceCellWidths( - for text: String, - targetWidth: Int - ) -> [Int]? { - guard !text.isEmpty, targetWidth > 0 else { return nil } - var widths: [Int] = [] - var expandable: [Bool] = [] - var hasUntrustedExpansionCandidate = false - widths.reserveCapacity(text.count) - expandable.reserveCapacity(text.count) - for character in text { - let width = character.renderGridEstimatedCellWidth - let canExpand = character.canExpandForAmbiguousRenderGridWidth - widths.append(width) - expandable.append(canExpand) - if width == 1, - !canExpand, - character.unicodeScalars.contains(where: { - $0.value > 0x7F - && !$0.isRenderGridZeroWidthScalar - }) { - hasUntrustedExpansionCandidate = true - } - } - let total = widths.reduce(0, +) - if total < targetWidth { - guard !hasUntrustedExpansionCandidate else { - return nil - } - var remaining = targetWidth - total - for index in widths.indices where remaining > 0 && widths[index] < 2 { - guard expandable[index] else { - continue - } - widths[index] += 1 - remaining -= 1 - } - guard remaining == 0 else { - return nil - } - } else if total > targetWidth { - var excess = total - targetWidth - for index in widths.indices.reversed() where excess > 0 && widths[index] > 1 { - widths[index] -= 1 - excess -= 1 - } - guard excess == 0 else { - return nil - } - } - return widths - } - private func appendCursor(row: Int?, column: Int, to bytes: inout Data) { if let row { bytes.append(0x1B) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayout.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayout.swift new file mode 100644 index 000000000000..73d5359c3b6c --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayout.swift @@ -0,0 +1,42 @@ +/// A complete, immutable snapshot of one workspace's panes and surface tabs. +public struct MobileWorkspaceLayout: Codable, Equatable, Sendable { + /// The Mac-side pane layout revision. + public let version: Int + + /// The focused pane identifier, when a pane has focus. + public let focusedPaneID: String? + + /// The root of the recursive split tree. + public let root: MobileWorkspaceLayoutNode + + /// Creates a workspace pane-layout snapshot. + /// + /// - Parameters: + /// - version: The Mac-side pane layout revision. + /// - focusedPaneID: The focused pane identifier, when any. + /// - root: The root of the recursive split tree. + public init(version: Int, focusedPaneID: String?, root: MobileWorkspaceLayoutNode) { + self.version = version + self.focusedPaneID = focusedPaneID + self.root = root + } + + /// Adds the user-visible topology to a caller-provided hash. + /// + /// The signature includes split structure and orientation, pane and surface + /// ordering, pane selection, and focused pane. It intentionally excludes + /// divider ratios, the revision number, titles, and surface types so divider + /// drags do not flood layout invalidation while structural changes still do. + /// + /// - Parameter hasher: The hash accumulator to update. + public func hashTopology(into hasher: inout Hasher) { + hasher.combine(focusedPaneID) + root.hashTopology(into: &hasher) + } + + private enum CodingKeys: String, CodingKey { + case version + case focusedPaneID = "focused_pane_id" + case root + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutNode.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutNode.swift new file mode 100644 index 000000000000..b97fa62916ba --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutNode.swift @@ -0,0 +1,63 @@ +/// One recursive node in a synced workspace pane layout. +public indirect enum MobileWorkspaceLayoutNode: Codable, Equatable, Sendable { + /// A branch dividing its rectangle between two child nodes. + case split(MobileWorkspaceLayoutSplit) + + /// A leaf pane containing surface tabs. + case pane(MobileWorkspaceLayoutPane) + + private enum CodingKeys: String, CodingKey { + case kind + } + + private enum Kind: String, Codable { + case split + case pane + } + + /// Decodes a node from the `kind`-discriminated layout wire shape. + /// + /// - Parameter decoder: The decoder for one layout node. + /// - Throws: A decoding error for an unknown kind or malformed node. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + switch try container.decode(Kind.self, forKey: .kind) { + case .split: + self = try .split(MobileWorkspaceLayoutSplit(from: decoder)) + case .pane: + self = try .pane(MobileWorkspaceLayoutPane(from: decoder)) + } + } + + /// Encodes a node into the `kind`-discriminated layout wire shape. + /// + /// - Parameter encoder: The encoder receiving one layout node. + /// - Throws: An encoding error from the destination encoder. + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case let .split(split): + try container.encode(Kind.split, forKey: .kind) + try split.encode(to: encoder) + case let .pane(pane): + try container.encode(Kind.pane, forKey: .kind) + try pane.encode(to: encoder) + } + } + + func hashTopology(into hasher: inout Hasher) { + switch self { + case let .split(split): + hasher.combine(Kind.split.rawValue) + hasher.combine(split.id) + hasher.combine(split.orientation) + split.first.hashTopology(into: &hasher) + split.second.hashTopology(into: &hasher) + case let .pane(pane): + hasher.combine(Kind.pane.rawValue) + hasher.combine(pane.id) + hasher.combine(pane.selectedSurfaceID) + hasher.combine(pane.surfaces.map(\.id)) + } + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutOrientation.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutOrientation.swift new file mode 100644 index 000000000000..63efdd513d95 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutOrientation.swift @@ -0,0 +1,8 @@ +/// The axis along which a workspace split divides its rectangle. +public enum MobileWorkspaceLayoutOrientation: String, Codable, Equatable, Sendable { + /// Places the split's children side by side. + case horizontal + + /// Stacks the split's children vertically. + case vertical +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutPane.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutPane.swift new file mode 100644 index 000000000000..3f2fba2099f8 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutPane.swift @@ -0,0 +1,33 @@ +/// One leaf pane in a synced workspace layout. +public struct MobileWorkspaceLayoutPane: Codable, Equatable, Sendable { + /// The stable pane identifier. + public let id: String + + /// The selected surface identifier, when the pane has a selection. + public let selectedSurfaceID: String? + + /// The pane's surfaces in tab order. + public let surfaces: [MobileWorkspaceLayoutSurface] + + /// Creates a pane snapshot. + /// + /// - Parameters: + /// - id: The stable pane identifier. + /// - selectedSurfaceID: The selected surface identifier, when any. + /// - surfaces: The pane's surfaces in tab order. + public init( + id: String, + selectedSurfaceID: String?, + surfaces: [MobileWorkspaceLayoutSurface] + ) { + self.id = id + self.selectedSurfaceID = selectedSurfaceID + self.surfaces = surfaces + } + + private enum CodingKeys: String, CodingKey { + case id + case selectedSurfaceID = "selected_surface_id" + case surfaces + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSplit.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSplit.swift new file mode 100644 index 000000000000..3773b110e442 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSplit.swift @@ -0,0 +1,39 @@ +/// One branch split in a synced workspace layout. +public struct MobileWorkspaceLayoutSplit: Codable, Equatable, Sendable { + /// The stable split identifier. + public let id: String + + /// The axis along which this split divides its rectangle. + public let orientation: MobileWorkspaceLayoutOrientation + + /// The first child's proportional share of the split rectangle. + public let ratio: Double + + /// The first child node. + public let first: MobileWorkspaceLayoutNode + + /// The second child node. + public let second: MobileWorkspaceLayoutNode + + /// Creates a split snapshot. + /// + /// - Parameters: + /// - id: The stable split identifier. + /// - orientation: The split axis. + /// - ratio: The first child's proportional share. + /// - first: The first child node. + /// - second: The second child node. + public init( + id: String, + orientation: MobileWorkspaceLayoutOrientation, + ratio: Double, + first: MobileWorkspaceLayoutNode, + second: MobileWorkspaceLayoutNode + ) { + self.id = id + self.orientation = orientation + self.ratio = ratio + self.first = first + self.second = second + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSurface.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSurface.swift new file mode 100644 index 000000000000..aae6cfa6ea07 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSurface.swift @@ -0,0 +1,23 @@ +/// One surface tab in a synced workspace pane. +public struct MobileWorkspaceLayoutSurface: Codable, Equatable, Sendable { + /// The stable surface identifier. + public let id: String + + /// The raw panel type reported by the Mac. + public let type: String + + /// The surface's display title. + public let title: String + + /// Creates a surface tab snapshot. + /// + /// - Parameters: + /// - id: The stable surface identifier. + /// - type: The raw panel type reported by the Mac. + /// - title: The surface's display title. + public init(id: String, type: String, title: String) { + self.id = id + self.type = type + self.title = title + } +} diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift index 7526eac80785..efd0fb716411 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncFrameCodingTests.swift @@ -4,6 +4,22 @@ import Testing @testable import CMUXMobileCore struct MobileStateSyncFrameCodingTests { + private var layout: MobileWorkspaceLayout { + MobileWorkspaceLayout( + version: 4, + focusedPaneID: "pane-1", + root: .pane( + MobileWorkspaceLayoutPane( + id: "pane-1", + selectedSurfaceID: "t-1", + surfaces: [ + MobileWorkspaceLayoutSurface(id: "t-1", type: "terminal", title: "zsh") + ] + ) + ) + ) + } + private var workspace: WorkspaceSyncRecord { WorkspaceSyncRecord( id: "ws-1", @@ -29,7 +45,8 @@ struct MobileStateSyncFrameCodingTests { isReady: true, isFocused: false ) - ] + ], + layout: layout ) } @@ -51,6 +68,12 @@ struct MobileStateSyncFrameCodingTests { let terminals = object["terminals"] as? [[String: Any]] #expect(terminals?.first?["is_ready"] as? Bool == true) #expect(terminals?.first?["is_focused"] as? Bool == false) + let encodedLayout = try #require(object["layout"] as? [String: Any]) + #expect(encodedLayout["version"] as? Int == 4) + #expect(encodedLayout["focused_pane_id"] as? String == "pane-1") + let root = try #require(encodedLayout["root"] as? [String: Any]) + #expect(root["kind"] as? String == "pane") + #expect(root["selected_surface_id"] as? String == "t-1") } @Test func workspaceRecordDefaultsMissingDescriptionTruncatedFlagToFalse() throws { diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift index 3d89b9409c72..c9e69022053d 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileStateSyncStoreTests.swift @@ -9,7 +9,8 @@ struct MobileStateSyncStoreTests { title: String = "ws", preview: String? = nil, hasUnread: Bool = false, - sortIndex: Int = 0 + sortIndex: Int = 0, + layout: MobileWorkspaceLayout? = nil ) -> WorkspaceSyncRecord { WorkspaceSyncRecord( id: id, @@ -32,7 +33,25 @@ struct MobileStateSyncStoreTests { isReady: true, isFocused: true ) - ] + ], + layout: layout + ) + } + + private func paneLayout(selectedSurfaceID: String) -> MobileWorkspaceLayout { + MobileWorkspaceLayout( + version: 1, + focusedPaneID: "pane-1", + root: .pane( + MobileWorkspaceLayoutPane( + id: "pane-1", + selectedSurfaceID: selectedSurfaceID, + surfaces: [ + MobileWorkspaceLayoutSurface(id: "surface-1", type: "terminal", title: "One"), + MobileWorkspaceLayoutSurface(id: "surface-2", type: "terminal", title: "Two"), + ] + ) + ) ) } @@ -66,6 +85,22 @@ struct MobileStateSyncStoreTests { #expect(change?.toRev == 2) } + @Test func changedPaneSelectionTravelsInWorkspaceDelta() { + let store = MobileSyncCollectionStore() + _ = store.apply(rows: [ + workspace(id: "a", layout: paneLayout(selectedSurfaceID: "surface-1")), + workspace(id: "b"), + ]) + + let change = store.apply(rows: [ + workspace(id: "a", layout: paneLayout(selectedSurfaceID: "surface-2")), + workspace(id: "b"), + ]) + + #expect(change?.records.map(\.syncID) == ["a"]) + #expect(change?.records.first?.layout?.root == paneLayout(selectedSurfaceID: "surface-2").root) + } + @Test func removalBecomesTombstoneAndDeltaCarriesIt() { let store = MobileSyncCollectionStore() _ = store.apply(rows: [workspace(id: "a"), workspace(id: "b")]) diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift new file mode 100644 index 000000000000..eba9ef939aa5 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift @@ -0,0 +1,297 @@ +import Testing +@testable import CMUXMobileCore + +@Suite struct MobileTerminalRenderGridPaneMapPreviewTests { + @Test func emptyGridProducesSpaceCanvas() throws { + let rows = try Self.frame( + columns: 4, + rowCount: 2, + rowSpans: [] + ).paneMapPreviewRows() + + #expect(rows == [" ", " "]) + } + + @Test func laterOverlappingSpanWinsInSourceOrder() throws { + let rows = try Self.frame( + columns: 4, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 0, text: "abcd"), + .init(row: 0, column: 1, text: "XY"), + ] + ).paneMapPreviewRows() + + #expect(rows == ["aXYd"]) + } + + @Test func wideGlyphKeepsFollowingSpansInProducerColumns() throws { + let rows = try Self.frame( + columns: 6, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 0, text: "界A", cellWidth: 3), + .init(row: 0, column: 4, text: "Z"), + ] + ).paneMapPreviewRows() + + #expect(rows == ["界A Z "]) + } + + @Test func laterSpanClearsWideGlyphWhoseContinuationItOverlaps() throws { + let rows = try Self.frame( + columns: 4, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 0, text: "界A", cellWidth: 3), + .init(row: 0, column: 1, text: "XY"), + ] + ).paneMapPreviewRows() + + #expect(rows == [" XY "]) + } + + @Test func spanAtFinalGridColumnFitsCanvas() throws { + let rows = try Self.frame( + columns: 4, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 2, text: "WX"), + ] + ).paneMapPreviewRows() + + #expect(rows == [" WX"]) + } + + @Test func windowFollowsTopAnchoredContentOnTallGrid() throws { + let rows = try Self.frame( + columns: 3, + rowCount: 40, + rowSpans: [ + .init(row: 0, column: 0, text: "top"), + .init(row: 2, column: 0, text: "cat"), + ], + cursorRow: 3 + ).paneMapPreviewRows() + + #expect(rows.count == 20) + #expect(rows[0] == "top") + #expect(rows[2] == "cat") + } + + @Test func windowStaysBottomAnchoredWhenContentFillsTail() throws { + let rows = try Self.frame( + columns: 3, + rowCount: 40, + rowSpans: [ + .init(row: 39, column: 0, text: "end"), + ] + ).paneMapPreviewRows() + + #expect(rows.count == 20) + #expect(rows.last == "end") + } + + @Test func boundedPreviewUsesLatestScrollbackAndViewportRows() throws { + let frame = try MobileTerminalRenderGridFrame( + surfaceID: "terminal-preview", + stateSeq: 1, + columns: 4, + rows: 3, + rowSpans: [ + .init(row: 0, column: 0, text: "v0"), + .init(row: 1, column: 0, text: "v1"), + .init(row: 2, column: 0, text: "v2"), + ], + scrollbackRows: 4, + scrollbackSpans: [ + .init(row: 0, column: 0, text: "s0"), + .init(row: 1, column: 0, text: "s1"), + .init(row: 2, column: 0, text: "s2"), + .init(row: 3, column: 0, text: "s3"), + ] + ) + + #expect(frame.paneMapPreview(maximumRows: 4).textRows == [ + "s3 ", "v0 ", "v1 ", "v2 ", + ]) + } + + @Test func alternateScreenPreviewIgnoresPrimaryScrollback() throws { + let frame = try MobileTerminalRenderGridFrame( + surfaceID: "terminal-preview", + stateSeq: 1, + columns: 4, + rows: 2, + rowSpans: [ + .init(row: 0, column: 0, text: "a0"), + .init(row: 1, column: 0, text: "a1"), + ], + activeScreen: .alternate, + scrollbackRows: 2, + scrollbackSpans: [ + .init(row: 0, column: 0, text: "s0"), + .init(row: 1, column: 0, text: "s1"), + ] + ) + + #expect(frame.paneMapPreview().textRows == ["a0 ", "a1 "]) + } + + @Test func previewKeepsRendererEffectiveBackground() throws { + var effective = TerminalTheme.monokai + effective.background = "#123456" + + let frame = try MobileTerminalRenderGridFrame( + surfaceID: "terminal-preview", + stateSeq: 1, + columns: 2, + rows: 1, + rowSpans: [], + terminalBackground: "#abcdef", + terminalTheme: effective + ) + + #expect(frame.paneMapPreview().terminalTheme == effective) + } + + @Test func completePreviewKeepsShortTerminalContentAtTheTop() throws { + let preview = try Self.frame( + columns: 4, + rowCount: 40, + rowSpans: [ + .init(row: 0, column: 0, text: "top"), + .init(row: 2, column: 0, text: "end"), + ] + ).paneMapPreview() + + #expect(preview.firstSourceRow == 0) + #expect(preview.rows.count == 40) + #expect(preview.textRows[0] == "top ") + #expect(preview.textRows[2] == "end ") + #expect(preview.textRows[39] == " ") + } + + @Test func completePreviewPreservesTUIStylesAndWideGlyphContinuations() throws { + let styles: [MobileTerminalRenderGridFrame.Style] = [ + .default, + .init(id: 1, foreground: "#00ff00", background: "#001100", bold: true), + .init(id: 2, inverse: true), + ] + let frame = try MobileTerminalRenderGridFrame( + surfaceID: "terminal-preview", + stateSeq: 1, + columns: 6, + rows: 2, + styles: styles, + rowSpans: [ + .init(row: 0, column: 0, styleID: 1, text: "界A", cellWidth: 3), + .init(row: 1, column: 1, styleID: 2, text: "BOX"), + ] + ) + + let preview = frame.paneMapPreview() + + #expect(preview.rows[0][0].text == "界") + #expect(preview.rows[0][0].styleID == 1) + #expect(preview.rows[0][0].columnSpan == 2) + #expect(preview.rows[0][1].text.isEmpty) + #expect(preview.rows[0][1].styleID == 1) + #expect(preview.rows[0][1].columnSpan == 0) + #expect(preview.rows[1][1].styleID == 2) + #expect(preview.stylesByID[1]?.background == "#001100") + #expect(preview.stylesByID[2]?.inverse == true) + } + + @Test func aggregateWidthDoesNotGuessBetweenAmbiguousGraphemes() { + let partiallyExpanded = MobileTerminalRenderGridFrame.RowSpan( + row: 0, + column: 0, + text: "¡¡", + cellWidth: 3 + ) + let fullyExpanded = MobileTerminalRenderGridFrame.RowSpan( + row: 0, + column: 0, + text: "¡¡", + cellWidth: 4 + ) + + #expect(partiallyExpanded.resolvedCharacterCellWidths == nil) + #expect(fullyExpanded.resolvedCharacterCellWidths == [2, 2]) + } + + @Test func aggregateWidthDoesNotGuessWhichWideGraphemeContracted() { + let partiallyContracted = MobileTerminalRenderGridFrame.RowSpan( + row: 0, + column: 0, + text: "界界", + cellWidth: 3 + ) + let fullyContracted = MobileTerminalRenderGridFrame.RowSpan( + row: 0, + column: 0, + text: "界界", + cellWidth: 2 + ) + + #expect(partiallyContracted.resolvedCharacterCellWidths == nil) + #expect(fullyContracted.resolvedCharacterCellWidths == [1, 1]) + } + + @Test func decReverseVideoResolvesFromFinalModeSetting() throws { + let reenabled = try Self.frame( + columns: 2, + rowCount: 1, + rowSpans: [.init(row: 0, column: 0, text: "ab")], + modes: [ + .init(code: 5, on: true), + .init(code: 5, on: false), + .init(code: 5, on: true), + ] + ).paneMapPreview() + + let disabledLast = try Self.frame( + columns: 2, + rowCount: 1, + rowSpans: [.init(row: 0, column: 0, text: "ab")], + modes: [ + .init(code: 5, on: true), + .init(code: 5, on: false), + ] + ).paneMapPreview() + + // Replay applies mode settings in order (last wins); the preview must + // agree so a frame that re-disables reverse video does not render + // permanently inverted. Legacy frames reverse the fallback theme. + let fallback = TerminalTheme.monokai + let reenabledTheme = reenabled.resolvedTerminalTheme(fallback: fallback) + let disabledTheme = disabledLast.resolvedTerminalTheme(fallback: fallback) + let base = fallback.validatedOrDefault() + + #expect(reenabledTheme.foreground == base.background) + #expect(reenabledTheme.background == base.foreground) + #expect(disabledTheme.foreground == base.foreground) + #expect(disabledTheme.background == base.background) + } + + private static func frame( + columns: Int, + rowCount: Int, + rowSpans: [MobileTerminalRenderGridFrame.RowSpan], + cursorRow: Int? = nil, + modes: [MobileTerminalRenderGridFrame.ModeSetting] = [] + ) throws -> MobileTerminalRenderGridFrame { + try MobileTerminalRenderGridFrame( + surfaceID: "terminal-preview", + stateSeq: 1, + columns: columns, + rows: rowCount, + cursor: cursorRow.map { + MobileTerminalRenderGridFrame.Cursor(row: $0, column: 0) + }, + rowSpans: rowSpans, + modes: modes + ) + } +} diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileWorkspaceLayoutTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileWorkspaceLayoutTests.swift new file mode 100644 index 000000000000..591723b107e5 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileWorkspaceLayoutTests.swift @@ -0,0 +1,100 @@ +import Foundation +import Testing + +@testable import CMUXMobileCore + +struct MobileWorkspaceLayoutTests { + private func layout( + version: Int = 7, + ratio: Double = 0.4, + focusedPaneID: String? = "pane-left", + selectedSurfaceID: String? = "surface-shell", + title: String = "Shell", + type: String = "terminal" + ) -> MobileWorkspaceLayout { + MobileWorkspaceLayout( + version: version, + focusedPaneID: focusedPaneID, + root: .split( + MobileWorkspaceLayoutSplit( + id: "split-root", + orientation: .horizontal, + ratio: ratio, + first: .pane( + MobileWorkspaceLayoutPane( + id: "pane-left", + selectedSurfaceID: selectedSurfaceID, + surfaces: [ + MobileWorkspaceLayoutSurface( + id: "surface-shell", + type: type, + title: title + ) + ] + ) + ), + second: .pane( + MobileWorkspaceLayoutPane( + id: "pane-right", + selectedSurfaceID: "surface-preview", + surfaces: [ + MobileWorkspaceLayoutSurface( + id: "surface-preview", + type: "browser", + title: "Preview" + ) + ] + ) + ) + ) + ) + ) + } + + private func topologySignature(_ layout: MobileWorkspaceLayout) -> Int { + var hasher = Hasher() + layout.hashTopology(into: &hasher) + return hasher.finalize() + } + + @Test func roundTripsExactLayoutV1WireShape() throws { + let original = layout() + let object = try MobileSyncFrameCoder().jsonObject(from: original) + + #expect(object["version"] as? Int == 7) + #expect(object["focused_pane_id"] as? String == "pane-left") + let root = try #require(object["root"] as? [String: Any]) + #expect(root["kind"] as? String == "split") + #expect(root["orientation"] as? String == "horizontal") + #expect(root["ratio"] as? Double == 0.4) + let first = try #require(root["first"] as? [String: Any]) + #expect(first["kind"] as? String == "pane") + #expect(first["selected_surface_id"] as? String == "surface-shell") + let surfaces = try #require(first["surfaces"] as? [[String: Any]]) + #expect(surfaces.first?["id"] as? String == "surface-shell") + #expect(surfaces.first?["type"] as? String == "terminal") + #expect(surfaces.first?["title"] as? String == "Shell") + + let decoded = try MobileSyncFrameCoder().decode( + MobileWorkspaceLayout.self, + fromJSONObject: object + ) + #expect(decoded == original) + } + + @Test func topologyHashIgnoresPresentationOnlyChanges() { + let baseline = topologySignature(layout()) + + #expect(topologySignature(layout(version: 99)) == baseline) + #expect(topologySignature(layout(ratio: 0.8)) == baseline) + #expect(topologySignature(layout(title: "Renamed")) == baseline) + #expect(topologySignature(layout(type: "browser")) == baseline) + } + + @Test func topologyHashTracksFocusAndPaneSelection() { + let baseline = topologySignature(layout()) + + #expect(topologySignature(layout(focusedPaneID: "pane-right")) != baseline) + #expect(topologySignature(layout(selectedSurfaceID: nil)) != baseline) + } +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift index 32ba45910135..abd0235959ee 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift @@ -1,3 +1,4 @@ +public import CMUXMobileCore public import Foundation /// Typed decoder for the `workspace.list` / `mobile.workspace.list` RPC result. @@ -5,6 +6,9 @@ public import Foundation /// The wire shape is snake_case (the Mac side of PR 5079 already emits it); the /// `CodingKeys` map it onto camelCase Swift properties without changing the wire. public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { + /// Compatibility name for the shared workspace pane-layout DTO. + public typealias Layout = MobileWorkspaceLayout + /// A workspace entry in the list response. public struct Workspace: Decodable, Sendable { /// Stable workspace identifier. @@ -47,6 +51,8 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { public let hasUnread: Bool? /// Terminals belonging to this workspace. public let terminals: [Terminal] + /// The workspace's pane layout, or `nil` when absent or malformed. + public let layout: MobileWorkspaceLayout? private enum CodingKeys: String, CodingKey { case id @@ -64,11 +70,54 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { case lastActivityAt = "last_activity_at" case hasUnread = "has_unread" case terminals + case layout + } + + /// Decodes a workspace while isolating optional layout decoding failures. + /// - Parameter decoder: The decoder for one workspace object. + /// - Throws: A decoding error when a required non-layout workspace field is malformed. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + windowID = try container.decodeIfPresent(String.self, forKey: .windowID) + title = try container.decode(String.self, forKey: .title) + customDescription = try container.decodeIfPresent(String.self, forKey: .customDescription) + customDescriptionIsTruncated = try container.decodeIfPresent( + Bool.self, + forKey: .customDescriptionIsTruncated + ) + customColorHex = try container.decodeIfPresent(String.self, forKey: .customColorHex) + currentDirectory = try container.decodeIfPresent(String.self, forKey: .currentDirectory) + isSelected = try container.decode(Bool.self, forKey: .isSelected) + isPinned = try container.decodeIfPresent(Bool.self, forKey: .isPinned) + groupID = try container.decodeIfPresent(String.self, forKey: .groupID) + preview = try container.decodeIfPresent(String.self, forKey: .preview) + previewAt = try container.decodeIfPresent(Double.self, forKey: .previewAt) + lastActivityAt = try container.decodeIfPresent(Double.self, forKey: .lastActivityAt) + hasUnread = try container.decodeIfPresent(Bool.self, forKey: .hasUnread) + terminals = try container.decode([Terminal].self, forKey: .terminals) + layout = try? container.decode(MobileWorkspaceLayout.self, forKey: .layout) } - /// Memberwise construction for callers that assemble a row from an - /// already-synced local source (mobile state sync v2 projects its - /// record mirror through the same apply path as the wire response). + /// Creates a workspace row from an already-synced local record. + /// + /// - Parameters: + /// - id: The stable workspace identifier. + /// - windowID: The owning Mac window identifier, when reported. + /// - title: The workspace's display title. + /// - customDescription: The custom workspace description, when reported. + /// - customDescriptionIsTruncated: Whether the custom description was truncated. + /// - customColorHex: The custom workspace color as `#RRGGBB`, when reported. + /// - currentDirectory: The presented working directory, when reported. + /// - isSelected: Whether the Mac currently has this workspace selected. + /// - isPinned: Whether the workspace is pinned, when reported. + /// - groupID: The owning group identifier, when any. + /// - preview: The latest activity preview, when any. + /// - previewAt: The preview's Unix epoch timestamp, when any. + /// - lastActivityAt: The workspace's last-activity timestamp, when reported. + /// - hasUnread: Whether the workspace has unread activity, when reported. + /// - terminals: Terminal rows belonging to this workspace. + /// - layout: The shared pane-layout snapshot, when available. public init( id: String, windowID: String?, @@ -84,7 +133,8 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { previewAt: Double?, lastActivityAt: Double?, hasUnread: Bool?, - terminals: [Terminal] + terminals: [Terminal], + layout: MobileWorkspaceLayout? = nil ) { self.id = id self.windowID = windowID @@ -101,6 +151,7 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { self.lastActivityAt = lastActivityAt self.hasUnread = hasUnread self.terminals = terminals + self.layout = layout } } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift index b04a367aabe0..60eedae0c29c 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import Foundation public import CmuxMobileShellModel @@ -21,11 +22,95 @@ extension MobileWorkspacePreview { hasUnread: remote.hasUnread ?? false, terminals: remote.terminals.map { terminal in MobileTerminalPreview(remote: terminal) - } + }, + layout: remote.layout.map(MobilePaneLayout.init(remote:)) ) } } +private extension MobilePaneLayout { + init(remote: MobileWorkspaceLayout) { + self.init( + version: remote.version, + focusedPaneID: remote.focusedPaneID, + root: Node(remote: remote.root) + ) + } +} + +private extension MobilePaneLayout.Node { + init(remote: MobileWorkspaceLayoutNode) { + switch remote { + case let .split(split): + self = .split(MobilePaneSplit(remote: split)) + case let .pane(pane): + self = .pane(MobilePaneNode(remote: pane)) + } + } +} + +private extension MobilePaneSplit { + init(remote: MobileWorkspaceLayoutSplit) { + self.init( + id: remote.id, + orientation: MobilePaneSplitOrientation(remote: remote.orientation), + ratio: remote.ratio, + first: MobilePaneLayout.Node(remote: remote.first), + second: MobilePaneLayout.Node(remote: remote.second) + ) + } +} + +private extension MobilePaneSplitOrientation { + init(remote: MobileWorkspaceLayoutOrientation) { + switch remote { + case .horizontal: + self = .horizontal + case .vertical: + self = .vertical + } + } +} + +private extension MobilePaneNode { + init(remote: MobileWorkspaceLayoutPane) { + self.init( + id: remote.id, + selectedSurfaceID: remote.selectedSurfaceID, + surfaces: remote.surfaces.map(MobilePaneSurface.init(remote:)) + ) + } +} + +private extension MobilePaneSurface { + init(remote: MobileWorkspaceLayoutSurface) { + self.init( + id: remote.id, + type: MobilePaneSurfaceType(remoteRawValue: remote.type), + title: remote.title + ) + } +} + +private extension MobilePaneSurfaceType { + init(remoteRawValue: String) { + switch remoteRawValue { + case "terminal": self = .terminal + case "browser": self = .browser + case "markdown": self = .markdown + case "filepreview": self = .filepreview + case "rightSidebarTool": self = .rightSidebarTool + case "customSidebar": self = .customSidebar + case "agentSession": self = .agentSession + case "project": self = .project + case "extensionBrowser": self = .extensionBrowser + case "workspaceTodo": self = .workspaceTodo + case "cloudVMLoading": self = .cloudVMLoading + default: self = .other(remoteRawValue) + } + } +} + extension MobileWorkspaceGroupPreview { /// Build a group preview value from a remote workspace-list group entry. /// - Parameter remote: A group decoded from the RPC response. diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift new file mode 100644 index 000000000000..0718da06ea86 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift @@ -0,0 +1,219 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation +import Testing + +@testable import CmuxMobileRPC + +@Suite struct MobilePaneLayoutDecodeTests { + @Test func memberwiseWorkspaceProjectionRetainsSharedLayout() throws { + let sharedLayout = MobileWorkspaceLayout( + version: 21, + focusedPaneID: "pane-1", + root: .pane( + MobileWorkspaceLayoutPane( + id: "pane-1", + selectedSurfaceID: "surface-1", + surfaces: [ + MobileWorkspaceLayoutSurface( + id: "surface-1", + type: "terminal", + title: "Shell" + ) + ] + ) + ) + ) + let remote = MobileSyncWorkspaceListResponse.Workspace( + id: "workspace-1", + windowID: "window-1", + title: "Projected", + currentDirectory: nil, + isSelected: true, + isPinned: false, + groupID: nil, + preview: nil, + previewAt: nil, + lastActivityAt: 1, + hasUnread: false, + terminals: [], + layout: sharedLayout + ) + + #expect(remote.layout == sharedLayout) + let projected = MobileWorkspacePreview(remote: remote) + let layout = try #require(projected.layout) + #expect(layout.version == 21) + #expect(layout.focusedPaneID == "pane-1") + #expect(layout.orderedPanes.map(\.id) == ["pane-1"]) + #expect(layout.orderedPanes.first?.selectedSurfaceID == "surface-1") + } + + @Test func decodesAndMapsFullNestedLayout() throws { + let data = Data(""" + { + "workspaces": [ + { + "id": "workspace-1", + "window_id": "window-1", + "title": "Pane Layout", + "current_directory": "/tmp/project", + "is_selected": true, + "terminals": [ + { + "id": "surface-terminal", + "title": "Agent", + "current_directory": "/tmp/project", + "is_focused": true, + "is_ready": true + } + ], + "layout": { + "version": 12, + "focused_pane_id": "pane-tabs", + "root": { + "kind": "split", + "id": "split-root", + "orientation": "horizontal", + "ratio": 0.01, + "first": { + "kind": "pane", + "id": "pane-tabs", + "selected_surface_id": "surface-browser", + "surfaces": [ + {"id": "surface-terminal", "type": "terminal", "title": "Agent"}, + {"id": "surface-browser", "type": "browser", "title": "Preview"} + ] + }, + "second": { + "kind": "split", + "id": "split-nested", + "orientation": "vertical", + "ratio": 1.2, + "first": { + "kind": "pane", + "id": "pane-docs", + "selected_surface_id": "surface-markdown", + "surfaces": [ + {"id": "surface-markdown", "type": "markdown", "title": "README"} + ] + }, + "second": { + "kind": "pane", + "id": "pane-tools", + "selected_surface_id": "surface-file", + "surfaces": [ + {"id": "surface-file", "type": "filepreview", "title": "Diff"}, + {"id": "surface-sidebar-tool", "type": "rightSidebarTool", "title": "Tool"}, + {"id": "surface-custom-sidebar", "type": "customSidebar", "title": "Custom"}, + {"id": "surface-agent", "type": "agentSession", "title": "Agent Session"}, + {"id": "surface-project", "type": "project", "title": "Project"}, + {"id": "surface-extension", "type": "extensionBrowser", "title": "Extension"}, + {"id": "surface-todo", "type": "workspaceTodo", "title": "Todos"}, + {"id": "surface-cloud", "type": "cloudVMLoading", "title": "Starting VM"}, + {"id": "surface-future", "type": "futurePanel", "title": "Future"} + ] + } + } + } + } + } + ] + } + """.utf8) + + let response = try MobileSyncWorkspaceListResponse.decode(data) + let remoteWorkspace = try #require(response.workspaces.first) + let workspace = MobileWorkspacePreview(remote: remoteWorkspace) + let layout = try #require(workspace.layout) + + #expect(layout.version == 12) + #expect(layout.focusedPaneID == "pane-tabs") + #expect(layout.orderedPanes.map(\.id) == ["pane-tabs", "pane-docs", "pane-tools"]) + #expect(layout.pane(containing: "surface-browser")?.selectedSurfaceID == "surface-browser") + + guard case let .split(rootSplit) = layout.root else { + Issue.record("Expected a root split") + return + } + #expect(rootSplit.id == "split-root") + #expect(rootSplit.orientation == .horizontal) + #expect(rootSplit.ratio == 0.05) + guard case let .split(nestedSplit) = rootSplit.second else { + Issue.record("Expected the root's second child to be a split") + return + } + #expect(nestedSplit.orientation == .vertical) + #expect(nestedSplit.ratio == 0.95) + + let tabTypes = try #require(layout.orderedPanes.first).surfaces.map(\.type) + #expect(tabTypes == [.terminal, .browser]) + let toolTypes = try #require(layout.orderedPanes.last).surfaces.map(\.type) + #expect(toolTypes == [ + .filepreview, + .rightSidebarTool, + .customSidebar, + .agentSession, + .project, + .extensionBrowser, + .workspaceTodo, + .cloudVMLoading, + .other("futurePanel"), + ]) + } + + @Test func missingAndMalformedLayoutsDoNotFailWorkspaceList() throws { + let data = Data(""" + { + "workspaces": [ + { + "id": "workspace-old", + "title": "Older Mac", + "is_selected": true, + "terminals": [] + }, + { + "id": "workspace-garbage-kind", + "title": "Future Kind", + "is_selected": false, + "terminals": [], + "layout": { + "version": 13, + "focused_pane_id": null, + "root": {"kind": "grid", "id": "unsupported"} + } + }, + { + "id": "workspace-malformed-pane", + "title": "Malformed Pane", + "is_selected": false, + "terminals": [], + "layout": { + "version": 14, + "focused_pane_id": null, + "root": { + "kind": "pane", + "id": "pane-without-surfaces", + "selected_surface_id": null + } + } + } + ] + } + """.utf8) + + let response = try MobileSyncWorkspaceListResponse.decode(data) + + #expect(response.workspaces.count == 3) + #expect(response.workspaces.allSatisfy { $0.layout == nil }) + #expect(response.workspaces.map { MobileWorkspacePreview(remote: $0).layout }.allSatisfy { $0 == nil }) + #expect(response.workspaces.map(\.id) == [ + "workspace-old", + "workspace-garbage-kind", + "workspace-malformed-pane", + ]) + #expect(response.workspaces.map(\.title) == ["Older Mac", "Future Kind", "Malformed Pane"]) + #expect(response.workspaces.map(\.isSelected) == [true, false, false]) + #expect(response.workspaces.allSatisfy { $0.terminals.isEmpty }) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobilePairingFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobilePairingFailure.swift index 6149af73c1d0..251ddcddca66 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobilePairingFailure.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobilePairingFailure.swift @@ -431,7 +431,7 @@ extension MobilePairingFailureCategory { if let connectionError = error as? MobileShellConnectionError { switch connectionError { - case .requestTimedOut, .connectAttemptGated: + case .requestTimedOut: return .handshakeTimedOut(host: host, port: port) case .connectAttemptGated: // Another attempt owns this route: the Mac did not time out, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift index 92fe13582bc6..eaca0c31d7bb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift @@ -35,6 +35,10 @@ extension MobileShellComposite { public var supportsWorkspaceCloseActions: Bool { supportedHostCapabilities.contains(Self.workspaceCloseCapability) } /// Whether the Mac supports workspace move/reorder requests. public var supportsWorkspaceMoveActions: Bool { supportedHostCapabilities.contains(Self.workspaceMoveCapability) && allowsMacScopedWorkspaceMutations } + /// Whether the Mac supports workspace pane-content reorder requests. + public var supportsWorkspacePaneReorder: Bool { + supportedHostCapabilities.contains(Self.workspacePaneReorderCapability) + } /// Whether the Mac supports workspace group mutation requests. public var supportsWorkspaceGroupActions: Bool { supportedHostCapabilities.contains(Self.workspaceGroupActionsCapability) && allowsMacScopedWorkspaceMutations } /// Whether the Mac supports creating a workspace directly inside a group. diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index aeedc4cfa41c..11e2cffd26e1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -901,6 +901,7 @@ extension MobileShellComposite { if stateSyncActive { return await performStateSyncFetch(client: client, timeoutNanoseconds: timeoutNanoseconds) } + let authorityGeneration = foregroundWorkspaceListAuthorityGeneration do { let request = try MobileCoreRPCClient.requestData( method: "mobile.workspace.list", @@ -912,6 +913,14 @@ extension MobileShellComposite { ) let response = try MobileSyncWorkspaceListResponse.decode(data) guard remoteClient === client, connectionState == .connected else { return false } + // A mutation applied a newer authoritative list while this fetch + // was in flight; applying the captured snapshot would roll that + // mutation back in the UI. The round-trip already proved liveness, + // and any later Mac change re-triggers an event refresh under the + // new generation, so dropping the stale payload is safe. + guard foregroundWorkspaceListAuthorityGeneration == authorityGeneration else { + return true + } // Re-check authority AFTER the await: negotiation can grant v2 in // the window while this legacy request was in flight, and applying // the captured full list then would overwrite newer mirror state. diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift index 6d1a8717063e..03eed71bc1b4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift @@ -35,7 +35,8 @@ extension MobileShellComposite { supportsCloseActions: supportedHostCapabilities.contains("workspace.close.v1"), supportsMoveActions: supportedHostCapabilities.contains("workspace.move.v1") && allowsMacScopedMutations, supportsGroupActions: supportedHostCapabilities.contains("workspace.group_actions.v1") && allowsMacScopedMutations, - supportsGroupCreate: supportedHostCapabilities.contains("workspace.group_create.v1") && allowsMacScopedMutations + supportsGroupCreate: supportedHostCapabilities.contains("workspace.group_create.v1") && allowsMacScopedMutations, + supportsPaneReorder: supportedHostCapabilities.contains(Self.workspacePaneReorderCapability) ) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift new file mode 100644 index 000000000000..4dcaf3b65719 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift @@ -0,0 +1,101 @@ +public import CMUXMobileCore +internal import CmuxMobileDiagnostics +internal import CmuxMobileRPC +internal import Foundation + +extension MobileShellComposite { + private nonisolated static func decodePaneMapPreviewResponse( + _ data: Data + ) async throws -> MobileTerminalReplayResponse { + let decodeTask = Task.detached(priority: Task.currentPriority) { [data] in + try Task.checkCancellation() + let payload = try MobileTerminalReplayResponse.decode(data) + try Task.checkCancellation() + return payload + } + return try await withTaskCancellationHandler { + try await decodeTask.value + } onCancel: { + decodeTask.cancel() + } + } + + /// Fetches a read-only render-grid snapshot for one pane-map terminal preview. + /// + /// This side channel deliberately omits the mobile terminal client and viewport + /// fields so observing the pane map cannot resize the Mac's shared terminal grid. + /// It also stays outside the mounted terminal replay lifecycle and its barriers. + /// + /// - Parameters: + /// - remoteWorkspaceID: The Mac-local workspace identifier expected by RPC. + /// - surfaceID: The terminal surface whose render grid should be previewed. + /// - Returns: The decoded render grid, or `nil` when the request or decode fails. + public func fetchPaneMapPreviewGrid( + remoteWorkspaceID: String, + surfaceID: String + ) async -> MobileTerminalRenderGridFrame? { + guard let client = remoteClient else { return nil } + + do { + let request = try MobileCoreRPCClient.requestData( + method: "mobile.terminal.replay", + params: [ + "workspace_id": remoteWorkspaceID, + "surface_id": surfaceID, + // Previews consume only the render grid; hosts skip the + // unbounded VT/byte fallback instead of shipping a payload + // this side would decode and discard. + "grid_only": true, + ] + ) + let data = try await client.sendRequest(request) + try Task.checkCancellation() + guard remoteClient === client else { return nil } + let payload = try await Self.decodePaneMapPreviewResponse(data) + try Task.checkCancellation() + guard remoteClient === client else { return nil } + let grid = payload.renderGrid + MobileDebugLog.anchormux( + "CMUX_PANEMAP preview surface=\(surfaceID) grid=\(grid != nil) gridSurface=\(grid?.surfaceID ?? "nil") spans=\(grid?.rowSpans.count ?? -1) bytes=\(payload.dataBase64?.count ?? 0)" + ) + guard grid?.surfaceID == surfaceID else { + MobileDebugLog.anchormux( + "CMUX_PANEMAP preview rejected requested=\(surfaceID) returned=\(grid?.surfaceID ?? "nil")" + ) + return nil + } + return grid + } catch is CancellationError { + return nil + } catch { + MobileDebugLog.anchormux("CMUX_PANEMAP preview surface=\(surfaceID) error=\(error)") + return nil + } + } + + /// Fetches pane-map previews with at most four replay requests in flight. + /// + /// Selected pane tabs are enqueued before the remaining terminal surfaces. + /// Duplicate identifiers are removed while preserving that priority order. + /// + /// - Parameters: + /// - remoteWorkspaceID: The Mac-local workspace identifier expected by RPC. + /// - selectedSurfaceIDs: Selected terminal tabs, in pane order. + /// - remainingSurfaceIDs: Other terminal tabs, in pane and tab order. + /// - Returns: Successfully decoded render grids keyed by surface identifier. + public func fetchPaneMapPreviewGrids( + remoteWorkspaceID: String, + selectedSurfaceIDs: [String], + remainingSurfaceIDs: [String] + ) async -> [String: MobileTerminalRenderGridFrame] { + await PaneMapPreviewFetcher().fetch( + selectedSurfaceIDs: selectedSurfaceIDs, + remainingSurfaceIDs: remainingSurfaceIDs + ) { [weak self] surfaceID in + await self?.fetchPaneMapPreviewGrid( + remoteWorkspaceID: remoteWorkspaceID, + surfaceID: surfaceID + ) + } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 7b866c132230..9e12b2caceff 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -365,7 +365,8 @@ extension MobileShellComposite { isFocused: terminal.isFocused, isReady: terminal.isReady ) - } + }, + layout: record.layout ) } let groups = stateSyncMirror.groups.orderedRecords.map { record in diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift index bf9511732291..409f18f5d6b0 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift @@ -17,6 +17,35 @@ private let mobileShellLog = Logger( // actions (e.g. attempting to close the last workspace), and dropped push events // without re-fetching unrelated saved Macs for a single owner-local edit. extension MobileShellComposite { + /// Reorder complete pane contents on the owning Mac, then refresh its + /// authoritative workspace layout regardless of success or failure. + @discardableResult + public func reorderWorkspacePanes( + id: MobileWorkspacePreview.ID, + orderedPaneIDs: [String], + baseLayoutRevision: Int? = nil + ) async -> Result { + guard workspaceActionCapabilities(for: id).supportsPaneReorder else { + return .failure(.unsupported(hostDisplayName: workspaceHostDisplayName(for: id))) + } + guard !orderedPaneIDs.isEmpty, Set(orderedPaneIDs).count == orderedPaneIDs.count else { + return .failure(.rejected(hostDisplayName: workspaceHostDisplayName(for: id))) + } + var params = workspaceMutationParams(id: id) + params["ordered_pane_ids"] = orderedPaneIDs + // The layout revision the drag was computed against; the Mac rejects + // the reorder as a conflict when its layout moved past this baseline. + if let baseLayoutRevision { + params["base_layout_version"] = baseLayoutRevision + } + return await sendWorkspaceMutation( + method: "workspace.pane.reorder", + params: params, + id: id, + actionName: "pane_reorder", + authoritativeWorkspaceListResponse: true + ) + } /// Rename a workspace on the Mac. /// @@ -396,7 +425,8 @@ extension MobileShellComposite { params: [String: Any], id: MobileWorkspacePreview.ID, actionName: String, - refreshAfterMutation: Bool = true + refreshAfterMutation: Bool = true, + authoritativeWorkspaceListResponse: Bool = false ) async -> Result { let target = workspaceMutationTarget(for: id) return await sendWorkspaceMutation( @@ -409,7 +439,8 @@ extension MobileShellComposite { ), logID: id.rawValue, actionName: actionName, - refreshAfterMutation: refreshAfterMutation + refreshAfterMutation: refreshAfterMutation, + authoritativeWorkspaceListResponse: authoritativeWorkspaceListResponse ) } @@ -452,6 +483,7 @@ extension MobileShellComposite { logID: String, actionName: String, refreshAfterMutation: Bool = true, + authoritativeWorkspaceListResponse: Bool = false, isMacScoped: Bool = false ) async -> Result { // Route the mutation to the Mac that actually OWNS this workspace. The @@ -471,6 +503,7 @@ extension MobileShellComposite { return .failure(.notConnected(hostDisplayName: hostDisplayName)) } let generation = connectionGeneration + var appliedAuthoritativeWorkspaceList = false MobileDebugLog.anchormux("workspace.mutation sending action=\(actionName) id=\(logID) foreground=\(target.isForeground)") do { let request = try MobileCoreRPCClient.requestData(method: method, params: params) @@ -478,10 +511,22 @@ extension MobileShellComposite { isMacScoped && hostAuthorizesAccountScopedMutations(target: target) ? .omit : .whenCovered - _ = try await client.sendRequest( + let responseData = try await client.sendRequest( request, attachTicketPolicy: attachTicketPolicy ) + if authoritativeWorkspaceListResponse { + let response = try MobileSyncWorkspaceListResponse.decode(responseData) + guard applyAuthoritativeWorkspaceMutationResponse( + response, + target: target, + client: client, + connectionGeneration: generation + ) else { + throw MobileShellConnectionError.invalidResponse + } + appliedAuthoritativeWorkspaceList = true + } } catch { // Diagnostics carry only the bounded failure vocabulary plus the // short RPC code: an rpcError message is an arbitrary host string @@ -512,13 +557,71 @@ extension MobileShellComposite { return .failure(workspaceMutationFailure(error, hostDisplayName: hostDisplayName)) } // Re-sync the authoritative list for the Mac we actually mutated. - if refreshAfterMutation { + if refreshAfterMutation, !appliedAuthoritativeWorkspaceList { await refreshAfterWorkspaceMutation(target) } MobileDebugLog.anchormux("workspace.mutation accepted action=\(actionName) id=\(logID)") return .success(()) } + private func applyAuthoritativeWorkspaceMutationResponse( + _ response: MobileSyncWorkspaceListResponse, + target: WorkspaceMutationTarget, + client: MobileCoreRPCClient, + connectionGeneration: UUID + ) -> Bool { + guard !Task.isCancelled else { return false } + if target.isForeground { + guard isCurrentRemoteOperation( + client: client, + generation: connectionGeneration + ) else { + return false + } + applyRemoteWorkspaceList(response) + // A workspace.list fetch already in flight captured the + // pre-mutation layout; retiring its authority makes it drop on + // arrival instead of rolling this response back. + noteForegroundAuthoritativeWorkspaceListApplied() + return true + } + + guard let ownerKey = target.ownerKey, + let subscription = secondaryMacSubscriptions[ownerKey], + subscription.client === client, + !subscription.isTransitioningToFocus else { + return false + } + subscription.workspaceRefreshGeneration &+= 1 + // Same race on secondary Macs: a refresh pass that already consumed its + // pending flag publishes its (now pre-mutation) snapshot unconditionally. + // Re-arming the flag makes that in-flight owner run a trailing + // authoritative pass instead of exiting on the stale publish. + if subscription.refreshTask != nil || subscription.deferredRefreshTask != nil { + subscription.refreshPending = true + } + let workspaces = response.workspaces.map { remote -> MobileWorkspacePreview in + var workspace = MobileWorkspacePreview(remote: remote) + workspace.macDeviceID = subscription.macDeviceID + workspace.macInstanceTag = subscription.storedInstanceTag + return workspace + } + let groups = groupCollapseStore.apply( + to: response.groups.map { MobileWorkspaceGroupPreview(remote: $0) } + ) + workspacesByMac[ownerKey] = MacWorkspaceState( + macDeviceID: subscription.macDeviceID, + instanceTag: subscription.storedInstanceTag, + displayName: workspacesByMac[ownerKey]?.displayName + ?? subscription.displayName, + workspaces: workspaces, + groups: groups, + status: .connected, + actionCapabilities: subscription.actionCapabilities + ) + return true + } + private func workspaceMutationParams(id: MobileWorkspacePreview.ID) -> [String: Any] { var params: [String: Any] = [ "workspace_id": remoteWorkspaceID(for: id).rawValue, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 8ff72a7b1d5f..456a9ec3f178 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -117,6 +117,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { static let workspaceReadStateCapability = "workspace.read_state.v1" static let workspaceCloseCapability = "workspace.close.v1" static let workspaceMoveCapability = "workspace.move.v1" + static let workspacePaneReorderCapability = "workspace.pane_reorder.v1" static let workspaceMutationAccountAuthCapability = "workspace.mutations.account_auth.v1" static let workspaceGroupActionsCapability = "workspace.group_actions.v1" static let workspaceCreateInGroupCapability = "workspace.create_in_group.v1", workspaceGroupCreateCapability = "workspace.group_create.v1" @@ -981,6 +982,21 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// pre-mutation state. private var foregroundWorkspaceMutationRefreshPending = false private var foregroundWorkspaceMutationRefreshGeneration = UUID() + /// Bumped whenever a mutation applies its authoritative workspace-list + /// response. Legacy full-list fetches capture this before their RPC and + /// drop their (pre-mutation) snapshot when it moved during the await. + @ObservationIgnored var foregroundWorkspaceListAuthorityGeneration: UInt64 = 0 + + /// Called after a mutation applied its authoritative workspace-list + /// response: retires in-flight legacy list fetches and, when the + /// post-mutation refresh loop is already running, re-arms its pending flag + /// so one trailing authoritative pass reconciles anything that raced. + func noteForegroundAuthoritativeWorkspaceListApplied() { + foregroundWorkspaceListAuthorityGeneration &+= 1 + if foregroundWorkspaceMutationRefreshTask != nil { + foregroundWorkspaceMutationRefreshPending = true + } + } @ObservationIgnored var notificationFeedSnapshotsByMac: [String: NotificationFeedMacSnapshot] = [:] @ObservationIgnored var notificationFeedKnownRevisionsByMac: [String: Int] = [:] @ObservationIgnored var notificationFeedSuccessfulMacIDs: Set = [] @@ -1599,6 +1615,13 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { clearMacSwitchAttemptState() connectionGeneration = UUID() connectionAttemptGeneration = UUID() + // Retire any in-flight dialing transport synchronously: the generation + // bumps above make its owning connect() drop it at the next guard, but + // that is bounded by the pairing timeout, and a signed-out session must + // not keep a previous account's dial alive in the meantime. + if let attemptClient = replaceConnectionAttemptClientOwnership(with: nil) { + scheduleClientDisconnect(attemptClient) + } isSignedIn = false connectionState = .disconnected macConnectionStatus = .unavailable @@ -6960,6 +6983,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "source": .string("list_tap"), ]) setSelectedWorkspaceID(resolvedRowID) + syncSelectedTerminalForWorkspaceEntry() // Tapping into a workspace is a read receipt: clear its unread on the Mac // (like opening a thread marks it read), so it drops out of the unread // list and the back-button count. Only when the Mac advertises read-state @@ -9440,6 +9464,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { selectedTerminalID = selectedWorkspace.preferredTerminal?.id } + func syncSelectedTerminalForWorkspaceEntry() { + guard let selectedWorkspace else { + selectedTerminalID = nil + return + } + selectedTerminalID = selectedWorkspace.preferredEntryTerminal?.id + } + // MARK: - Per-terminal composer drafts /// Enqueue one draft-store operation on a strictly ordered (FIFO) pipeline. @@ -12219,6 +12251,42 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } private extension MobileWorkspacePreview { + var preferredEntryTerminal: MobileTerminalPreview? { + // Entry lands on the focused pane when it has a READY terminal, so the + // user opens onto a renderable endpoint. An unready focused selection + // only wins when nothing in the workspace is ready (nothing better to + // offer, and the pane context is worth restoring once it wakes). + let paneTerminals = focusedPaneTerminals + if let readyInPane = paneTerminals.first(where: \.isReady) { + return readyInPane + } + if let focused = paneTerminals.first, !hasReadyTerminal { + return focused + } + return preferredTerminal + } + + /// The focused pane's terminals with its selected surface first. + private var focusedPaneTerminals: [MobileTerminalPreview] { + guard let layout else { return [] } + let panes = layout.orderedPanes + let focusedPane = layout.focusedPaneID.flatMap { focusedPaneID in + panes.first { $0.id == focusedPaneID } + } ?? (panes.count == 1 ? panes.first : nil) + guard let focusedPane else { return [] } + var terminalIDs = focusedPane.surfaces + .filter { $0.type.isTerminal } + .map(\.id) + if let selectedSurfaceID = focusedPane.selectedSurfaceID, + let selectedIndex = terminalIDs.firstIndex(of: selectedSurfaceID) { + terminalIDs.remove(at: selectedIndex) + terminalIDs.insert(selectedSurfaceID, at: 0) + } + return terminalIDs.compactMap { terminalID in + terminals.first { $0.id.rawValue == terminalID } + } + } + var preferredTerminal: MobileTerminalPreview? { terminals.first { $0.isReady && $0.isFocused } ?? terminals.first { $0.isReady } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PaneMapPreviewFetcher.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PaneMapPreviewFetcher.swift new file mode 100644 index 000000000000..d87f15d1c455 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PaneMapPreviewFetcher.swift @@ -0,0 +1,75 @@ +internal import CMUXMobileCore + +/// Schedules pane-map replay snapshots with a bounded request window. +/// +/// Selected surfaces are placed first, duplicates keep their first position, +/// and cancellation prevents queued work from entering the active window. +struct PaneMapPreviewFetcher: Sendable { + let maximumConcurrentRequests: Int + + init(maximumConcurrentRequests: Int = 4) { + self.maximumConcurrentRequests = max(1, maximumConcurrentRequests) + } + + func fetch( + selectedSurfaceIDs: [String], + remainingSurfaceIDs: [String], + fetchGrid: @escaping @Sendable (String) async -> MobileTerminalRenderGridFrame? + ) async -> [String: MobileTerminalRenderGridFrame] { + let surfaceIDs = orderedSurfaceIDs( + selectedSurfaceIDs: selectedSurfaceIDs, + remainingSurfaceIDs: remainingSurfaceIDs + ) + guard !surfaceIDs.isEmpty, !Task.isCancelled else { return [:] } + + return await withTaskGroup( + of: (String, MobileTerminalRenderGridFrame?).self, + returning: [String: MobileTerminalRenderGridFrame].self + ) { group in + var nextIndex = 0 + + func enqueueNext() { + guard !Task.isCancelled, nextIndex < surfaceIDs.count else { return } + let surfaceID = surfaceIDs[nextIndex] + nextIndex += 1 + group.addTask { + guard !Task.isCancelled else { return (surfaceID, nil) } + return (surfaceID, await fetchGrid(surfaceID)) + } + } + + for _ in 0.. [String] { + var seenSurfaceIDs: Set = [] + var result: [String] = [] + result.reserveCapacity(selectedSurfaceIDs.count + remainingSurfaceIDs.count) + for surfaceID in selectedSurfaceIDs where seenSurfaceIDs.insert(surfaceID).inserted { + result.append(surfaceID) + } + for surfaceID in remainingSurfaceIDs where seenSurfaceIDs.insert(surfaceID).inserted { + result.append(surfaceID) + } + return result + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index fa136c521546..22617e60b4d9 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -128,6 +128,103 @@ import Testing #expect(refreshed.terminals.last?.viewportFit == nil) } + @Test func openingWorkspacePrefersFocusedPaneSelectedTerminalOverStaleSelection() async { + let store = MobileShellComposite.preview() + let workspace = MobileWorkspacePreview( + id: "workspace-panes", + name: "Panes", + terminals: [ + MobileTerminalPreview(id: "terminal-stale", name: "stale", isReady: true), + MobileTerminalPreview(id: "terminal-focused", name: "focused", isReady: true), + ], + layout: MobilePaneLayout( + version: 1, + focusedPaneID: "pane-focused", + root: .pane(MobilePaneNode( + id: "pane-focused", + selectedSurfaceID: "terminal-focused", + surfaces: [ + MobilePaneSurface(id: "terminal-stale", type: .terminal, title: "stale"), + MobilePaneSurface(id: "terminal-focused", type: .terminal, title: "focused"), + ] + )) + ) + ) + store.replaceForegroundWorkspaceState([workspace]) + store.selectedWorkspaceID = workspace.id + store.selectedTerminalID = "terminal-stale" + + await store.openWorkspace(workspace.id) + + #expect(store.selectedTerminalID?.rawValue == "terminal-focused") + } + + @Test func openingWorkspacePrefersReadyTerminalOverUnreadyFocusedPaneSelection() async { + let store = MobileShellComposite.preview() + let workspace = MobileWorkspacePreview( + id: "workspace-panes", + name: "Panes", + terminals: [ + MobileTerminalPreview(id: "terminal-ready", name: "ready", isReady: true), + MobileTerminalPreview(id: "terminal-sleeping", name: "sleeping", isReady: false), + ], + layout: MobilePaneLayout( + version: 1, + focusedPaneID: "pane-focused", + root: .pane(MobilePaneNode( + id: "pane-focused", + selectedSurfaceID: "terminal-sleeping", + surfaces: [ + MobilePaneSurface(id: "terminal-ready", type: .terminal, title: "ready"), + MobilePaneSurface(id: "terminal-sleeping", type: .terminal, title: "sleeping"), + ] + )) + ) + ) + store.replaceForegroundWorkspaceState([workspace]) + store.selectedWorkspaceID = workspace.id + store.selectedTerminalID = nil + + await store.openWorkspace(workspace.id) + + // The focused pane's selection is hibernated while a sibling terminal + // in the same pane can render; entry must land on the renderable one. + #expect(store.selectedTerminalID?.rawValue == "terminal-ready") + } + + @Test func openingWorkspaceKeepsUnreadyFocusedPaneTerminalWhenNothingIsReady() async { + let store = MobileShellComposite.preview() + let workspace = MobileWorkspacePreview( + id: "workspace-panes", + name: "Panes", + terminals: [ + MobileTerminalPreview(id: "terminal-a", name: "a", isReady: false), + MobileTerminalPreview(id: "terminal-b", name: "b", isReady: false), + ], + layout: MobilePaneLayout( + version: 1, + focusedPaneID: "pane-focused", + root: .pane(MobilePaneNode( + id: "pane-focused", + selectedSurfaceID: "terminal-b", + surfaces: [ + MobilePaneSurface(id: "terminal-a", type: .terminal, title: "a"), + MobilePaneSurface(id: "terminal-b", type: .terminal, title: "b"), + ] + )) + ) + ) + store.replaceForegroundWorkspaceState([workspace]) + store.selectedWorkspaceID = workspace.id + store.selectedTerminalID = nil + + await store.openWorkspace(workspace.id) + + // Nothing can render yet, so the focused pane's selection is still the + // right context to restore once its surface wakes. + #expect(store.selectedTerminalID?.rawValue == "terminal-b") + } + @Test func remoteRefreshMissingGroupFieldPreservesGroupHeaders() throws { let store = groupedForegroundStore() let response = try MobileSyncWorkspaceListResponse.decode(Data(#""" diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 83b185da2280..3ec650a8c0a7 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -22,6 +22,7 @@ actor LivenessHostRouter { var method: String? var topics: [String]? var workspaceID: String? + var surfaceID: String? var streamID: String? var groupID: String? var action: String? @@ -82,6 +83,7 @@ actor LivenessHostRouter { private var macDisplayName: String? = "Test Mac" private var workspaceListResponseHook: (@Sendable () -> Void)? private var workspaceListTitles: [String] = [] + private var paneReorderResult: [String: Any]? /// FIFO of scripted `mobile.sync.fetch` results (state sync v2 tests). private var syncFetchResults: [[String: Any]] = [] private var replayPayloads: [(text: String?, sequence: UInt64?, renderGrid: MobileTerminalRenderGridFrame?)] = [] @@ -115,6 +117,7 @@ actor LivenessHostRouter { method: String?, topics: [String]?, workspaceID: String? = nil, + surfaceID: String? = nil, streamID: String? = nil, groupID: String? = nil, action: String? = nil, @@ -126,6 +129,7 @@ actor LivenessHostRouter { method: method, topics: topics, workspaceID: workspaceID, + surfaceID: surfaceID, streamID: streamID, groupID: groupID, action: action, @@ -237,6 +241,12 @@ actor LivenessHostRouter { recorded.filter { $0.method == method }.map(\.workspaceID) } + func surfaceIDs(for method: String) -> [String] { + recorded + .filter { $0.method == method } + .compactMap(\.surfaceID) + } + func streamIDs(for method: String) -> [String?] { recorded.filter { $0.method == method }.map(\.streamID) } @@ -271,6 +281,11 @@ actor LivenessHostRouter { workspaceListResponseHook = hook } + func scriptPaneReorderResult(jsonData: Data) { + paneReorderResult = try? JSONSerialization.jsonObject(with: jsonData) + as? [String: Any] + } + func enqueueReplayTexts(_ texts: [String]) { replayTexts.append(contentsOf: texts) } @@ -502,6 +517,14 @@ actor LivenessHostRouter { ], ], ]) + case "workspace.pane.reorder": + guard let paneReorderResult else { + return try? Self.errorFrame( + id: id, + message: "unscripted pane reorder" + ) + } + return try? Self.resultFrame(id: id, result: paneReorderResult) case "mobile.host.status": hostStatusRequestCount += 1 if heldHostStatusRequestNumbers.contains(hostStatusRequestCount) { @@ -799,6 +822,7 @@ actor LivenessTransport: CmxByteTransport { method: method, topics: topics, workspaceID: params?["workspace_id"] as? String, + surfaceID: params?["surface_id"] as? String, streamID: streamID, groupID: params?["group_id"] as? String, action: params?["action"] as? String, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift index 3b8f85da9dc4..aca59fea1429 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -65,6 +65,66 @@ private func syncSnapshotResultData( return try JSONEncoder().encode(response) } +private func syncSnapshotResultDataWithPaneLayout() -> Data { + Data( + #""" + { + "epoch": "epoch-layout", + "workspaces": { + "mode": "snapshot", + "rev": 1, + "records": [ + { + "id": "workspace-layout", + "window_id": "window-layout", + "title": "Pane layout", + "is_selected": true, + "is_pinned": false, + "last_activity_at": 1, + "has_unread": false, + "sort_index": 0, + "terminals": [], + "layout": { + "version": 7, + "focused_pane_id": "pane-left", + "root": { + "kind": "split", + "id": "split-root", + "orientation": "horizontal", + "ratio": 0.4, + "first": { + "kind": "pane", + "id": "pane-left", + "selected_surface_id": "surface-shell", + "surfaces": [ + {"id": "surface-shell", "type": "terminal", "title": "Shell"} + ] + }, + "second": { + "kind": "pane", + "id": "pane-right", + "selected_surface_id": "surface-preview", + "surfaces": [ + {"id": "surface-preview", "type": "browser", "title": "Preview"} + ] + } + } + } + } + ], + "removed_ids": [] + }, + "groups": { + "mode": "snapshot", + "rev": 1, + "records": [], + "removed_ids": [] + } + } + """#.utf8 + ) +} + private func syncDeltaEventFrame( epoch: String, fromRev: UInt64, @@ -109,6 +169,26 @@ private let workspaceRowActionCapabilities = [ @MainActor struct MobileShellStateSyncTests { + @Test func stateSyncSnapshotProjectsPaneLayoutIntoWorkspaceList() async throws { + let router = LivenessHostRouter() + await router.scriptSyncFetchResult(jsonData: syncSnapshotResultDataWithPaneLayout()) + let box = TransportBox() + let clock = TestClock() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + + let projected = try await pollUntil { + store.workspaces.first(where: { $0.id.rawValue == "workspace-layout" })?.layout != nil + } + #expect(projected, "state sync v2 must preserve the Mac pane layout") + let workspace = try #require( + store.workspaces.first(where: { $0.id.rawValue == "workspace-layout" }) + ) + let layout = try #require(workspace.layout) + #expect(layout.version == 7) + #expect(layout.focusedPaneID == "pane-left") + #expect(layout.orderedPanes.map(\.id) == ["pane-left", "pane-right"]) + } + @Test func negotiationAppliesSnapshotAndSuppressesLegacyRefetch() async throws { let firstWorkspaceID = UUID().uuidString let router = LivenessHostRouter() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift index b14c999b46e1..0a75e2273f27 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift @@ -48,6 +48,7 @@ import Testing #expect(!oldMac.store.supportsWorkspaceMetadata) #expect(!oldMac.store.supportsWorkspaceReadStateActions && !oldMac.store.supportsWorkspaceCloseActions) #expect(!oldMac.store.supportsWorkspaceMoveActions && !oldMac.store.supportsWorkspaceGroupActions) + #expect(!oldMac.store.supportsWorkspacePaneReorder) #expect(!oldMac.store.supportsWorkspaceCreateInGroup) #expect(!oldMac.store.supportsWorkspaceGroupCreate) @@ -69,6 +70,7 @@ import Testing "workspace.read_state.v1", "workspace.close.v1", "workspace.move.v1", + "workspace.pane_reorder.v1", "workspace.group_actions.v1", "workspace.create_in_group.v1", "workspace.group_create.v1", @@ -78,6 +80,7 @@ import Testing #expect(scoped.store.workspaces.first?.actionCapabilities.supportsWorkspaceMetadata == true) #expect(scoped.store.supportsWorkspaceReadStateActions && scoped.store.supportsWorkspaceCloseActions) #expect(!scoped.store.supportsWorkspaceMoveActions && !scoped.store.supportsWorkspaceGroupActions) + #expect(scoped.store.supportsWorkspacePaneReorder) #expect(!scoped.store.supportsWorkspaceCreateInGroup) #expect(!scoped.store.supportsWorkspaceGroupCreate) @@ -87,6 +90,7 @@ import Testing ticketTerminalID: nil ) #expect(macWide.store.supportsWorkspaceMoveActions && macWide.store.supportsWorkspaceGroupActions) + #expect(macWide.store.supportsWorkspacePaneReorder) #expect(macWide.store.supportsWorkspaceCreateInGroup) #expect(macWide.store.supportsWorkspaceGroupCreate) } @@ -254,6 +258,157 @@ import Testing #expect(await router.count(of: "workspace.move") == 1) } + @Test func paneReorderAppliesTheRPCsAuthoritativeLayoutBeforeReturning() async throws { + let connected = try await connectedStore(capabilities: [ + "events.v1", + "terminal.render_grid.v1", + "terminal.replay.v1", + "workspace.pane_reorder.v1", + ]) + let store = connected.store + let router = connected.router + await router.scriptPaneReorderResult(jsonData: Data(#""" + { + "workspaces": [{ + "id": "live-workspace", + "title": "Live Workspace", + "is_selected": true, + "terminals": [ + {"id": "terminal-a", "title": "A", "is_focused": false}, + {"id": "terminal-b", "title": "B", "is_focused": true} + ], + "layout": { + "version": 2, + "focused_pane_id": "pane-left", + "root": { + "kind": "split", + "id": "split-root", + "orientation": "horizontal", + "ratio": 0.5, + "first": { + "kind": "pane", + "id": "pane-left", + "selected_surface_id": "terminal-b", + "surfaces": [ + {"id": "terminal-b", "type": "terminal", "title": "B"} + ] + }, + "second": { + "kind": "pane", + "id": "pane-right", + "selected_surface_id": "terminal-a", + "surfaces": [ + {"id": "terminal-a", "type": "terminal", "title": "A"} + ] + } + } + } + }], + "groups": [] + } + """#.utf8)) + let workspaceID = try #require(store.workspaces.first?.id) + let workspaceListRequestsBefore = await router.count(of: "workspace.list") + + guard case .success = await store.reorderWorkspacePanes( + id: workspaceID, + orderedPaneIDs: ["pane-right", "pane-left"] + ) else { + return #expect(Bool(false), "pane reorder should accept the authoritative response") + } + + let layout = try #require(store.workspaces.first?.layout) + #expect(layout.version == 2) + #expect(layout.orderedPanes.map(\.id) == ["pane-left", "pane-right"]) + #expect(layout.orderedPanes.map(\.selectedSurfaceID) == ["terminal-b", "terminal-a"]) + #expect(await router.count(of: "workspace.list") == workspaceListRequestsBefore) + await store.remoteClient?.disconnect() + } + + @Test func inFlightWorkspaceListCannotOverwriteReorderAuthoritativeLayout() async throws { + let connected = try await connectedStore(capabilities: [ + "events.v1", + "terminal.render_grid.v1", + "terminal.replay.v1", + "workspace.pane_reorder.v1", + ]) + let store = connected.store + let router = connected.router + await router.scriptPaneReorderResult(jsonData: Data(#""" + { + "workspaces": [{ + "id": "live-workspace", + "title": "Live Workspace", + "is_selected": true, + "terminals": [ + {"id": "terminal-a", "title": "A", "is_focused": false}, + {"id": "terminal-b", "title": "B", "is_focused": true} + ], + "layout": { + "version": 2, + "focused_pane_id": "pane-left", + "root": { + "kind": "split", + "id": "split-root", + "orientation": "horizontal", + "ratio": 0.5, + "first": { + "kind": "pane", + "id": "pane-left", + "selected_surface_id": "terminal-b", + "surfaces": [ + {"id": "terminal-b", "type": "terminal", "title": "B"} + ] + }, + "second": { + "kind": "pane", + "id": "pane-right", + "selected_surface_id": "terminal-a", + "surfaces": [ + {"id": "terminal-a", "type": "terminal", "title": "A"} + ] + } + } + } + }], + "groups": [] + } + """#.utf8)) + let workspaceID = try #require(store.workspaces.first?.id) + + // A legacy full-list fetch is already in flight (its response held) + // when the reorder returns its authoritative layout. The held response + // captured the pre-reorder state and must be dropped on arrival. + await router.holdNextWorkspaceListRequests() + let staleReload = Task { @MainActor in + await store.reloadWorkspaceListFromMac() + } + let listRequestStarted = await router.waitForCount( + of: "mobile.workspace.list", + atLeast: 1, + recordIssueOnTimeout: false + ) + #expect(listRequestStarted) + + guard case .success = await store.reorderWorkspacePanes( + id: workspaceID, + orderedPaneIDs: ["pane-right", "pane-left"] + ) else { + return #expect(Bool(false), "pane reorder should accept the authoritative response") + } + + await router.releaseAllHeld() + _ = await staleReload.value + + // The reorder's authoritative layout survives; the stale pre-mutation + // snapshot did not roll it back. + let layout = try #require(store.workspaces.first?.layout) + #expect(layout.version == 2) + #expect(layout.orderedPanes.map(\.id) == ["pane-left", "pane-right"]) + #expect(layout.orderedPanes.map(\.selectedSurfaceID) == ["terminal-b", "terminal-a"]) + await store.remoteClient?.disconnect() + } + private func connectedStore( capabilities: [String], ticketWorkspaceID: String = "live-workspace", diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift new file mode 100644 index 000000000000..225446845363 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift @@ -0,0 +1,236 @@ +import CMUXMobileCore +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct PaneMapPreviewFetchTests { + @Test func selectedSurfacesLeadDeduplicatedFourRequestWindow() async throws { + let surfaceIDs = ["selected-2", "selected-1", "selected-3", "selected-4", "other-1", "other-2"] + let frames = try Dictionary(uniqueKeysWithValues: surfaceIDs.enumerated().map { index, surfaceID in + ( + surfaceID, + try Self.frame(surfaceID: surfaceID, stateSeq: UInt64(index + 1)) + ) + }) + let gate = PaneMapPreviewFetchGate(frames: frames) + let fetcher = PaneMapPreviewFetcher(maximumConcurrentRequests: 4) + + let fetch = Task { + await fetcher.fetch( + selectedSurfaceIDs: ["selected-2", "selected-1", "selected-2", "selected-3", "selected-4"], + remainingSurfaceIDs: ["other-1", "selected-1", "other-2"] + ) { surfaceID in + await gate.fetch(surfaceID: surfaceID) + } + } + await gate.waitUntilStarted(count: 4) + let firstWindow = await gate.startedSurfaceIDs() + + #expect(firstWindow.count == 4) + #expect(Set(firstWindow) == Set(["selected-2", "selected-1", "selected-3", "selected-4"])) + + await gate.release() + let grids = await fetch.value + let allRequestedSurfaceIDs = await gate.startedSurfaceIDs() + + #expect(allRequestedSurfaceIDs.count == surfaceIDs.count) + #expect(Set(allRequestedSurfaceIDs) == Set(surfaceIDs)) + #expect(Set(grids.keys) == Set(surfaceIDs)) + } + + @Test func cancellationDoesNotStartQueuedRequests() async throws { + let router = LivenessHostRouter() + let box = TransportBox() + let clock = TestClock() + let store = MobileShellComposite.preview() + try installFreshLivenessRemoteClient( + on: store, + router: router, + box: box, + clock: clock + ) + let surfaceIDs = (1...8).map { "surface-\($0)" } + for (index, surfaceID) in surfaceIDs.enumerated() { + await router.enqueueReplayRenderGrid(try Self.frame( + surfaceID: surfaceID, + stateSeq: UInt64(index + 1) + )) + } + await router.holdNextReplayResponses(count: 4) + + let fetch = Task { @MainActor in + await store.fetchPaneMapPreviewGrids( + remoteWorkspaceID: "workspace", + selectedSurfaceIDs: [], + remainingSurfaceIDs: surfaceIDs + ) + } + let filledWindow = await router.waitForCount( + of: "mobile.terminal.replay", + atLeast: 4, + recordIssueOnTimeout: false + ) + fetch.cancel() + await router.releaseAllHeld() + // fetchPaneMapPreviewGrids runs entirely inside a task group, so once + // `fetch.value` resolves no further replay requests can start; the + // recorded set is final without any settling delay. + _ = await fetch.value + let requestedSurfaceIDs = await router.surfaceIDs(for: "mobile.terminal.replay") + + #expect(filledWindow) + #expect(requestedSurfaceIDs.count == 4) + await store.remoteClient?.disconnect() + } + + @Test func connectionReplacementRejectsHeldPreviewResponse() async throws { + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let clock = TestClock() + let store = MobileShellComposite.preview() + try installFreshLivenessRemoteClient( + on: store, + router: oldRouter, + box: oldBox, + clock: clock + ) + let oldClient = try #require(store.remoteClient) + await oldRouter.enqueueReplayRenderGrid(try Self.frame( + surfaceID: "surface-old", + stateSeq: 1 + )) + await oldRouter.holdNextReplayResponses() + + let fetch = Task { @MainActor in + await store.fetchPaneMapPreviewGrid( + remoteWorkspaceID: "workspace", + surfaceID: "surface-old" + ) + } + let requestStarted = await oldRouter.waitForCount( + of: "mobile.terminal.replay", + atLeast: 1, + recordIssueOnTimeout: false + ) + let replacementRouter = LivenessHostRouter() + let replacementBox = TransportBox() + try installFreshLivenessRemoteClient( + on: store, + router: replacementRouter, + box: replacementBox, + clock: clock + ) + await oldRouter.releaseAllHeld() + let grid = await fetch.value + + #expect(requestStarted) + #expect(grid == nil) + await oldClient.disconnect() + await store.remoteClient?.disconnect() + } + + @Test func mismatchedSurfaceResponseIsRejected() async throws { + let router = LivenessHostRouter() + let box = TransportBox() + let clock = TestClock() + let store = MobileShellComposite.preview() + try installFreshLivenessRemoteClient( + on: store, + router: router, + box: box, + clock: clock + ) + await router.enqueueReplayRenderGrid(try Self.frame( + surfaceID: "different-surface", + stateSeq: 1 + )) + + let grid = await store.fetchPaneMapPreviewGrid( + remoteWorkspaceID: "workspace", + surfaceID: "requested-surface" + ) + + #expect(grid == nil) + await store.remoteClient?.disconnect() + } + + private static func frame( + surfaceID: String, + stateSeq: UInt64 + ) throws -> MobileTerminalRenderGridFrame { + try MobileTerminalRenderGridFrame( + surfaceID: surfaceID, + stateSeq: stateSeq, + columns: 8, + rows: 1, + rowSpans: [.init(row: 0, column: 0, text: surfaceID.prefix(8).description)] + ) + } +} + +private actor PaneMapPreviewFetchGate { + private let frames: [String: MobileTerminalRenderGridFrame] + private var started: [String] = [] + private var startedCountTarget: Int? + private var startedCountContinuation: CheckedContinuation? + private var releaseContinuations: [CheckedContinuation] = [] + private var isReleased = false + + init(frames: [String: MobileTerminalRenderGridFrame]) { + self.frames = frames + } + + func fetch(surfaceID: String) async -> MobileTerminalRenderGridFrame? { + started.append(surfaceID) + if let startedCountTarget, + started.count >= startedCountTarget { + self.startedCountTarget = nil + startedCountContinuation?.resume() + startedCountContinuation = nil + } + + if !isReleased { + await withCheckedContinuation { continuation in + releaseContinuations.append(continuation) + } + } + return frames[surfaceID] + } + + /// Waits until `count` fetches have started, or until `timeout` elapses so a + /// fetcher that starts fewer requests fails the caller's assertions instead + /// of hanging the suite on an unresumed continuation. + func waitUntilStarted(count: Int, timeout: Duration = .seconds(5)) async { + guard started.count < count else { return } + startedCountTarget = count + let timeoutTask = Task { + try? await Task.sleep(for: timeout) + resumeStartedWaiterAfterTimeout() + } + await withCheckedContinuation { continuation in + startedCountContinuation = continuation + } + timeoutTask.cancel() + } + + private func resumeStartedWaiterAfterTimeout() { + guard startedCountContinuation != nil else { return } + startedCountTarget = nil + startedCountContinuation?.resume() + startedCountContinuation = nil + } + + func startedSurfaceIDs() -> [String] { + started + } + + func release() { + isReleased = true + let continuations = releaseContinuations + releaseContinuations.removeAll() + for continuation in continuations { + continuation.resume() + } + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneLayout.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneLayout.swift new file mode 100644 index 000000000000..5de05a716b5e --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneLayout.swift @@ -0,0 +1,115 @@ +public import Foundation + +/// A value snapshot of a workspace's split-pane layout. +public struct MobilePaneLayout: Sendable, Equatable { + /// A node in the recursive pane layout tree. + public indirect enum Node: Sendable, Equatable { + /// A branch that divides its rectangle between two child nodes. + case split(MobilePaneSplit) + /// A leaf pane containing an ordered set of surfaces. + case pane(MobilePaneNode) + } + + /// The Mac-side pane layout version associated with this snapshot. + public let version: Int + /// The focused pane identifier, when the Mac reports one. + public let focusedPaneID: String? + /// The root of the recursive split-pane tree. + public let root: Node + + /// Creates a pane layout snapshot. + /// - Parameters: + /// - version: The Mac-side pane layout version. + /// - focusedPaneID: The focused pane identifier, when known. + /// - root: The root of the recursive split-pane tree. + public init(version: Int, focusedPaneID: String?, root: Node) { + self.version = version + self.focusedPaneID = focusedPaneID + self.root = root + } + + /// The layout's panes in depth-first, first-child-then-second-child order. + public var orderedPanes: [MobilePaneNode] { + var panes: [MobilePaneNode] = [] + Self.appendPanes(in: root, to: &panes) + return panes + } + + /// Finds the pane containing a surface. + /// - Parameter surfaceID: The stable surface identifier to find. + /// - Returns: The containing pane, or `nil` when the surface is absent. + public func pane(containing surfaceID: String) -> MobilePaneNode? { + orderedPanes.first { pane in + pane.surfaces.contains { $0.id == surfaceID } + } + } + + /// Computes pane rectangles in unit space without applying a gutter. + /// - Returns: A dictionary from pane identifier to its rectangle in the `0...1` unit square. + public func normalizedRects() -> [String: CGRect] { + var rects: [String: CGRect] = [:] + Self.appendNormalizedRects( + for: root, + in: CGRect(x: 0, y: 0, width: 1, height: 1), + to: &rects + ) + return rects + } + + private static func appendPanes(in node: Node, to panes: inout [MobilePaneNode]) { + switch node { + case let .split(split): + appendPanes(in: split.first, to: &panes) + appendPanes(in: split.second, to: &panes) + case let .pane(pane): + panes.append(pane) + } + } + + private static func appendNormalizedRects( + for node: Node, + in rect: CGRect, + to rects: inout [String: CGRect] + ) { + switch node { + case let .pane(pane): + rects[pane.id] = rect + case let .split(split): + let ratio = CGFloat(split.ratio) + let firstRect: CGRect + let secondRect: CGRect + switch split.orientation { + case .horizontal: + let firstWidth = rect.width * ratio + firstRect = CGRect( + x: rect.minX, + y: rect.minY, + width: firstWidth, + height: rect.height + ) + secondRect = CGRect( + x: rect.minX + firstWidth, + y: rect.minY, + width: rect.width - firstWidth, + height: rect.height + ) + case .vertical: + let firstHeight = rect.height * ratio + firstRect = CGRect( + x: rect.minX, + y: rect.minY, + width: rect.width, + height: firstHeight + ) + secondRect = CGRect( + x: rect.minX, + y: rect.minY + firstHeight, + width: rect.width, + height: rect.height - firstHeight + ) + } + appendNormalizedRects(for: split.first, in: firstRect, to: &rects) + appendNormalizedRects(for: split.second, in: secondRect, to: &rects) + } + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneNode.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneNode.swift new file mode 100644 index 000000000000..cc658382bbe2 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneNode.swift @@ -0,0 +1,20 @@ +/// A leaf pane containing ordered workspace surfaces. +public struct MobilePaneNode: Sendable, Equatable { + /// The stable pane identifier. + public let id: String + /// The selected surface identifier within the pane, when one is selected. + public let selectedSurfaceID: String? + /// The pane's surfaces in tab order. + public let surfaces: [MobilePaneSurface] + + /// Creates a pane node. + /// - Parameters: + /// - id: The stable pane identifier. + /// - selectedSurfaceID: The selected surface identifier, when known. + /// - surfaces: The pane's surfaces in tab order. + public init(id: String, selectedSurfaceID: String?, surfaces: [MobilePaneSurface]) { + self.id = id + self.selectedSurfaceID = selectedSurfaceID + self.surfaces = surfaces + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift new file mode 100644 index 000000000000..19cfc9a484bd --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift @@ -0,0 +1,34 @@ +/// A branch in a mobile pane layout tree. +public struct MobilePaneSplit: Sendable, Equatable { + /// The stable split identifier. + public let id: String + /// The axis along which this split divides its rectangle. + public let orientation: MobilePaneSplitOrientation + /// The first child's proportional share, clamped to `0.05...0.95`. + public let ratio: Double + /// The first child in depth-first layout order. + public let first: MobilePaneLayout.Node + /// The second child in depth-first layout order. + public let second: MobilePaneLayout.Node + + /// Creates a split node. + /// - Parameters: + /// - id: The stable split identifier. + /// - orientation: The split axis. + /// - ratio: The first child's proportional share. + /// - first: The first child node. + /// - second: The second child node. + public init( + id: String, + orientation: MobilePaneSplitOrientation, + ratio: Double, + first: MobilePaneLayout.Node, + second: MobilePaneLayout.Node + ) { + self.id = id + self.orientation = orientation + self.ratio = ratio.isFinite ? min(max(ratio, 0.05), 0.95) : 0.5 + self.first = first + self.second = second + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplitOrientation.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplitOrientation.swift new file mode 100644 index 000000000000..9241ad5573b4 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplitOrientation.swift @@ -0,0 +1,7 @@ +/// The axis along which a pane split divides its available rectangle. +public enum MobilePaneSplitOrientation: Sendable, Equatable { + /// Places the first and second children side by side. + case horizontal + /// Stacks the first child above the second child in unit-space order. + case vertical +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurface.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurface.swift new file mode 100644 index 000000000000..6846ddf96bb5 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurface.swift @@ -0,0 +1,20 @@ +/// A surface tab contained by a mobile pane node. +public struct MobilePaneSurface: Sendable, Equatable { + /// The stable surface identifier shared with terminal RPC identifiers. + public let id: String + /// The surface's content type. + public let type: MobilePaneSurfaceType + /// The surface's display title as reported by the Mac. + public let title: String + + /// Creates a pane surface snapshot. + /// - Parameters: + /// - id: The stable surface identifier. + /// - type: The surface's content type. + /// - title: The surface's display title. + public init(id: String, type: MobilePaneSurfaceType, title: String) { + self.id = id + self.type = type + self.title = title + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurfaceType.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurfaceType.swift new file mode 100644 index 000000000000..b893d92e165e --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurfaceType.swift @@ -0,0 +1,35 @@ +/// The content kind displayed by a pane surface. +public enum MobilePaneSurfaceType: Sendable, Equatable { + /// A streamable terminal surface. + case terminal + /// A browser surface. + case browser + /// A rendered Markdown surface. + case markdown + /// A file preview surface. + case filepreview + /// A right-sidebar tool surface. + case rightSidebarTool + /// A custom-sidebar surface. + case customSidebar + /// An agent-session surface. + case agentSession + /// A project surface. + case project + /// An extension browser surface. + case extensionBrowser + /// A workspace todo surface. + case workspaceTodo + /// A cloud VM loading surface. + case cloudVMLoading + /// A surface kind introduced by a newer Mac version. + case other(String) + + /// Whether this surface type can be streamed through the mobile terminal lane. + public var isTerminal: Bool { + if case .terminal = self { + return true + } + return false + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift index 2e48c6cf4802..933721c45f65 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift @@ -14,6 +14,8 @@ public struct MobileWorkspaceActionCapabilities: Equatable, Sendable { public var supportsGroupActions: Bool /// Whether workspace group creation requests are supported. public var supportsGroupCreate: Bool + /// Whether complete pane-content reorder requests are supported. + public var supportsPaneReorder: Bool /// No workspace actions are supported. public static let none = MobileWorkspaceActionCapabilities() @@ -26,7 +28,8 @@ public struct MobileWorkspaceActionCapabilities: Equatable, Sendable { supportsCloseActions: Bool = false, supportsMoveActions: Bool = false, supportsGroupActions: Bool = false, - supportsGroupCreate: Bool = false + supportsGroupCreate: Bool = false, + supportsPaneReorder: Bool = false ) { self.supportsWorkspaceActions = supportsWorkspaceActions self.supportsWorkspaceMetadata = supportsWorkspaceMetadata @@ -35,5 +38,6 @@ public struct MobileWorkspaceActionCapabilities: Equatable, Sendable { self.supportsMoveActions = supportsMoveActions self.supportsGroupActions = supportsGroupActions self.supportsGroupCreate = supportsGroupCreate + self.supportsPaneReorder = supportsPaneReorder } } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspacePreview.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspacePreview.swift index 72d7cb9d8af3..81992ab9d490 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspacePreview.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspacePreview.swift @@ -2,10 +2,10 @@ public import Foundation /// A lightweight, `Sendable` snapshot of a remote workspace shown in the mobile shell. /// -/// This is a pure value model: it carries the workspace identity, display name, and -/// the ordered list of its terminals. It is decoupled from any connection, RPC, or -/// rendering concern so that both the domain coordinators and the SwiftUI layer can -/// consume the same immutable shape. +/// This is a pure value model: it carries the workspace identity, display name, +/// ordered terminals, and optional pane layout. It is decoupled from any connection, +/// RPC, or rendering concern so domain coordinators and SwiftUI can consume the same +/// immutable shape. public struct MobileWorkspacePreview: Identifiable, Equatable, Sendable { /// A stable, string-backed identifier for a ``MobileWorkspacePreview``. public struct ID: RawRepresentable, Hashable, Codable, Sendable, ExpressibleByStringLiteral { @@ -88,6 +88,8 @@ public struct MobileWorkspacePreview: Identifiable, Equatable, Sendable { public var hasUnread: Bool /// The terminals contained in the workspace, in display order. public var terminals: [MobileTerminalPreview] + /// The workspace's split-pane layout, when reported by the Mac. + public let layout: MobilePaneLayout? /// The owning Mac's DISTINCT color index in the aggregated list, stamped by /// ``MobileWorkspaceAggregation/derivedWorkspaces`` so same-Mac workspaces /// share one avatar color and different Macs are guaranteed distinct. `nil` @@ -131,6 +133,7 @@ public struct MobileWorkspacePreview: Identifiable, Equatable, Sendable { /// - lastActivityAt: When the workspace last had activity. Defaults to `nil`. /// - hasUnread: Whether the workspace has unread activity. Defaults to `false`. /// - terminals: The terminals contained in the workspace, in display order. + /// - layout: The workspace's split-pane layout. Defaults to `nil` for older Macs. public init( id: ID, macDeviceID: String? = nil, @@ -147,7 +150,8 @@ public struct MobileWorkspacePreview: Identifiable, Equatable, Sendable { previewAt: Date? = nil, lastActivityAt: Date? = nil, hasUnread: Bool = false, - terminals: [MobileTerminalPreview] + terminals: [MobileTerminalPreview], + layout: MobilePaneLayout? = nil ) { self.id = id self.remoteWorkspaceID = nil @@ -166,5 +170,6 @@ public struct MobileWorkspacePreview: Identifiable, Equatable, Sendable { self.lastActivityAt = lastActivityAt self.hasUnread = hasUnread self.terminals = terminals + self.layout = layout } } diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift new file mode 100644 index 000000000000..9e81bc2c8950 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift @@ -0,0 +1,136 @@ +import Foundation +import Testing + +@testable import CmuxMobileShellModel + +@Suite struct MobilePaneLayoutTests { + @Test func singlePaneOccupiesFullUnitRect() throws { + let layout = MobilePaneLayout( + version: 1, + focusedPaneID: "pane-a", + root: .pane(pane("pane-a")) + ) + + let rect = try #require(layout.normalizedRects()["pane-a"]) + #expect(rect == CGRect(x: 0, y: 0, width: 1, height: 1)) + } + + @Test func horizontalSplitUsesRatioForFirstPaneWidth() throws { + let layout = MobilePaneLayout( + version: 2, + focusedPaneID: nil, + root: .split(MobilePaneSplit( + id: "split-root", + orientation: .horizontal, + ratio: 0.3, + first: .pane(pane("pane-a")), + second: .pane(pane("pane-b")) + )) + ) + let rects = layout.normalizedRects() + + #expect(try #require(rects["pane-a"]) == CGRect(x: 0, y: 0, width: 0.3, height: 1)) + #expect(try #require(rects["pane-b"]) == CGRect(x: 0.3, y: 0, width: 0.7, height: 1)) + } + + @Test func nestedHorizontalAndVerticalSplitsComposeUnitRects() throws { + let layout = MobilePaneLayout( + version: 3, + focusedPaneID: "pane-c", + root: .split(MobilePaneSplit( + id: "split-horizontal", + orientation: .horizontal, + ratio: 0.5, + first: .pane(pane("pane-a")), + second: .split(MobilePaneSplit( + id: "split-vertical", + orientation: .vertical, + ratio: 0.25, + first: .pane(pane("pane-b")), + second: .pane(pane("pane-c")) + )) + )) + ) + let rects = layout.normalizedRects() + + #expect(try #require(rects["pane-a"]) == CGRect(x: 0, y: 0, width: 0.5, height: 1)) + #expect(try #require(rects["pane-b"]) == CGRect(x: 0.5, y: 0, width: 0.5, height: 0.25)) + #expect(try #require(rects["pane-c"]) == CGRect(x: 0.5, y: 0.25, width: 0.5, height: 0.75)) + } + + @Test func splitInitializerEnforcesFiniteDisplayableRatios() { + #expect(split(ratio: -1).ratio == 0.05) + #expect(split(ratio: 0.01).ratio == 0.05) + #expect(split(ratio: 0.25).ratio == 0.25) + #expect(split(ratio: 0.99).ratio == 0.95) + #expect(split(ratio: 2).ratio == 0.95) + #expect(split(ratio: .nan).ratio == 0.5) + #expect(split(ratio: .infinity).ratio == 0.5) + #expect(split(ratio: -.infinity).ratio == 0.5) + } + + @Test func paneLookupAndOrderedPanesFollowDepthFirstOrder() { + let firstPane = pane( + "pane-a", + surfaces: [surface("surface-a", type: .terminal)] + ) + let secondPane = pane( + "pane-b", + surfaces: [ + surface("surface-b", type: .browser), + surface("surface-c", type: .markdown), + ] + ) + let thirdPane = pane( + "pane-c", + surfaces: [surface("surface-d", type: .other("future"))] + ) + let layout = MobilePaneLayout( + version: 4, + focusedPaneID: "pane-b", + root: .split(MobilePaneSplit( + id: "split-root", + orientation: .horizontal, + ratio: 0.5, + first: .split(MobilePaneSplit( + id: "split-nested", + orientation: .vertical, + ratio: 0.5, + first: .pane(firstPane), + second: .pane(secondPane) + )), + second: .pane(thirdPane) + )) + ) + + #expect(layout.orderedPanes.map(\.id) == ["pane-a", "pane-b", "pane-c"]) + #expect(layout.pane(containing: "surface-c") == secondPane) + #expect(layout.pane(containing: "missing") == nil) + #expect(firstPane.surfaces[0].type.isTerminal) + #expect(!secondPane.surfaces[0].type.isTerminal) + } + + private func pane( + _ id: String, + surfaces: [MobilePaneSurface] = [] + ) -> MobilePaneNode { + MobilePaneNode(id: id, selectedSurfaceID: surfaces.first?.id, surfaces: surfaces) + } + + private func split(ratio: Double) -> MobilePaneSplit { + MobilePaneSplit( + id: "split", + orientation: .horizontal, + ratio: ratio, + first: .pane(pane("pane-a")), + second: .pane(pane("pane-b")) + ) + } + + private func surface( + _ id: String, + type: MobilePaneSurfaceType + ) -> MobilePaneSurface { + MobilePaneSurface(id: id, type: type, title: id) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/AgentChatDemoScreen.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/AgentChatDemoScreen.swift index ea09af438ca6..027bfdb63706 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/AgentChatDemoScreen.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/AgentChatDemoScreen.swift @@ -65,6 +65,7 @@ struct AgentChatDemoScreen: View { hasBackButton: true, hasTrailingCluster: true, hasChatToggle: true, + reservesPaneMapControls: false, isEnabled: true, workspaceName: inlineWorkspaceTitle ?? "", hasUnread: false, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index fd00d5d49f2c..371253cf9cb4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -83,6 +83,14 @@ struct CMUXMobileRootView: View { #endif } + private var debugPreview: AnyView? { + #if os(iOS) && DEBUG + return configuredDebugPreview + #else + return nil + #endif + } + private var shouldShowWorkspaceListLayoutPreview: Bool { #if os(iOS) && DEBUG return UITestConfig.workspaceListLayoutPreviewEnabled @@ -316,6 +324,8 @@ struct CMUXMobileRootView: View { agentChatDemoPreview } else if shouldShowTerminalLayoutPreview { terminalLayoutPreview + } else if let debugPreview { + debugPreview } else if shouldShowWorkspaceListLayoutPreview { workspaceListLayoutPreview } else if shouldShowHiddenComputersPreview { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/ChatAgentStateKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/ChatAgentStateKind.swift new file mode 100644 index 000000000000..ab6953562dad --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/ChatAgentStateKind.swift @@ -0,0 +1,5 @@ +/// The agent activity states represented by a surface-deck status dot. +enum ChatAgentStateKind: Equatable { + case working + case needsInput +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift new file mode 100644 index 000000000000..5b903e4a7ee8 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift @@ -0,0 +1,36 @@ +#if DEBUG +import Foundation + +enum MobileRootDebugPreviewRoute: Equatable { + case panesTabs + + init?(environment: [String: String]) { + guard environment["CMUX_UITEST_PANES_PREVIEW"] == "1" else { + return nil + } + self = .panesTabs + } +} + +#if canImport(UIKit) +import SwiftUI + +extension CMUXMobileRootView { + var configuredDebugPreview: AnyView? { + guard let route = MobileRootDebugPreviewRoute( + environment: ProcessInfo.processInfo.environment + ) else { + return nil + } + switch route { + case .panesTabs: + return AnyView( + NavigationStack { + PanesTabsPreviewHost() + } + ) + } + } +} +#endif +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift new file mode 100644 index 000000000000..5ba230d92121 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -0,0 +1,735 @@ +#if canImport(UIKit) && DEBUG +import CMUXMobileCore +import CmuxMobileShellModel +import CmuxMobileSupport +import CmuxMobileWorkspace +import os +import SwiftUI +import UIKit + +/// Fixture-driven host for exercising the production panes-and-tabs UI without a paired Mac. +struct PanesTabsPreviewHost: View { + private static let logger = Logger(subsystem: "dev.cmux.ios", category: "PanesTabsPreviewHost") + private static let claudeSurfaceID = "preview-claude" + private static let zshSurfaceID = "preview-zsh" + private static let testsSurfaceID = "preview-bun-tests" + private static let logSurfaceID = "preview-server-log" + private static let browserSurfaceID = "preview-browser" + private static let gitSurfaceID = "preview-git" + + @State private var selectedSurfaceID = Self.claudeSurfaceID + @Namespace private var paneZoomNamespace + @State private var paneZoomPresentation = PaneZoomPresentationState() + @State private var orderedFixturePaneIDs = [ + "preview-pane-left-top", + "preview-pane-left-bottom", + "preview-pane-tests", + "preview-pane-server", + ] + @State private var paneMapRefreshTrigger = 0 + @State private var fixtureLayoutRevision = 0 + @State private var isPaneMapRefreshing = false + @State private var contentWidth: CGFloat = 0 + @State private var autoplayStep = 0 + private let terminalTheme = TerminalTheme.monokai + + private let workspace = MobileWorkspacePreview( + id: "preview-api-server", + name: "api-server", + terminals: [ + MobileTerminalPreview( + id: MobileTerminalPreview.ID(rawValue: Self.claudeSurfaceID), + name: "claude", + isFocused: true + ), + MobileTerminalPreview( + id: MobileTerminalPreview.ID(rawValue: Self.zshSurfaceID), + name: "zsh" + ), + MobileTerminalPreview( + id: MobileTerminalPreview.ID(rawValue: Self.testsSurfaceID), + name: "bun test --watch" + ), + MobileTerminalPreview( + id: MobileTerminalPreview.ID(rawValue: Self.logSurfaceID), + name: "server.log" + ), + MobileTerminalPreview( + id: MobileTerminalPreview.ID(rawValue: Self.gitSurfaceID), + name: "lazygit" + ), + ], + layout: MobilePaneLayout( + version: 12, + focusedPaneID: "preview-pane-left-top", + root: .split( + MobilePaneSplit( + id: "preview-split-root", + orientation: .horizontal, + ratio: 0.6, + first: .split( + MobilePaneSplit( + id: "preview-split-left", + orientation: .vertical, + ratio: 0.35, + first: .pane( + MobilePaneNode( + id: "preview-pane-left-top", + selectedSurfaceID: Self.claudeSurfaceID, + surfaces: [ + MobilePaneSurface( + id: Self.claudeSurfaceID, + type: .terminal, + title: "claude" + ), + MobilePaneSurface( + id: Self.zshSurfaceID, + type: .terminal, + title: "zsh" + ), + ] + ) + ), + second: .pane( + MobilePaneNode( + id: "preview-pane-left-bottom", + selectedSurfaceID: Self.gitSurfaceID, + surfaces: [ + MobilePaneSurface( + id: Self.gitSurfaceID, + type: .terminal, + title: "lazygit" + ) + ] + ) + ) + ) + ), + second: .split( + MobilePaneSplit( + id: "preview-split-right", + orientation: .vertical, + ratio: 0.65, + first: .pane( + MobilePaneNode( + id: "preview-pane-tests", + selectedSurfaceID: Self.testsSurfaceID, + surfaces: [ + MobilePaneSurface( + id: Self.testsSurfaceID, + type: .terminal, + title: "bun test --watch" + ), + ] + ) + ), + second: .pane( + MobilePaneNode( + id: "preview-pane-server", + selectedSurfaceID: Self.logSurfaceID, + surfaces: [ + MobilePaneSurface( + id: Self.logSurfaceID, + type: .terminal, + title: "server.log" + ), + MobilePaneSurface( + id: Self.browserSurfaceID, + type: .browser, + title: "localhost:3000" + ), + ] + ) + ) + ) + ) + ) + ) + ) + ) + + private let agentStateKindsBySurfaceID: [String: ChatAgentStateKind] = [ + Self.claudeSurfaceID: .working, + Self.testsSurfaceID: .needsInput, + ] + + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + @Environment(\.verticalSizeClass) private var verticalSizeClass + + /// Mirror the shell's layout policy so the fixture exercises the same + /// pane-zoom hosting the real workspace destination uses on this device: + /// the compact shell pushes workspace details inside a `NavigationStack` + /// (push hosting), the regular-width shell hosts them as a split detail + /// column (column hosting). + private var paneZoomHosting: PaneZoomHosting { + MobileWorkspaceShellLayoutPolicy.usesCompactStack( + horizontalSizeClass: horizontalSizeClass, + verticalSizeClass: verticalSizeClass + ) ? .navigationPush : .column + } + + var body: some View { + Group { + if fixtureLayout != nil { + if paneZoomHosting == .navigationPush { + // Stand-in for the compact shell's outer stack, which owns + // the pane-map root's navigation bar in push hosting. + NavigationStack { + paneZoomContent + } + } else { + paneZoomContent + } + } else { + terminalPreviewEndpoint + .mobileSurfaceDeckInset( + isVisible: paneZoomPresentation.isTerminalPresented, + value: deckValue, + actions: deckActions, + terminalTheme: terminalTheme + ) + } + } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + } + + @ViewBuilder + private var paneZoomContent: some View { + if let layout = fixtureLayout { + PaneZoomHost( + presentation: $paneZoomPresentation, + hosting: paneZoomHosting, + terminalTheme: terminalTheme, + zoomSourceID: paneZoomSourceSurfaceID, + zoomNamespace: paneZoomNamespace + ) { + PaneMapOverlay( + value: PaneMapValue( + layout: layout, + phoneSelectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID + ), + terminalTheme: terminalTheme, + zoomNamespace: paneZoomNamespace, + isVisible: !paneZoomPresentation.isTerminalPresented, + allowsReordering: true, + refreshTrigger: paneMapRefreshTrigger, + fetchPreviews: Self.fetchFixturePreviews, + selectTerminal: presentTerminalFromPaneMap, + reorderPanes: reorderFixturePanes, + refreshingChanged: { isPaneMapRefreshing = $0 } + ) + .accessibilityHidden(paneZoomPresentation.isTerminalPresented) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } + .navigationTitle(workspace.name) + .mobileTerminalNavigationChrome(theme: terminalTheme) + .toolbar { previewToolbar(mode: .paneMap) } + .navigationBarBackButtonHidden(true) + .background { autoplayDriver(for: .paneMap) } + } terminal: { + terminalPreviewEndpoint + .mobileSurfaceDeckInset( + isVisible: paneZoomPresentation.isTerminalPresented, + value: deckValue, + actions: deckActions, + terminalTheme: terminalTheme + ) + .navigationBarBackButtonHidden(true) + } + } + } + + private var terminalPreviewEndpoint: some View { + ZStack(alignment: .topTrailing) { + terminalTheme.terminalBackgroundColor + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea(.container, edges: [.horizontal, .top, .bottom]) + } + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } + .navigationTitle(workspace.name) + .mobileTerminalNavigationChrome(theme: terminalTheme) + .toolbar { previewToolbar(mode: .terminal) } + .background { autoplayDriver(for: .terminal) } + .accessibilityIdentifier("PanesTabsPreviewHost") + } + + private var deckValue: SurfaceDeckValue { + SurfaceDeckValue( + workspace: workspace, + selectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID, + canCreateWorkspace: true + ) + } + + private var deckActions: SurfaceDeckActions { + SurfaceDeckActions( + selectTerminal: { selectedSurfaceID = $0.rawValue }, + presentPaneMap: presentPaneMap, + createTerminal: {}, + openBrowser: {}, + createWorkspace: {} + ) + } + + private func presentPaneMap() { + paneZoomPresentation.presentPaneMap(from: selectedSurfaceID) + } + + private func presentTerminalFromPaneMap(_ terminalID: MobileTerminalPreview.ID) { + paneZoomPresentation.presentTerminal(surfaceID: terminalID.rawValue) + selectedSurfaceID = terminalID.rawValue + } + + private func returnToTerminalFromPaneMap() { + paneZoomPresentation.presentTerminal(surfaceID: paneZoomSourceSurfaceID) + } + + private enum AutoplayLocation { + case terminal + case paneMap + } + + private func autoplayDriver(for location: AutoplayLocation) -> some View { + PanesTabsAutoplayDriver( + isEnabled: ProcessInfo.processInfo.environment["CMUX_UITEST_PANES_PREVIEW_AUTOPLAY"] == "1" + && fixtureLayout != nil, + location: location, + isTerminalPresented: paneZoomPresentation.isTerminalPresented, + step: $autoplayStep, + presentPaneMap: presentPaneMap, + presentTerminal: { + presentTerminalFromPaneMap(MobileTerminalPreview.ID(rawValue: Self.claudeSurfaceID)) + }, + returnToTerminal: returnToTerminalFromPaneMap + ) + .frame(width: 1, height: 1) + .opacity(0) + .allowsHitTesting(false) + .accessibilityHidden(true) + } + + @MainActor + private struct PanesTabsAutoplayDriver: UIViewRepresentable { + let isEnabled: Bool + let location: AutoplayLocation + let isTerminalPresented: Bool + @Binding var step: Int + let presentPaneMap: () -> Void + let presentTerminal: () -> Void + let returnToTerminal: () -> Void + + func makeCoordinator() -> Coordinator { + Coordinator() + } + + func makeUIView(context: Context) -> UIView { + let view = UIView(frame: .zero) + view.isUserInteractionEnabled = false + context.coordinator.update(self) + return view + } + + func updateUIView(_ uiView: UIView, context: Context) { + context.coordinator.update(self) + } + + static func dismantleUIView(_ uiView: UIView, coordinator: Coordinator) { + coordinator.cancel() + } + + @MainActor + final class Coordinator { + private var task: Task? + private var scheduledKey: String? + + func update(_ parent: PanesTabsAutoplayDriver) { + guard parent.isEnabled else { + cancel() + return + } + guard let plan = Plan( + step: parent.step, + location: parent.location, + isTerminalPresented: parent.isTerminalPresented + ) else { + cancel() + return + } + let nextKey = [ + "\(parent.step)", + String(describing: parent.location), + parent.isTerminalPresented ? "terminal" : "paneMap", + ].joined(separator: ":") + guard scheduledKey != nextKey else { return } + cancel() + scheduledKey = nextKey + PanesTabsPreviewHost.logger.notice("autoplay: schedule \(nextKey, privacy: .public)") + task = Task { @MainActor [weak self] in + do { + try await Task.sleep(for: .seconds(plan.delay)) + } catch { + return + } + guard !Task.isCancelled, + parent.step == plan.expectedStep else { return } + PanesTabsPreviewHost.logger.notice("autoplay: fire \(nextKey, privacy: .public)") + parent.step = plan.nextStep + parent.run(plan.action) + self?.cancel() + } + } + + func cancel() { + task?.cancel() + task = nil + scheduledKey = nil + } + } + + private enum Action: Sendable { + case presentPaneMap + case presentTerminal + case returnToTerminal + } + + private func run(_ action: Action) { + switch action { + case .presentPaneMap: + presentPaneMap() + case .presentTerminal: + presentTerminal() + case .returnToTerminal: + returnToTerminal() + } + } + + private struct Plan: Sendable { + let expectedStep: Int + let nextStep: Int + let delay: TimeInterval + let action: Action + + init?(step: Int, location: AutoplayLocation, isTerminalPresented: Bool) { + switch (step, location, isTerminalPresented) { + case (0, .terminal, true): + expectedStep = 0 + nextStep = 1 + delay = 5 + action = .presentPaneMap + case (1, .paneMap, false): + expectedStep = 1 + nextStep = 2 + delay = 1.1 + action = .presentTerminal + case (2, .terminal, true): + expectedStep = 2 + nextStep = 3 + delay = 1.1 + action = .presentPaneMap + case (3, .paneMap, false): + expectedStep = 3 + nextStep = 4 + delay = 1.1 + action = .returnToTerminal + default: + return nil + } + } + } + } + + private var paneZoomSourceSurfaceID: String { + paneZoomPresentation.sourceSurfaceID ?? selectedSurfaceID + } + + private enum PreviewToolbarMode { + case paneMap + case terminal + } + + @ToolbarContentBuilder + private func previewToolbar(mode: PreviewToolbarMode) -> some ToolbarContent { + ToolbarItem(id: "workspace-back", placement: .topBarLeading) { + WorkspaceBackButton(unreadCount: 2, action: {}) + } + if #available(iOS 26.0, *) { + ToolbarSpacer(.fixed, placement: .topBarLeading) + } + ToolbarItem(id: "workspace-title", placement: .topBarLeading) { + previewWorkspaceTitleMenu(mode: mode) + } + switch mode { + case .paneMap: + ToolbarItem(id: "pane-map-refresh", placement: .topBarTrailing) { + PaneMapRefreshToolbarButton( + isRefreshing: isPaneMapRefreshing, + refresh: { paneMapRefreshTrigger &+= 1 } + ) + } + ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { + PaneMapDoneToolbarButton(done: returnToTerminalFromPaneMap) + } + case .terminal: + ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { + previewToolbarTrailingContent + } + } + } + + private func previewWorkspaceTitleMenu(mode: PreviewToolbarMode) -> some View { + let value = WorkspaceTitleMenuValue( + contentWidth: contentWidth, + hasBackButton: true, + hasTrailingCluster: true, + hasChatToggle: false, + reservesPaneMapControls: true, + isEnabled: true, + workspaceName: workspace.name, + hasUnread: false, + canCustomizeWorkspace: false, + canRenameWorkspace: true, + canToggleReadState: false, + canCloseWorkspace: false, + labelToken: .standard( + title: workspace.name, + subtitle: previewToolbarSubtitle(mode: mode) + ), + terminalTheme: terminalTheme + ) + return WorkspaceTitleMenu( + value: value, + menuContent: { + WorkspaceTitleMenuContent( + workspaceName: value.workspaceName, + hasUnread: value.hasUnread, + canCustomizeWorkspace: value.canCustomizeWorkspace, + canRenameWorkspace: value.canRenameWorkspace, + canToggleReadState: value.canToggleReadState, + canCloseWorkspace: value.canCloseWorkspace, + presentCustomization: {}, + presentRename: {}, + toggleReadState: {}, + requestClose: {} + ) + }, + label: { + WorkspaceToolbarTitleView( + title: workspace.name, + subtitle: previewToolbarSubtitle(mode: mode) + ) + } + ) + .equatable() + } + + private func previewToolbarSubtitle(mode: PreviewToolbarMode) -> String? { + switch mode { + case .paneMap: + guard let layout = fixtureLayout else { return nil } + return PaneMapValue( + layout: layout, + phoneSelectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID + ).countSubtitle + case .terminal: + return workspace.terminals.first { + $0.id.rawValue == selectedSurfaceID + }?.name + } + } + + private var previewToolbarTrailingContent: some View { + WorkspaceUtilitiesMenu( + showsViewAsText: false, + showsPaneMap: true, + terminalTheme: terminalTheme, + presentPaneMap: presentPaneMap, + openTextSheet: {}, + copyDebugLogs: {}, + sendFeedback: {} + ) + } + + private var fixtureLayout: MobilePaneLayout? { + guard let baseLayout = workspace.layout else { return nil } + let panesByID = Dictionary( + uniqueKeysWithValues: baseLayout.orderedPanes.map { ($0.id, $0) } + ) + let slotPaneIDs = baseLayout.orderedPanes.map(\.id) + let contentsBySlotID = Dictionary( + uniqueKeysWithValues: zip(slotPaneIDs, orderedFixturePaneIDs).compactMap { + slotID, contentID in + panesByID[contentID].map { (slotID, $0) } + } + ) + let focusedPaneID = baseLayout.focusedPaneID.flatMap { focusedContentID in + orderedFixturePaneIDs.firstIndex(of: focusedContentID).map { + slotPaneIDs[$0] + } + } + return MobilePaneLayout( + version: baseLayout.version + paneMapRefreshTrigger + fixtureLayoutRevision, + focusedPaneID: focusedPaneID, + root: replacingFixturePaneContents( + in: baseLayout.root, + contentsBySlotID: contentsBySlotID + ) + ) + } + + private func replacingFixturePaneContents( + in node: MobilePaneLayout.Node, + contentsBySlotID: [String: MobilePaneNode] + ) -> MobilePaneLayout.Node { + switch node { + case .pane(let slot): + guard let content = contentsBySlotID[slot.id] else { return node } + return .pane(MobilePaneNode( + id: slot.id, + selectedSurfaceID: content.selectedSurfaceID, + surfaces: content.surfaces + )) + case .split(let split): + return .split(MobilePaneSplit( + id: split.id, + orientation: split.orientation, + ratio: split.ratio, + first: replacingFixturePaneContents( + in: split.first, + contentsBySlotID: contentsBySlotID + ), + second: replacingFixturePaneContents( + in: split.second, + contentsBySlotID: contentsBySlotID + ) + )) + } + } + + @MainActor + private func reorderFixturePanes( + _ orderedPaneIDs: [String], + baseLayoutRevision: Int + ) async -> Bool { + guard let slotPaneIDs = workspace.layout?.orderedPanes.map(\.id), + orderedPaneIDs.count == slotPaneIDs.count, + Set(orderedPaneIDs) == Set(slotPaneIDs) else { + return false + } + let currentContentBySlotID = Dictionary( + uniqueKeysWithValues: zip(slotPaneIDs, orderedFixturePaneIDs) + ) + orderedFixturePaneIDs = orderedPaneIDs.compactMap { + currentContentBySlotID[$0] + } + fixtureLayoutRevision &+= 1 + await Task.yield() + return true + } + + private static func fetchFixturePreviews( + selectedSurfaceIDs: [String], + remainingSurfaceIDs: [String] + ) async -> [String: MobileTerminalRenderGridFrame] { + let textBySurfaceID = [ + claudeSurfaceID: """ + ╭─ Claude Code ─────────────────────────╮ + │ I’ll inspect the routing layer first. │ + ╰───────────────────────────────────────╯ + Read Sources/API/Router.ts + Edit Sources/API/Router.ts + Running focused tests… + """, + zshSurfaceID: """ + api-server % git status --short + M Sources/API/Router.ts + api-server % bun run lint + Checked 42 files in 318ms. No fixes needed. + api-server % + """, + testsSurfaceID: """ + bun test v1.2.18 + ✓ auth middleware (12 tests) + ✓ router params (8 tests) + ✗ websocket reconnect + expected 2 messages, received 1 + Waiting for file changes… + """, + logSurfaceID: """ + 14:32:08 INFO listening on http://localhost:3000 + 14:32:11 GET /api/health 200 3ms + 14:32:14 POST /api/chat 202 18ms + 14:32:15 INFO stream connected client=mobile + 14:32:19 GET /assets/app.js 304 2ms + """, + gitSurfaceID: """ + ┌─ Status ───────────────┐┌─ Staged ───────────────┐ + │M Sources/API/Router.ts ││ │ + │M Tests/RouterTests.ts ││ │ + └────────────────────────┘└────────────────────────┘ + ┌─ Commits ────────────────────────────────────────┐ + │d85a567 Test mobile observer via emitted updates │ + └──────────────────────────────────────────────────┘ + """, + ] + + var previews: [String: MobileTerminalRenderGridFrame] = [:] + for surfaceID in selectedSurfaceIDs + remainingSurfaceIDs where previews[surfaceID] == nil { + guard let text = textBySurfaceID[surfaceID] else { + continue + } + if surfaceID == claudeSurfaceID { + previews[surfaceID] = try? styledClaudeFrame() + } else { + previews[surfaceID] = try? MobileTerminalRenderGridFrame.fromPlainRows( + surfaceID: surfaceID, + stateSeq: 1, + columns: 50, + rows: 12, + text: text + ) + } + } + return previews + } + + private static func styledClaudeFrame() throws -> MobileTerminalRenderGridFrame { + var effectiveTheme = TerminalTheme.monokai + effectiveTheme.background = "#123456" + return try MobileTerminalRenderGridFrame( + surfaceID: claudeSurfaceID, + stateSeq: 1, + columns: 50, + rows: 12, + styles: [ + .default, + .init(id: 1, foreground: "#a6e22e", bold: true), + .init(id: 2, foreground: "#272822", background: "#66d9ef", bold: true), + .init(id: 3, foreground: "#e6db74"), + ], + rowSpans: [ + .init(row: 0, column: 0, styleID: 2, text: " Claude Code "), + .init(row: 1, column: 0, styleID: 1, text: "╭──────────────────────────────────────────────╮"), + .init(row: 2, column: 0, styleID: 1, text: "│"), + .init(row: 2, column: 2, text: "I’ll inspect the routing layer first."), + .init(row: 2, column: 47, styleID: 1, text: "│"), + .init(row: 3, column: 0, styleID: 1, text: "╰──────────────────────────────────────────────╯"), + .init(row: 5, column: 0, styleID: 3, text: "Read"), + .init(row: 5, column: 6, text: "Sources/API/Router.ts"), + .init(row: 6, column: 0, styleID: 3, text: "Edit"), + .init(row: 6, column: 6, text: "Sources/API/Router.ts"), + .init(row: 8, column: 0, styleID: 1, text: "Running focused tests…"), + ], + terminalBackground: "#abcdef", + terminalTheme: effectiveTheme + ) + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileConnectionRecoveryOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileConnectionRecoveryOverlay.swift index ce7f0d66f8dd..dcd423043c5b 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileConnectionRecoveryOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileConnectionRecoveryOverlay.swift @@ -4,6 +4,7 @@ import SwiftUI private struct MobileConnectionRecoveryOverlay: ViewModifier { @Bindable var store: CMUXMobileShellStore var signOut: (@MainActor @Sendable () -> Void)? + var isActive = true func body(content: Content) -> some View { // Reauth is a blocking condition, not a status: the Mac rejected the @@ -11,7 +12,7 @@ private struct MobileConnectionRecoveryOverlay: ViewModifier { // surface. Transient reconnects and failed attempts keep the terminal // visible and ride the status pill / picker status line instead. content.overlay(alignment: .top) { - if store.connectionRequiresReauth { + if isActive, store.connectionRequiresReauth { MobileConnectionRecoveryBanner( connectionRequiresReauth: store.connectionRequiresReauth, connectionError: store.connectionError, @@ -23,10 +24,21 @@ private struct MobileConnectionRecoveryOverlay: ViewModifier { } extension View { + /// - Parameter isActive: Whether this attachment point is the visible + /// layer. The workspace detail attaches the overlay to both its base + /// layer and the terminal's full-screen cover; only the visible layer + /// renders the banner so it never draws twice. func mobileConnectionRecoveryOverlay( store: CMUXMobileShellStore, - signOut: (@MainActor @Sendable () -> Void)? + signOut: (@MainActor @Sendable () -> Void)?, + isActive: Bool = true ) -> some View { - modifier(MobileConnectionRecoveryOverlay(store: store, signOut: signOut)) + modifier( + MobileConnectionRecoveryOverlay( + store: store, + signOut: signOut, + isActive: isActive + ) + ) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift index 5188fbe0f1c8..a89b96cc90e3 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift @@ -10,6 +10,7 @@ struct MobileLeadingToolbarTitleWidth { let hasBackButton: Bool let hasTrailingCluster: Bool let hasChatToggle: Bool + let reservesPaneMapControls: Bool static let backButtonReserve: CGFloat = 44 static let trailingReserveBase: CGFloat = 64 @@ -17,14 +18,17 @@ struct MobileLeadingToolbarTitleWidth { static let barMarginsAndSpacing: CGFloat = 84 static let unmeasuredFallback: CGFloat = 140 static let maximumMeasuredCap: CGFloat = unmeasuredFallback - static let floor: CGFloat = 96 var cap: CGFloat { guard contentWidth > 0 else { return Self.unmeasuredFallback } let leading = hasBackButton ? Self.backButtonReserve : 0 - let trailing = hasTrailingCluster + let terminalTrailing = hasTrailingCluster ? Self.trailingReserveBase + (hasChatToggle ? Self.chatToggleReserve : 0) : 0 + let paneMapTrailing = reservesPaneMapControls + ? PaneMapToolbarMetrics.trailingClusterWidth + : 0 + let trailing = max(terminalTrailing, paneMapTrailing) let measuredCap = max(0, contentWidth - leading - trailing - Self.barMarginsAndSpacing) return min(Self.maximumMeasuredCap, measuredCap) } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionLayout.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionLayout.swift new file mode 100644 index 000000000000..14b20018e57d --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionLayout.swift @@ -0,0 +1,231 @@ +import CmuxMobileShellModel +import UIKit + +/// Pure constrained layout used by the pane-map collection view. +struct PaneMapCollectionLayoutEngine { + struct Insets: Equatable { + let top: CGFloat + let leading: CGFloat + let bottom: CGFloat + let trailing: CGFloat + + static let paneMap = Insets(top: 8, leading: 16, bottom: 16, trailing: 16) + } + + struct Result: Equatable { + let framesByPaneID: [String: CGRect] + let orderedFrames: [CGRect] + let contentSize: CGSize + let overflowsHorizontally: Bool + let overflowsVertically: Bool + } + + let minimumItemSize: CGSize + let spacing: CGFloat + let insets: Insets + + init( + minimumItemSize: CGSize = CGSize(width: 156, height: 220), + spacing: CGFloat = 14, + insets: Insets = .paneMap + ) { + self.minimumItemSize = minimumItemSize + self.spacing = spacing + self.insets = insets + } + + func layout(_ layout: MobilePaneLayout, in viewportSize: CGSize) -> Result { + let viewportWidth = max(0, viewportSize.width) + let viewportHeight = max(0, viewportSize.height) + let availableSize = CGSize( + width: max(0, viewportWidth - insets.leading - insets.trailing), + height: max(0, viewportHeight - insets.top - insets.bottom) + ) + let minimumRootSize = minimumSize(for: layout.root) + let rootSize = CGSize( + width: max(availableSize.width, minimumRootSize.width), + height: max(availableSize.height, minimumRootSize.height) + ) + let rootRect = CGRect( + x: insets.leading, + y: insets.top, + width: rootSize.width, + height: rootSize.height + ) + + var framesByPaneID: [String: CGRect] = [:] + appendFrames(for: layout.root, in: rootRect, to: &framesByPaneID) + let contentSize = CGSize( + width: rootSize.width + insets.leading + insets.trailing, + height: rootSize.height + insets.top + insets.bottom + ) + return Result( + framesByPaneID: framesByPaneID, + orderedFrames: layout.orderedPanes.compactMap { framesByPaneID[$0.id] }, + contentSize: contentSize, + overflowsHorizontally: contentSize.width > viewportWidth + 0.5, + overflowsVertically: contentSize.height > viewportHeight + 0.5 + ) + } + + private func minimumSize(for node: MobilePaneLayout.Node) -> CGSize { + switch node { + case .pane: + return minimumItemSize + case let .split(split): + let first = minimumSize(for: split.first) + let second = minimumSize(for: split.second) + switch split.orientation { + case .horizontal: + return CGSize( + width: first.width + spacing + second.width, + height: max(first.height, second.height) + ) + case .vertical: + return CGSize( + width: max(first.width, second.width), + height: first.height + spacing + second.height + ) + } + } + } + + private func appendFrames( + for node: MobilePaneLayout.Node, + in rect: CGRect, + to framesByPaneID: inout [String: CGRect] + ) { + switch node { + case let .pane(pane): + framesByPaneID[pane.id] = rect.integral + case let .split(split): + let firstMinimum = minimumSize(for: split.first) + let secondMinimum = minimumSize(for: split.second) + let firstRect: CGRect + let secondRect: CGRect + + switch split.orientation { + case .horizontal: + let distributableWidth = max(0, rect.width - spacing) + let firstWidth = constrainedLength( + preferred: distributableWidth * CGFloat(split.ratio), + total: distributableWidth, + firstMinimum: firstMinimum.width, + secondMinimum: secondMinimum.width + ) + firstRect = CGRect( + x: rect.minX, + y: rect.minY, + width: firstWidth, + height: rect.height + ) + secondRect = CGRect( + x: firstRect.maxX + spacing, + y: rect.minY, + width: max(0, distributableWidth - firstWidth), + height: rect.height + ) + case .vertical: + let distributableHeight = max(0, rect.height - spacing) + let firstHeight = constrainedLength( + preferred: distributableHeight * CGFloat(split.ratio), + total: distributableHeight, + firstMinimum: firstMinimum.height, + secondMinimum: secondMinimum.height + ) + firstRect = CGRect( + x: rect.minX, + y: rect.minY, + width: rect.width, + height: firstHeight + ) + secondRect = CGRect( + x: rect.minX, + y: firstRect.maxY + spacing, + width: rect.width, + height: max(0, distributableHeight - firstHeight) + ) + } + + appendFrames(for: split.first, in: firstRect, to: &framesByPaneID) + appendFrames(for: split.second, in: secondRect, to: &framesByPaneID) + } + } + + private func constrainedLength( + preferred: CGFloat, + total: CGFloat, + firstMinimum: CGFloat, + secondMinimum: CGFloat + ) -> CGFloat { + min( + max(preferred, firstMinimum), + max(firstMinimum, total - secondMinimum) + ) + } +} + +/// UICollectionView layout that assigns the constrained pane slots by depth-first order. +final class PaneMapCollectionLayout: UICollectionViewLayout { + var paneLayout: MobilePaneLayout { + didSet { + guard paneLayout != oldValue else { return } + invalidateLayout() + } + } + + private let engine: PaneMapCollectionLayoutEngine + private var attributes: [UICollectionViewLayoutAttributes] = [] + private var result: PaneMapCollectionLayoutEngine.Result? + + init( + paneLayout: MobilePaneLayout, + engine: PaneMapCollectionLayoutEngine = PaneMapCollectionLayoutEngine() + ) { + self.paneLayout = paneLayout + self.engine = engine + super.init() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func prepare() { + super.prepare() + guard let collectionView else { return } + let result = engine.layout(paneLayout, in: collectionView.bounds.size) + self.result = result + let itemCount = collectionView.numberOfItems(inSection: 0) + attributes = (0.. [UICollectionViewLayoutAttributes]? { + attributes.filter { $0.frame.intersects(rect) } + } + + override func layoutAttributesForItem( + at indexPath: IndexPath + ) -> UICollectionViewLayoutAttributes? { + guard attributes.indices.contains(indexPath.item) else { return nil } + return attributes[indexPath.item] + } + + override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { + guard let collectionView else { return false } + return collectionView.bounds.size != newBounds.size + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift new file mode 100644 index 000000000000..b6230a025a70 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -0,0 +1,626 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import CmuxMobileTerminal +import SwiftUI +import UIKit + +struct PaneMapCollectionItem: Equatable, Identifiable { + let pane: MobilePaneNode + let paneNumber: Int + let paneCount: Int + let isFocusedOnMac: Bool + let selectedSurfaceID: String? + let phoneSelectedSurfaceID: String? + let preview: MobileTerminalPaneMapPreview? + let isLoadingPreview: Bool + let agentStateKind: ChatAgentStateKind? + + var id: String { pane.id } + + var selectedSurface: MobilePaneSurface? { + guard let selectedSurfaceID else { return pane.surfaces.first } + return pane.surfaces.first { $0.id == selectedSurfaceID } + } + + /// The same pane content relabeled for a new visible position, so + /// accessibility ordinals track optimistic reorders instead of waiting for + /// the next authoritative snapshot. + func withPanePosition(number: Int) -> PaneMapCollectionItem { + PaneMapCollectionItem( + pane: pane, + paneNumber: number, + paneCount: paneCount, + isFocusedOnMac: isFocusedOnMac, + selectedSurfaceID: selectedSurfaceID, + phoneSelectedSurfaceID: phoneSelectedSurfaceID, + preview: preview, + isLoadingPreview: isLoadingPreview, + agentStateKind: agentStateKind + ) + } +} + +struct PaneMapOverflowLabels { + let leading: String + let trailing: String + let top: String + let bottom: String +} + +/// UIKit collection surface for native interactive movement and fluid system zoom sources. +struct PaneMapCollectionView: UIViewRepresentable { + let items: [PaneMapCollectionItem] + let layout: MobilePaneLayout + let terminalTheme: TerminalTheme + let zoomNamespace: Namespace.ID + let overflowLabels: PaneMapOverflowLabels + let allowsReordering: Bool + /// Whether the map is the visible layer. While the terminal's full-screen + /// cover is up the map stays mounted underneath, and its UIKit elements + /// must leave the accessibility tree: SwiftUI's `accessibilityHidden` on + /// an ancestor is not honored for bridged UIKit content under a cover. + let isVisible: Bool + let selectPreviewSurface: (_ paneID: String, _ surfaceID: String) -> Void + let jumpToTerminal: (_ surfaceID: String) -> Void + let reorderPanes: (_ orderedPaneIDs: [String], _ baseLayoutRevision: Int) async -> Bool + + func makeCoordinator() -> Coordinator { + Coordinator(parent: self) + } + + func makeUIView(context: Context) -> PaneMapCollectionContainerView { + let collectionLayout = PaneMapCollectionLayout(paneLayout: layout) + let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionLayout) + collectionView.backgroundColor = .clear + collectionView.alwaysBounceHorizontal = false + collectionView.alwaysBounceVertical = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.keyboardDismissMode = .interactive + collectionView.showsHorizontalScrollIndicator = true + collectionView.showsVerticalScrollIndicator = true + collectionView.accessibilityIdentifier = "MobilePaneMapCollection" + collectionView.register( + UICollectionViewCell.self, + forCellWithReuseIdentifier: Coordinator.cellReuseIdentifier + ) + collectionView.dataSource = context.coordinator + collectionView.delegate = context.coordinator + + let container = PaneMapCollectionContainerView(collectionView: collectionView) + container.configure( + terminalTheme: terminalTheme, + labels: overflowLabels, + scrollStep: context.coordinator.scrollOneViewport + ) + container.accessibilityElementsHidden = !isVisible + context.coordinator.attach(collectionView: collectionView, container: container) + context.coordinator.reconcile(items: items) + return container + } + + func updateUIView(_ container: PaneMapCollectionContainerView, context: Context) { + context.coordinator.parent = self + if let collectionLayout = container.collectionView.collectionViewLayout + as? PaneMapCollectionLayout { + collectionLayout.paneLayout = layout + } + container.collectionView.dragInteractionEnabled = allowsReordering + container.configure( + terminalTheme: terminalTheme, + labels: overflowLabels, + scrollStep: context.coordinator.scrollOneViewport + ) + container.accessibilityElementsHidden = !isVisible + context.coordinator.reconcile(items: items) + } + + @MainActor + final class Coordinator: NSObject, + UICollectionViewDataSource, + UICollectionViewDelegate, + UICollectionViewDragDelegate, + UICollectionViewDropDelegate, + UIGestureRecognizerDelegate + { + static let cellReuseIdentifier = "PaneMapCollectionCell" + + var parent: PaneMapCollectionView + private(set) var orderedItems: [PaneMapCollectionItem] = [] + private weak var collectionView: UICollectionView? + private weak var container: PaneMapCollectionContainerView? + private var isMovingItem = false + private var pendingItems: [PaneMapCollectionItem]? + private var authoritativeItemsByID: [String: PaneMapCollectionItem] + private var reorderState: PaneMapReorderState + private var selectionArbitration = PaneMapSelectionArbitration() + private let tileMetrics = PaneMapTileMetrics() + private let tabStripMetrics = PaneMapTabStripMetrics() + + init(parent: PaneMapCollectionView) { + self.parent = parent + // A malformed remote layout can repeat a pane ID; first-wins keeps + // the coordinator alive instead of trapping on duplicate keys. + authoritativeItemsByID = Dictionary( + parent.items.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } + ) + reorderState = PaneMapReorderState( + authoritativePaneIDs: Self.deduplicatedPaneIDs(parent.items), + authoritativeRevision: parent.layout.version + ) + } + + private static func deduplicatedPaneIDs(_ items: [PaneMapCollectionItem]) -> [String] { + var seen: Set = [] + return items.map(\.id).filter { seen.insert($0).inserted } + } + + func attach( + collectionView: UICollectionView, + container: PaneMapCollectionContainerView + ) { + self.collectionView = collectionView + self.container = container + collectionView.dragInteractionEnabled = parent.allowsReordering + collectionView.reorderingCadence = .immediate + collectionView.dragDelegate = self + collectionView.dropDelegate = self + let resolvedTap = UILongPressGestureRecognizer( + target: self, + action: #selector(handleResolvedTap(_:)) + ) + resolvedTap.minimumPressDuration = 0 + resolvedTap.allowableMovement = 10 + resolvedTap.cancelsTouchesInView = false + resolvedTap.delegate = self + collectionView.addGestureRecognizer(resolvedTap) + } + + func reconcile(items: [PaneMapCollectionItem]) { + authoritativeItemsByID = Dictionary( + items.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } + ) + guard !isMovingItem else { + pendingItems = items + return + } + + reorderState.reconcile( + authoritativePaneIDs: Self.deduplicatedPaneIDs(items), + authoritativeRevision: parent.layout.version + ) + reloadVisibleItems() + } + + private func reloadVisibleItems() { + orderedItems = reorderState.visiblePaneIDs + .compactMap { authoritativeItemsByID[$0] } + .enumerated() + .map { index, item in item.withPanePosition(number: index + 1) } + collectionView?.reloadData() + collectionView?.collectionViewLayout.invalidateLayout() + container?.setNeedsLayout() + container?.prewarmDetachedCellLayout(estimatedSize: Self.detachedPrewarmSize()) + } + + private static func detachedPrewarmSize() -> CGSize { + let scenes = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + guard let scene else { return .zero } + return scene.keyWindow?.bounds.size ?? scene.screen.bounds.size + } + + func numberOfSections(in collectionView: UICollectionView) -> Int { 1 } + + func collectionView( + _ collectionView: UICollectionView, + numberOfItemsInSection section: Int + ) -> Int { + orderedItems.count + } + + func collectionView( + _ collectionView: UICollectionView, + cellForItemAt indexPath: IndexPath + ) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell( + withReuseIdentifier: Self.cellReuseIdentifier, + for: indexPath + ) + guard orderedItems.indices.contains(indexPath.item) else { return cell } + let item = orderedItems[indexPath.item] + cell.backgroundColor = .clear + cell.contentView.backgroundColor = .clear + cell.contentConfiguration = UIHostingConfiguration { + PaneMapTileView( + item: item, + terminalTheme: parent.terminalTheme, + zoomNamespace: parent.zoomNamespace, + selectPreviewSurface: { [weak self] surfaceID in + self?.selectionArbitration.cancel() + self?.parent.selectPreviewSurface(item.pane.id, surfaceID) + }, + jumpToTerminal: { [weak self] surfaceID in self?.resolveAccessibilitySelection(surfaceID) } + ) + } + .margins(.all, 0) + .background(.clear) + return cell + } + + func collectionView( + _ collectionView: UICollectionView, + itemsForBeginning session: UIDragSession, + at indexPath: IndexPath + ) -> [UIDragItem] { + guard parent.allowsReordering, + !reorderState.isMutationPending, + orderedItems.indices.contains(indexPath.item), + orderedItems.count > 1 else { return [] } + isMovingItem = true + selectionArbitration.dragSessionDidBegin() + let itemID = orderedItems[indexPath.item].id + let dragItem = UIDragItem(itemProvider: NSItemProvider(object: itemID as NSString)) + dragItem.localObject = itemID + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + return [dragItem] + } + + func collectionView( + _ collectionView: UICollectionView, + dropSessionDidUpdate session: UIDropSession, + withDestinationIndexPath destinationIndexPath: IndexPath? + ) -> UICollectionViewDropProposal { + guard session.localDragSession != nil else { + return UICollectionViewDropProposal(operation: .forbidden) + } + return UICollectionViewDropProposal( + operation: .move, + intent: .insertAtDestinationIndexPath + ) + } + + func collectionView( + _ collectionView: UICollectionView, + performDropWith coordinator: UICollectionViewDropCoordinator + ) { + guard let droppedItem = coordinator.items.first, + let sourceIndexPath = droppedItem.sourceIndexPath, + orderedItems.indices.contains(sourceIndexPath.item) else { return } + let proposedDestination = coordinator.destinationIndexPath + ?? IndexPath(item: orderedItems.count - 1, section: 0) + let destinationItem = min( + max(0, proposedDestination.item), + orderedItems.count - 1 + ) + let destinationIndexPath = IndexPath(item: destinationItem, section: 0) + guard let request = reorderState.beginMove( + from: sourceIndexPath.item, + to: destinationItem + ) else { + return + } + + collectionView.performBatchUpdates { + let item = orderedItems.remove(at: sourceIndexPath.item) + orderedItems.insert(item, at: destinationItem) + collectionView.moveItem(at: sourceIndexPath, to: destinationIndexPath) + } + coordinator.drop(droppedItem.dragItem, toItemAt: destinationIndexPath) + // Moved cells keep their pre-drag ordinals until reconfigured; + // relabel the optimistic order so VoiceOver reads the position the + // pane actually occupies during the mutation window. + orderedItems = orderedItems.enumerated().map { index, item in + item.withPanePosition(number: index + 1) + } + collectionView.reconfigureItems(at: collectionView.indexPathsForVisibleItems) + Task { [weak self] in + guard let self else { return } + let succeeded = await parent.reorderPanes( + request.orderedPaneIDs, + request.baseLayoutRevision + ) + completeReorder(requestID: request.id, succeeded: succeeded) + } + } + + func collectionView( + _ collectionView: UICollectionView, + dragSessionDidEnd session: UIDragSession + ) { + finishInteractiveMovement() + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + container?.updateOverflowIndicators() + selectionArbitration.touchMoved( + to: scrollView.panGestureRecognizer.location(in: scrollView) + ) + } + + func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + selectionArbitration.dragSessionDidBegin() + } + + private func finishInteractiveMovement() { + isMovingItem = false + collectionView?.collectionViewLayout.invalidateLayout() + if let pendingItems { + self.pendingItems = nil + reconcile(items: pendingItems) + } + } + + private func completeReorder(requestID: UUID, succeeded: Bool) { + let completion = reorderState.complete( + requestID: requestID, + succeeded: succeeded + ) + guard completion != .ignored else { return } + if completion == .rolledBack { + UINotificationFeedbackGenerator().notificationOccurred(.error) + } + reloadVisibleItems() + } + + private func resolveAccessibilitySelection(_ surfaceID: String) { + guard !isMovingItem, !reorderState.isMutationPending else { return } + parent.jumpToTerminal(surfaceID) + } + + @objc private func handleResolvedTap(_ gesture: UILongPressGestureRecognizer) { + guard let collectionView else { return } + let location = gesture.location(in: collectionView) + switch gesture.state { + case .began: + selectionArbitration.touchBegan(at: location) + case .changed: + selectionArbitration.touchMoved(to: location) + case .ended: + guard selectionArbitration.touchEnded(at: location), + !isMovingItem, + !reorderState.isMutationPending, + let indexPath = collectionView.indexPathForItem(at: location), + orderedItems.indices.contains(indexPath.item), + !isPointInTabSwitcher( + location, + indexPath: indexPath, + collectionView: collectionView + ), + let surfaceID = orderedItems[indexPath.item].selectedSurface?.id, + orderedItems[indexPath.item].selectedSurface?.type.isTerminal == true else { + return + } + parent.jumpToTerminal(surfaceID) + case .cancelled, .failed: + selectionArbitration.cancel() + default: + break + } + } + + private func isPointInTabSwitcher( + _ collectionLocation: CGPoint, + indexPath: IndexPath, + collectionView: UICollectionView + ) -> Bool { + guard orderedItems[indexPath.item].pane.surfaces.count > 1, + let cell = collectionView.cellForItem(at: indexPath) else { + return false + } + let previewBounds = CGRect( + x: cell.frame.minX, + y: cell.frame.minY, + width: cell.frame.width, + height: max(0, cell.bounds.height - tileMetrics.captionHeight) + ) + return tabStripMetrics.frame( + in: previewBounds, + tabCount: orderedItems[indexPath.item].pane.surfaces.count + ).contains(collectionLocation) + } + + func gestureRecognizer( + _ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer + ) -> Bool { + true + } + + func collectionView( + _ collectionView: UICollectionView, + dragPreviewParametersForItemAt indexPath: IndexPath + ) -> UIDragPreviewParameters? { + guard let cell = collectionView.cellForItem(at: indexPath) else { return nil } + let parameters = UIDragPreviewParameters() + parameters.backgroundColor = .clear + parameters.visiblePath = UIBezierPath( + roundedRect: cell.bounds, + cornerRadius: tileMetrics.cornerRadius + ) + return parameters + } + + func scrollOneViewport(_ direction: PaneMapOverflowDirection) { + guard let collectionView else { return } + let horizontalStep = max(80, collectionView.bounds.width * 0.72) + let verticalStep = max(80, collectionView.bounds.height * 0.72) + var offset = collectionView.contentOffset + switch direction { + case .leading: + offset.x -= horizontalStep + case .trailing: + offset.x += horizontalStep + case .top: + offset.y -= verticalStep + case .bottom: + offset.y += verticalStep + } + let maximumOffset = CGPoint( + x: max(0, collectionView.contentSize.width - collectionView.bounds.width), + y: max(0, collectionView.contentSize.height - collectionView.bounds.height) + ) + offset.x = min(maximumOffset.x, max(0, offset.x)) + offset.y = min(maximumOffset.y, max(0, offset.y)) + collectionView.setContentOffset(offset, animated: true) + } + } +} + +enum PaneMapOverflowDirection: CaseIterable { + case leading + case trailing + case top + case bottom + + var systemImage: String { + switch self { + case .leading: "chevron.left" + case .trailing: "chevron.right" + case .top: "chevron.up" + case .bottom: "chevron.down" + } + } +} + +final class PaneMapCollectionContainerView: UIView { + let collectionView: UICollectionView + private var buttons: [PaneMapOverflowDirection: PaneMapOverflowButton] = [:] + private var scrollStep: ((PaneMapOverflowDirection) -> Void)? + private var lastLayoutSize: CGSize = .zero + + init(collectionView: UICollectionView) { + self.collectionView = collectionView + super.init(frame: .zero) + addSubview(collectionView) + for direction in PaneMapOverflowDirection.allCases { + let button = PaneMapOverflowButton(direction: direction) + button.addAction(UIAction { [weak self] _ in + self?.scrollStep?(direction) + }, for: .primaryActionTriggered) + buttons[direction] = button + addSubview(button) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func configure( + terminalTheme: TerminalTheme, + labels: PaneMapOverflowLabels, + scrollStep: @escaping (PaneMapOverflowDirection) -> Void + ) { + backgroundColor = terminalTheme.terminalBackgroundUIColor + self.scrollStep = scrollStep + for button in buttons.values { + button.tintColor = terminalTheme.terminalForegroundUIColor + } + buttons[.leading]?.accessibilityLabel = labels.leading + buttons[.trailing]?.accessibilityLabel = labels.trailing + buttons[.top]?.accessibilityLabel = labels.top + buttons[.bottom]?.accessibilityLabel = labels.bottom + } + + override func layoutSubviews() { + super.layoutSubviews() + collectionView.frame = bounds + let buttonSize = CGSize(width: 38, height: 38) + let horizontalY = bounds.midY - buttonSize.height / 2 + let verticalX = bounds.midX - buttonSize.width / 2 + buttons[.leading]?.frame = CGRect( + x: 6, + y: horizontalY, + width: buttonSize.width, + height: buttonSize.height + ) + buttons[.trailing]?.frame = CGRect( + x: bounds.maxX - buttonSize.width - 6, + y: horizontalY, + width: buttonSize.width, + height: buttonSize.height + ) + buttons[.top]?.frame = CGRect( + x: verticalX, + y: 6, + width: buttonSize.width, + height: buttonSize.height + ) + buttons[.bottom]?.frame = CGRect( + x: verticalX, + y: bounds.maxY - buttonSize.height - 6, + width: buttonSize.width, + height: buttonSize.height + ) + if lastLayoutSize != bounds.size { + lastLayoutSize = bounds.size + collectionView.collectionViewLayout.invalidateLayout() + } + collectionView.layoutIfNeeded() + updateOverflowIndicators() + } + + /// Materializes the map's cells while this view has no window. + /// + /// The map is the navigation-stack root and a restored workspace starts + /// with the terminal pushed on top, so UIKit never lays this view out + /// before the first terminal→map pop. The zoom transition's matched + /// source tile lives inside a cell; if no cell exists when that pop + /// begins, the unzoom degrades to a hard cut. Sizing the detached + /// container to the scene estimate and forcing layout creates the tiles + /// ahead of the first pop; the real layout pass corrects the geometry. + func prewarmDetachedCellLayout(estimatedSize: CGSize) { + guard window == nil else { return } + if bounds.size == .zero { + guard estimatedSize != .zero else { return } + frame = CGRect(origin: .zero, size: estimatedSize) + } + layoutIfNeeded() + } + + func updateOverflowIndicators() { + let maximumX = max(0, collectionView.contentSize.width - collectionView.bounds.width) + let maximumY = max(0, collectionView.contentSize.height - collectionView.bounds.height) + let offset = collectionView.contentOffset + buttons[.leading]?.isHidden = maximumX <= 1 || offset.x <= 4 + buttons[.trailing]?.isHidden = maximumX <= 1 || offset.x >= maximumX - 4 + buttons[.top]?.isHidden = maximumY <= 1 || offset.y <= 4 + buttons[.bottom]?.isHidden = maximumY <= 1 || offset.y >= maximumY - 4 + } +} + +private final class PaneMapOverflowButton: UIButton { + private let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterial)) + + init(direction: PaneMapOverflowDirection) { + super.init(frame: .zero) + isAccessibilityElement = true + accessibilityTraits = .button + tintColor = .label + setImage(UIImage(systemName: direction.systemImage), for: .normal) + imageView?.contentMode = .scaleAspectFit + blurView.isUserInteractionEnabled = false + blurView.clipsToBounds = true + insertSubview(blurView, at: 0) + layer.shadowColor = UIColor.black.cgColor + layer.shadowOpacity = 0.22 + layer.shadowRadius = 8 + layer.shadowOffset = CGSize(width: 0, height: 3) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func layoutSubviews() { + super.layoutSubviews() + blurView.frame = bounds + blurView.layer.cornerRadius = bounds.width / 2 + } +} + diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift new file mode 100644 index 000000000000..bf62d1e4e308 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -0,0 +1,215 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import CmuxMobileSupport +import SwiftUI + +/// Full-screen interactive map of a workspace's Mac pane layout. +struct PaneMapOverlay: View { + let value: PaneMapValue + let terminalTheme: TerminalTheme + let zoomNamespace: Namespace.ID + let isVisible: Bool + let allowsReordering: Bool + let refreshTrigger: Int + let fetchPreviews: ([String], [String]) async -> [String: MobileTerminalRenderGridFrame] + let selectTerminal: (MobileTerminalPreview.ID) -> Void + let reorderPanes: ([String], Int) async -> Bool + let refreshingChanged: (Bool) -> Void + + @State private var selectedSurfaceIDsByPaneID: [String: String] + @State private var previewsBySurfaceID: [String: MobileTerminalPaneMapPreview] = [:] + @State private var isRefreshing = false + @State private var refreshTask: Task? + @State private var refreshGeneration: UUID? + + init( + value: PaneMapValue, + terminalTheme: TerminalTheme, + zoomNamespace: Namespace.ID, + isVisible: Bool, + allowsReordering: Bool, + refreshTrigger: Int, + fetchPreviews: @escaping ([String], [String]) async -> [String: MobileTerminalRenderGridFrame], + selectTerminal: @escaping (MobileTerminalPreview.ID) -> Void, + reorderPanes: @escaping ([String], Int) async -> Bool, + refreshingChanged: @escaping (Bool) -> Void + ) { + self.value = value + self.terminalTheme = terminalTheme + self.zoomNamespace = zoomNamespace + self.isVisible = isVisible + self.allowsReordering = allowsReordering + self.refreshTrigger = refreshTrigger + self.fetchPreviews = fetchPreviews + self.selectTerminal = selectTerminal + self.reorderPanes = reorderPanes + self.refreshingChanged = refreshingChanged + _selectedSurfaceIDsByPaneID = State(initialValue: value.initialSurfaceIDsByPaneID) + } + + var body: some View { + PaneMapCollectionView( + items: collectionItems, + layout: value.layout, + terminalTheme: terminalTheme, + zoomNamespace: zoomNamespace, + overflowLabels: overflowLabels, + allowsReordering: allowsReordering, + isVisible: isVisible, + selectPreviewSurface: selectPreviewSurface, + jumpToTerminal: jumpToTerminal, + reorderPanes: reorderPanes + ) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background { + // In push hosting the map stays mounted under the terminal's + // full-screen cover, and SwiftUI's subtree-level + // `accessibilityHidden` is not honored across that covered + // boundary (the whole map tree stayed queryable). Swap the marker + // identifier while covered so "map is presented" queries cannot + // match; the collection's own elements hide at the UIKit level. + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + .accessibilityElement() + .accessibilityIdentifier( + isVisible ? "MobilePaneMapOverlay" : "MobilePaneMapOverlayCovered" + ) + } + .onAppear { + if isVisible { + startPreviewRefresh() + } + } + .onDisappear { + cancelPreviewRefresh() + } + .onChange(of: isVisible) { _, isVisible in + if isVisible { + startPreviewRefresh() + } else { + cancelPreviewRefresh() + } + } + .onChange(of: refreshTrigger) { _, _ in + guard isVisible else { return } + cancelPreviewRefresh() + startPreviewRefresh() + } + .onChange(of: value.layout) { _, _ in + selectedSurfaceIDsByPaneID = value.reconciledSurfaceIDs( + current: selectedSurfaceIDsByPaneID + ) + let validSurfaceIDs = Set(value.panes.flatMap(\.surfaces).map(\.id)) + previewsBySurfaceID = previewsBySurfaceID.filter { + validSurfaceIDs.contains($0.key) + } + guard isVisible else { return } + cancelPreviewRefresh() + startPreviewRefresh() + } + } + + private var collectionItems: [PaneMapCollectionItem] { + value.panes.enumerated().map { index, pane in + let selectedSurfaceID = selectedSurfaceIDsByPaneID[pane.id] + return PaneMapCollectionItem( + pane: pane, + paneNumber: index + 1, + paneCount: value.panes.count, + isFocusedOnMac: value.layout.focusedPaneID == pane.id, + selectedSurfaceID: selectedSurfaceID, + phoneSelectedSurfaceID: value.phoneSelectedSurfaceID, + preview: selectedSurfaceID.flatMap { previewsBySurfaceID[$0] }, + isLoadingPreview: isRefreshing, + agentStateKind: selectedSurfaceID.flatMap { + value.agentStateKindsBySurfaceID[$0] + } + ) + } + } + + private var overflowLabels: PaneMapOverflowLabels { + PaneMapOverflowLabels( + leading: L10n.string( + "mobile.paneMap.more.leading", + defaultValue: "More panes to the left" + ), + trailing: L10n.string( + "mobile.paneMap.more.trailing", + defaultValue: "More panes to the right" + ), + top: L10n.string( + "mobile.paneMap.more.top", + defaultValue: "More panes above" + ), + bottom: L10n.string( + "mobile.paneMap.more.bottom", + defaultValue: "More panes below" + ) + ) + } + + private func selectPreviewSurface(paneID: String, surfaceID: String) { + selectedSurfaceIDsByPaneID[paneID] = surfaceID + } + + private func jumpToTerminal(_ surfaceID: String) { + selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) + } + + private func startPreviewRefresh() { + guard refreshTask == nil else { return } + let generation = UUID() + refreshGeneration = generation + refreshTask = Task { + await refreshAllPreviews(generation: generation) + guard refreshGeneration == generation else { return } + refreshTask = nil + } + } + + private func cancelPreviewRefresh() { + refreshGeneration = nil + refreshTask?.cancel() + refreshTask = nil + isRefreshing = false + refreshingChanged(false) + } + + private func refreshAllPreviews(generation: UUID) async { + // A task cancelled (and superseded) before its body ran must not touch + // the spinner: it would publish refreshing=true and then skip its own + // generation-gated clear, wedging the toolbar in the loading state + // while blocking the successor behind `isRefreshing`. + guard !Task.isCancelled, refreshGeneration == generation else { return } + guard !isRefreshing else { return } + isRefreshing = true + refreshingChanged(true) + defer { + if refreshGeneration == generation { + isRefreshing = false + refreshingChanged(false) + } + } + + let selectedTerminalSurfaceIDs = value.panes.compactMap { pane -> String? in + guard let surfaceID = selectedSurfaceIDsByPaneID[pane.id], + pane.surfaces.first(where: { $0.id == surfaceID })?.type.isTerminal == true else { + return nil + } + return surfaceID + } + let selectedSet = Set(selectedTerminalSurfaceIDs) + let remainingTerminalSurfaceIDs = value.panes.flatMap(\.surfaces).compactMap { surface in + surface.type.isTerminal && !selectedSet.contains(surface.id) ? surface.id : nil + } + let frames = await fetchPreviews( + selectedTerminalSurfaceIDs, + remainingTerminalSurfaceIDs + ) + guard !Task.isCancelled, refreshGeneration == generation else { return } + previewsBySurfaceID = frames.mapValues { + $0.paneMapPreview(maximumRows: 96) + } + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift new file mode 100644 index 000000000000..c9c233a65f75 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift @@ -0,0 +1,104 @@ +import Foundation + +/// Optimistic pane-map ordering reconciled against the Mac's authoritative layout. +struct PaneMapReorderState: Equatable { + struct Request: Equatable, Sendable { + let id: UUID + let orderedPaneIDs: [String] + /// The authoritative layout revision this drag was computed against. + /// Sent to the Mac as the reorder's precondition so a stale drag fails + /// closed as a conflict instead of permuting the wrong pane contents. + let baseLayoutRevision: Int + } + + enum Completion: Equatable { + case ignored + case rolledBack + case awaitingAuthority + } + + private(set) var visiblePaneIDs: [String] + private(set) var authoritativePaneIDs: [String] + private(set) var authoritativeRevision: Int + private(set) var pendingRequest: Request? + private var receivedAuthorityWhilePending = false + private var pendingRequestWasAccepted = false + + var isMutationPending: Bool { + pendingRequest != nil + } + + init(authoritativePaneIDs: [String], authoritativeRevision: Int) { + self.visiblePaneIDs = authoritativePaneIDs + self.authoritativePaneIDs = authoritativePaneIDs + self.authoritativeRevision = authoritativeRevision + } + + mutating func beginMove(from sourceIndex: Int, to destinationIndex: Int) -> Request? { + guard pendingRequest == nil, + visiblePaneIDs.indices.contains(sourceIndex), + visiblePaneIDs.indices.contains(destinationIndex), + sourceIndex != destinationIndex else { + return nil + } + let movedPaneID = visiblePaneIDs.remove(at: sourceIndex) + visiblePaneIDs.insert(movedPaneID, at: destinationIndex) + let request = Request( + id: UUID(), + orderedPaneIDs: visiblePaneIDs, + baseLayoutRevision: authoritativeRevision + ) + pendingRequest = request + receivedAuthorityWhilePending = false + pendingRequestWasAccepted = false + return request + } + + mutating func reconcile( + authoritativePaneIDs: [String], + authoritativeRevision: Int + ) { + // Revisions are monotonic per Mac process, so a delayed older + // workspace-list response must never roll the map back after newer + // authority applied. (A Mac restart resets the counter, but that also + // drops the connection and rebuilds this state with a fresh baseline.) + guard authoritativeRevision >= self.authoritativeRevision else { return } + let receivedNewAuthority = authoritativeRevision > self.authoritativeRevision + self.authoritativePaneIDs = authoritativePaneIDs + self.authoritativeRevision = authoritativeRevision + guard pendingRequest != nil else { + visiblePaneIDs = authoritativePaneIDs + return + } + guard receivedNewAuthority else { return } + receivedAuthorityWhilePending = true + if pendingRequestWasAccepted { + finishSuccessfulMutationAfterAuthoritativeRefresh() + } + } + + mutating func complete(requestID: UUID, succeeded: Bool) -> Completion { + guard pendingRequest?.id == requestID else { return .ignored } + if !succeeded { + pendingRequest = nil + receivedAuthorityWhilePending = false + pendingRequestWasAccepted = false + visiblePaneIDs = authoritativePaneIDs + return .rolledBack + } + pendingRequestWasAccepted = true + guard receivedAuthorityWhilePending else { + return .awaitingAuthority + } + finishSuccessfulMutationAfterAuthoritativeRefresh() + return .awaitingAuthority + } + + mutating func finishSuccessfulMutationAfterAuthoritativeRefresh() { + guard pendingRequest != nil else { return } + pendingRequest = nil + receivedAuthorityWhilePending = false + pendingRequestWasAccepted = false + visiblePaneIDs = authoritativePaneIDs + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapSelectionArbitration.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapSelectionArbitration.swift new file mode 100644 index 000000000000..413cbe471c69 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapSelectionArbitration.swift @@ -0,0 +1,40 @@ +import CoreGraphics + +/// Resolves pane focus only after a stationary tap wins against scrolling and dragging. +struct PaneMapSelectionArbitration: Equatable { + private static let maximumTapTravel: CGFloat = 10 + + private var touchOrigin: CGPoint? + private var absorbedByMovement = false + + mutating func touchBegan(at point: CGPoint) { + touchOrigin = point + absorbedByMovement = false + } + + mutating func touchMoved(to point: CGPoint) { + guard let touchOrigin else { return } + let travel = hypot(point.x - touchOrigin.x, point.y - touchOrigin.y) + if travel > Self.maximumTapTravel { + absorbedByMovement = true + } + } + + mutating func dragSessionDidBegin() { + absorbedByMovement = true + } + + mutating func touchEnded(at point: CGPoint) -> Bool { + touchMoved(to: point) + defer { + touchOrigin = nil + absorbedByMovement = false + } + return touchOrigin != nil && !absorbedByMovement + } + + mutating func cancel() { + touchOrigin = nil + absorbedByMovement = false + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift new file mode 100644 index 000000000000..4ea2aa883b19 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -0,0 +1,614 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import CmuxMobileSupport +import SwiftUI + +struct PaneMapTileMetrics: Equatable { + let captionHeight: CGFloat = 38 + let cornerRadius: CGFloat = 16 +} + +struct PaneMapTerminalCanvasLayout: Equatable { + static let lineHeightRatio: CGFloat = 1.82 + static let glyphWidthRatio: CGFloat = 0.61 + + let contentRect: CGRect + let visibleRowRange: Range + let drawOrigin: CGPoint + let cellWidth: CGFloat + let lineHeight: CGFloat + let fontSize: CGFloat + + init( + size: CGSize, + columns: Int, + rowCount: Int, + inset: CGFloat + ) { + let safeSize = CGSize( + width: max(0, size.width), + height: max(0, size.height) + ) + let safeInset = max(0, inset) + contentRect = CGRect( + x: safeInset, + y: safeInset, + width: max(0, safeSize.width - (safeInset * 2)), + height: max(0, safeSize.height - (safeInset * 2)) + ) + + guard columns > 0, rowCount > 0, contentRect.width > 0 else { + visibleRowRange = 0..<0 + drawOrigin = contentRect.origin + cellWidth = 0 + lineHeight = 0 + fontSize = 0 + return + } + + cellWidth = contentRect.width / CGFloat(columns) + lineHeight = cellWidth * Self.lineHeightRatio + fontSize = cellWidth / Self.glyphWidthRatio + + let rowsThatFit = max( + 1, + Int((contentRect.height / max(lineHeight, 0.1)).rounded(.down)) + ) + let visibleRowCount = min(rowCount, rowsThatFit) + let isCropped = visibleRowCount < rowCount + let firstVisibleRow = isCropped ? rowCount - visibleRowCount : 0 + visibleRowRange = firstVisibleRow..<(firstVisibleRow + visibleRowCount) + drawOrigin = CGPoint( + x: contentRect.minX, + y: isCropped + ? contentRect.maxY - (CGFloat(visibleRowCount) * lineHeight) + : contentRect.minY + ) + } + + var lastRowMaxY: CGFloat { + drawOrigin.y + (CGFloat(visibleRowRange.count) * lineHeight) + } +} + +struct PaneMapTabStripMetrics: Equatable { + let tabWidth: CGFloat = 28 + let spacing: CGFloat = 2 + let padding: CGFloat = 3 + let maximumWidth: CGFloat = 132 + let bottomInset: CGFloat = 8 + + var height: CGFloat { + tabWidth + (padding * 2) + } + + func width(tabCount: Int) -> CGFloat { + guard tabCount > 0 else { return 0 } + let contentWidth = + (CGFloat(tabCount) * tabWidth) + + (CGFloat(max(0, tabCount - 1)) * spacing) + + (padding * 2) + return min(maximumWidth, contentWidth) + } + + func frame(in previewBounds: CGRect, tabCount: Int) -> CGRect { + let stripWidth = width(tabCount: tabCount) + return CGRect( + x: previewBounds.midX - (stripWidth / 2), + y: previewBounds.maxY - bottomInset - height, + width: stripWidth, + height: height + ) + } +} + +/// One floating Safari-style pane card rendered from immutable snapshots. +struct PaneMapTileView: View { + let item: PaneMapCollectionItem + let terminalTheme: TerminalTheme + let zoomNamespace: Namespace.ID + let selectPreviewSurface: (String) -> Void + let jumpToTerminal: (String) -> Void + private var metrics: PaneMapTileMetrics { PaneMapTileMetrics() } + + var body: some View { + VStack(spacing: 0) { + PaneMapPreviewCard( + item: item, + terminalTheme: terminalTheme, + selectPreviewSurface: selectPreviewSurface, + jumpToTerminal: jumpToTerminal + ) + .matchedTransitionSource( + id: item.selectedSurface?.id ?? item.id, + in: zoomNamespace + ) + PaneMapTileCaption(item: item, terminalTheme: terminalTheme) + .frame(height: metrics.captionHeight) + } + .accessibilityElement(children: .contain) + .accessibilityLabel(paneAccessibilityLabel) + .accessibilityValue( + item.isFocusedOnMac + ? L10n.string("mobile.paneMap.focusedOnMac", defaultValue: "Focused on Mac") + : "" + ) + .accessibilityIdentifier("MobilePaneMapPane-\(item.pane.id)") + } + + private var paneAccessibilityLabel: String { + String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.panePosition", + defaultValue: "Pane %d of %d" + ), + item.paneNumber, + item.paneCount + ) + } +} + +private struct PaneMapPreviewCard: View { + let item: PaneMapCollectionItem + let terminalTheme: TerminalTheme + let selectPreviewSurface: (String) -> Void + let jumpToTerminal: (String) -> Void + private var metrics: PaneMapTileMetrics { PaneMapTileMetrics() } + + private var selectedSurface: MobilePaneSurface? { item.selectedSurface } + private var isPhoneSelected: Bool { + selectedSurface?.id == item.phoneSelectedSurfaceID + } + + var body: some View { + let shape = RoundedRectangle( + cornerRadius: metrics.cornerRadius, + style: .continuous + ) + + ZStack { + previewTerminalTheme.terminalBackgroundColor + + if let selectedSurface { + PaneMapSurfacePreview( + surface: selectedSurface, + preview: item.preview, + isLoadingPreview: item.isLoadingPreview, + terminalTheme: terminalTheme, + jumpToTerminal: jumpToTerminal + ) + } + + VStack { + HStack(alignment: .top) { + Spacer(minLength: 0) + if item.isFocusedOnMac { + PaneMapMacFocusBadge(terminalTheme: terminalTheme) + } + } + Spacer(minLength: 0) + if item.pane.surfaces.count > 1 { + PaneMapTabSwitcher( + pane: item.pane, + selectedSurfaceID: item.selectedSurfaceID, + terminalTheme: terminalTheme, + selectPreviewSurface: selectPreviewSurface + ) + } + } + .padding(8) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(previewTerminalTheme.terminalBackgroundColor) + .overlay { + shape.stroke(.white.opacity(0.16), lineWidth: 1) + } + .overlay { + if isPhoneSelected { + shape.stroke(Color.accentColor, lineWidth: 2.5) + } + } + .clipShape(shape) + .shadow(color: .black.opacity(0.28), radius: 9, y: 5) + } + + private var previewTerminalTheme: TerminalTheme { + item.preview?.resolvedTerminalTheme(fallback: terminalTheme) ?? terminalTheme + } +} + +private struct PaneMapSurfacePreview: View { + let surface: MobilePaneSurface + let preview: MobileTerminalPaneMapPreview? + let isLoadingPreview: Bool + let terminalTheme: TerminalTheme + let jumpToTerminal: (String) -> Void + + var body: some View { + ZStack { + if surface.type.isTerminal { + PaneMapTerminalPreview( + preview: preview, + isLoadingPreview: isLoadingPreview, + terminalTheme: terminalTheme + ) + .contentShape(Rectangle()) + .accessibilityLabel(surfaceAccessibilityLabel) + .accessibilityIdentifier("MobilePaneMapTile-\(surface.id)") + .accessibilityAddTraits(.isButton) + .accessibilityAction { + jumpToTerminal(surface.id) + } + } else { + PaneMapUnavailableSurfacePreview( + surface: surface, + terminalTheme: terminalTheme + ) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private var surfaceAccessibilityLabel: String { + String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.openNamedTerminal", + defaultValue: "Open terminal: %@" + ), + surface.title + ) + } +} + +private struct PaneMapTerminalPreview: View { + let preview: MobileTerminalPaneMapPreview? + let isLoadingPreview: Bool + let terminalTheme: TerminalTheme + + var body: some View { + let resolvedTerminalTheme = + preview?.resolvedTerminalTheme(fallback: terminalTheme) ?? terminalTheme + + ZStack(alignment: .topLeading) { + resolvedTerminalTheme.terminalBackgroundColor + if let preview { + PaneMapTerminalCanvas( + preview: preview, + terminalTheme: resolvedTerminalTheme + ) + } else if isLoadingPreview { + ProgressView() + .controlSize(.mini) + .tint(terminalTheme.terminalChromeForegroundColor.opacity(0.55)) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .clipped() + } +} + +private struct PaneMapTerminalCanvas: View { + let preview: MobileTerminalPaneMapPreview + let terminalTheme: TerminalTheme + + var body: some View { + Canvas(opaque: true, colorMode: .nonLinear, rendersAsynchronously: true) { context, size in + context.fill( + Path(CGRect(origin: .zero, size: size)), + with: .color(terminalTheme.terminalBackgroundColor) + ) + guard preview.columns > 0, !preview.rows.isEmpty else { return } + + let layout = PaneMapTerminalCanvasLayout( + size: size, + columns: preview.columns, + rowCount: preview.rows.count, + inset: 6 + ) + guard !layout.visibleRowRange.isEmpty else { return } + context.clip(to: Path(layout.contentRect)) + + for (visibleRowIndex, sourceRowIndex) in layout.visibleRowRange.enumerated() { + let row = preview.rows[sourceRowIndex] + drawBackgrounds( + row, + rowIndex: visibleRowIndex, + origin: layout.drawOrigin, + cellWidth: layout.cellWidth, + lineHeight: layout.lineHeight, + context: &context + ) + drawGlyphs( + row, + rowIndex: visibleRowIndex, + origin: layout.drawOrigin, + cellWidth: layout.cellWidth, + lineHeight: layout.lineHeight, + fontSize: layout.fontSize, + context: &context + ) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private func drawBackgrounds( + _ row: [MobileTerminalPaneMapPreview.Cell], + rowIndex: Int, + origin: CGPoint, + cellWidth: CGFloat, + lineHeight: CGFloat, + context: inout GraphicsContext + ) { + var startColumn = 0 + while startColumn < row.count { + let styleID = row[startColumn].styleID + var endColumn = startColumn + 1 + while endColumn < row.count, row[endColumn].styleID == styleID { + endColumn += 1 + } + if let background = resolvedStyle(styleID).background { + context.fill( + Path(CGRect( + x: origin.x + (CGFloat(startColumn) * cellWidth), + y: origin.y + (CGFloat(rowIndex) * lineHeight), + width: CGFloat(endColumn - startColumn) * cellWidth, + height: lineHeight + )), + with: .color(background) + ) + } + startColumn = endColumn + } + } + + private func drawGlyphs( + _ row: [MobileTerminalPaneMapPreview.Cell], + rowIndex: Int, + origin: CGPoint, + cellWidth: CGFloat, + lineHeight: CGFloat, + fontSize: CGFloat, + context: inout GraphicsContext + ) { + for (column, cell) in row.enumerated() + where cell.columnSpan > 0 && cell.text != " " && !cell.text.isEmpty { + let style = resolvedStyle(cell.styleID) + guard !style.isInvisible else { continue } + var text = Text(cell.text) + .font(.system( + size: fontSize, + weight: style.isBold ? .bold : .regular, + design: .monospaced + )) + .foregroundStyle(style.foreground.opacity(style.isFaint ? 0.56 : 1)) + if style.isItalic { text = text.italic() } + if style.isUnderlined { text = text.underline() } + if style.isStruckThrough { text = text.strikethrough() } + context.draw( + text, + at: CGPoint( + x: origin.x + (CGFloat(column) * cellWidth), + y: origin.y + (CGFloat(rowIndex) * lineHeight) + ), + anchor: .topLeading + ) + if style.isOverlined { + let width = CGFloat(max(1, cell.columnSpan)) * cellWidth + context.stroke( + Path(CGRect( + x: origin.x + (CGFloat(column) * cellWidth), + y: origin.y + (CGFloat(rowIndex) * lineHeight), + width: width, + height: 0.5 + )), + with: .color(style.foreground), + lineWidth: max(0.35, fontSize * 0.06) + ) + } + } + } + + private func resolvedStyle(_ styleID: Int) -> PaneMapResolvedTerminalStyle { + let style = preview.stylesByID[styleID] ?? .default + let defaultForeground = terminalTheme.terminalForegroundColor + let defaultBackground = terminalTheme.terminalBackgroundColor + let explicitForeground = style.foreground.map(Color.init(terminalHex:)) + let explicitBackground = style.background.map(Color.init(terminalHex:)) + let foreground: Color + let background: Color? + if style.inverse { + foreground = explicitBackground ?? defaultBackground + background = explicitForeground ?? defaultForeground + } else { + foreground = explicitForeground ?? defaultForeground + background = explicitBackground + } + return PaneMapResolvedTerminalStyle( + foreground: foreground, + background: background, + isBold: style.bold, + isFaint: style.faint, + isItalic: style.italic, + isUnderlined: style.underline, + isInvisible: style.invisible, + isStruckThrough: style.strikethrough, + isOverlined: style.overline + ) + } +} + +private struct PaneMapResolvedTerminalStyle { + let foreground: Color + let background: Color? + let isBold: Bool + let isFaint: Bool + let isItalic: Bool + let isUnderlined: Bool + let isInvisible: Bool + let isStruckThrough: Bool + let isOverlined: Bool +} + +private struct PaneMapUnavailableSurfacePreview: View { + let surface: MobilePaneSurface + let terminalTheme: TerminalTheme + + var body: some View { + VStack(spacing: 7) { + Image(systemName: surface.type.paneMapSystemImage) + .font(.title2.weight(.medium)) + Text( + L10n.string( + "mobile.paneMap.unavailableOnPhone", + defaultValue: "Unavailable on iPhone" + ) + ) + .font(.caption2.weight(.medium)) + } + .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.72)) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .accessibilityLabel(surface.title) + } +} + +private struct PaneMapMacFocusBadge: View { + let terminalTheme: TerminalTheme + + var body: some View { + Image(systemName: "macwindow") + .font(.caption2.weight(.semibold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .frame(width: 28, height: 26) + .mobileGlassPill() + .accessibilityLabel( + L10n.string("mobile.paneMap.focusedOnMac", defaultValue: "Focused on Mac") + ) + } +} + +private struct PaneMapTabSwitcher: View { + let pane: MobilePaneNode + let selectedSurfaceID: String? + let terminalTheme: TerminalTheme + let selectPreviewSurface: (String) -> Void + private var metrics: PaneMapTabStripMetrics { PaneMapTabStripMetrics() } + + var body: some View { + ScrollView(.horizontal) { + HStack(spacing: metrics.spacing) { + ForEach(pane.surfaces, id: \.id) { surface in + let isSelected = surface.id == selectedSurfaceID + Button { + selectPreviewSurface(surface.id) + } label: { + Image(systemName: surface.type.paneMapSystemImage) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle( + isSelected + ? terminalTheme.terminalBackgroundColor + : terminalTheme.terminalChromeForegroundColor.opacity(0.82) + ) + .frame(width: metrics.tabWidth, height: metrics.tabWidth) + .background( + isSelected + ? terminalTheme.terminalChromeForegroundColor.opacity(0.9) + : .clear, + in: Circle() + ) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel(surface.title) + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier("MobilePaneMapTab-\(surface.id)") + } + } + .padding(metrics.padding) + } + .scrollIndicators(.hidden) + .frame( + width: metrics.width(tabCount: pane.surfaces.count), + height: metrics.height + ) + .mobileGlassPill() + .accessibilityIdentifier("MobilePaneMapTabStrip-\(pane.id)") + } +} + +private struct PaneMapTileCaption: View { + let item: PaneMapCollectionItem + let terminalTheme: TerminalTheme + + var body: some View { + HStack(spacing: 6) { + if let surface = item.selectedSurface { + Image(systemName: surface.type.paneMapSystemImage) + .font(.caption2.weight(.semibold)) + Text(surface.title) + .font(.caption.weight(.semibold)) + .lineLimit(1) + .truncationMode(.tail) + .accessibilityIdentifier("MobilePaneMapCaption-\(surface.id)") + } + Spacer(minLength: 0) + if let agentStateKind = item.agentStateKind { + Circle() + .fill(agentStateKind == .working ? Color.green : Color.orange) + .frame(width: 7, height: 7) + .accessibilityLabel(statusAccessibilityValue(agentStateKind)) + } + } + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .padding(.horizontal, 4) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .combine) + } + + private func statusAccessibilityValue(_ kind: ChatAgentStateKind) -> String { + switch kind { + case .working: + return L10n.string("mobile.agent.status.working", defaultValue: "Agent working") + case .needsInput: + return L10n.string("mobile.agent.status.needsInput", defaultValue: "Agent needs input") + } + } +} + +private extension MobilePaneSurfaceType { + var paneMapSystemImage: String { + switch self { + case .terminal: + return "terminal" + case .browser: + return "globe" + case .markdown: + return "doc.text" + case .agentSession: + return "sparkles" + case .workspaceTodo: + return "checklist" + case .filepreview: + return "doc" + case .project: + return "folder" + case .rightSidebarTool, .customSidebar, .extensionBrowser, .cloudVMLoading, .other: + return "rectangle" + } + } +} + +private extension Color { + init(terminalHex: String) { + guard let rgb = TerminalTheme.rgbComponents(terminalHex) else { + self = .primary + return + } + self.init( + red: Double(rgb.red) / 255, + green: Double(rgb.green) / 255, + blue: Double(rgb.blue) / 255 + ) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift new file mode 100644 index 000000000000..18b5f5f98cc5 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift @@ -0,0 +1,42 @@ +import CmuxMobileSupport +import SwiftUI + +struct PaneMapRefreshToolbarButton: View { + let isRefreshing: Bool + let refresh: () -> Void + + var body: some View { + Button(action: refresh) { + Group { + if isRefreshing { + ProgressView() + .controlSize(.small) + } else { + Image(systemName: "arrow.clockwise") + } + } + .frame(width: 24, height: 24) + } + .frame(width: PaneMapToolbarMetrics.refreshWidth, height: PaneMapToolbarMetrics.height) + .disabled(isRefreshing) + .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) + .accessibilityIdentifier("MobilePaneMapRefresh") + } +} + +struct PaneMapDoneToolbarButton: View { + let done: () -> Void + + var body: some View { + Button(action: done) { + Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .font(.subheadline.weight(.semibold)) + .lineLimit(1) + .minimumScaleFactor(0.82) + .frame(maxWidth: .infinity) + } + .frame(width: PaneMapToolbarMetrics.doneWidth, height: PaneMapToolbarMetrics.height) + .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .accessibilityIdentifier("MobilePaneMapDone") + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarMetrics.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarMetrics.swift new file mode 100644 index 000000000000..2480d2b0efd8 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarMetrics.swift @@ -0,0 +1,12 @@ +import CoreGraphics + +struct PaneMapToolbarMetrics: Equatable { + static let refreshWidth: CGFloat = 44 + static let doneWidth: CGFloat = 58 + static let spacing: CGFloat = 0 + static let height: CGFloat = 44 + + static var trailingClusterWidth: CGFloat { + refreshWidth + spacing + doneWidth + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift new file mode 100644 index 000000000000..e9f9b2a6fdbc --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift @@ -0,0 +1,80 @@ +import CmuxMobileShellModel +import CmuxMobileSupport + +/// Immutable workspace and status state rendered by ``PaneMapOverlay``. +struct PaneMapValue: Equatable { + let layout: MobilePaneLayout + let phoneSelectedSurfaceID: String? + let agentStateKindsBySurfaceID: [String: ChatAgentStateKind] + + var panes: [MobilePaneNode] { layout.orderedPanes } + + var tabCount: Int { + panes.reduce(into: 0) { count, pane in + count += pane.surfaces.count + } + } + + var countSubtitle: String { + switch (panes.count == 1, tabCount == 1) { + case (true, true): + return L10n.string( + "mobile.paneMap.count.onePane.oneTab", + defaultValue: "1 pane · 1 tab" + ) + case (true, false): + return String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.count.onePane.otherTabs", + defaultValue: "1 pane · %d tabs" + ), + tabCount + ) + case (false, true): + return String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.count.otherPanes.oneTab", + defaultValue: "%d panes · 1 tab" + ), + panes.count + ) + case (false, false): + return String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.count.otherPanes.otherTabs", + defaultValue: "%d panes · %d tabs" + ), + panes.count, + tabCount + ) + } + } + + var initialSurfaceIDsByPaneID: [String: String] { + reconciledSurfaceIDs(current: [:]) + } + + /// Keeps valid in-map selections and replaces entries removed by a newer + /// layout snapshot with that pane's authoritative fallback selection. + func reconciledSurfaceIDs(current: [String: String]) -> [String: String] { + var result: [String: String] = [:] + for pane in panes { + if let currentSurfaceID = current[pane.id], + pane.surfaces.contains(where: { $0.id == currentSurfaceID }) { + result[pane.id] = currentSurfaceID + continue + } + + let phoneSurfaceID = phoneSelectedSurfaceID.flatMap { candidate in + pane.surfaces.contains { $0.id == candidate } ? candidate : nil + } + let paneSurfaceID = pane.selectedSurfaceID.flatMap { candidate in + pane.surfaces.contains { $0.id == candidate } ? candidate : nil + } + if let surfaceID = phoneSurfaceID ?? paneSurfaceID ?? pane.surfaces.first?.id { + result[pane.id] = surfaceID + } + } + return result + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift new file mode 100644 index 000000000000..8f88ba7a3fb3 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -0,0 +1,300 @@ +import CMUXMobileCore +import CmuxMobileTerminal +import SwiftUI +#if os(iOS) +import UIKit +#endif + +/// Stable routing state for the native pane-map zoom presentation. +struct PaneZoomPresentationState: Equatable { + enum Endpoint: Hashable { + case paneMap + case terminal + } + + private(set) var navigationPath: [Endpoint] = [.terminal] + private(set) var sourceSurfaceID: String? + + var endpoint: Endpoint { + navigationPath.last == .terminal ? .terminal : .paneMap + } + + var isTerminalPresented: Bool { + endpoint == .terminal + } + + mutating func presentPaneMap(from surfaceID: String?) { + if let surfaceID, !surfaceID.isEmpty { + sourceSurfaceID = surfaceID + } + navigationPath = [] + } + + mutating func presentTerminal(surfaceID: String) { + guard !surfaceID.isEmpty else { return } + sourceSurfaceID = surfaceID + navigationPath = [.terminal] + } + + mutating func presentationDidChange(isTerminalPresented: Bool) { + navigationPath = isTerminalPresented ? [.terminal] : [] + } + + mutating func layoutAvailabilityDidChange(hasLayout: Bool) { + guard !hasLayout else { return } + presentationDidChange(isTerminalPresented: true) + } + + mutating func navigationPathDidChange(_ path: [Endpoint]) { + navigationPath = path.last == .terminal ? [.terminal] : [] + } +} + +/// How a ``PaneZoomHost`` sits in the surrounding navigation hierarchy. +enum PaneZoomHosting { + /// The workspace detail is a pushed destination of an ancestor + /// `NavigationStack` (every compact shell push context: the workspaces + /// tab, notifications, and notification search). Nesting another + /// `NavigationStack` here makes it join the window's shared + /// `NavigationAuthority`, whose queue then reconciles one stack's bound + /// path against the other stack's column and force-`try!`s an + /// `AnyNavigationPath.Error.comparisonTypeMismatch` + /// (`NavigationColumnState.boundPathChange`), killing the app. Type-erasing + /// the nested path to `NavigationPath` does not help: the misrouted + /// comparison still throws, just on a later push. So in this hosting the + /// terminal is a zoom `fullScreenCover`, which owns its own navigation + /// context and never enters the ancestor's authority. + case navigationPush + /// The workspace detail owns its navigation column (the split view's + /// detail on regular width, or a standalone host such as the panes + /// fixture). A `NavigationStack` here is the documented column pattern, + /// so the terminal stays a pushed route over the pane-map root. + case column +} + +/// Keeps the pane-map route local to a workspace destination. The parent +/// context still owns workspace-list navigation and its shared back button, +/// while the restored terminal is installed on top of the pane map from the +/// first frame. The hosting decides the mechanism: a zoom full-screen cover +/// under an ancestor stack, or a pushed route in an owned column stack. +struct PaneZoomHost: View { + @Binding var presentation: PaneZoomPresentationState + let hosting: PaneZoomHosting + let terminalTheme: TerminalTheme + /// The matched-transition source id (the selected surface's pane-map tile). + let zoomSourceID: String + /// The namespace shared with the pane-map tiles' `matchedTransitionSource`. + let zoomNamespace: Namespace.ID + @ViewBuilder let root: () -> Root + @ViewBuilder let terminal: () -> Terminal + + var body: some View { + switch hosting { + case .navigationPush: + presentationHost + case .column: + columnStackHost + } + // Tab-bar visibility is owned by the shell's per-route policy + // (WorkspaceShellView). Hiding it here too would override the split + // layout's explicit `.visible` detail policy from deeper in the same + // subtree, collapsing the iPad tab bar for pane-enabled workspaces. + } + + /// Push hosting: the pane map renders directly in the ancestor stack's + /// destination (using its navigation bar), and the terminal is a zoom + /// full-screen cover with its own root-only stack for the shared toolbar. + /// + /// While the cover is up, the pane map's bar stays mounted underneath and + /// iOS keeps its items (the shared back button, title menu, changes chip) + /// in the accessibility tree, so every shared identifier would exist + /// twice, confusing assistive tech and failing identifier-based + /// automation with "multiple matching elements". Hiding the covered bar + /// removes those items entirely; it returns automatically the moment the + /// terminal starts unzooming back into its tile. + private var presentationHost: some View { + root() + .toolbar( + presentation.isTerminalPresented ? .hidden : .automatic, + for: .navigationBar + ) + .fullScreenCover(isPresented: isTerminalPresentedBinding) { + terminalHost + } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + #if os(iOS) + .background { + PaneZoomNavigationHostBackground( + color: terminalTheme.terminalBackgroundUIColor + ) + } + #endif + } + + private var terminalHost: some View { + NavigationStack { + terminal() + } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + #if os(iOS) + .background { + PaneZoomNavigationHostBackground( + color: terminalTheme.terminalBackgroundUIColor + ) + } + #endif + .navigationTransition(.zoom(sourceID: zoomSourceID, in: zoomNamespace)) + } + + /// Column hosting: this component owns the stack, with the pane map as its + /// root and the terminal pushed on the first frame. + private var columnStackHost: some View { + NavigationStack(path: navigationPath) { + root() + .navigationDestination(for: PaneZoomPresentationState.Endpoint.self) { endpoint in + if endpoint == .terminal { + terminal() + .navigationTransition(.zoom(sourceID: zoomSourceID, in: zoomNamespace)) + } + } + } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + #if os(iOS) + .background { + PaneZoomNavigationHostBackground( + color: terminalTheme.terminalBackgroundUIColor + ) + } + #endif + } + + private var isTerminalPresentedBinding: Binding { + Binding( + get: { presentation.isTerminalPresented }, + set: { presentation.presentationDidChange(isTerminalPresented: $0) } + ) + } + + private var navigationPath: Binding<[PaneZoomPresentationState.Endpoint]> { + Binding( + get: { presentation.navigationPath }, + set: { presentation.navigationPathDidChange($0) } + ) + } +} + +#if os(iOS) +private struct PaneZoomNavigationHostBackground: UIViewRepresentable { + let color: UIColor + + func makeUIView(context: Context) -> PaneZoomNavigationBackgroundBridgeView { + let view = PaneZoomNavigationBackgroundBridgeView() + view.color = color + return view + } + + func updateUIView( + _ uiView: PaneZoomNavigationBackgroundBridgeView, + context: Context + ) { + uiView.color = color + uiView.applyBackground() + } + + static func dismantleUIView( + _ uiView: PaneZoomNavigationBackgroundBridgeView, + coordinator: () + ) { + uiView.restoreBackgrounds() + } +} + +final class PaneZoomNavigationBackgroundBridgeView: UIView { + @MainActor private final class BackgroundSnapshot { + weak var view: UIView? + let originalColor: UIColor? + var appliedColor: UIColor? + + init(view: UIView) { + self.view = view + self.originalColor = view.backgroundColor + } + } + + private var backgroundSnapshots: [ObjectIdentifier: BackgroundSnapshot] = [:] + + var color: UIColor = .clear { + didSet { applyBackground() } + } + + override func didMoveToWindow() { + super.didMoveToWindow() + applyBackground() + } + + override func didMoveToSuperview() { + super.didMoveToSuperview() + applyBackground() + } + + func applyBackground() { + backgroundColor = .clear + guard window != nil else { + restoreBackgrounds() + return + } + + var ancestor = superview + var hops = 0 + while let view = ancestor, !(view is UIWindow), hops < 16 { + applyColor(to: view) + ancestor = view.superview + hops += 1 + } + + var responder: UIResponder? = self + var responderHops = 0 + while let current = responder, responderHops < 32 { + if let viewController = current as? UIViewController { + applyColor(to: viewController.view) + if let navigationView = viewController.navigationController?.view { + applyColor(to: navigationView) + } + } + if let navigationController = current as? UINavigationController { + applyColor(to: navigationController.view) + } + responder = current.next + responderHops += 1 + } + } + + func restoreBackgrounds() { + for snapshot in backgroundSnapshots.values { + guard let view = snapshot.view, + view.backgroundColor == snapshot.appliedColor else { + continue + } + view.backgroundColor = snapshot.originalColor + } + backgroundSnapshots.removeAll() + } + + private func applyColor(to view: UIView) { + let key = ObjectIdentifier(view) + let snapshot = backgroundSnapshots[key] ?? BackgroundSnapshot(view: view) + snapshot.appliedColor = color + backgroundSnapshots[key] = snapshot + view.backgroundColor = color + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckActions.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckActions.swift new file mode 100644 index 000000000000..4499f44a1a5d --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckActions.swift @@ -0,0 +1,10 @@ +import CmuxMobileShellModel + +/// User actions emitted by ``SurfaceDeckBar`` without exposing mutable stores to its chip subtree. +struct SurfaceDeckActions { + let selectTerminal: (MobileTerminalPreview.ID) -> Void + let presentPaneMap: () -> Void + let createTerminal: () -> Void + let openBrowser: () -> Void + let createWorkspace: () -> Void +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift new file mode 100644 index 000000000000..78e164d79876 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -0,0 +1,343 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import CmuxMobileSupport +import SwiftUI + +/// Snapshot-isolated bottom bar for switching among a workspace's panes and surface tabs. +struct SurfaceDeckBar: View, Equatable { + let value: SurfaceDeckValue + let actions: SurfaceDeckActions + let terminalTheme: TerminalTheme + var clock: any Clock = ContinuousClock() + + @State private var unavailableHintID: UUID? + + nonisolated static func == (lhs: Self, rhs: Self) -> Bool { + lhs.value == rhs.value && lhs.terminalTheme == rhs.terminalTheme + } + + var body: some View { + VStack(spacing: 4) { + if let unavailableHintID { + Text( + L10n.string( + "mobile.surfaceDeck.terminalsOnly", + defaultValue: "Terminals only on iPhone for now" + ) + ) + .font(.caption) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .padding(.horizontal, 12) + .frame(height: 28) + .mobileGlassPill() + .transition(.move(edge: .bottom).combined(with: .opacity)) + .task(id: unavailableHintID) { + // This is an intended, bounded auto-dismiss. The task is + // cancelled when the hint changes or the deck leaves view. + try? await clock.sleep(for: .seconds(3)) + guard !Task.isCancelled else { return } + withAnimation(.snappy(duration: 0.2)) { + self.unavailableHintID = nil + } + } + } + + deckSurface + } + .padding(.horizontal, 8) + .padding(.top, 4) + .padding(.bottom, 6) + // The deck is terminal chrome: it extends the terminal's themed + // background under the glass pills (and into the home-indicator + // region), so the light theme foreground stays readable instead of + // landing on the system background. + .background( + terminalTheme.terminalBackgroundColor + .ignoresSafeArea(edges: .bottom) + ) + .accessibilityElement(children: .contain) + .accessibilityLabel(L10n.string("mobile.surfaceDeck.label", defaultValue: "Workspace surfaces")) + .accessibilityIdentifier("MobileSurfaceDeck") + } + + // No shared GlassEffectContainer here: it composites the pills' glass + // above the scroll view's clip, so scrolled-away chips bleed under the + // fixed trailing controls. Each pill/circle carries its own glass. + private var deckSurface: some View { + deckContent + } + + private var deckContent: some View { + HStack(spacing: 8) { + ScrollViewReader { proxy in + ScrollView(.horizontal) { + HStack(spacing: 8) { + ForEach(value.groups) { group in + paneGroup(group) + } + } + .scrollTargetLayout() + } + .scrollIndicators(.hidden) + .onAppear { + scrollToSelection(using: proxy, animated: false) + } + .onChange(of: value.selectedSurfaceID) { _, _ in + scrollToSelection(using: proxy, animated: true) + } + } + + fixedControls + } + .frame(height: 36) + } + + private func paneGroup(_ group: SurfaceDeckValue.PaneGroup) -> some View { + HStack(spacing: 2) { + ForEach(group.chips) { chip in + surfaceChip(chip, paneNumber: group.number, paneCount: group.totalCount) + } + } + .padding(2) + .frame(height: 36) + .mobileGlassPill() + .accessibilityElement(children: .contain) + .accessibilityLabel( + paneAccessibilityLabel(number: group.number, totalCount: group.totalCount) + ) + .accessibilityIdentifier("MobileSurfaceDeckPane-\(group.id)") + } + + private func surfaceChip( + _ chip: SurfaceDeckValue.Chip, + paneNumber: Int, + paneCount: Int + ) -> some View { + let isSelected = chip.id == value.selectedSurfaceID + let statusKind = value.agentStateKindsBySurfaceID[chip.id] + return Button { + if chip.isTerminal { + actions.selectTerminal(MobileTerminalPreview.ID(rawValue: chip.id)) + } else { + withAnimation(.snappy(duration: 0.2)) { + unavailableHintID = UUID() + } + } + } label: { + HStack(spacing: 5) { + if let statusKind { + Circle() + .fill(statusColor(statusKind)) + .frame(width: 6, height: 6) + } + + Image(systemName: systemImage(for: chip.type)) + .font(.caption.weight(.medium)) + + Text(chip.title) + .font(.caption.weight(.medium)) + .lineLimit(1) + .frame(maxWidth: 96) + } + .foregroundStyle( + isSelected + ? terminalTheme.terminalChromeForegroundColor + : terminalTheme.terminalChromeForegroundColor.opacity(0.72) + ) + .padding(.horizontal, 9) + .frame(height: 32) + .background { + if isSelected { + Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.16)) + } + } + .contentShape(Capsule()) + } + .buttonStyle(.plain) + .opacity(chip.isTerminal ? 1 : 0.5) + .id(chip.id) + .accessibilityLabel( + chipAccessibilityLabel( + chip, + paneNumber: paneNumber, + paneCount: paneCount + ) + ) + .accessibilityValue(statusAccessibilityValue(statusKind)) + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier("MobileSurfaceDeckChip-\(chip.id)") + } + + private var fixedControls: some View { + HStack(spacing: 8) { + if value.showsPaneMap { + Button(action: actions.presentPaneMap) { + Image(systemName: "rectangle.split.2x2") + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .frame(width: 32, height: 32) + .mobileGlassCircle() + } + .buttonStyle(.plain) + .accessibilityLabel(L10n.string("mobile.surfaceDeck.paneMap", defaultValue: "Pane Map")) + .accessibilityIdentifier("MobileSurfaceDeckPaneMap") + } + + Menu { + Button(action: actions.createTerminal) { + Label(L10n.string("mobile.terminal.new", defaultValue: "New Terminal"), systemImage: "plus") + } + .accessibilityIdentifier("MobileNewTerminalMenuItem") + + Button(action: actions.openBrowser) { + Label(L10n.string("mobile.browser.new", defaultValue: "New Browser"), systemImage: "globe") + } + .accessibilityIdentifier("MobileNewBrowserMenuItem") + + Button(action: actions.createWorkspace) { + Label( + L10n.string("mobile.workspace.new", defaultValue: "New Workspace"), + systemImage: "plus.square.on.square" + ) + } + .disabled(!value.canCreateWorkspace) + .accessibilityIdentifier("MobileNewWorkspaceMenuItem") + } label: { + Image(systemName: "plus") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .frame(width: 32, height: 32) + .mobileGlassCircle() + } + .accessibilityLabel(L10n.string("mobile.surfaceDeck.add", defaultValue: "Add Surface")) + .accessibilityIdentifier("MobileSurfaceDeckAdd") + } + } + + private func scrollToSelection(using proxy: ScrollViewProxy, animated: Bool) { + guard let selectedSurfaceID = value.selectedSurfaceID else { return } + if animated { + withAnimation(.snappy(duration: 0.25)) { + proxy.scrollTo(selectedSurfaceID, anchor: .center) + } + } else { + proxy.scrollTo(selectedSurfaceID, anchor: .center) + } + } + + private func statusColor(_ kind: ChatAgentStateKind) -> Color { + switch kind { + case .working: + return .green + case .needsInput: + return .orange + } + } + + private func systemImage(for type: MobilePaneSurfaceType) -> String { + switch type { + case .terminal: + return "terminal" + case .browser: + return "globe" + case .markdown: + return "doc.text" + case .agentSession: + return "sparkles" + case .workspaceTodo: + return "checklist" + case .filepreview: + return "doc" + case .project: + return "folder" + case .rightSidebarTool, .customSidebar, .extensionBrowser, .cloudVMLoading, .other: + return "rectangle" + } + } + + private func chipAccessibilityLabel( + _ chip: SurfaceDeckValue.Chip, + paneNumber: Int, + paneCount: Int + ) -> String { + if chip.isTerminal { + return String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.terminalInPane", + defaultValue: "%@, terminal, pane %d of %d" + ), + chip.title, + paneNumber, + paneCount + ) + } + return String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.unavailableInPane", + defaultValue: "%@, unavailable on iPhone, pane %d of %d" + ), + chip.title, + paneNumber, + paneCount + ) + } + + private func paneAccessibilityLabel(number: Int, totalCount: Int) -> String { + String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.panePosition", + defaultValue: "Pane %d of %d" + ), + number, + totalCount + ) + } + + private func statusAccessibilityValue(_ kind: ChatAgentStateKind?) -> String { + switch kind { + case .working: + return L10n.string( + "mobile.agent.status.working", + defaultValue: "Agent working" + ) + case .needsInput: + return L10n.string( + "mobile.agent.status.needsInput", + defaultValue: "Agent needs input" + ) + case nil: + return "" + } + } +} + +#if os(iOS) +extension View { + /// Installs the deck on the terminal destination so it contributes a real + /// safe-area inset to the terminal viewport. Applying `safeAreaInset` + /// outside a nested navigation stack lets its UIKit-hosted destination + /// cover the deck on iOS. + func mobileSurfaceDeckInset( + isVisible: Bool, + value: SurfaceDeckValue, + actions: SurfaceDeckActions, + terminalTheme: TerminalTheme + ) -> some View { + safeAreaInset(edge: .bottom, spacing: 0) { + if isVisible { + SurfaceDeckBar( + value: value, + actions: actions, + terminalTheme: terminalTheme + ) + .equatable() + .transition(.opacity.combined(with: .move(edge: .bottom))) + } + } + // The terminal owns keyboard geometry. Keeping the deck at the + // physical bottom lets the keyboard cover it instead of lifting it. + .ignoresSafeArea(isVisible ? .keyboard : [], edges: .bottom) + .animation(.snappy(duration: 0.18), value: isVisible) + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift new file mode 100644 index 000000000000..7d7ad9fa5373 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift @@ -0,0 +1,69 @@ +import CmuxMobileShellModel + +/// Immutable workspace surface state rendered by ``SurfaceDeckBar``. +struct SurfaceDeckValue: Equatable { + /// One pane's ordered surface chips. + struct PaneGroup: Identifiable, Equatable { + let id: String + let number: Int + let totalCount: Int + let chips: [Chip] + } + + /// One surface chip in a pane group. + struct Chip: Identifiable, Equatable { + let id: String + let title: String + let type: MobilePaneSurfaceType + + var isTerminal: Bool { type.isTerminal } + } + + let groups: [PaneGroup] + let selectedSurfaceID: String? + let agentStateKindsBySurfaceID: [String: ChatAgentStateKind] + let canCreateWorkspace: Bool + let showsPaneMap: Bool + + init( + workspace: MobileWorkspacePreview, + selectedSurfaceID: String?, + agentStateKindsBySurfaceID: [String: ChatAgentStateKind], + canCreateWorkspace: Bool + ) { + if let layout = workspace.layout { + let panes = layout.orderedPanes + groups = panes.enumerated().map { index, pane in + PaneGroup( + id: pane.id, + number: index + 1, + totalCount: panes.count, + chips: pane.surfaces.map { surface in + Chip(id: surface.id, title: surface.title, type: surface.type) + } + ) + } + } else { + groups = [ + PaneGroup( + id: workspace.id.rawValue, + number: 1, + totalCount: 1, + chips: workspace.terminals.map { terminal in + Chip(id: terminal.id.rawValue, title: terminal.name, type: .terminal) + } + ), + ] + } + self.selectedSurfaceID = selectedSurfaceID + self.agentStateKindsBySurfaceID = agentStateKindsBySurfaceID + self.canCreateWorkspace = canCreateWorkspace + showsPaneMap = workspace.layout != nil + } + + /// The deck owns the only in-workspace creation controls, so it remains + /// visible even when the workspace has zero or one terminal. + var shouldShow: Bool { + true + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift deleted file mode 100644 index 7e48e37a7c16..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift +++ /dev/null @@ -1,144 +0,0 @@ -import CMUXMobileCore -import CmuxMobileSupport -import SwiftUI - -/// Snapshot-isolated native menu for switching the active workspace surface. -struct TerminalPickerMenu: View, Equatable { - let value: TerminalPickerMenuValue - let actions: TerminalPickerMenuActions - let terminalTheme: TerminalTheme - #if DEBUG - private let diagnostics = TerminalPickerMenuDiagnostics() - #endif - - nonisolated static func == (lhs: Self, rhs: Self) -> Bool { - lhs.value == rhs.value && lhs.terminalTheme == rhs.terminalTheme - } - - var body: some View { - Menu { - instrumentedMenuContent - } label: { - Label( - value.selectedName ?? L10n.string("mobile.terminal.select", defaultValue: "Terminal"), - systemImage: "rectangle.stack" - ) - .labelStyle(.iconOnly) - } - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .accessibilityLabel(L10n.string("mobile.terminal.picker.title", defaultValue: "Terminals")) - .accessibilityIdentifier("MobileTerminalDropdown") - .accessibilityValue(value.selectedName ?? "") - } - - @ViewBuilder - private var instrumentedMenuContent: some View { - #if DEBUG - let _ = diagnostics.recordContentBuilderEvaluation(rowCount: value.rows.count) - #endif - menuContent - } - - @ViewBuilder - private var menuContent: some View { - Section(L10n.string("mobile.terminal.picker.title", defaultValue: "Terminals")) { - ForEach(value.rows) { terminal in - Button { - actions.selectTerminal(terminal.id) - } label: { - Label( - terminal.name, - systemImage: terminal.id == value.selectedID - && !value.hasActiveBrowser - && value.activeBrowserStreamPanelID == nil - ? "checkmark.circle.fill" - : "terminal" - ) - } - .accessibilityIdentifier("MobileTerminalMenuItem-\(terminal.id.rawValue)") - } - } - - if value.supportsBrowserStream { - if !value.browserStreamRows.isEmpty { - Section(L10n.string("mobile.browserStream.menuTitle", defaultValue: "Mac Browsers")) { - ForEach(value.browserStreamRows) { panel in - Button { actions.selectBrowserStream(panel.id) } label: { - Label( - panel.label, - systemImage: panel.id == value.activeBrowserStreamPanelID - ? "checkmark.circle.fill" - : "globe" - ) - } - .accessibilityIdentifier("BrowserStreamMenuItem-\(panel.id)") - } - } - } - } else { - Section(L10n.string("mobile.browserStream.menuTitle", defaultValue: "Mac Browsers")) { - Label( - L10n.string("mobile.macUpdateHint.browserStream", defaultValue: "Update cmux on your Mac to stream browser panes"), - systemImage: "arrow.down.circle" - ) - .accessibilityIdentifier("BrowserStreamMacUpdateHint") - } - } - - Section { - Button(action: actions.createWorkspace) { - Label( - L10n.string("mobile.workspace.new", defaultValue: "New Workspace"), - systemImage: "plus.square.on.square" - ) - } - .disabled(!value.canCreateWorkspace) - .accessibilityIdentifier("MobileNewWorkspaceMenuItem") - - Button(action: actions.createTerminal) { - Label(L10n.string("mobile.terminal.new", defaultValue: "New Terminal"), systemImage: "plus") - } - .accessibilityIdentifier("MobileNewTerminalMenuItem") - - Button(action: actions.openBrowser) { - Label( - L10n.string("mobile.browser.new", defaultValue: "New Browser"), - systemImage: value.hasActiveBrowser ? "checkmark.circle.fill" : "globe" - ) - } - .accessibilityIdentifier("MobileNewBrowserMenuItem") - } - - #if canImport(UIKit) - Section { - if !value.hasActiveBrowser && !value.isChatMode { - Button(action: actions.openTextSheet) { - Label( - L10n.string("mobile.terminal.viewAsText", defaultValue: "View as Text"), - systemImage: "doc.plaintext" - ) - } - .accessibilityIdentifier("MobileViewAsTextMenuItem") - } - - #if DEBUG - Button(action: actions.copyDebugLogs) { - Label( - L10n.string("mobile.debug.copyLogs", defaultValue: "Copy Debug Logs"), - systemImage: "doc.on.clipboard" - ) - } - .accessibilityIdentifier("MobileCopyDebugLogsMenuItem") - #endif - - Button(action: actions.sendFeedback) { - Label( - L10n.string("mobile.feedback.send", defaultValue: "Send Feedback"), - systemImage: "paperplane" - ) - } - .accessibilityIdentifier("MobileSendFeedbackMenuItem") - } - #endif - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuActions.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuActions.swift deleted file mode 100644 index 882eb6ca8c51..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuActions.swift +++ /dev/null @@ -1,13 +0,0 @@ -import CmuxMobileShellModel - -/// User actions emitted by ``TerminalPickerMenu`` without exposing mutable stores to its row subtree. -struct TerminalPickerMenuActions { - let selectTerminal: (MobileTerminalPreview.ID) -> Void - let createWorkspace: () -> Void - let createTerminal: () -> Void - let openBrowser: () -> Void - let selectBrowserStream: (String) -> Void - let openTextSheet: () -> Void - let copyDebugLogs: () -> Void - let sendFeedback: () -> Void -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuDiagnostics.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuDiagnostics.swift deleted file mode 100644 index 655f19595ce6..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuDiagnostics.swift +++ /dev/null @@ -1,41 +0,0 @@ -#if DEBUG -import Foundation -import OSLog - -/// DEBUG-only events for counting terminal-picker menu evaluation and snapshot writes. -struct TerminalPickerMenuDiagnostics { - private let logger = Logger( - subsystem: Bundle.main.bundleIdentifier ?? "com.cmuxterm.app", - category: "TerminalPickerMenu" - ) - private let signpostLog = OSLog( - subsystem: Bundle.main.bundleIdentifier ?? "com.cmuxterm.app", - category: "TerminalPickerMenu" - ) - - func recordContentBuilderEvaluation(rowCount: Int) { - logger.debug("content-builder evaluated rows=\(rowCount, privacy: .public)") - os_signpost( - .event, - log: signpostLog, - name: "ContentBuilderEvaluation", - "rows=%{public}d", - rowCount - ) - } - - func recordRowsWrite(rowCount: Int, includesTitleChanges: Bool) { - logger.debug( - "snapshot rows write rows=\(rowCount, privacy: .public) includeTitles=\(includesTitleChanges, privacy: .public)" - ) - os_signpost( - .event, - log: signpostLog, - name: "SnapshotRowsWrite", - "rows=%{public}d includeTitles=%{public}d", - rowCount, - includesTitleChanges ? 1 : 0 - ) - } -} -#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuValue.swift deleted file mode 100644 index eb41f85fed97..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuValue.swift +++ /dev/null @@ -1,39 +0,0 @@ -import CmuxMobileShellModel - -/// Immutable state that determines the native terminal picker's presented menu. -struct TerminalPickerMenuValue: Equatable { - let rows: [TerminalPickerMenuRow] - let selectedID: MobileTerminalPreview.ID? - let selectedName: String? - let canCreateWorkspace: Bool - let hasActiveBrowser: Bool - let isChatMode: Bool - let browserStreamRows: [BrowserStreamPickerRow] - let supportsBrowserStream: Bool - let activeBrowserStreamPanelID: String? - - init( - liveTerminals: [MobileTerminalPreview], - snapshotRows: [TerminalPickerMenuRow], - selectedID: MobileTerminalPreview.ID?, - canCreateWorkspace: Bool, - hasActiveBrowser: Bool, - isChatMode: Bool, - browserStreamRows: [BrowserStreamPickerRow] = [], - supportsBrowserStream: Bool = false, - activeBrowserStreamPanelID: String? = nil - ) { - rows = snapshotRows.isEmpty - ? liveTerminals.map(TerminalPickerMenuRow.init) - : snapshotRows - let selection = rows.resolvedTerminalPickerSelection(selectedID: selectedID) - self.selectedID = selection?.id - selectedName = selection?.name - self.canCreateWorkspace = canCreateWorkspace - self.hasActiveBrowser = hasActiveBrowser - self.isChatMode = isChatMode - self.browserStreamRows = browserStreamRows - self.supportsBrowserStream = supportsBrowserStream - self.activeBrowserStreamPanelID = activeBrowserStreamPanelID - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift index 67666795b5cd..44e0d3490b16 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift @@ -19,6 +19,10 @@ struct WorkspaceDetailContainer: View { let setWorkspaceUnread: ((MobileWorkspacePreview.ID, Bool) -> Void)? let closeWorkspace: ((MobileWorkspacePreview.ID) -> Void)? let safeAreaContext: MobileTerminalSafeAreaContext + /// Forwarded to ``WorkspaceDetailView``: `.navigationPush` when this + /// container is a pushed destination of an ancestor `NavigationStack`, + /// `.column` when it owns its navigation column (split detail). + let paneZoomHosting: PaneZoomHosting let backButtonConfiguration: WorkspaceBackButtonConfiguration? let signOut: (@MainActor @Sendable () -> Void)? @State private var routeWorkspaceSnapshot: MobileWorkspacePreview? @@ -56,6 +60,7 @@ struct WorkspaceDetailContainer: View { reportTerminalViewport: store.reportTerminalViewport, sendTerminalInput: store.sendTerminalRawInput, safeAreaContext: safeAreaContext, + paneZoomHosting: paneZoomHosting, backButtonConfiguration: backButtonConfiguration, signOut: signOut ) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift index 5cb51ca4bbba..cef9087701d1 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift @@ -19,6 +19,7 @@ struct WorkspaceDetailCreateDelayedTerminalPreviewView: View { name: "cmux", terminals: [ MobileTerminalPreview(id: initialTerminalID, name: "Build"), + MobileTerminalPreview(id: "terminal-tests", name: "Tests"), ] ), MobileWorkspacePreview( diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+AgentChat.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+AgentChat.swift index b32cc2b8c7b8..62b9ebe3d81c 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+AgentChat.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+AgentChat.swift @@ -122,7 +122,7 @@ extension WorkspaceDetailView { .frame(width: 44, height: 44) .transition(.scale(scale: 0.82, anchor: .trailing).combined(with: .opacity)) } - terminalPickerToolbarButton + workspaceUtilitiesToolbarButton .frame(width: 44, height: 44) } .frame(width: shouldShowChatToggle ? 96 : 44, height: 44, alignment: .trailing) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+MenuState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+MenuState.swift index 023076fa2cfa..7588be1f2bc0 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+MenuState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView+MenuState.swift @@ -1,71 +1,4 @@ -import CmuxMobileShellModel - -struct TerminalPickerMenuRow: Identifiable, Equatable { - let id: MobileTerminalPreview.ID - let name: String - - init(_ terminal: MobileTerminalPreview) { - id = terminal.id - name = terminal.name - } -} - -/// Structural change token for the native menu; title churn must not rebuild an open picker. -struct TerminalPickerMenuMembership: Equatable { - let ids: [MobileTerminalPreview.ID] - - init(_ rows: [TerminalPickerMenuRow]) { - ids = rows.map(\.id) - } -} - -extension Collection where Element == TerminalPickerMenuRow { - func resolvedTerminalPickerSelection( - selectedID: MobileTerminalPreview.ID? - ) -> (id: MobileTerminalPreview.ID, name: String)? { - if let selectedID, - let selected = first(where: { $0.id == selectedID }) { - return (id: selected.id, name: selected.name) - } - guard let first else { return nil } - return (id: first.id, name: first.name) - } -} - extension WorkspaceDetailView { - var terminalPickerLiveRows: [TerminalPickerMenuRow] { - workspace.terminals.map(TerminalPickerMenuRow.init) - } - - var terminalPickerLiveMembership: TerminalPickerMenuMembership { - TerminalPickerMenuMembership(terminalPickerLiveRows) - } - - func syncTerminalPickerRows(includeTitleChanges: Bool = false) { - let rows = terminalPickerLiveRows - if includeTitleChanges { - guard terminalPickerRows != rows else { return } - #if DEBUG - TerminalPickerMenuDiagnostics().recordRowsWrite( - rowCount: rows.count, - includesTitleChanges: true - ) - #endif - terminalPickerRows = rows - return - } - guard terminalPickerRows.isEmpty - || TerminalPickerMenuMembership(terminalPickerRows) != TerminalPickerMenuMembership(rows) - else { return } - #if DEBUG - TerminalPickerMenuDiagnostics().recordRowsWrite( - rowCount: rows.count, - includesTitleChanges: false - ) - #endif - terminalPickerRows = rows - } - var hasTitleMenuActions: Bool { customizeWorkspace != nil || workspace.actionCapabilities.supportsWorkspaceActions diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 1344ed8683b2..c0efa41cb616 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -41,6 +41,11 @@ struct WorkspaceDetailView: View { let reportTerminalViewport: (MobileWorkspacePreview.ID, MobileTerminalPreview.ID, MobileTerminalViewportSize) -> Void let sendTerminalInput: (String) -> Void let safeAreaContext: MobileTerminalSafeAreaContext + /// How the pane-zoom pair may be hosted here: `.navigationPush` when this + /// view is a pushed destination of an ancestor `NavigationStack` (where a + /// nested stack would trap the shared `NavigationAuthority`), `.column` + /// when it owns its navigation column (split detail, standalone hosts). + let paneZoomHosting: PaneZoomHosting let backButtonConfiguration: WorkspaceBackButtonConfiguration? let signOut: (@MainActor @Sendable () -> Void)? @Environment(BrowserSurfaceStore.self) var browserStore @@ -56,7 +61,7 @@ struct WorkspaceDetailView: View { @State private var isSubmittingFeedback = false @State private var feedbackErrorMessage: String? @State private var isTextSheetPresented = false - /// Drives the rename-workspace dialog launched from the picker menu, and its + /// Drives the rename-workspace dialog launched from the title menu, and its /// editable text (seeded with the current name when presented). @State var isRenamePresented = false @State var renameText = "" @@ -66,7 +71,10 @@ struct WorkspaceDetailView: View { @State private var contentWidth: CGFloat = 0 /// Terminal captured for the current "View as Text" sheet presentation. @State private var textSheetSurfaceID: String? - @State var terminalPickerRows: [TerminalPickerMenuRow] = [] + @Namespace private var paneZoomNamespace + @State private var paneZoomPresentation = PaneZoomPresentationState() + @State private var paneMapRefreshTrigger = 0 + @State private var isPaneMapRefreshing = false /// Chat-mode toggle for inline agent chat in place of the terminal. @State var isChatMode = false /// The session chat mode was entered on, pinned so sorting cannot swap the conversation @@ -121,45 +129,105 @@ struct WorkspaceDetailView: View { } #endif var body: some View { - let content = Group { detailSurfaceContent } - #if os(iOS) - content - .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } - .navigationTitle(systemNavigationTitle) - .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) - .toolbar { workspaceDetailToolbar } - .task(id: chatRefreshKey) { await refreshChatSessions() } - .task(id: workspace.rpcWorkspaceID.rawValue) { - await store.refreshMobileBrowserPanels(workspaceID: workspace.rpcWorkspaceID.rawValue) - } - .task(id: chatConversationWarmKey) { await runWarmChatConversation() } - .onAppear { refreshWorkspaceChangesHint() } - .onChange(of: workspaceChangesHintEligibilityKey) { _, _ in - refreshWorkspaceChangesHint() - } - .onChange(of: selectedTerminalID) { _, _ in - visibleArtifactCount = 0 - refreshCachedChatToggleAnchor() - syncTerminalPickerRows(includeTitleChanges: true) - } - .onChange(of: store.supportsTerminalArtifacts) { _, supportsArtifacts in - visibleArtifactCount = 0 - } - .onChange(of: store.supportsChatArtifactGallery) { _, _ in - visibleArtifactCount = 0 - } + // The presentation set is attached twice with opposite gates: once + // here (live whenever the base layer is what the user sees) and once + // inside the terminal's full-screen cover in push hosting (live while + // the cover is up), because a covered base cannot present sheets or + // dialogs. Exactly one attachment is active at a time. + detailPresentations( + detailRootContent, + active: !terminalCoverIsPresented + ) + #else + Group { detailSurfaceContent } .closeWorkspaceConfirmation( isPresented: $isConfirmingClose, confirm: confirmCloseWorkspaceFromMenu ) - .sheet(isPresented: $isFeedbackComposerPresented) { + .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) + #endif + } + + #if os(iOS) + private var detailRootContent: some View { + Group { + if let layout = workspace.layout { + PaneZoomHost( + presentation: $paneZoomPresentation, + hosting: paneZoomHosting, + terminalTheme: store.activeTerminalTheme, + zoomSourceID: paneZoomSourceSurfaceID, + zoomNamespace: paneZoomNamespace + ) { + paneMapRoot(layout: layout) + .accessibilityHidden(paneZoomPresentation.isTerminalPresented) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } + .navigationTitle(systemNavigationTitle) + .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) + .toolbar { workspaceDetailToolbar(mode: .paneMap) } + .navigationBarBackButtonHidden(true) + } terminal: { + detailPresentations( + terminalWorkspaceEndpoint + .mobileSurfaceDeckInset( + isVisible: shouldShowSurfaceDeck, + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme + ) + .navigationBarBackButtonHidden(true), + active: terminalCoverIsPresented + ) + } + } else { + terminalWorkspaceEndpoint + .mobileSurfaceDeckInset( + isVisible: shouldShowSurfaceDeck, + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme + ) + } + } + .background { + store.activeTerminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + .onChange(of: workspace.layout != nil) { _, hasLayout in + paneZoomPresentation.layoutAvailabilityDidChange(hasLayout: hasLayout) + } + } + + /// Whether the terminal currently renders inside a full-screen cover + /// (push hosting only), which blocks presentations from the covered base. + private var terminalCoverIsPresented: Bool { + paneZoomHosting == .navigationPush + && workspace.layout != nil + && paneZoomPresentation.isTerminalPresented + } + + /// The workspace detail's sheets, dialogs, and the connection-recovery + /// overlay. Attached to both the base layer and the terminal cover with + /// opposite `active` gates so state stays shared while only the visible + /// layer presents. Gating happens through the bindings (not structurally) + /// so flipping layers never changes subtree identity. + private func detailPresentations( + _ content: some View, + active: Bool + ) -> some View { + content + .closeWorkspaceConfirmation( + isPresented: presentationGate($isConfirmingClose, active: active), + confirm: confirmCloseWorkspaceFromMenu + ) + .sheet(isPresented: presentationGate($isFeedbackComposerPresented, active: active)) { feedbackComposer } - .sheet(isPresented: $isTextSheetPresented) { + .sheet(isPresented: presentationGate($isTextSheetPresented, active: active)) { TerminalTextSheetView(surfaceID: textSheetSurfaceID) } - .sheet(isPresented: $isWorkspaceChangesSheetPresented) { + .sheet(isPresented: presentationGate($isWorkspaceChangesSheetPresented, active: active)) { WorkspaceChangesSheet( store: store, workspaceID: workspace.rpcWorkspaceID.rawValue, @@ -169,30 +237,118 @@ struct WorkspaceDetailView: View { .presentationDragIndicator(.visible) } .workspaceRenameDialog( - isPresented: $isRenamePresented, + isPresented: presentationGate($isRenamePresented, active: active), text: $renameText, onSave: commitRenameFromDialog ) - .sheet(isPresented: $isCustomizationPresented) { + .sheet(isPresented: presentationGate($isCustomizationPresented, active: active)) { WorkspaceCustomizationSheet(workspace: workspace) { initialDraft, submittedDraft in await customizeWorkspace?(workspace.id, initialDraft, submittedDraft) ?? .failure() } } - .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) - #else - content - .closeWorkspaceConfirmation( - isPresented: $isConfirmingClose, - confirm: confirmCloseWorkspaceFromMenu + .mobileConnectionRecoveryOverlay( + store: store, + signOut: signOut, + isActive: active ) - .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) - #endif } - #if os(iOS) + /// A presentation binding that reads as presented only while its layer is + /// the visible one. Writes always land in the shared state, so a dismiss + /// from either layer clears the flag. + private func presentationGate( + _ binding: Binding, + active: Bool + ) -> Binding { + Binding( + get: { active && binding.wrappedValue }, + set: { binding.wrappedValue = $0 } + ) + } + + private var shouldShowSurfaceDeck: Bool { + // The deck is the workspace's surface picker, including the documented + // exit path from a browser stream (BrowserStreamPane has no close + // affordance of its own). Hiding it during a stream would strand + // no-layout workspaces on the stream with no way back to a terminal. + (activeSurface == .terminal || activeSurface == .browserStream) + && paneZoomPresentation.isTerminalPresented + && surfaceDeckValue.shouldShow + } + + private var terminalWorkspaceEndpoint: some View { + let content = Group { detailSurfaceContent } + + return content + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } + .navigationTitle(systemNavigationTitle) + .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) + .toolbar { workspaceDetailToolbar(mode: .terminal) } + .task(id: chatRefreshKey) { await refreshChatSessions() } + .task(id: workspace.rpcWorkspaceID.rawValue) { + await store.refreshMobileBrowserPanels(workspaceID: workspace.rpcWorkspaceID.rawValue) + } + .task(id: chatConversationWarmKey) { await runWarmChatConversation() } + .onAppear { refreshWorkspaceChangesHint() } + .onChange(of: workspaceChangesHintEligibilityKey) { _, _ in + refreshWorkspaceChangesHint() + } + .onChange(of: selectedTerminalID) { _, _ in + visibleArtifactCount = 0 + refreshCachedChatToggleAnchor() + } + .onChange(of: store.supportsTerminalArtifacts) { _, supportsArtifacts in + visibleArtifactCount = 0 + } + .onChange(of: store.supportsChatArtifactGallery) { _, _ in + visibleArtifactCount = 0 + } + } + + private func paneMapRoot(layout: MobilePaneLayout) -> some View { + PaneMapOverlay( + value: PaneMapValue( + layout: layout, + phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, + agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds + ), + terminalTheme: store.activeTerminalTheme, + zoomNamespace: paneZoomNamespace, + isVisible: !paneZoomPresentation.isTerminalPresented, + allowsReordering: workspace.actionCapabilities.supportsPaneReorder, + refreshTrigger: paneMapRefreshTrigger, + fetchPreviews: { selectedSurfaceIDs, remainingSurfaceIDs in + await store.fetchPaneMapPreviewGrids( + remoteWorkspaceID: workspace.rpcWorkspaceID.rawValue, + selectedSurfaceIDs: selectedSurfaceIDs, + remainingSurfaceIDs: remainingSurfaceIDs + ) + }, + selectTerminal: presentTerminalFromPaneMap, + reorderPanes: reorderPanesFromMap, + refreshingChanged: { isPaneMapRefreshing = $0 } + ) + } + + private var paneZoomSourceSurfaceID: String { + paneZoomPresentation.sourceSurfaceID + ?? selectedTerminal?.id.rawValue + ?? workspace.layout?.orderedPanes + .compactMap(\.selectedSurfaceID) + .first + ?? "" + } + + private enum WorkspaceDetailToolbarMode { + case paneMap + case terminal + } + @ToolbarContentBuilder - private var workspaceDetailToolbar: some ToolbarContent { + private func workspaceDetailToolbar( + mode: WorkspaceDetailToolbarMode + ) -> some ToolbarContent { if backButtonConfiguration != nil { ToolbarItem(id: "workspace-back", placement: .topBarLeading) { workspaceBackToolbarButton @@ -202,16 +358,7 @@ struct WorkspaceDetailView: View { } } ToolbarItem(id: "workspace-title", placement: .topBarLeading) { - workspaceTitleToolbarMenu - } - if let selectedTerminalID, - store.isAlternateScreen(surfaceID: selectedTerminalID), - displaySettings.showAltScreenNotice { - ToolbarItem(id: "workspace-altscreen-notice", placement: .topBarTrailing) { - AltScreenNoticeButton { - displaySettings.showAltScreenNotice = false - } - } + workspaceTitleToolbarMenu(mode: mode) } if workspaceChangesAreAvailable { ToolbarItem(id: "workspace-changes", placement: .topBarTrailing) { @@ -225,17 +372,35 @@ struct WorkspaceDetailView: View { .environment(\.colorScheme, store.activeTerminalTheme.terminalColorScheme) } } - ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { - toolbarTrailingCluster + switch mode { + case .terminal: + ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { + workspaceToolbarTrailingContent + } + case .paneMap: + ToolbarItem(id: "pane-map-refresh", placement: .topBarTrailing) { + PaneMapRefreshToolbarButton( + isRefreshing: isPaneMapRefreshing, + refresh: refreshPaneMapFromToolbar + ) + } + ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { + PaneMapDoneToolbarButton(done: returnToTerminalFromPaneMap) + } } } - private var workspaceTitleToolbarMenu: some View { + private func workspaceTitleToolbarMenu( + mode: WorkspaceDetailToolbarMode + ) -> some View { let value = WorkspaceTitleMenuValue( contentWidth: contentWidth, hasBackButton: backButtonConfiguration != nil, hasTrailingCluster: true, + // Reserve the same leading-title geometry in both endpoints even + // though the chat control itself only appears in terminal mode. hasChatToggle: shouldShowChatToggle, + reservesPaneMapControls: workspace.layout != nil, isEnabled: hasTitleMenuActions, workspaceName: workspace.name, hasUnread: workspace.hasUnread, @@ -243,7 +408,7 @@ struct WorkspaceDetailView: View { canRenameWorkspace: renameWorkspace != nil, canToggleReadState: setWorkspaceUnread != nil, canCloseWorkspace: closeWorkspace != nil, - labelToken: toolbarTitleLabelToken, + labelToken: toolbarTitleLabelToken(mode: mode), terminalTheme: store.activeTerminalTheme ) return WorkspaceTitleMenu( @@ -293,8 +458,21 @@ struct WorkspaceDetailView: View { .equatable() } - private var toolbarTitleLabelToken: WorkspaceTitleMenuLabelToken { - if isChatMode, + private func toolbarTitleLabelToken( + mode: WorkspaceDetailToolbarMode + ) -> WorkspaceTitleMenuLabelToken { + if mode == .paneMap, + let layout = workspace.layout { + let paneMapValue = PaneMapValue( + layout: layout, + phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, + agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds + ) + return .standard( + title: workspace.name, + subtitle: paneMapValue.countSubtitle + ) + } else if isChatMode, let session = chosenChatSession, let conversation = chatConversationStores[session.id] { return .chat( @@ -312,6 +490,21 @@ struct WorkspaceDetailView: View { return .standard(title: workspace.name, subtitle: selectedToolbarSubtitle) } } + + @ViewBuilder + private var workspaceToolbarTrailingContent: some View { + HStack(spacing: 8) { + if let selectedTerminalID, + store.isAlternateScreen(surfaceID: selectedTerminalID), + displaySettings.showAltScreenNotice { + AltScreenNoticeButton { + displaySettings.showAltScreenNotice = false + } + .frame(width: 44, height: 44) + } + toolbarTrailingCluster + } + } #endif func detailContent() -> some View { @@ -559,7 +752,6 @@ struct WorkspaceDetailView: View { @ViewBuilder private var terminalToolbarButtons: some View { newWorkspaceToolbarButton - terminalPickerToolbarButton } #if os(iOS) @@ -587,41 +779,105 @@ struct WorkspaceDetailView: View { .accessibilityIdentifier("MobileTerminalNewWorkspaceButton") } - // Native menu keeps press-drag-release selection and routes through - // `selectTerminalFromPicker`; keyboard-dismiss-on-open is unavailable. - var terminalPickerToolbarButton: some View { - TerminalPickerMenu( - value: TerminalPickerMenuValue( - liveTerminals: workspace.terminals, - snapshotRows: terminalPickerRows, - selectedID: store.selectedTerminalID, - canCreateWorkspace: canCreateWorkspace, - hasActiveBrowser: activeBrowser != nil, - isChatMode: isChatMode, - browserStreamRows: browserStreamStore.panels(in: workspace.rpcWorkspaceID.rawValue).map(BrowserStreamPickerRow.init), - supportsBrowserStream: store.supportsBrowserStream, - activeBrowserStreamPanelID: activeBrowserStream?.id - ), - actions: TerminalPickerMenuActions( - selectTerminal: selectTerminalFromPicker, - createWorkspace: createWorkspaceFromToolbar, - createTerminal: createTerminalFromToolbar, - openBrowser: openBrowserFromToolbar, - selectBrowserStream: selectBrowserStreamFromToolbar, - openTextSheet: openTextSheetFromMenu, - copyDebugLogs: { - #if DEBUG - copyDebugLogsFromMenu() - #endif - }, - sendFeedback: openFeedbackComposerFromMenu - ), - terminalTheme: store.activeTerminalTheme + var workspaceUtilitiesToolbarButton: some View { + WorkspaceUtilitiesMenu( + showsViewAsText: activeBrowser == nil && activeBrowserStream == nil && !isChatMode, + showsPaneMap: workspace.layout != nil, + browserStreamRows: browserStreamStore + .panels(in: workspace.rpcWorkspaceID.rawValue) + .map(BrowserStreamPickerRow.init), + supportsBrowserStream: store.supportsBrowserStream, + activeBrowserStreamPanelID: activeBrowserStream?.id, + terminalTheme: store.activeTerminalTheme, + selectBrowserStream: selectBrowserStreamFromToolbar, + presentPaneMap: presentPaneMap, + openTextSheet: openTextSheetFromMenu, + copyDebugLogs: { + #if DEBUG + copyDebugLogsFromMenu() + #endif + }, + sendFeedback: openFeedbackComposerFromMenu ) - .equatable() - .simultaneousGesture(TapGesture().onEnded { syncTerminalPickerRows(includeTitleChanges: true) }) - .onAppear { syncTerminalPickerRows(includeTitleChanges: true) } - .onChange(of: terminalPickerLiveMembership) { _, _ in syncTerminalPickerRows() } + } + + private var surfaceDeckValue: SurfaceDeckValue { + SurfaceDeckValue( + workspace: workspace, + selectedSurfaceID: selectedTerminal?.id.rawValue, + agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds, + canCreateWorkspace: canCreateWorkspace + ) + } + + private var surfaceDeckActions: SurfaceDeckActions { + SurfaceDeckActions( + selectTerminal: selectTerminalFromDeck, + presentPaneMap: presentPaneMap, + createTerminal: createTerminalFromToolbar, + openBrowser: openBrowserFromToolbar, + createWorkspace: createWorkspaceFromToolbar + ) + } + + private var surfaceDeckAgentStateKinds: [String: ChatAgentStateKind] { + var result: [String: ChatAgentStateKind] = [:] + for session in store.cachedChatSessions(workspaceID: workspace.id.rawValue) { + guard let terminalID = session.terminalID else { continue } + switch session.state { + case .working: + result[terminalID] = .working + case .needsInput: + result[terminalID] = .needsInput + case .idle, .ended: + break + } + } + return result + } + + private func presentPaneMap() { + guard workspace.layout != nil else { return } + paneZoomPresentation.presentPaneMap( + from: selectedTerminal?.id.rawValue + ) + } + + private func presentTerminalFromPaneMap(_ terminalID: MobileTerminalPreview.ID) { + paneZoomPresentation.presentTerminal(surfaceID: terminalID.rawValue) + selectTerminalFromDeck(terminalID) + } + + private func returnToTerminalFromPaneMap() { + guard !paneZoomSourceSurfaceID.isEmpty else { return } + paneZoomPresentation.presentTerminal(surfaceID: paneZoomSourceSurfaceID) + } + + private func refreshPaneMapFromToolbar() { + paneMapRefreshTrigger &+= 1 + } + + @MainActor + private func reorderPanesFromMap( + _ orderedPaneIDs: [String], + baseLayoutRevision: Int + ) async -> Bool { + let result = await store.reorderWorkspacePanes( + id: workspace.id, + orderedPaneIDs: orderedPaneIDs, + baseLayoutRevision: baseLayoutRevision + ) + guard case .success = result else { + toasts.present(.failure( + L10n.string( + "mobile.paneMap.reorderFailed", + defaultValue: "Couldn’t rearrange panes on your Mac." + ), + coalescingKey: "pane-map.reorder-failed" + )) + return false + } + return true } #if canImport(UIKit) @@ -809,7 +1065,7 @@ struct WorkspaceDetailView: View { closeWorkspace?(workspace.id) } - /// Toggle the current workspace's read state from the picker menu. + /// Toggle the current workspace's read state from the title menu. private func toggleWorkspaceReadStateFromMenu() { let id = workspace.id let markUnread = !workspace.hasUnread @@ -853,7 +1109,7 @@ struct WorkspaceDetailView: View { dismissTerminalKeyboardForChrome() // Opens (or reveals the existing) browser pane for this workspace. The // detail view flips to the browser because `activeBrowser` becomes - // non-nil; the picker shows a check next to "New Browser" while it is up. + // non-nil. browserStore.openBrowser(for: workspace.id.rawValue) stopActiveBrowserStream() } @@ -874,13 +1130,13 @@ struct WorkspaceDetailView: View { Task { await store.stopMobileBrowserStream(panelID: stream.id) } } - private func selectTerminalFromPicker(_ terminalID: MobileTerminalPreview.ID) { + private func selectTerminalFromDeck(_ terminalID: MobileTerminalPreview.ID) { dismissTerminalKeyboardForChrome() // Choosing a terminal returns from the browser pane (if up) to the // terminal. Closing the browser is enough to flip the detail view back. browserStore.closeBrowser(for: workspace.id.rawValue) stopActiveBrowserStream() - // Switching from the picker is chrome, not a typing intent, so the + // Switching from the deck is chrome, not a typing intent, so the // newly-selected surface must not grab the keyboard on attach. The // store suppresses the target's autofocus (and is a no-op when it is // already selected). A push-notification deep link uses the plain diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index 655545535b83..c1ace45757b2 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -235,6 +235,7 @@ struct WorkspaceShellView: View { workspaceTabContent( canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection ) + .toolbarVisibility(primaryTabBarVisibility, for: .tabBar) } notifications: { NavigationStack(path: $notificationNavigationPath) { NotificationFeedStoreView( @@ -253,7 +254,8 @@ struct WorkspaceShellView: View { workspaceDestination( for: workspaceID, createWorkspace: createWorkspaceInCompactStack, - canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection + canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection, + paneZoomHosting: .navigationPush ) .toolbarVisibility(.hidden, for: .tabBar) } @@ -277,6 +279,7 @@ struct WorkspaceShellView: View { projection: notificationFeedProjection ) } + .toolbarVisibility(primaryTabBarVisibility, for: .tabBar) .environment(\.workspaceRootToolbarContentWidth, geometry.size.width) .environment(\.workspaceRootToolbarRenderContext, toolbarRenderContext) .onChange(of: primarySearchCoordinator.isPresented) { _, isPresented in @@ -409,13 +412,23 @@ struct WorkspaceShellView: View { workspaceDestination( for: workspaceID, createWorkspace: createWorkspaceInCompactStack, - canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection + canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection, + paneZoomHosting: .navigationPush ) .toolbarVisibility(.hidden, for: .tabBar) } } } + #if os(iOS) + private var primaryTabBarVisibility: Visibility { + let workspaceIsPushed = usesCompactStack && !compactNavigationPath.isEmpty + let notificationRouteIsPushed = !notificationNavigationPath.isEmpty + || !notificationSearchNavigationPath.isEmpty + return workspaceIsPushed || notificationRouteIsPushed ? .hidden : .automatic + } + #endif + private func layoutContent(canCreateWorkspaceForSelection: Bool) -> some View { Group { if usesCompactStack { @@ -463,6 +476,7 @@ struct WorkspaceShellView: View { for: workspaceID, createWorkspace: createWorkspaceInCompactStack, canCreateWorkspaceForSelection: canCreateWorkspaceForSelection, + paneZoomHosting: .navigationPush, backButtonConfiguration: WorkspaceBackButtonConfiguration( unreadCount: unreadWorkspaceCount(excluding: workspaceID), badgeContrast: .darkBackground, @@ -556,6 +570,7 @@ struct WorkspaceShellView: View { for: store.selectedWorkspaceID, createWorkspace: createWorkspaceIfConnected, canCreateWorkspaceForSelection: canCreateWorkspaceForSelection, + paneZoomHosting: .column, safeAreaContext: splitColumnVisibility == .detailOnly ? .fullWidth : .splitSidebarVisible ) #if os(iOS) @@ -1037,6 +1052,7 @@ struct WorkspaceShellView: View { for workspaceID: MobileWorkspacePreview.ID?, createWorkspace: @escaping () -> Void, canCreateWorkspaceForSelection: Bool, + paneZoomHosting: PaneZoomHosting, safeAreaContext: MobileTerminalSafeAreaContext = .fullWidth, backButtonConfiguration: WorkspaceBackButtonConfiguration? = nil ) -> some View { @@ -1050,6 +1066,7 @@ struct WorkspaceShellView: View { setWorkspaceUnread: setWorkspaceUnreadClosure, closeWorkspace: closeWorkspaceClosure, safeAreaContext: safeAreaContext, + paneZoomHosting: paneZoomHosting, backButtonConfiguration: backButtonConfiguration, signOut: signOut ) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenu.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenu.swift index 08779fcb02c1..9b38cdb562d4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenu.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenu.swift @@ -29,18 +29,10 @@ struct WorkspaceTitleMenu: View, Equatable { } private var fittedLabel: some View { - let cap = MobileLeadingToolbarTitleWidth( - contentWidth: value.contentWidth, - hasBackButton: value.hasBackButton, - hasTrailingCluster: value.hasTrailingCluster, - hasChatToggle: value.hasChatToggle - ).cap - return label() - .frame( - minWidth: min(MobileLeadingToolbarTitleWidth.floor, cap), - maxWidth: cap, - alignment: .leading - ) + // Terminal and pane-map subtitles have different intrinsic widths. + // Pin the shared title shell to geometry-derived space so navigating + // between those endpoints cannot move or resize the toolbar title. + .frame(width: value.titleWidth, alignment: .leading) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift index fd8ea8bbecfc..5b10a44c5556 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift @@ -6,6 +6,7 @@ struct WorkspaceTitleMenuValue: Equatable { let hasBackButton: Bool let hasTrailingCluster: Bool let hasChatToggle: Bool + let reservesPaneMapControls: Bool let isEnabled: Bool let workspaceName: String let hasUnread: Bool @@ -15,4 +16,14 @@ struct WorkspaceTitleMenuValue: Equatable { let canCloseWorkspace: Bool let labelToken: WorkspaceTitleMenuLabelToken let terminalTheme: TerminalTheme + + var titleWidth: CGFloat { + MobileLeadingToolbarTitleWidth( + contentWidth: contentWidth, + hasBackButton: hasBackButton, + hasTrailingCluster: hasTrailingCluster, + hasChatToggle: hasChatToggle, + reservesPaneMapControls: reservesPaneMapControls + ).cap + } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift new file mode 100644 index 000000000000..ac1f6b884517 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift @@ -0,0 +1,96 @@ +import CMUXMobileCore +import CmuxMobileSupport +import SwiftUI + +/// Workspace-level utilities that remain in the top-right toolbar. +struct WorkspaceUtilitiesMenu: View { + let showsViewAsText: Bool + let showsPaneMap: Bool + var browserStreamRows: [BrowserStreamPickerRow] = [] + var supportsBrowserStream = true + var activeBrowserStreamPanelID: String? + let terminalTheme: TerminalTheme + var selectBrowserStream: (String) -> Void = { _ in } + let presentPaneMap: () -> Void + let openTextSheet: () -> Void + let copyDebugLogs: () -> Void + let sendFeedback: () -> Void + + var body: some View { + Menu { + if showsPaneMap { + Button(action: presentPaneMap) { + Label( + L10n.string("mobile.surfaceDeck.paneMap", defaultValue: "Pane Map"), + systemImage: "rectangle.split.2x2" + ) + } + .accessibilityIdentifier("MobilePaneMapMenuItem") + } + + if supportsBrowserStream { + if !browserStreamRows.isEmpty { + Section(L10n.string("mobile.browserStream.menuTitle", defaultValue: "Mac Browsers")) { + ForEach(browserStreamRows) { panel in + Button { selectBrowserStream(panel.id) } label: { + Label( + panel.label, + systemImage: panel.id == activeBrowserStreamPanelID + ? "checkmark.circle.fill" + : "globe" + ) + } + .accessibilityIdentifier("BrowserStreamMenuItem-\(panel.id)") + } + } + } + } else { + Section(L10n.string("mobile.browserStream.menuTitle", defaultValue: "Mac Browsers")) { + Label( + L10n.string( + "mobile.macUpdateHint.browserStream", + defaultValue: "Update cmux on your Mac to stream browser panes" + ), + systemImage: "arrow.down.circle" + ) + .accessibilityIdentifier("BrowserStreamMacUpdateHint") + } + } + + if showsViewAsText { + Button(action: openTextSheet) { + Label( + L10n.string("mobile.terminal.viewAsText", defaultValue: "View as Text"), + systemImage: "doc.plaintext" + ) + } + .accessibilityIdentifier("MobileViewAsTextMenuItem") + } + + #if DEBUG + Button(action: copyDebugLogs) { + Label( + L10n.string("mobile.debug.copyLogs", defaultValue: "Copy Debug Logs"), + systemImage: "doc.on.clipboard" + ) + } + .accessibilityIdentifier("MobileCopyDebugLogsMenuItem") + #endif + + Button(action: sendFeedback) { + Label( + L10n.string("mobile.feedback.send", defaultValue: "Send Feedback"), + systemImage: "paperplane" + ) + } + .accessibilityIdentifier("MobileSendFeedbackMenuItem") + } label: { + Image(systemName: "ellipsis.circle") + } + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .accessibilityLabel( + L10n.string("mobile.workspace.utilitiesMenu", defaultValue: "Workspace Utilities") + ) + .accessibilityIdentifier("MobileWorkspaceUtilitiesMenu") + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileInjectedAttachStartupTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileInjectedAttachStartupTests.swift deleted file mode 100644 index e7dfc1f447ab..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileInjectedAttachStartupTests.swift +++ /dev/null @@ -1,41 +0,0 @@ -import CmuxMobileShellModel -import Testing -@testable import CmuxMobileShellUI - -@Suite -struct MobileInjectedAttachStartupTests { - @Test - @MainActor - func beginsRouteAdmissionWithoutAnExternalTransportReadinessBarrier() async throws { - let coordinator = MobileStartupConnectionCoordinator() - let attempt = try #require(coordinator.claimInjectedAttach()) - let recorder = MobileInjectedAttachURLRecorder() - let attachURL = "cmux-ios://attach?v=2&payload=iroh-route" - - let completion = await coordinator.connectInjectedAttach( - attempt, - attachURL: attachURL - ) { rawURL in - await recorder.record(rawURL) - return MobilePairingURLConnectionResult.connected - } - - let completedAttempt = try #require(completion) - #expect(await recorder.values() == [attachURL]) - #expect(completedAttempt.result == .connected) - #expect(!completedAttempt.shouldReconnectStoredMac) - #expect(coordinator.claimStoredReconnect() == nil) - } -} - -private actor MobileInjectedAttachURLRecorder { - private var urls: [String] = [] - - func record(_ url: String) { - urls.append(url) - } - - func values() -> [String] { - urls - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileLeadingToolbarTitleWidthTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileLeadingToolbarTitleWidthTests.swift index 13fff10647f1..9229e6167884 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileLeadingToolbarTitleWidthTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileLeadingToolbarTitleWidthTests.swift @@ -7,13 +7,15 @@ import Testing _ contentWidth: CGFloat, hasBackButton: Bool = true, hasTrailingCluster: Bool = true, - hasChatToggle: Bool = true + hasChatToggle: Bool = true, + reservesPaneMapControls: Bool = false ) -> CGFloat { MobileLeadingToolbarTitleWidth( contentWidth: contentWidth, hasBackButton: hasBackButton, hasTrailingCluster: hasTrailingCluster, - hasChatToggle: hasChatToggle + hasChatToggle: hasChatToggle, + reservesPaneMapControls: reservesPaneMapControls ).cap } @@ -60,6 +62,32 @@ import Testing #expect(withoutTrailing == expected) } + @Test func paneMapControlsReserveTheirRenderedWidth() { + let contentWidth: CGFloat = 260 + let withoutPaneMap = cap( + contentWidth, + hasTrailingCluster: true, + hasChatToggle: false, + reservesPaneMapControls: false + ) + let withPaneMap = cap( + contentWidth, + hasTrailingCluster: true, + hasChatToggle: false, + reservesPaneMapControls: true + ) + let expected = min( + MobileLeadingToolbarTitleWidth.maximumMeasuredCap, + contentWidth + - MobileLeadingToolbarTitleWidth.backButtonReserve + - PaneMapToolbarMetrics.trailingClusterWidth + - MobileLeadingToolbarTitleWidth.barMarginsAndSpacing + ) + + #expect(withPaneMap == expected) + #expect(withPaneMap < withoutPaneMap) + } + @Test func measuredWidthDoesNotExpandPastInitialFallback() { #expect(cap(800, hasChatToggle: false) == MobileLeadingToolbarTitleWidth.unmeasuredFallback) } diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootDebugPreviewRouteTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootDebugPreviewRouteTests.swift new file mode 100644 index 000000000000..43ccf907724d --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootDebugPreviewRouteTests.swift @@ -0,0 +1,21 @@ +#if DEBUG +import Testing +@testable import CmuxMobileShellUI + +@Suite +struct MobileRootDebugPreviewRouteTests { + @Test + func panesPreviewRequiresExactEnabledValue() { + #expect(MobileRootDebugPreviewRoute(environment: [ + "CMUX_UITEST_PANES_PREVIEW": "1", + ]) == .panesTabs) + #expect(MobileRootDebugPreviewRoute(environment: [:]) == nil) + #expect(MobileRootDebugPreviewRoute(environment: [ + "CMUX_UITEST_PANES_PREVIEW": "0", + ]) == nil) + #expect(MobileRootDebugPreviewRoute(environment: [ + "CMUX_UITEST_PANES_PREVIEW": "true", + ]) == nil) + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift new file mode 100644 index 000000000000..49cb7dad83af --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -0,0 +1,352 @@ +import CoreGraphics +import CmuxMobileShellModel +import Testing +#if os(iOS) +import SwiftUI +import UIKit +#endif +@testable import CmuxMobileShellUI + +@Suite struct PaneMapCollectionLayoutEngineTests { + private let engine = PaneMapCollectionLayoutEngine() + + @Test func undersizedSiblingBorrowsSpaceFromTheLargerPane() throws { + let layout = horizontalLayout(ratio: 0.95, paneIDs: ["large", "small"]) + + let result = engine.layout(layout, in: CGSize(width: 390, height: 700)) + let large = try #require(result.framesByPaneID["large"]) + let small = try #require(result.framesByPaneID["small"]) + + #expect(!result.overflowsHorizontally) + #expect(large.width >= 156) + #expect(small.width >= 156) + #expect(small.minX - large.maxX == 14) + #expect(small.width == 156) + } + + @Test func impossibleMinimumWidthsProduceHorizontalOverflow() throws { + let layout = horizontalLayout( + ratio: 0.5, + paneIDs: ["one", "two", "three"] + ) + + let result = engine.layout(layout, in: CGSize(width: 390, height: 700)) + + #expect(result.overflowsHorizontally) + #expect(!result.overflowsVertically) + #expect(result.contentSize.width == 528) + for paneID in ["one", "two", "three"] { + #expect(try #require(result.framesByPaneID[paneID]).width >= 156) + } + } + + @Test func undersizedVerticalSiblingBorrowsSpaceFromTheLargerPane() throws { + let layout = verticalLayout(ratio: 0.95, paneIDs: ["large", "small"]) + + let result = engine.layout(layout, in: CGSize(width: 390, height: 520)) + let large = try #require(result.framesByPaneID["large"]) + let small = try #require(result.framesByPaneID["small"]) + + #expect(!result.overflowsVertically) + #expect(large.height >= 220) + #expect(small.height == 220) + #expect(small.minY - large.maxY == 14) + } + + @Test func impossibleMinimumHeightsProduceVerticalOverflow() throws { + let layout = verticalLayout( + ratio: 0.5, + paneIDs: ["one", "two", "three"] + ) + + let result = engine.layout(layout, in: CGSize(width: 390, height: 520)) + + #expect(!result.overflowsHorizontally) + #expect(result.overflowsVertically) + #expect(result.contentSize.height == 712) + for paneID in ["one", "two", "three"] { + #expect(try #require(result.framesByPaneID[paneID]).height >= 220) + } + } + + @Test func fourPaneGridPreservesMacRatiosWhenMinimumsFit() throws { + let layout = fourPaneLayout() + + let result = engine.layout(layout, in: CGSize(width: 1_000, height: 800)) + let topLeft = try #require(result.framesByPaneID["top-left"]) + let bottomLeft = try #require(result.framesByPaneID["bottom-left"]) + let topRight = try #require(result.framesByPaneID["top-right"]) + let bottomRight = try #require(result.framesByPaneID["bottom-right"]) + + #expect(!result.overflowsHorizontally) + #expect(!result.overflowsVertically) + #expect(topLeft.width > topRight.width) + #expect(topLeft.height < bottomLeft.height) + #expect(topRight.height > bottomRight.height) + #expect(abs(topLeft.width / (topLeft.width + topRight.width) - 0.6) < 0.01) + #expect(abs(topLeft.height / (topLeft.height + bottomLeft.height) - 0.35) < 0.01) + #expect(abs(topRight.height / (topRight.height + bottomRight.height) - 0.65) < 0.01) + } + + private func horizontalLayout(ratio: Double, paneIDs: [String]) -> MobilePaneLayout { + precondition(paneIDs.count >= 2) + var node = MobilePaneLayout.Node.pane(pane(paneIDs.last!)) + for paneID in paneIDs.dropLast().reversed() { + node = .split(MobilePaneSplit( + id: "split-\(paneID)", + orientation: .horizontal, + ratio: ratio, + first: .pane(pane(paneID)), + second: node + )) + } + return MobilePaneLayout(version: 1, focusedPaneID: nil, root: node) + } + + private func verticalLayout(ratio: Double, paneIDs: [String]) -> MobilePaneLayout { + precondition(paneIDs.count >= 2) + var node = MobilePaneLayout.Node.pane(pane(paneIDs.last!)) + for paneID in paneIDs.dropLast().reversed() { + node = .split(MobilePaneSplit( + id: "split-\(paneID)", + orientation: .vertical, + ratio: ratio, + first: .pane(pane(paneID)), + second: node + )) + } + return MobilePaneLayout(version: 1, focusedPaneID: nil, root: node) + } + + private func fourPaneLayout() -> MobilePaneLayout { + MobilePaneLayout( + version: 1, + focusedPaneID: "top-left", + root: .split(MobilePaneSplit( + id: "root", + orientation: .horizontal, + ratio: 0.6, + first: .split(MobilePaneSplit( + id: "left", + orientation: .vertical, + ratio: 0.35, + first: .pane(pane("top-left")), + second: .pane(pane("bottom-left")) + )), + second: .split(MobilePaneSplit( + id: "right", + orientation: .vertical, + ratio: 0.65, + first: .pane(pane("top-right")), + second: .pane(pane("bottom-right")) + )) + )) + ) + } + + private func pane(_ id: String) -> MobilePaneNode { + MobilePaneNode(id: id, selectedSurfaceID: nil, surfaces: []) + } +} + +@Suite struct PaneZoomPresentationStateTests { + @Test func bothDirectionsKeepTheSameStableZoomSource() { + var state = PaneZoomPresentationState() + + state.presentPaneMap(from: "terminal-a") + #expect(state.endpoint == .paneMap) + #expect(state.sourceSurfaceID == "terminal-a") + + state.presentTerminal(surfaceID: "terminal-b") + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-b") + + state.presentationDidChange(isTerminalPresented: false) + #expect(state.endpoint == .paneMap) + #expect(state.sourceSurfaceID == "terminal-b") + } + + @Test func anInteractiveCancellationDoesNotDiscardTheSource() { + var state = PaneZoomPresentationState() + state.presentTerminal(surfaceID: "terminal-a") + + state.presentationDidChange(isTerminalPresented: false) + state.presentationDidChange(isTerminalPresented: true) + + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-a") + } + + @Test func startsWithTheRestoredTerminalAlreadyInstalledInItsLocalPath() { + var state = PaneZoomPresentationState() + + #expect(state.navigationPath == [.terminal]) + #expect(state.isTerminalPresented) + + state.navigationPathDidChange([]) + #expect(state.endpoint == .paneMap) + + state.presentTerminal(surfaceID: "terminal-a") + #expect(state.navigationPath == [.terminal]) + state.navigationPathDidChange([.terminal]) + #expect(state.endpoint == .terminal) + } + + @Test func anEmptyTerminalIDCannotBreakTheMatchedSource() { + var state = PaneZoomPresentationState() + state.presentTerminal(surfaceID: "terminal-a") + state.presentTerminal(surfaceID: "") + + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-a") + } + + @Test func missingLayoutForcesTerminalRouteBeforeReconnect() { + var state = PaneZoomPresentationState() + state.presentPaneMap(from: "terminal-a") + + state.layoutAvailabilityDidChange(hasLayout: false) + + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-a") + } +} + +#if os(iOS) +@MainActor +@Suite struct PaneMapColdOpenPrewarmTests { + /// A restored workspace mounts the map as a covered navigation-stack root: + /// UIKit never attaches it to a window or runs a layout pass, so without a + /// pre-warm the zoom's matched source cells don't exist when the first + /// terminal→map pop starts and the transition degrades to a hard cut. + @Test func detachedMapMaterializesZoomSourceCellsBeforeFirstPop() { + let panes = [ + MobilePaneNode( + id: "alpha", + selectedSurfaceID: "surface-alpha", + surfaces: [ + MobilePaneSurface(id: "surface-alpha", type: .terminal, title: "alpha") + ] + ), + MobilePaneNode( + id: "beta", + selectedSurfaceID: "surface-beta", + surfaces: [ + MobilePaneSurface(id: "surface-beta", type: .terminal, title: "beta") + ] + ), + ] + let layout = MobilePaneLayout( + version: 1, + focusedPaneID: "alpha", + root: .split(MobilePaneSplit( + id: "root", + orientation: .horizontal, + ratio: 0.5, + first: .pane(panes[0]), + second: .pane(panes[1]) + )) + ) + let items = panes.enumerated().map { index, pane in + PaneMapCollectionItem( + pane: pane, + paneNumber: index + 1, + paneCount: panes.count, + isFocusedOnMac: pane.id == "alpha", + selectedSurfaceID: pane.selectedSurfaceID, + phoneSelectedSurfaceID: "surface-alpha", + preview: nil, + isLoadingPreview: false, + agentStateKind: nil + ) + } + let representable = PaneMapCollectionView( + items: items, + layout: layout, + terminalTheme: .monokai, + zoomNamespace: Namespace().wrappedValue, + overflowLabels: PaneMapOverflowLabels( + leading: "leading", + trailing: "trailing", + top: "top", + bottom: "bottom" + ), + allowsReordering: true, + isVisible: false, + selectPreviewSurface: { _, _ in }, + jumpToTerminal: { _ in }, + reorderPanes: { _, _ in true } + ) + let coordinator = PaneMapCollectionView.Coordinator(parent: representable) + let collectionView = UICollectionView( + frame: .zero, + collectionViewLayout: PaneMapCollectionLayout(paneLayout: layout) + ) + collectionView.register( + UICollectionViewCell.self, + forCellWithReuseIdentifier: PaneMapCollectionView.Coordinator.cellReuseIdentifier + ) + collectionView.dataSource = coordinator + collectionView.delegate = coordinator + let container = PaneMapCollectionContainerView(collectionView: collectionView) + container.frame = CGRect(x: 0, y: 0, width: 390, height: 700) + coordinator.attach(collectionView: collectionView, container: container) + + coordinator.reconcile(items: items) + + #expect(container.window == nil) + #expect(collectionView.numberOfItems(inSection: 0) == panes.count) + #expect(collectionView.visibleCells.count == panes.count) + } + + /// The navigation-stack root can also stay entirely unsized while covered; + /// the pre-warm must impose the scene estimate itself before forcing layout. + @Test func zeroSizedDetachedContainerAdoptsTheEstimatedSize() { + let collectionView = UICollectionView( + frame: .zero, + collectionViewLayout: UICollectionViewFlowLayout() + ) + let container = PaneMapCollectionContainerView(collectionView: collectionView) + + container.prewarmDetachedCellLayout( + estimatedSize: CGSize(width: 390, height: 700) + ) + + #expect(container.bounds.size == CGSize(width: 390, height: 700)) + #expect(collectionView.bounds.size == CGSize(width: 390, height: 700)) + } +} + +@MainActor +@Suite struct PaneZoomNavigationBackgroundBridgeTests { + @Test func restoresOwnedAncestorBackgroundsWithoutClobberingNewOwners() { + let originalRootColor = UIColor.red + let originalContainerColor = UIColor.orange + let root = UIViewController() + root.view.backgroundColor = originalRootColor + let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) + container.backgroundColor = originalContainerColor + root.view.addSubview(container) + let bridge = PaneZoomNavigationBackgroundBridgeView( + frame: CGRect(x: 0, y: 0, width: 1, height: 1) + ) + container.addSubview(bridge) + let window = UIWindow(frame: root.view.bounds) + window.rootViewController = root + window.isHidden = false + + bridge.color = .blue + bridge.applyBackground() + + #expect(container.backgroundColor == .blue) + #expect(root.view.backgroundColor == .blue) + + container.backgroundColor = .green + bridge.restoreBackgrounds() + + #expect(container.backgroundColor == .green) + #expect(root.view.backgroundColor == originalRootColor) + window.isHidden = true + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift new file mode 100644 index 000000000000..845151abcb7e --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift @@ -0,0 +1,167 @@ +import Foundation +import Testing +@testable import CmuxMobileShellUI + +@Suite struct PaneMapReorderStateTests { + @Test func beginMoveCapturesBaseLayoutRevision() { + var state = PaneMapReorderState( + authoritativePaneIDs: ["a", "b", "c"], + authoritativeRevision: 7 + ) + + let request = state.beginMove(from: 0, to: 2) + + #expect(request?.baseLayoutRevision == 7) + #expect(request?.orderedPaneIDs == ["b", "c", "a"]) + } + + @Test func lowerRevisionReconcileDoesNotRollBackAuthority() { + var state = PaneMapReorderState( + authoritativePaneIDs: ["b", "a", "c"], + authoritativeRevision: 5 + ) + + // A delayed pre-reorder workspace-list response arrives after newer + // authority already applied. + state.reconcile(authoritativePaneIDs: ["a", "b", "c"], authoritativeRevision: 4) + + #expect(state.authoritativePaneIDs == ["b", "a", "c"]) + #expect(state.authoritativeRevision == 5) + #expect(state.visiblePaneIDs == ["b", "a", "c"]) + } + + @Test func lowerRevisionDoesNotCompletePendingMutation() { + var state = PaneMapReorderState( + authoritativePaneIDs: ["a", "b", "c"], + authoritativeRevision: 5 + ) + let request = state.beginMove(from: 0, to: 1) + #expect(request != nil) + + // Stale response from before the drag must neither count as the + // mutation's authoritative refresh nor overwrite the optimistic order. + state.reconcile(authoritativePaneIDs: ["a", "b", "c"], authoritativeRevision: 4) + let completion = state.complete(requestID: request!.id, succeeded: true) + + #expect(completion == .awaitingAuthority) + #expect(state.isMutationPending) + #expect(state.visiblePaneIDs == ["b", "a", "c"]) + + // The genuinely newer authority then completes the mutation. + state.reconcile(authoritativePaneIDs: ["b", "a", "c"], authoritativeRevision: 6) + #expect(!state.isMutationPending) + #expect(state.visiblePaneIDs == ["b", "a", "c"]) + } + + @Test func equalRevisionReconcileStillUpdatesContentWithoutPendingMutation() { + var state = PaneMapReorderState( + authoritativePaneIDs: ["a", "b"], + authoritativeRevision: 3 + ) + + state.reconcile(authoritativePaneIDs: ["a", "b"], authoritativeRevision: 3) + + #expect(state.visiblePaneIDs == ["a", "b"]) + #expect(state.authoritativeRevision == 3) + } + + @Test func newerRevisionRollsBackAbandonedOptimisticOrder() { + var state = PaneMapReorderState( + authoritativePaneIDs: ["a", "b", "c"], + authoritativeRevision: 5 + ) + let request = state.beginMove(from: 0, to: 2) + #expect(request != nil) + + _ = state.complete(requestID: request!.id, succeeded: false) + + #expect(state.visiblePaneIDs == ["a", "b", "c"]) + #expect(!state.isMutationPending) + } + + @Test func failureRollsBackToTheLatestAuthoritativeOrder() throws { + var state = PaneMapReorderState( + authoritativePaneIDs: ["left", "middle", "right"], + authoritativeRevision: 10 + ) + + let pendingRequest = state.beginMove(from: 0, to: 2) + let request = try #require(pendingRequest) + #expect(state.visiblePaneIDs == ["middle", "right", "left"]) + + state.reconcile( + authoritativePaneIDs: ["left", "right", "middle"], + authoritativeRevision: 11 + ) + #expect( + state.visiblePaneIDs == ["middle", "right", "left"], + "An in-flight optimistic move must remain stable while the Mac refresh arrives" + ) + + #expect(state.complete(requestID: request.id, succeeded: false) == .rolledBack) + #expect(state.visiblePaneIDs == ["left", "right", "middle"]) + #expect(!state.isMutationPending) + } + + @Test func successWaitsForAndThenUsesTheAuthoritativeMacOrder() throws { + var state = PaneMapReorderState( + authoritativePaneIDs: ["one", "two", "three"], + authoritativeRevision: 20 + ) + + let pendingRequest = state.beginMove(from: 2, to: 0) + let request = try #require(pendingRequest) + #expect(request.orderedPaneIDs == ["three", "one", "two"]) + + state.reconcile( + authoritativePaneIDs: ["one", "two", "three"], + authoritativeRevision: 20 + ) + #expect(state.complete(requestID: request.id, succeeded: true) == .awaitingAuthority) + #expect(state.visiblePaneIDs == ["three", "one", "two"]) + #expect(state.isMutationPending) + + state.reconcile( + authoritativePaneIDs: ["one", "two", "three"], + authoritativeRevision: 21 + ) + #expect(state.visiblePaneIDs == ["one", "two", "three"]) + #expect(!state.isMutationPending) + } + + @Test func authoritativeRevisionCanArriveBeforeTheRequestCompletion() throws { + var state = PaneMapReorderState( + authoritativePaneIDs: ["left", "right"], + authoritativeRevision: 30 + ) + + let pendingRequest = state.beginMove(from: 0, to: 1) + let request = try #require(pendingRequest) + state.reconcile( + authoritativePaneIDs: ["left", "right"], + authoritativeRevision: 31 + ) + + #expect(state.isMutationPending) + #expect(state.complete(requestID: request.id, succeeded: true) == .awaitingAuthority) + #expect(state.visiblePaneIDs == ["left", "right"]) + #expect(!state.isMutationPending) + } + + @Test func staleCompletionCannotOverwriteANewerMove() throws { + var state = PaneMapReorderState( + authoritativePaneIDs: ["a", "b", "c"], + authoritativeRevision: 40 + ) + + let firstPendingRequest = state.beginMove(from: 0, to: 1) + let first = try #require(firstPendingRequest) + #expect(state.complete(requestID: first.id, succeeded: false) == .rolledBack) + + let secondPendingRequest = state.beginMove(from: 2, to: 0) + let second = try #require(secondPendingRequest) + #expect(state.complete(requestID: first.id, succeeded: true) == .ignored) + #expect(state.visiblePaneIDs == second.orderedPaneIDs) + #expect(state.isMutationPending) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapSelectionArbitrationTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapSelectionArbitrationTests.swift new file mode 100644 index 000000000000..f1013684cc54 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapSelectionArbitrationTests.swift @@ -0,0 +1,23 @@ +import CoreGraphics +import Testing +@testable import CmuxMobileShellUI + +@Suite struct PaneMapSelectionArbitrationTests { + @Test func scrollAndDragMovementDoNotResolveAsPaneSelection() { + var arbitration = PaneMapSelectionArbitration() + + arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) + arbitration.touchMoved(to: CGPoint(x: 32, y: 10)) + let movementResolvedAsTap = arbitration.touchEnded(at: CGPoint(x: 32, y: 10)) + #expect(!movementResolvedAsTap) + + arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) + arbitration.dragSessionDidBegin() + let dragResolvedAsTap = arbitration.touchEnded(at: CGPoint(x: 10, y: 10)) + #expect(!dragResolvedAsTap) + + arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) + let stationaryTouchResolvedAsTap = arbitration.touchEnded(at: CGPoint(x: 11, y: 11)) + #expect(stationaryTouchResolvedAsTap) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift new file mode 100644 index 000000000000..0a2dea52cfb8 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift @@ -0,0 +1,57 @@ +import CoreGraphics +import Testing +@testable import CmuxMobileShellUI + +@Suite struct PaneMapTerminalPreviewLayoutTests { + @Test func overflowingPreviewUsesInsetLatestRowsAndBottomAttachment() { + let layout = PaneMapTerminalCanvasLayout( + size: CGSize(width: 112, height: 50), + columns: 10, + rowCount: 20, + inset: 6 + ) + + #expect(layout.contentRect == CGRect(x: 6, y: 6, width: 100, height: 38)) + #expect(layout.visibleRowRange == 18..<20) + #expect(layout.drawOrigin.x == 6) + #expect(layout.drawOrigin.y >= 6) + #expect(abs(layout.lastRowMaxY - layout.contentRect.maxY) < 0.001) + } + + @Test func shortPreviewKeepsItsFirstRowTopAttachedInsideTheInset() { + let layout = PaneMapTerminalCanvasLayout( + size: CGSize(width: 112, height: 80), + columns: 10, + rowCount: 2, + inset: 6 + ) + + #expect(layout.visibleRowRange == 0..<2) + #expect(layout.drawOrigin == CGPoint(x: 6, y: 6)) + } +} + +@Suite struct PaneMapTabStripMetricsTests { + @Test func stripHugsTabsUntilItsMaximumWidth() { + let metrics = PaneMapTabStripMetrics() + #expect(metrics.width(tabCount: 2) == 64) + #expect(metrics.width(tabCount: 3) == 94) + #expect(metrics.width(tabCount: 4) == 124) + #expect(metrics.width(tabCount: 5) == 132) + #expect(metrics.width(tabCount: 20) == 132) + } + + @Test func hitFrameMatchesTheCenteredVisibleStrip() { + let metrics = PaneMapTabStripMetrics() + let previewBounds = CGRect(x: 20, y: 40, width: 156, height: 200) + + #expect( + metrics.frame(in: previewBounds, tabCount: 2) + == CGRect(x: 66, y: 198, width: 64, height: 34) + ) + #expect( + metrics.frame(in: previewBounds, tabCount: 20) + == CGRect(x: 32, y: 198, width: 132, height: 34) + ) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift new file mode 100644 index 000000000000..ca2165e8f8dd --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift @@ -0,0 +1,174 @@ +import CmuxMobileShellModel +import Testing +@testable import CmuxMobileShellUI + +@Suite struct SurfaceDeckValueTests { + @Test func deckRemainsVisibleForCreationActionsWithZeroOrOneTerminal() { + let noTerminals = MobileWorkspacePreview( + id: "empty-workspace", + name: "Empty Workspace", + terminals: [] + ) + let emptyValue = value(workspace: noTerminals, selectedSurfaceID: nil) + + let oneTerminal = MobileWorkspacePreview( + id: "workspace", + name: "Workspace", + terminals: [MobileTerminalPreview(id: "terminal-1", name: "Build")] + ) + let oneValue = value(workspace: oneTerminal, selectedSurfaceID: "terminal-1") + + #expect(emptyValue.groups.count == 1) + #expect(emptyValue.groups[0].chips.isEmpty) + #expect(emptyValue.shouldShow) + #expect(oneValue.groups.count == 1) + #expect(oneValue.groups[0].chips.map(\.id) == ["terminal-1"]) + #expect(oneValue.shouldShow) + } + + @Test func olderMacUsesOneTerminalGroupAndPreservesSurfaceOrder() { + let oneTerminal = MobileWorkspacePreview( + id: "workspace", + name: "Workspace", + terminals: [MobileTerminalPreview(id: "terminal-1", name: "Build")] + ) + let oneValue = value(workspace: oneTerminal, selectedSurfaceID: "terminal-1") + + let twoTerminals = MobileWorkspacePreview( + id: "workspace", + name: "Workspace", + terminals: [ + MobileTerminalPreview(id: "terminal-1", name: "Build"), + MobileTerminalPreview(id: "terminal-2", name: "Tests"), + ] + ) + let twoValue = value(workspace: twoTerminals, selectedSurfaceID: "terminal-2") + + #expect(oneValue.groups.count == 1) + #expect(oneValue.groups[0].chips.map(\.id) == ["terminal-1"]) + #expect(oneValue.showsPaneMap == false) + #expect(twoValue.groups[0].chips.map(\.id) == ["terminal-1", "terminal-2"]) + #expect(twoValue.shouldShow) + #expect(twoValue.selectedSurfaceID == "terminal-2") + } + + @Test func layoutPreservesPaneAndSurfaceOrderIncludingDisabledSurfaceTypes() { + let workspace = MobileWorkspacePreview( + id: "workspace", + name: "Workspace", + terminals: [MobileTerminalPreview(id: "terminal-1", name: "Build")], + layout: MobilePaneLayout( + version: 3, + focusedPaneID: "pane-2", + root: .split( + MobilePaneSplit( + id: "split", + orientation: .horizontal, + ratio: 0.5, + first: .pane( + MobilePaneNode( + id: "pane-1", + selectedSurfaceID: "terminal-1", + surfaces: [ + MobilePaneSurface(id: "terminal-1", type: .terminal, title: "Build"), + MobilePaneSurface(id: "browser-1", type: .browser, title: "Docs"), + ] + ) + ), + second: .pane( + MobilePaneNode( + id: "pane-2", + selectedSurfaceID: "markdown-1", + surfaces: [ + MobilePaneSurface(id: "markdown-1", type: .markdown, title: "Notes") + ] + ) + ) + ) + ) + ) + ) + + let deck = value(workspace: workspace, selectedSurfaceID: "terminal-1") + + #expect(deck.groups.map(\.id) == ["pane-1", "pane-2"]) + #expect(deck.groups.map(\.number) == [1, 2]) + #expect(deck.groups.map(\.totalCount) == [2, 2]) + #expect(deck.groups[0].chips.map(\.id) == ["terminal-1", "browser-1"]) + #expect(deck.groups[0].chips[0].isTerminal) + #expect(deck.groups[0].chips[1].isTerminal == false) + #expect(deck.groups[1].chips.map(\.title) == ["Notes"]) + #expect(deck.shouldShow) + #expect(deck.showsPaneMap) + } + + @Test func valueCarriesPrecomputedAgentStatesWithoutStoreReferences() { + let workspace = MobileWorkspacePreview( + id: "workspace", + name: "Workspace", + terminals: [ + MobileTerminalPreview(id: "terminal-1", name: "Build"), + MobileTerminalPreview(id: "terminal-2", name: "Tests"), + ] + ) + + let deck = SurfaceDeckValue( + workspace: workspace, + selectedSurfaceID: "terminal-1", + agentStateKindsBySurfaceID: [ + "terminal-1": .working, + "terminal-2": .needsInput, + ], + canCreateWorkspace: false + ) + + #expect(deck.agentStateKindsBySurfaceID["terminal-1"] == .working) + #expect(deck.agentStateKindsBySurfaceID["terminal-2"] == .needsInput) + #expect(deck.canCreateWorkspace == false) + } + + @Test func paneMapSelectionReconcilesRemovedSurfacesAndPanes() { + let layout = MobilePaneLayout( + version: 4, + focusedPaneID: "pane-1", + root: .pane( + MobilePaneNode( + id: "pane-1", + selectedSurfaceID: "terminal-new", + surfaces: [ + MobilePaneSurface(id: "terminal-keep", type: .terminal, title: "Keep"), + MobilePaneSurface(id: "terminal-new", type: .terminal, title: "New"), + ] + ) + ) + ) + let paneMap = PaneMapValue( + layout: layout, + phoneSelectedSurfaceID: "terminal-new", + agentStateKindsBySurfaceID: [:] + ) + + #expect( + paneMap.reconciledSurfaceIDs(current: [ + "pane-1": "terminal-removed", + "pane-removed": "terminal-old", + ]) == ["pane-1": "terminal-new"] + ) + #expect( + paneMap.reconciledSurfaceIDs(current: ["pane-1": "terminal-keep"]) + == ["pane-1": "terminal-keep"] + ) + } + + private func value( + workspace: MobileWorkspacePreview, + selectedSurfaceID: String? + ) -> SurfaceDeckValue { + SurfaceDeckValue( + workspace: workspace, + selectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: [:], + canCreateWorkspace: true + ) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalPickerMenuValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalPickerMenuValueTests.swift deleted file mode 100644 index 518085bed429..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalPickerMenuValueTests.swift +++ /dev/null @@ -1,92 +0,0 @@ -import CmuxMobileShellModel -import Testing -@testable import CmuxMobileShellUI - -@Suite struct TerminalPickerMenuValueTests { - @Test func previewChurnDoesNotChangeSeededMenuValueButMembershipDoes() { - let terminal = MobileTerminalPreview(id: "terminal-1", name: "Build") - let snapshotRows = [TerminalPickerMenuRow(terminal)] - let baseline = menuValue(liveTerminals: [terminal], snapshotRows: snapshotRows) - - var titleOnlyTerminal = terminal - titleOnlyTerminal.name = "Build output" - let titleOnlyChange = menuValue(liveTerminals: [titleOnlyTerminal], snapshotRows: snapshotRows) - - var viewportOnlyTerminal = terminal - viewportOnlyTerminal.viewportFit = MobileTerminalViewportFit( - effective: MobileTerminalViewportSize(columns: 80, rows: 24), - client: MobileTerminalViewportSize(columns: 100, rows: 30), - isCurrentClientLimiting: false - ) - let viewportOnlyChange = menuValue(liveTerminals: [viewportOnlyTerminal], snapshotRows: snapshotRows) - - let addedTerminal = MobileTerminalPreview(id: "terminal-2", name: "Tests") - let membershipRows = snapshotRows + [TerminalPickerMenuRow(addedTerminal)] - let membershipChange = menuValue( - liveTerminals: [viewportOnlyTerminal, addedTerminal], - snapshotRows: membershipRows - ) - - #expect(titleOnlyChange == baseline) - #expect(viewportOnlyChange == baseline) - #expect(membershipChange != baseline) - } - - @Test func selectionIsResolvedFromTheRowsDisplayedByTheMenu() { - let liveTerminals = [ - MobileTerminalPreview(id: "terminal-live", name: "Live") - ] - let snapshotRows = [ - TerminalPickerMenuRow(MobileTerminalPreview(id: "terminal-snapshot", name: "Snapshot")), - TerminalPickerMenuRow(MobileTerminalPreview(id: "terminal-selected", name: "Selected")), - ] - - let selected = menuValue( - liveTerminals: liveTerminals, - snapshotRows: snapshotRows, - selectedID: "terminal-selected" - ) - let staleSelection = menuValue( - liveTerminals: liveTerminals, - snapshotRows: snapshotRows, - selectedID: "terminal-live" - ) - - #expect(selected.selectedID == MobileTerminalPreview.ID(rawValue: "terminal-selected")) - #expect(selected.selectedName == "Selected") - #expect(staleSelection.selectedID == MobileTerminalPreview.ID(rawValue: "terminal-snapshot")) - #expect(staleSelection.selectedName == "Snapshot") - } - - @Test func emptySnapshotUsesLiveRowsAndHandlesNoTerminals() { - let liveTerminal = MobileTerminalPreview(id: "terminal-live", name: "Live") - let firstOpen = menuValue( - liveTerminals: [liveTerminal], - snapshotRows: [], - selectedID: "missing" - ) - let noTerminals = menuValue(liveTerminals: [], snapshotRows: [], selectedID: "missing") - - #expect(firstOpen.rows == [TerminalPickerMenuRow(liveTerminal)]) - #expect(firstOpen.selectedID == liveTerminal.id) - #expect(firstOpen.selectedName == liveTerminal.name) - #expect(noTerminals.rows.isEmpty) - #expect(noTerminals.selectedID == nil) - #expect(noTerminals.selectedName == nil) - } - - private func menuValue( - liveTerminals: [MobileTerminalPreview], - snapshotRows: [TerminalPickerMenuRow], - selectedID: MobileTerminalPreview.ID? = "terminal-1" - ) -> TerminalPickerMenuValue { - TerminalPickerMenuValue( - liveTerminals: liveTerminals, - snapshotRows: snapshotRows, - selectedID: selectedID, - canCreateWorkspace: true, - hasActiveBrowser: false, - isChatMode: false - ) - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift index cd358a6a1876..77c58fa8d1e6 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift @@ -45,6 +45,17 @@ import Testing #expect(available != unavailable) } + @Test func titleWidthDoesNotDependOnEndpointSubtitle() { + let terminal = menuValue( + labelToken: .standard(title: "Workspace", subtitle: "claude") + ) + let paneMap = menuValue( + labelToken: .standard(title: "Workspace", subtitle: "4 panes") + ) + + #expect(terminal.titleWidth == paneMap.titleWidth) + } + private func menuValue( labelToken: WorkspaceTitleMenuLabelToken, canCustomizeWorkspace: Bool = true @@ -54,6 +65,7 @@ import Testing hasBackButton: true, hasTrailingCluster: true, hasChatToggle: true, + reservesPaneMapControls: true, isEnabled: true, workspaceName: "Workspace", hasUnread: false, diff --git a/Packages/macOS/CmuxPanes/Sources/CmuxPanes/Model/PaneTreeModel.swift b/Packages/macOS/CmuxPanes/Sources/CmuxPanes/Model/PaneTreeModel.swift index 3075179a2215..b211c7828604 100644 --- a/Packages/macOS/CmuxPanes/Sources/CmuxPanes/Model/PaneTreeModel.swift +++ b/Packages/macOS/CmuxPanes/Sources/CmuxPanes/Model/PaneTreeModel.swift @@ -4,9 +4,9 @@ public import Bonsplit /// The per-workspace pane-tree sub-model: owns the panel registry and the /// pane-layout bookkeeping the legacy `Workspace` god object kept in its -/// `panels` / `paneLayoutVersion` / `surfaceIdToPanelId` / -/// `lastOrderedPanelIds` stored properties. The split tree itself lives in -/// `BonsplitController`; this model owns the workspace-side mapping onto it. +/// `panels` / `paneLayoutVersion` / `surfaceIdToPanelId` stored properties. +/// The split tree itself lives in `BonsplitController`; this model owns the +/// workspace-side mapping onto it. /// /// The owning `Workspace` composition root holds one instance, forwards its /// legacy accessors here, and implements `PaneTreeHosting` to receive the @@ -41,11 +41,6 @@ public final class PaneTreeModel { /// tabs to one live PTY. public private(set) var surfaceIdToPanelId: [TabID: UUID] = [:] - /// Snapshot of the spatially ordered panel ids from the last geometry - /// notification, used to gate `paneLayoutVersion` bumps to genuine - /// reorder events (legacy `Workspace.lastOrderedPanelIds`). - public var lastOrderedPanelIds: [UUID] = [] - /// Reverse index for targeted panel lookups and stale-surface removal. @ObservationIgnored private var panelIdToSurfaceId: [UUID: TabID] = [:] diff --git a/Packages/macOS/CmuxPanes/Tests/CmuxPanesTests/PaneTreeModelTests.swift b/Packages/macOS/CmuxPanes/Tests/CmuxPanesTests/PaneTreeModelTests.swift index 3c3e02e68b0f..6f9840229c43 100644 --- a/Packages/macOS/CmuxPanes/Tests/CmuxPanesTests/PaneTreeModelTests.swift +++ b/Packages/macOS/CmuxPanes/Tests/CmuxPanesTests/PaneTreeModelTests.swift @@ -83,8 +83,6 @@ struct PaneTreeModelTests { let panelId = UUID() model.bindSurface(tabId, toPanelId: panelId) #expect(model.surfaceIdToPanelId[tabId] == panelId) - model.lastOrderedPanelIds = [panelId] - #expect(model.lastOrderedPanelIds == [panelId]) } /// The registry queries resolve through the surface-id mapping exactly diff --git a/Packages/macOS/CmuxWorkspaces/Package.swift b/Packages/macOS/CmuxWorkspaces/Package.swift index bee786966729..20fd1bb0aaae 100644 --- a/Packages/macOS/CmuxWorkspaces/Package.swift +++ b/Packages/macOS/CmuxWorkspaces/Package.swift @@ -14,6 +14,8 @@ let package = Package( ), ], dependencies: [ + // Shared mobile pane-layout DTOs are consumed by both the Mac host and iOS. + .package(path: "../../Shared/CMUXMobileCore"), // WorkspaceGroupNewPlacement (the typed setting value for new // in-group workspace placement) is owned by CmuxSettings. .package(path: "../CmuxSettings"), @@ -28,6 +30,7 @@ let package = Package( .target( name: "CmuxWorkspaces", dependencies: [ + .product(name: "CMUXMobileCore", package: "CMUXMobileCore"), .product(name: "CmuxSettings", package: "CmuxSettings"), .product(name: "Bonsplit", package: "bonsplit"), .product(name: "CMUXDebugLog", package: "CMUXDebugLog"), @@ -43,6 +46,7 @@ let package = Package( name: "CmuxWorkspacesTests", dependencies: [ "CmuxWorkspaces", + .product(name: "CMUXMobileCore", package: "CMUXMobileCore"), .product(name: "Bonsplit", package: "bonsplit"), .product(name: "CmuxTestSupport", package: "CmuxTestSupport"), ], diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSerializer.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSerializer.swift new file mode 100644 index 000000000000..242ff68e6b46 --- /dev/null +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSerializer.swift @@ -0,0 +1,130 @@ +public import Bonsplit +public import CMUXMobileCore + +/// Converts bonsplit's external tree into the shared mobile pane-layout DTO. +public struct MobileWorkspaceLayoutSerializer: Sendable { + /// Creates a stateless workspace-layout serializer. + public init() {} + + /// Builds the shared pane-layout snapshot from a bonsplit tree. + /// + /// - Parameters: + /// - tree: The source bonsplit tree. + /// - version: The workspace's pane-layout revision. + /// - focusedPaneID: The focused pane identifier, when any. + /// - surfacesByTabID: Panel metadata keyed by bonsplit tab identifier. + /// - Returns: A complete shared pane-layout snapshot. + public func layout( + tree: ExternalTreeNode, + version: Int, + focusedPaneID: String?, + surfacesByTabID: [String: MobileWorkspaceLayoutSurfaceMetadata] + ) -> MobileWorkspaceLayout { + MobileWorkspaceLayout( + version: version, + focusedPaneID: focusedPaneID, + root: layoutNode(tree, surfacesByTabID: surfacesByTabID) + ) + } + + /// Returns every bonsplit tab in pane-spatial and then tab order. + /// + /// - Parameter tree: The source bonsplit tree. + /// - Returns: Tabs in depth-first pane order without recursive array copies. + public func tabs(in tree: ExternalTreeNode) -> [ExternalTab] { + var result: [ExternalTab] = [] + appendTabs(in: tree, to: &result) + return result + } + + /// Returns pane identities, tab ordering, and selection in spatial order. + /// + /// - Parameter tree: The source bonsplit tree. + /// - Returns: Pane topology in depth-first spatial order. + public func paneTopology(in tree: ExternalTreeNode) -> [MobileWorkspacePaneTopology] { + var result: [MobileWorkspacePaneTopology] = [] + appendPaneTopology(in: tree, to: &result) + return result + } + + private func appendTabs(in node: ExternalTreeNode, to result: inout [ExternalTab]) { + switch node { + case let .pane(pane): + result.append(contentsOf: pane.tabs) + case let .split(split): + appendTabs(in: split.first, to: &result) + appendTabs(in: split.second, to: &result) + } + } + + private func appendPaneTopology( + in node: ExternalTreeNode, + to result: inout [MobileWorkspacePaneTopology] + ) { + switch node { + case let .pane(pane): + result.append( + MobileWorkspacePaneTopology( + id: pane.id, + surfaceIDs: pane.tabs.map(\.id), + selectedSurfaceID: pane.selectedTabId + ) + ) + case let .split(split): + appendPaneTopology(in: split.first, to: &result) + appendPaneTopology(in: split.second, to: &result) + } + } + + private func layoutNode( + _ node: ExternalTreeNode, + surfacesByTabID: [String: MobileWorkspaceLayoutSurfaceMetadata] + ) -> MobileWorkspaceLayoutNode { + switch node { + case let .pane(pane): + let surfaces = pane.tabs.map { tab in + let metadata = surfacesByTabID[tab.id] + ?? MobileWorkspaceLayoutSurfaceMetadata( + id: tab.id, + type: "terminal", + title: tab.title + ) + return MobileWorkspaceLayoutSurface( + id: metadata.id, + type: metadata.type, + title: metadata.title + ) + } + let selectedSurfaceID = pane.selectedTabId.map { tabID in + surfacesByTabID[tabID]?.id ?? tabID + } + return .pane( + MobileWorkspaceLayoutPane( + id: pane.id, + selectedSurfaceID: selectedSurfaceID, + surfaces: surfaces + ) + ) + case let .split(split): + let orientation: MobileWorkspaceLayoutOrientation + switch split.orientation { + case "vertical": + orientation = .vertical + case "horizontal": + orientation = .horizontal + default: + assertionFailure("Bonsplit emitted an unsupported orientation: \(split.orientation)") + orientation = .horizontal + } + return .split( + MobileWorkspaceLayoutSplit( + id: split.id, + orientation: orientation, + ratio: split.dividerPosition, + first: layoutNode(split.first, surfacesByTabID: surfacesByTabID), + second: layoutNode(split.second, surfacesByTabID: surfacesByTabID) + ) + ) + } + } +} diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSurfaceMetadata.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSurfaceMetadata.swift new file mode 100644 index 000000000000..c86e5cac7a00 --- /dev/null +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSurfaceMetadata.swift @@ -0,0 +1,23 @@ +/// Mac-side metadata that maps a bonsplit tab to its mobile surface identity. +public struct MobileWorkspaceLayoutSurfaceMetadata: Equatable, Sendable { + /// The stable panel identifier exposed to mobile clients. + public let id: String + + /// The raw panel type exposed to mobile clients. + public let type: String + + /// The surface's current display title. + public let title: String + + /// Creates metadata for one bonsplit tab. + /// + /// - Parameters: + /// - id: The stable panel identifier exposed to mobile clients. + /// - type: The raw panel type exposed to mobile clients. + /// - title: The surface's current display title. + public init(id: String, type: String, title: String) { + self.id = id + self.type = type + self.title = title + } +} diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspacePaneTopology.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspacePaneTopology.swift new file mode 100644 index 000000000000..0291fc93a903 --- /dev/null +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspacePaneTopology.swift @@ -0,0 +1,23 @@ +/// The identifiers and selected tab for one pane in spatial tree order. +public struct MobileWorkspacePaneTopology: Equatable, Sendable { + /// The stable pane identifier. + public let id: String + + /// Surface identifiers in tab order. + public let surfaceIDs: [String] + + /// The selected surface identifier, when any. + public let selectedSurfaceID: String? + + /// Creates one pane-topology snapshot. + /// + /// - Parameters: + /// - id: The stable pane identifier. + /// - surfaceIDs: Surface identifiers in tab order. + /// - selectedSurfaceID: The selected surface identifier, when any. + public init(id: String, surfaceIDs: [String], selectedSurfaceID: String?) { + self.id = id + self.surfaceIDs = surfaceIDs + self.selectedSurfaceID = selectedSurfaceID + } +} diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceListModel.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceListModel.swift index b2e9ae6eed85..0f7c23e495b8 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceListModel.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceListModel.swift @@ -3,17 +3,14 @@ public import Observation /// The per-workspace surface-list derivation model: turns the live bonsplit /// split tree and panel registry into the ordered panel-id lists the rest of -/// the app navigates by, and owns the reorder-detection that bumps the -/// workspace's pane-layout version. +/// the app navigates by. /// /// This is the navigation-state half of what the legacy `Workspace` god object /// computed inline: `orderedPanelIds`, `focusedPanelId`, /// `representativePanelIdForWorkspaceManualUnread()`, -/// `effectiveSelectedPanelId(inPane:)`, the `tabIdsToLeft/Right/CloseOthers` -/// pane queries, and the `paneLayoutVersion` bump in the geometry-change -/// handler. It owns no stored panel state itself; the registry and the -/// `lastOrderedPanelIds`/`paneLayoutVersion` bookkeeping live in the -/// workspace's `PaneTreeModel`, reached through ``WorkspaceSurfaceTreeReading``. +/// `effectiveSelectedPanelId(inPane:)`, and the `tabIdsToLeft/Right/CloseOthers` +/// pane queries. It owns no stored panel state itself; the registry lives in +/// the workspace's `PaneTreeModel`, reached through ``WorkspaceSurfaceTreeReading``. /// /// The owning `Workspace` composition root holds one instance, attaches itself /// as the tree-reading host (weak, to avoid a retain cycle), and forwards its @@ -130,27 +127,4 @@ public final class WorkspaceSurfaceListModel { guard let tree else { return [] } return tree.surfaceIdsInTabOrder(inPaneId: paneId).filter { $0 != anchorSurfaceId } } - - /// Reconciles the reorder-detection bookkeeping after a geometry change. - /// - /// Every order/membership mutation (same-pane reorder, cross-pane move, - /// split, close) routes through the workspace's geometry-change handler. A - /// pure reorder mutates only bonsplit's internal state, which is not - /// observed, so observers would miss it. This bumps `paneLayoutVersion` - /// only when the ordered panel-id sequence actually changed, so divider - /// drags and selection-only events (also routed through that handler) do - /// not fire an app-wide change (legacy gate in - /// `Workspace.splitTabBar(_:didChangeGeometry:)`). - /// - /// Returns whether the layout version was bumped, for callers that want to - /// observe the decision in tests. - @discardableResult - public func registerGeometryChange() -> Bool { - guard let tree else { return false } - let currentOrder = orderedPanelIds - guard currentOrder != tree.lastOrderedPanelIds else { return false } - tree.lastOrderedPanelIds = currentOrder - tree.bumpPaneLayoutVersion() - return true - } } diff --git a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceTreeReading.swift b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceTreeReading.swift index 9aadb747afbc..90334e642a30 100644 --- a/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceTreeReading.swift +++ b/Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/SurfaceList/WorkspaceSurfaceTreeReading.swift @@ -1,18 +1,18 @@ public import Foundation /// The workspace-side seam the surface-list model reads through to derive its -/// ordered panel lists and reorder-detection state. +/// ordered panel lists. /// /// **Why a synchronous read-only protocol and not value snapshots.** Every /// derivation (`orderedPanelIds`, `focusedPanelId`, -/// `representativePanelId(forWorkspaceManualUnread:)`, the reorder bump) is one -/// MainActor turn that must observe the live `BonsplitController` split tree and -/// the live panel registry exactly as the legacy computed properties on -/// `Workspace` did. The split tree, pane selection, and tab order are owned by -/// `BonsplitController`; the panel registry, `lastOrderedPanelIds`, and -/// `paneLayoutVersion` are owned by the workspace's `PaneTreeModel`. The model -/// reads them through this seam so it never imports `Bonsplit` and stays a pure -/// leaf, while the values it sees are always the authoritative current state. +/// `representativePanelId(forWorkspaceManualUnread:)`) is one MainActor turn +/// that must observe the live `BonsplitController` split tree and the live +/// panel registry exactly as the legacy computed properties on `Workspace` +/// did. The split tree, pane selection, and tab order are owned by +/// `BonsplitController`; the panel registry is owned by the workspace's +/// `PaneTreeModel`. The model reads them through this seam so it never imports +/// `Bonsplit` and stays a pure leaf, while the values it sees are always the +/// authoritative current state. /// /// All identifiers are surfaced as `UUID`/`UUID` arrays: bonsplit `TabID`/ /// `PaneID` are 1:1 with `UUID`, so the seam erases the opaque bonsplit types at @@ -71,16 +71,4 @@ public protocol WorkspaceSurfaceTreeReading: AnyObject { /// directory/branch resolution owned by the workspace, so it stays /// host-side. var firstSidebarOrderedPanelId: UUID? { get } - - // MARK: Reorder bookkeeping (PaneTreeModel-owned) - - /// The spatially ordered panel ids captured at the last geometry - /// notification, used to gate reorder bumps (legacy - /// `Workspace.lastOrderedPanelIds`, owned by `PaneTreeModel`). - var lastOrderedPanelIds: [UUID] { get set } - - /// Bumps the monotonic pane-layout version (legacy - /// `Workspace.paneLayoutVersion &+= 1`, owned by `PaneTreeModel`). Wrapping - /// add, matching the legacy `&+=`. - func bumpPaneLayoutVersion() } diff --git a/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/MobileWorkspaceLayoutSerializerTests.swift b/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/MobileWorkspaceLayoutSerializerTests.swift new file mode 100644 index 000000000000..2463cdbbded8 --- /dev/null +++ b/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/MobileWorkspaceLayoutSerializerTests.swift @@ -0,0 +1,94 @@ +import Bonsplit +import CMUXMobileCore +import Testing + +@testable import CmuxWorkspaces + +struct MobileWorkspaceLayoutSerializerTests { + private let frame = PixelRect(x: 0, y: 0, width: 100, height: 100) + + @Test func serializesSpatialOrderAndPanelMetadata() throws { + let tree = ExternalTreeNode.split( + ExternalSplitNode( + id: "split-root", + orientation: "horizontal", + dividerPosition: 0.4, + first: .pane( + ExternalPaneNode( + id: "pane-left", + frame: frame, + tabs: [ + ExternalTab(id: "tab-shell", title: "Fallback shell"), + ExternalTab(id: "tab-preview", title: "Fallback preview"), + ], + selectedTabId: "tab-preview" + ) + ), + second: .pane( + ExternalPaneNode( + id: "pane-right", + frame: frame, + tabs: [ExternalTab(id: "tab-docs", title: "Docs")], + selectedTabId: "tab-docs" + ) + ) + ) + ) + let serializer = MobileWorkspaceLayoutSerializer() + + #expect(serializer.tabs(in: tree).map(\.id) == ["tab-shell", "tab-preview", "tab-docs"]) + #expect(serializer.paneTopology(in: tree) == [ + MobileWorkspacePaneTopology( + id: "pane-left", + surfaceIDs: ["tab-shell", "tab-preview"], + selectedSurfaceID: "tab-preview" + ), + MobileWorkspacePaneTopology( + id: "pane-right", + surfaceIDs: ["tab-docs"], + selectedSurfaceID: "tab-docs" + ), + ]) + + let layout = serializer.layout( + tree: tree, + version: 9, + focusedPaneID: "pane-right", + surfacesByTabID: [ + "tab-shell": MobileWorkspaceLayoutSurfaceMetadata( + id: "panel-shell", + type: "terminal", + title: "Renamed shell" + ), + "tab-preview": MobileWorkspaceLayoutSurfaceMetadata( + id: "panel-preview", + type: "browser", + title: "Preview" + ), + ] + ) + + #expect(layout.version == 9) + #expect(layout.focusedPaneID == "pane-right") + guard case let .split(split) = layout.root else { + Issue.record("Expected a root split") + return + } + #expect(split.orientation == .horizontal) + #expect(split.ratio == 0.4) + guard case let .pane(left) = split.first, + case let .pane(right) = split.second else { + Issue.record("Expected two pane children") + return + } + #expect(left.selectedSurfaceID == "panel-preview") + #expect(left.surfaces == [ + MobileWorkspaceLayoutSurface(id: "panel-shell", type: "terminal", title: "Renamed shell"), + MobileWorkspaceLayoutSurface(id: "panel-preview", type: "browser", title: "Preview"), + ]) + #expect(right.selectedSurfaceID == "tab-docs") + #expect(right.surfaces == [ + MobileWorkspaceLayoutSurface(id: "tab-docs", type: "terminal", title: "Docs") + ]) + } +} diff --git a/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/WorkspaceSurfaceListModelTests.swift b/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/WorkspaceSurfaceListModelTests.swift index 460416e76ac6..90812c381b39 100644 --- a/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/WorkspaceSurfaceListModelTests.swift +++ b/Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/WorkspaceSurfaceListModelTests.swift @@ -21,10 +21,6 @@ private final class FakeTree: WorkspaceSurfaceTreeReading { var registry: Set = [] var firstSidebarOrderedPanelId: UUID? - var lastOrderedPanelIds: [UUID] = [] - private(set) var bumpCount = 0 - func bumpPaneLayoutVersion() { bumpCount &+= 1 } - var surfaceIdsInTabOrderAcrossAllPanes: [UUID] { panes.flatMap(\.surfaceIds) } @@ -181,36 +177,10 @@ private final class FakeTree: WorkspaceSurfaceTreeReading { #expect(model.surfaceIdsToRight(of: c, inPaneId: pane) == []) } - @Test func registerGeometryChangeBumpsOnlyOnReorder() { - let (model, tree) = make() - let s1 = UUID(), s2 = UUID() - let p1 = UUID(), p2 = UUID() - let pane = UUID() - tree.panes = [.init(id: pane, surfaceIds: [s1, s2], selectedIndex: 0)] - tree.surfaceToPanel = [s1: p1, s2: p2] - tree.registry = [p1, p2] - - // First call: order changed from empty -> bump. - #expect(model.registerGeometryChange() == true) - #expect(tree.bumpCount == 1) - #expect(tree.lastOrderedPanelIds == [p1, p2]) - - // No change -> no bump. - #expect(model.registerGeometryChange() == false) - #expect(tree.bumpCount == 1) - - // Reorder -> bump. - tree.panes = [.init(id: pane, surfaceIds: [s2, s1], selectedIndex: 0)] - #expect(model.registerGeometryChange() == true) - #expect(tree.bumpCount == 2) - #expect(tree.lastOrderedPanelIds == [p2, p1]) - } - @Test func detachedModelReturnsEmptyDefaults() { let model = WorkspaceSurfaceListModel() #expect(model.orderedPanelIds == []) #expect(model.focusedPanelId == nil) #expect(model.representativePanelIdForWorkspaceManualUnread() == nil) - #expect(model.registerGeometryChange() == false) } } diff --git a/Sources/Mobile/MobileHostService+Capabilities.swift b/Sources/Mobile/MobileHostService+Capabilities.swift index 3b9c3e6828e0..0c3c031192ef 100644 --- a/Sources/Mobile/MobileHostService+Capabilities.swift +++ b/Sources/Mobile/MobileHostService+Capabilities.swift @@ -87,6 +87,8 @@ extension MobileHostService { // workspace.group.collapse/expand from mobile. iOS feature-detects // this to render collapsible groups only against a Mac that emits them. "workspace.groups.v1", + "workspace.layout.v1", + "workspace.pane_reorder.v1", ] if !includingWorkspaceChanges { capabilities.removeAll { $0 == Self.workspaceChangesCapability } diff --git a/Sources/Mobile/MobileHostService+TicketAuthorization.swift b/Sources/Mobile/MobileHostService+TicketAuthorization.swift index b60465907edb..6880a69fd40d 100644 --- a/Sources/Mobile/MobileHostService+TicketAuthorization.swift +++ b/Sources/Mobile/MobileHostService+TicketAuthorization.swift @@ -72,7 +72,7 @@ extension MobileHostService { authorization: authorization, workspaceSelection: workspaceSelection.value ) - case "workspace.action", "workspace.close": + case "workspace.action", "workspace.close", "workspace.pane.reorder": return ticketWorkspaceAuthorizationError(authorization: authorization, workspaceSelection: workspaceSelection.value) case "workspace.group.action", "workspace.group.create": return ticketMacScopedWorkspaceMutationAuthorizationError(authorization: authorization) diff --git a/Sources/Mobile/MobileStateSync.swift b/Sources/Mobile/MobileStateSync.swift index c6cb76cdf8b9..9861a23fb2d8 100644 --- a/Sources/Mobile/MobileStateSync.swift +++ b/Sources/Mobile/MobileStateSync.swift @@ -226,7 +226,8 @@ final class MobileStateSyncHost { lastActivityAt: (latestNotification?.createdAt ?? workspace.createdAt).timeIntervalSince1970, hasUnread: notificationStore?.workspaceIsUnread(forTabId: workspace.id) ?? false, sortIndex: sortIndex, - terminals: terminals + terminals: terminals, + layout: workspace.mobileWorkspaceLayoutSnapshot() ) } diff --git a/Sources/Mobile/MobileWorkspaceListObserver.swift b/Sources/Mobile/MobileWorkspaceListObserver.swift index 26fee1acb349..329691b36749 100644 --- a/Sources/Mobile/MobileWorkspaceListObserver.swift +++ b/Sources/Mobile/MobileWorkspaceListObserver.swift @@ -42,6 +42,10 @@ final class MobileWorkspaceListObserver { private var subscriptionsChangeObserver: NSObjectProtocol? private var pipelinesAttached = false private var lastSummaryHash: Int = 0 + /// Delivery is injected so callers can observe the observer's published + /// updates without reaching into its deduplication state. Production uses + /// the legacy invalidation event and the v2 state-sync broadcaster. + private let workspaceUpdateEmitter: @MainActor () -> Void /// Throttle window with `latest: true`. First event in a burst emits /// immediately (iPhone gets the change in milliseconds), subsequent /// events within the window collapse to one trailing emit carrying the @@ -73,10 +77,18 @@ final class MobileWorkspaceListObserver { init( tabManager: TabManager, notificationStore: TerminalNotificationStore? = nil, + workspaceUpdateEmitter: (@MainActor () -> Void)? = nil, configStore: CmuxConfigStore? = nil ) { self.tabManager = tabManager self.notificationStore = notificationStore + self.workspaceUpdateEmitter = workspaceUpdateEmitter ?? { + MobileHostService.shared.emitEvent(topic: "workspace.updated", payload: [:]) + // v2 phones get per-record deltas instead of the empty invalidation + // above. Same tick, same throttle; a no-op diff emits nothing, and the + // call returns immediately when no phone subscribed to the delta topic. + MobileStateSyncHost.shared.broadcastIfSubscribed() + } self.configStore = configStore #if DEBUG cmuxDebugLog("mobile.observer init tabs=\(tabManager.tabs.count)") @@ -397,18 +409,15 @@ final class MobileWorkspaceListObserver { #if DEBUG cmuxDebugLog("mobile.observer EMIT workspace.updated hash=\(hash) tabs=\(tabManager.tabs.count) force=\(force)") #endif - MobileHostService.shared.emitEvent(topic: "workspace.updated", payload: [:]) - // v2 phones get per-record deltas instead of the empty invalidation - // above. Same tick, same throttle; a no-op diff emits nothing, and the - // call returns immediately when no phone subscribed to the delta topic. - MobileStateSyncHost.shared.broadcastIfSubscribed() + workspaceUpdateEmitter() } /// Stable hash of the iOS-facing shape: workspace ids + titles + their /// panels in spatial order + each panel's displayed (custom-aware) title and - /// directory. Mutations that don't show up on the mobile list (pane geometry, - /// scrollback content, focus only) don't trip the event, so we don't fan out - /// on every keystroke. + /// directory + the shared mobile pane topology. The topology includes split + /// structure/orientation, pane ids, surface order, selected surfaces, and the + /// focused pane. It deliberately excludes split ratios, so divider drags do + /// not spam events. Scrollback content remains excluded. /// /// The panel ids are hashed in `orderedPanelIds` order (not the sorted set), /// so a pure drag-reorder, which changes the spatial order but not the id set, @@ -511,6 +520,7 @@ final class MobileWorkspaceListObserver { hasher.combine(workspace.panelTitle(panelId: id)) hasher.combine(workspace.reportedPanelDirectory(panelId: id)) } + workspace.mobileWorkspaceLayoutSnapshot().hashTopology(into: &hasher) hasher.combine(workspace.presentedCurrentDirectory) // Todo mutations change the list-facing shape; without these the // hash-diff would suppress the re-emit the publishers above fire. diff --git a/Sources/TerminalController+MobileWorkspaceList.swift b/Sources/TerminalController+MobileWorkspaceList.swift index a5f62edc9897..aa2b5b29288c 100644 --- a/Sources/TerminalController+MobileWorkspaceList.swift +++ b/Sources/TerminalController+MobileWorkspaceList.swift @@ -9,6 +9,7 @@ import Foundation // serializing the workspace and group-section payloads, and the mobile-gated // group collapse/expand handler. Lives in its own file so the mobile list // payload code stays together without growing TerminalController.swift. + extension TerminalController { /// Mobile-gated collapse/expand of a workspace group. This requires an /// explicit, resolvable `group_id` (it must never fall back to the Mac's @@ -239,6 +240,8 @@ extension TerminalController { ] } + let layout = workspace.mobileWorkspaceLayoutSnapshot() + let store = notificationStore ?? AppDelegate.shared?.notificationStore let latestNotification = store?.latestNotification(forTabId: workspace.id) let preview = Self.mobileWorkspacePreview(latestNotification: latestNotification) @@ -246,7 +249,7 @@ extension TerminalController { MobileWorkspaceMetadataLimits.projectedCustomDescription(workspace.customDescription), constrainedToJSONEscapedUTF8Budget: &descriptionBudget ) - return [ + var payload: [String: Any] = [ "id": workspace.id.uuidString, "window_id": v2OrNull(windowID?.uuidString), "title": workspace.title, @@ -278,6 +281,10 @@ extension TerminalController { "has_unread": store?.workspaceIsUnread(forTabId: workspace.id) ?? false, "terminals": terminals ] + if let layoutObject = try? MobileSyncFrameCoder().jsonObject(from: layout) { + payload["layout"] = layoutObject + } + return payload } /// Mobile-gated close of one explicit workspace. The Mac remains diff --git a/Sources/TerminalController+WorkspaceMove.swift b/Sources/TerminalController+WorkspaceMove.swift index 29632d6a3146..f612a6e575c8 100644 --- a/Sources/TerminalController+WorkspaceMove.swift +++ b/Sources/TerminalController+WorkspaceMove.swift @@ -1,6 +1,97 @@ import Foundation extension TerminalController { + /// Mobile-gated pane-content reorder within one workspace split tree. + func v2MobileWorkspacePaneReorder(params: [String: Any]) -> V2CallResult { + if let error = mobileWorkspaceIDValidationError(params: params) { + return error + } + guard let workspaceID = v2UUID(params, "workspace_id") else { + return .err(code: "invalid_params", message: "Missing or invalid workspace_id", data: nil) + } + guard let orderedPaneIDStrings = params["ordered_pane_ids"] as? [String], + !orderedPaneIDStrings.isEmpty else { + return .err(code: "invalid_params", message: "Missing or invalid ordered_pane_ids", data: nil) + } + let orderedPaneIDs = orderedPaneIDStrings.compactMap(UUID.init(uuidString:)) + guard orderedPaneIDs.count == orderedPaneIDStrings.count, + Set(orderedPaneIDs).count == orderedPaneIDs.count else { + return .err(code: "invalid_params", message: "ordered_pane_ids must be unique UUIDs", data: nil) + } + let baseLayoutVersion = v2Int(params, "base_layout_version") + if v2HasNonNullParam(params, "base_layout_version"), baseLayoutVersion == nil { + return .err(code: "invalid_params", message: "base_layout_version must be an integer", data: nil) + } + guard let tabManager = v2ResolveMobileWorkspaceOwner(workspaceID: workspaceID, params: params) else { + return .err(code: "unavailable", message: "Workspace context is unavailable", data: nil) + } + + var mutationError: V2CallResult? + v2MainSync { + guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceID }) else { + mutationError = .err( + code: "not_found", + message: "Workspace not found", + data: ["workspace_id": workspaceID.uuidString] + ) + return + } + // Slot IDs stay stable across content reorders, so the set check alone + // cannot see that another reorder landed after the phone captured its + // snapshot. The phone's observed layout version is the precondition + // that makes concurrent reorders (second phone, Mac-local drag) fail + // closed as a conflict instead of silently permuting the wrong panes. + if let baseLayoutVersion, workspace.paneLayoutVersion != baseLayoutVersion { + mutationError = .err( + code: "conflict", + message: "Pane layout changed before the reorder completed", + data: ["workspace_id": workspaceID.uuidString] + ) + return + } + let authoritativePaneIDs = workspace.spatiallyOrderedPaneIds + guard orderedPaneIDs.count == authoritativePaneIDs.count, + Set(orderedPaneIDs) == Set(authoritativePaneIDs) else { + mutationError = .err( + code: "conflict", + message: "Pane layout changed before the reorder completed", + data: ["workspace_id": workspaceID.uuidString] + ) + return + } + guard workspace.applyMobilePaneOrder(orderedPaneIDs) else { + mutationError = .err( + code: "rejected", + message: "Pane reorder could not be applied", + data: ["workspace_id": workspaceID.uuidString] + ) + return + } + } + if let mutationError { + return mutationError + } + + var listParams = params + listParams.removeValue(forKey: "ordered_pane_ids") + listParams.removeValue(forKey: "base_layout_version") + return v2MobileWorkspaceList(params: listParams, tabManager: tabManager) + } + + /// Mobile mutations route to the workspace's owning window first: the phone's + /// snapshot can carry a stale `window_id` after the workspace moved windows, + /// and honoring that id would reject a valid mutation instead of reaching the + /// owner. Falls back to the shared resolver for workspaces not found by id. + private nonisolated func v2ResolveMobileWorkspaceOwner( + workspaceID: UUID, + params: [String: Any] + ) -> TabManager? { + if let owner = v2MainSync({ AppDelegate.shared?.tabManagerFor(tabId: workspaceID) }) { + return owner + } + return v2ResolveTabManager(params: params) + } + /// Mobile-gated workspace reorder/group move. func v2MobileWorkspaceMove(params: [String: Any]) -> V2CallResult { let hasMoveGroup = v2HasNonNullParam(params, "move_group") @@ -51,7 +142,7 @@ extension TerminalController { return .err(code: "invalid_params", message: "move_group must be a boolean", data: nil) } let moveGroup = parsedMoveGroup ?? false - guard let tabManager = v2ResolveTabManager(params: params) else { + guard let tabManager = v2ResolveMobileWorkspaceOwner(workspaceID: workspaceID, params: params) else { return .err(code: "unavailable", message: "Workspace context is unavailable", data: nil) } diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index c29f28dc91b2..904eb0f92cdd 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -14145,6 +14145,8 @@ class TerminalController { result = v2MobileWorkspaceAction(params: request.params) case "workspace.move": result = v2MobileWorkspaceMove(params: request.params) + case "workspace.pane.reorder": + result = v2MobileWorkspacePaneReorder(params: request.params) case "workspace.group.action", "workspace.group.create": result = request.method == "workspace.group.create" ? v2MobileWorkspaceGroupCreate(params: request.params) : v2MobileWorkspaceGroupAction(params: request.params) case let method where method.hasPrefix("mobile.chat."): @@ -14630,6 +14632,10 @@ class TerminalController { payload["columns"] = renderGrid.columns payload["rows"] = renderGrid.rows payload["render_grid"] = renderGridObject + } else if v2Bool(params, "grid_only") == true { + // Grid-only consumers (pane-map previews) discard byte/VT + // fallbacks, so skip the unbounded VT export a hibernated surface + // would otherwise ship just to be thrown away on the phone. } else { if let expectedViewport { guard let surface = terminalPanel.surface.liveSurfaceForGhosttyAccess( diff --git a/Sources/Workspace+MobilePaneLayoutSnapshot.swift b/Sources/Workspace+MobilePaneLayoutSnapshot.swift new file mode 100644 index 000000000000..b900c7e677ab --- /dev/null +++ b/Sources/Workspace+MobilePaneLayoutSnapshot.swift @@ -0,0 +1,29 @@ +import CMUXMobileCore +import CmuxWorkspaces +import Foundation + +extension Workspace { + /// Captures one canonical mobile pane-layout snapshot from the workspace. + func mobileWorkspaceLayoutSnapshot() -> MobileWorkspaceLayout { + let tree = bonsplitController.treeSnapshot() + let serializer = MobileWorkspaceLayoutSerializer() + var surfacesByTabID: [String: MobileWorkspaceLayoutSurfaceMetadata] = [:] + for tab in serializer.tabs(in: tree) { + let panelID = UUID(uuidString: tab.id).flatMap { panelId(forSurfaceId: $0) } + let panel = panelID.flatMap { panels[$0] } + surfacesByTabID[tab.id] = MobileWorkspaceLayoutSurfaceMetadata( + id: panelID?.uuidString ?? tab.id, + type: panel?.panelType.rawValue ?? PanelType.terminal.rawValue, + title: panelID.flatMap { panelTitle(panelId: $0) } + ?? panel?.displayTitle + ?? tab.title + ) + } + return serializer.layout( + tree: tree, + version: paneLayoutVersion, + focusedPaneID: bonsplitController.focusedPaneId?.id.uuidString, + surfacesByTabID: surfacesByTabID + ) + } +} diff --git a/Sources/Workspace+MobilePaneReorder.swift b/Sources/Workspace+MobilePaneReorder.swift new file mode 100644 index 000000000000..69149b7b33eb --- /dev/null +++ b/Sources/Workspace+MobilePaneReorder.swift @@ -0,0 +1,158 @@ +import Bonsplit +import Foundation + +extension Workspace { + /// Moves complete pane contents between the existing split-tree slots. + /// + /// Pane identities and divider geometry remain stable. The requested IDs name + /// the current pane content that should occupy each spatial slot, in the + /// workspace's current spatial order. + @discardableResult + func applyMobilePaneOrder(_ requestedPaneIDs: [UUID]) -> Bool { + let spatialPanes = spatiallyOrderedPaneIds + guard !isRemoteTmuxMirror, + layoutMode == .splits, + bonsplitController.configuration.allowCrossPaneTabMove, + requestedPaneIDs.count == spatialPanes.count, + Set(requestedPaneIDs) == Set(spatialPanes), + requestedPaneIDs != spatialPanes else { + return requestedPaneIDs == spatialPanes + } + + let panesByID = Dictionary( + uniqueKeysWithValues: bonsplitController.allPaneIds.map { ($0.id, $0) } + ) + guard spatialPanes.allSatisfy({ panesByID[$0] != nil }) else { return false } + + let tabsBySourcePaneID = Dictionary( + uniqueKeysWithValues: spatialPanes.map { paneID in + let pane = panesByID[paneID]! + return (paneID, bonsplitController.tabs(inPane: pane).map(\.id)) + } + ) + guard tabsBySourcePaneID.values.allSatisfy({ !$0.isEmpty }) else { return false } + + let selectedTabBySourcePaneID = Dictionary( + uniqueKeysWithValues: spatialPanes.compactMap { paneID in + let pane = panesByID[paneID]! + return bonsplitController.selectedTab(inPane: pane).map { (paneID, $0.id) } + } + ) + let originallyFocusedPaneID = bonsplitController.focusedPaneId?.id + var placeholderTabsByPaneID: [UUID: TabID] = [:] + var mutationSucceeded = true + + mobilePaneLayoutPublicationSuppressionCount += 1 + performRemoteTmuxMirrorMutation { + for paneID in spatialPanes { + guard let pane = panesByID[paneID], + let placeholder = bonsplitController.createTab( + title: "\u{200B}", + icon: nil, + inPane: pane + ) else { + mutationSucceeded = false + break + } + placeholderTabsByPaneID[paneID] = placeholder + } + + if mutationSucceeded { + for (destinationIndex, sourcePaneID) in requestedPaneIDs.enumerated() { + let destinationPaneID = spatialPanes[destinationIndex] + guard sourcePaneID != destinationPaneID, + let destinationPane = panesByID[destinationPaneID], + let tabs = tabsBySourcePaneID[sourcePaneID] else { + continue + } + for (tabIndex, tabID) in tabs.enumerated() + where !bonsplitController.moveTab( + tabID, + toPane: destinationPane, + atIndex: tabIndex + ) { + mutationSucceeded = false + break + } + if !mutationSucceeded { break } + } + } + + if !mutationSucceeded { + restoreMobilePaneOrder( + spatialPanes: spatialPanes, + panesByID: panesByID, + tabsBySourcePaneID: tabsBySourcePaneID + ) + } + + for placeholder in placeholderTabsByPaneID.values { + // Force-close bypasses close vetoes (e.g. a close-confirmation + // sheet in flight on the Mac) that would otherwise leave + // zero-width phantom tabs in the authoritative layout while + // this reorder reports success. If a placeholder still survives, + // fail the mutation so the phone reconciles instead of trusting + // a success response that contains the phantom. + if !requestCloseTab(placeholder, force: true), + panesByID.values.contains(where: { pane in + bonsplitController.tabs(inPane: pane).contains(where: { $0.id == placeholder }) + }) { + mutationSucceeded = false + } + } + + let selectionPanes = mutationSucceeded + ? requestedPaneIDs.enumerated().map { (spatialPanes[$0.offset], $0.element) } + : spatialPanes.map { ($0, $0) } + for (destinationPaneID, sourcePaneID) in selectionPanes { + guard let selectedTab = selectedTabBySourcePaneID[sourcePaneID], + let destinationPane = panesByID[destinationPaneID] else { + continue + } + bonsplitController.focusPane(destinationPane) + bonsplitController.selectTab(selectedTab) + } + } + + // The remote-mutation coordinator restores its entry focus when the + // closure exits. Reassert the content-relative focus afterward, while + // publication remains suppressed, so observers see only the final + // authoritative topology. + if let originallyFocusedPaneID { + let restoredFocusedPaneID: UUID + if mutationSucceeded, + let destinationIndex = requestedPaneIDs.firstIndex(of: originallyFocusedPaneID) { + restoredFocusedPaneID = spatialPanes[destinationIndex] + } else { + restoredFocusedPaneID = originallyFocusedPaneID + } + if let restoredFocusedPane = panesByID[restoredFocusedPaneID] { + bonsplitController.focusPane(restoredFocusedPane) + } + } + mobilePaneLayoutPublicationSuppressionCount -= 1 + + guard mutationSucceeded else { return false } + + publishMobilePaneLayoutRevisionIfChanged() + scheduleTerminalGeometryReconcile() + scheduleFocusReconcile() + return true + } + + private func restoreMobilePaneOrder( + spatialPanes: [UUID], + panesByID: [UUID: PaneID], + tabsBySourcePaneID: [UUID: [TabID]] + ) { + for paneID in spatialPanes { + guard let pane = panesByID[paneID], + let tabs = tabsBySourcePaneID[paneID] else { + continue + } + for (tabIndex, tabID) in tabs.enumerated() { + _ = bonsplitController.moveTab(tabID, toPane: pane, atIndex: tabIndex) + } + } + } +} diff --git a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift index d7e3b22eee4a..4e71b8f0c423 100644 --- a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift +++ b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift @@ -75,12 +75,22 @@ extension Workspace: WorkspaceSurfaceTreeReading { sidebarOrderedPanelIds().first } - var lastOrderedPanelIds: [UUID] { - get { paneTree.lastOrderedPanelIds } - set { paneTree.lastOrderedPanelIds = newValue } - } - - func bumpPaneLayoutVersion() { + /// Publishes one mobile layout revision when the ratio-insensitive pane + /// topology changed. The shared snapshot owns the comparison fields, so + /// legacy workspace-list invalidation and state sync v2 cannot drift. + @discardableResult + func publishMobilePaneLayoutRevisionIfChanged() -> Bool { + guard mobilePaneLayoutPublicationSuppressionCount == 0 else { + return false + } + var hasher = Hasher() + mobileWorkspaceLayoutSnapshot().hashTopology(into: &hasher) + let topologyHash = hasher.finalize() + guard topologyHash != lastPublishedMobilePaneLayoutTopologyHash else { + return false + } + lastPublishedMobilePaneLayoutTopologyHash = topologyHash paneLayoutVersion &+= 1 + return true } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 2e1bbe1a4c59..2c42620a9f29 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2299,20 +2299,26 @@ final class Workspace: Identifiable, ObservableObject { /// subscribers; same contract as `panelsPublisher`. let paneLayoutVersionPublisher = CurrentValueSubject(0) + /// Ratio-insensitive signature of the last mobile pane-layout revision. + /// Bonsplit delegates compare against it so topology, pane selection, and + /// pane focus publish exactly once while divider drags stay quiet. + var lastPublishedMobilePaneLayoutTopologyHash: Int? + + /// Defers mobile layout publication while one authoritative mutation performs + /// several Bonsplit operations. Nested transactions are supported so every + /// delegate callback stays quiet until the outer mutation publishes its final + /// reconciled snapshot. + var mobilePaneLayoutPublicationSuppressionCount = 0 + /// Mapping from bonsplit TabID to our Panel instances var panels: [UUID: any Panel] { get { paneTree.panels } set { paneTree.panels = newValue } } - /// Monotonic counter bumped only when the spatial (left-to-right, top-to-bottom) - /// order of panels changes without the panel *set* changing — i.e. a pure - /// drag-reorder of tabs within or across panes. Membership changes already - /// fire `$panels`; pure reorders mutate only `bonsplitController` state, which - /// is not `@Published`, so observers (e.g. the mobile workspace-list observer) - /// would otherwise never learn about a reorder. We gate the bump on an actual - /// change of `orderedPanelIds` so that divider drags and selection-only events - /// (which also flow through `didChangeGeometry`) do not fire `objectWillChange`. + /// Monotonic counter for the ratio-insensitive mobile pane layout. It bumps + /// when split topology, pane membership/order, selected surfaces, or focused + /// pane changes. Divider-only geometry changes intentionally do not bump it. var paneLayoutVersion: Int { get { paneTree.paneLayoutVersion } set { paneTree.paneLayoutVersion = newValue } @@ -12671,8 +12677,12 @@ extension Workspace: BonsplitDelegate { func splitTabBar(_ controller: BonsplitController, didSelectTab tab: Bonsplit.Tab, inPane pane: PaneID) { // Mirror bookkeeping restores selection from its transaction snapshot. - guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { return } + guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { + publishMobilePaneLayoutRevisionIfChanged() + return + } applyTabSelection(tabId: tab.id, inPane: pane) + publishMobilePaneLayoutRevisionIfChanged() } func splitTabBar(_ controller: BonsplitController, shouldSplitPane pane: PaneID, orientation: SplitOrientation) -> Bool { @@ -12750,15 +12760,23 @@ extension Workspace: BonsplitDelegate { func splitTabBar(_ controller: BonsplitController, didFocusPane pane: PaneID) { // Mirror bookkeeping restores pane focus without re-running activation. - guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { return } - // When a pane is focused, focus its selected tab's panel - guard let tab = controller.selectedTab(inPane: pane) else { return } + guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { + publishMobilePaneLayoutRevisionIfChanged() + return + } + // When a pane is focused, focus its selected tab's panel. An empty pane + // still changes the mobile layout's focused-pane identity. + guard let tab = controller.selectedTab(inPane: pane) else { + publishMobilePaneLayoutRevisionIfChanged() + return + } #if DEBUG AppDelegate.shared?.focusLog.append( "Workspace.didFocusPane paneId=\(pane.id.uuidString) tabId=\(tab.id) focusedPane=\(controller.focusedPaneId?.id.uuidString ?? "nil")" ) #endif applyTabSelection(tabId: tab.id, inPane: pane) + publishMobilePaneLayoutRevisionIfChanged() // Apply window background for terminal if let panelId = panelIdFromSurfaceId(tab.id), @@ -13295,13 +13313,10 @@ extension Workspace: BonsplitDelegate { object: self, userInfo: [GhosttyNotificationKey.tabId: id] ) - // Every order/membership mutation (same-pane reorder, cross-pane move, - // split, close) routes through here. A pure reorder mutates only - // bonsplit's internal state, which is not `@Published`, so observers - // would miss it. Bump `paneLayoutVersion` only when the ordered panel-id - // sequence actually changed, so divider drags and selection-only events - // (also routed here) do not fire `objectWillChange` app-wide. - surfaceList.registerGeometryChange() + // Every order/membership mutation routes through here. Compare the + // shared mobile snapshot so reparenting that preserves flat tab order is + // still published, while divider-only geometry remains a no-op. + publishMobilePaneLayoutRevisionIfChanged() scheduleTerminalGeometryReconcile() if !isDetachingCloseTransaction { scheduleFocusReconcile() diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 510fbedf74bd..6fcd82c7217c 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -2456,6 +2456,8 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources F0ACC0DE0000000000000003 /* Workspace+ForkConversationContextMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0ACC0DE0000000000000004 /* Workspace+ForkConversationContextMenu.swift */; }; F17F00000000000000000005 /* Workspace+FullWidthTab.swift in Sources */ = {isa = PBXBuildFile; fileRef = F17F00000000000000000006 /* Workspace+FullWidthTab.swift */; }; C0DE1A050000000000000001 /* Workspace+LayoutCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE1A050000000000000002 /* Workspace+LayoutCapture.swift */; }; + A18F4D6C1A2B3C4D5E6F7002 /* Workspace+MobilePaneLayoutSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = A18F4D6C1A2B3C4D5E6F7001 /* Workspace+MobilePaneLayoutSnapshot.swift */; }; + C0DE00000000000000000C91 /* Workspace+MobilePaneReorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE00000000000000000C90 /* Workspace+MobilePaneReorder.swift */; }; C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */; }; 797800030000000000000001 /* Workspace+PersistentRemotePTYReattach.swift in Sources */ = {isa = PBXBuildFile; fileRef = 797800030000000000000002 /* Workspace+PersistentRemotePTYReattach.swift */; }; 791100010000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 791100020000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift */; }; @@ -5043,6 +5045,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F0ACC0DE0000000000000004 /* Workspace+ForkConversationContextMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+ForkConversationContextMenu.swift"; sourceTree = ""; }; F17F00000000000000000006 /* Workspace+FullWidthTab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+FullWidthTab.swift"; sourceTree = ""; }; C0DE1A050000000000000002 /* Workspace+LayoutCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+LayoutCapture.swift"; sourceTree = ""; }; + A18F4D6C1A2B3C4D5E6F7001 /* Workspace+MobilePaneLayoutSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+MobilePaneLayoutSnapshot.swift"; sourceTree = ""; }; + C0DE00000000000000000C90 /* Workspace+MobilePaneReorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+MobilePaneReorder.swift"; sourceTree = ""; }; C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PanelLifecycle.swift"; sourceTree = ""; }; 797800030000000000000002 /* Workspace+PersistentRemotePTYReattach.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PersistentRemotePTYReattach.swift"; sourceTree = ""; }; 791100020000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteDisconnectPlaceholder.swift"; sourceTree = ""; }; @@ -6323,10 +6327,12 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C0DE00000000000000000C8A /* TerminalController+WorkspaceGroupAction.swift */, A17C0A110000000000000002 /* WorkspaceInitialCommandLoginShell.swift */, C0DE00000000000000000C88 /* TerminalController+WorkspaceMove.swift */, + C0DE00000000000000000C90 /* Workspace+MobilePaneReorder.swift */, C0DE00000000000000000C55 /* TerminalController+ControlPaneContext.swift */, 8777C0028777C0028777C002 /* TerminalController+DockControlTopology.swift */, C7A50B000000000000000001 /* TerminalControllerV2ParamParsingSupport.swift */, C7A50B000000000000000011 /* TerminalController+MobileWorkspaceList.swift */, + A18F4D6C1A2B3C4D5E6F7001 /* Workspace+MobilePaneLayoutSnapshot.swift */, D1FF00010000000000000001 /* TerminalController+MobileWorkspaceChanges.swift */, C7A505000000000000000001 /* TerminalControllerTopSupport.swift */, C7A501000000000000000001 /* CmuxTopSnapshot.swift */, @@ -9980,6 +9986,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F0ACC0DE0000000000000003 /* Workspace+ForkConversationContextMenu.swift in Sources */, F17F00000000000000000005 /* Workspace+FullWidthTab.swift in Sources */, C0DE1A050000000000000001 /* Workspace+LayoutCapture.swift in Sources */, + A18F4D6C1A2B3C4D5E6F7002 /* Workspace+MobilePaneLayoutSnapshot.swift in Sources */, + C0DE00000000000000000C91 /* Workspace+MobilePaneReorder.swift in Sources */, C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */, 797800030000000000000001 /* Workspace+PersistentRemotePTYReattach.swift in Sources */, 791100010000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift in Sources */, diff --git a/cmuxTests/MobileHostConnectionLifecycleTests.swift b/cmuxTests/MobileHostConnectionLifecycleTests.swift index 3cd8862488bb..a7328b4c9d8e 100644 --- a/cmuxTests/MobileHostConnectionLifecycleTests.swift +++ b/cmuxTests/MobileHostConnectionLifecycleTests.swift @@ -589,6 +589,7 @@ extension MobileHostAuthorizationTests { #expect(capabilities.contains("workspace.read_state.v1")) #expect(capabilities.contains("workspace.close.v1")) #expect(capabilities.contains("workspace.move.v1")) + #expect(capabilities.contains("workspace.pane_reorder.v1")) #expect(capabilities.contains("workspace.group_actions.v1")) #expect(Set(capabilities).isSuperset(of: [ "workspace.task_create.v1", diff --git a/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift b/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift index c64630fb85b2..d00f9754968e 100644 --- a/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift +++ b/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift @@ -312,6 +312,16 @@ struct MobileHostWorkspaceTicketAuthorizationTests { ("workspace.action", ["workspace_id": "other-workspace", "action": "rename"], "forbidden"), ("workspace.close", ["workspace_id": "workspace"], nil), ("workspace.close", ["workspace_id": "other-workspace"], "forbidden"), + ( + "workspace.pane.reorder", + ["workspace_id": "workspace", "ordered_pane_ids": "fixture"], + nil + ), + ( + "workspace.pane.reorder", + ["workspace_id": "other-workspace", "ordered_pane_ids": "fixture"], + "forbidden" + ), ] for testCase in cases { diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index 756b7c42718a..d48d042ce6fe 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -3,6 +3,7 @@ import AppKit import Bonsplit import CMUXMobileCore import CmuxCore +import Foundation #if canImport(cmux_DEV) @testable import cmux_DEV @@ -10,15 +11,33 @@ import CmuxCore @testable import cmux #endif -/// Covers the mobile workspace-list fidelity fixes: terminals are serialized in -/// the on-screen bonsplit spatial order, a terminal rename re-emits to the phone, -/// and a pure drag-reorder is detected even though it changes no panel-set state. +/// Covers the mobile workspace-list fidelity fixes: bonsplit layout serialization, +/// terminal spatial order, custom titles, and observer topology invalidation. /// /// `.serialized` because these exercise process-global surface registries via the /// real `Workspace`/`TabManager`/bonsplit model, which must not run concurrently. @MainActor @Suite(.serialized) struct MobileWorkspaceListFidelityTests { + private func firstValue( + from stream: AsyncStream, + within timeout: Duration = .seconds(2) + ) async -> Element? { + await withTaskGroup(of: Element?.self) { group in + group.addTask { + var iterator = stream.makeAsyncIterator() + return await iterator.next() + } + group.addTask { + try? await Task.sleep(for: timeout) + return nil + } + let value = await group.next() ?? nil + group.cancelAll() + return value + } + } + /// Builds a workspace with `count` terminals as tabs in a single pane so that /// a within-pane `reorderTab` genuinely changes their on-screen order. Returns /// the workspace and panel ids in spatial (tab) order. @@ -52,6 +71,112 @@ struct MobileWorkspaceListFidelityTests { return (workspace, orderedIds) } + private func canonicalJSON(_ object: Any) throws -> String { + let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + return try #require(String(data: data, encoding: .utf8)) + } + + @Test func splitTreeSerializesExactLayoutV1Shape() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let leftPanelID = try #require(workspace.focusedPanelId) + workspace.setPanelCustomTitle(panelId: leftPanelID, title: "Left shell") + let rightPanel = try #require( + workspace.newTerminalSplit( + from: leftPanelID, + orientation: .vertical, + focus: false, + initialDividerPosition: 0.3 + ) + ) + workspace.setPanelCustomTitle(panelId: rightPanel.id, title: "Right shell") + + let snapshot = workspace.bonsplitController.treeSnapshot() + guard case .split(let split) = snapshot, + case .pane(let firstPane) = split.first, + case .pane(let secondPane) = split.second else { + Issue.record("expected a root split with two pane children") + return + } + #expect(split.orientation == "vertical") + #expect(abs(split.dividerPosition - 0.3) < 0.000_1) + let firstTab = try #require(firstPane.tabs.first) + let secondTab = try #require(secondPane.tabs.first) + let firstSurfaceID = try #require(UUID(uuidString: firstTab.id)) + let secondSurfaceID = try #require(UUID(uuidString: secondTab.id)) + #expect(workspace.panelId(forSurfaceId: firstSurfaceID) == leftPanelID) + #expect(workspace.panelId(forSurfaceId: secondSurfaceID) == rightPanel.id) + let focusedPaneID = try #require(workspace.bonsplitController.focusedPaneId?.id.uuidString) + #expect(focusedPaneID == firstPane.id) + + let payload = TerminalController.shared.mobileWorkspacePayload( + workspace: workspace, + isSelected: true, + requestedTerminalID: nil + ) + let layout = try #require(payload["layout"] as? [String: Any]) + let expected: [String: Any] = [ + "version": workspace.paneLayoutVersion, + "focused_pane_id": firstPane.id, + "root": [ + "kind": "split", + "id": split.id, + "orientation": "vertical", + "ratio": 0.3, + "first": [ + "kind": "pane", + "id": firstPane.id, + "selected_surface_id": leftPanelID.uuidString, + "surfaces": [ + ["id": leftPanelID.uuidString, "type": "terminal", "title": "Left shell"], + ], + ], + "second": [ + "kind": "pane", + "id": secondPane.id, + "selected_surface_id": rightPanel.id.uuidString, + "surfaces": [ + ["id": rightPanel.id.uuidString, "type": "terminal", "title": "Right shell"], + ], + ], + ], + ] + #expect(try canonicalJSON(layout) == canonicalJSON(expected)) + } + + @Test func nonTerminalPanelAppearsOnlyInLayoutSurfaces() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let terminalID = try #require(workspace.focusedPanelId) + workspace.setPanelCustomTitle(panelId: terminalID, title: "Shell") + let paneID = try #require(workspace.bonsplitController.focusedPaneId) + let todoPanel = try #require(workspace.newWorkspaceTodoSurface(inPane: paneID, focus: false)) + workspace.setPanelCustomTitle(panelId: todoPanel.id, title: "Plan") + + let payload = TerminalController.shared.mobileWorkspacePayload( + workspace: workspace, + isSelected: true, + requestedTerminalID: nil + ) + let terminals = try #require(payload["terminals"] as? [[String: Any]]) + #expect(terminals.count == 1) + #expect(terminals.first?["id"] as? String == terminalID.uuidString) + #expect(!terminals.contains { $0["id"] as? String == todoPanel.id.uuidString }) + + let layout = try #require(payload["layout"] as? [String: Any]) + let root = try #require(layout["root"] as? [String: Any]) + #expect(root["kind"] as? String == "pane") + let surfaces = try #require(root["surfaces"] as? [[String: Any]]) + let todoSurface = try #require(surfaces.first { $0["id"] as? String == todoPanel.id.uuidString }) + #expect(todoSurface["type"] as? String == PanelType.workspaceTodo.rawValue) + #expect(todoSurface["title"] as? String == "Plan") + } + + @Test func mobileHostAdvertisesWorkspaceLayoutV1() { + #expect(MobileHostService.mobileHostCapabilities.contains("workspace.layout.v1")) + #expect(MobileHostService.mobileHostCapabilities.contains("workspace.pane_reorder.v1")) + } + @Test func observerPipelinesFollowSubscriberPresence() throws { let previousOverride = MobileWorkspaceListObserver.subscriberPresenceOverrideForTesting defer { MobileWorkspaceListObserver.subscriberPresenceOverrideForTesting = previousOverride } @@ -85,6 +210,55 @@ struct MobileWorkspaceListFidelityTests { #expect(!observer.pipelinesAttachedForTesting) } + @Test func observerPipelineEmitsForPaneSelectionAndSuppressesNoOp() async throws { + let previousOverride = MobileWorkspaceListObserver.subscriberPresenceOverrideForTesting + defer { MobileWorkspaceListObserver.subscriberPresenceOverrideForTesting = previousOverride } + MobileWorkspaceListObserver.subscriberPresenceOverrideForTesting = true + + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let firstPanelID = try #require(workspace.focusedPanelId) + let secondPanel = try #require(workspace.newTerminalSurfaceInFocusedPane(focus: false)) + let firstTabID = try #require(workspace.surfaceIdFromPanelId(firstPanelID)) + let secondTabID = try #require(workspace.surfaceIdFromPanelId(secondPanel.id)) + workspace.bonsplitController.selectTab(firstTabID) + let (updates, updateContinuation) = AsyncStream.makeStream( + bufferingPolicy: .unbounded + ) + defer { updateContinuation.finish() } + let observer = MobileWorkspaceListObserver( + tabManager: manager, + workspaceUpdateEmitter: { + if let focusedPanelID = workspace.focusedPanelId { + updateContinuation.yield(focusedPanelID) + } + } + ) + let initialSelection = try #require( + await firstValue(from: updates), + "the observer should publish its initial snapshot" + ) + #expect(initialSelection == firstPanelID) + + workspace.bonsplitController.selectTab(secondTabID) + let selectionUpdate = try #require( + await firstValue(from: updates), + "pane selection should publish without a fixed delay" + ) + #expect(selectionUpdate == secondPanel.id, "selection publishes through the observer") + + // Follow the no-op with a real selection. A redundant no-op emission + // would deliver `secondPanel.id` before the real selection and fail. + workspace.bonsplitController.selectTab(secondTabID) + workspace.bonsplitController.selectTab(firstTabID) + let selectionAfterNoOp = try #require( + await firstValue(from: updates), + "the real selection should publish after the no-op" + ) + #expect(selectionAfterNoOp == firstPanelID, "a no-op selection stays suppressed") + _ = observer + } + @Test func orderedPanelIdsMatchesBonsplitSpatialOrder() throws { let (workspace, createdOrder) = try makeWorkspaceWithSplitTerminals(count: 3) @@ -100,11 +274,226 @@ struct MobileWorkspaceListFidelityTests { #expect(ordered == expected) } + @Test func mobilePaneReorderMovesCompleteContentsThroughStableLayoutSlots() throws { + let (workspace, _) = try makeWorkspaceWithSplitTerminals(count: 3) + _ = try #require(workspace.newTerminalSurfaceInFocusedPane(focus: false)) + let spatialPaneIDs = workspace.spatiallyOrderedPaneIds + #expect(spatialPaneIDs.count == 3) + let panesByID = Dictionary( + uniqueKeysWithValues: workspace.bonsplitController.allPaneIds.map { ($0.id, $0) } + ) + let originalContents = try spatialPaneIDs.map { paneID in + let pane = try #require(panesByID[paneID]) + return workspace.bonsplitController.tabs(inPane: pane).compactMap { + workspace.panelIdFromSurfaceId($0.id) + } + } + #expect(originalContents[0].count == 2) + let originalFocusedPanelID = try #require(workspace.focusedPanelId) + let originalFocusedPaneID = try #require( + workspace.paneId(forPanelId: originalFocusedPanelID)?.id + ) + let requestedContentOrder = [ + spatialPaneIDs[2], + spatialPaneIDs[0], + spatialPaneIDs[1], + ] + let expectedPanelOrder = + originalContents[2] + originalContents[0] + originalContents[1] + let versionBefore = workspace.paneLayoutVersion + + #expect(workspace.applyMobilePaneOrder(requestedContentOrder)) + + #expect( + workspace.spatiallyOrderedPaneIds == spatialPaneIDs, + "Pane identities and split geometry must remain stable" + ) + #expect( + workspace.orderedPanelIds == expectedPanelOrder, + "Every pane's complete content must move into the requested spatial slot" + ) + let focusedPanelDestinationPaneID = try #require( + workspace.paneId(forPanelId: originalFocusedPanelID)?.id + ) + #expect(focusedPanelDestinationPaneID == spatialPaneIDs[1]) + #expect(workspace.bonsplitController.focusedPaneId?.id == focusedPanelDestinationPaneID) + #expect(originalFocusedPaneID != focusedPanelDestinationPaneID) + #expect( + workspace.paneLayoutVersion == versionBefore + 1, + "The multi-step Bonsplit mutation must publish one authoritative revision" + ) + } + + @Test func mobilePaneReorderRejectsStaleTopologyWithoutMutation() throws { + let (workspace, originalPanelOrder) = try makeWorkspaceWithSplitTerminals(count: 3) + let spatialPaneIDs = workspace.spatiallyOrderedPaneIds + let versionBefore = workspace.paneLayoutVersion + + #expect(!workspace.applyMobilePaneOrder(Array(spatialPaneIDs.dropLast()))) + #expect(workspace.spatiallyOrderedPaneIds == spatialPaneIDs) + #expect(workspace.orderedPanelIds == originalPanelOrder) + #expect(workspace.paneLayoutVersion == versionBefore) + } + + @Test func mobilePaneReorderRPCMutatesOwnerAndReturnsAuthoritativeList() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let firstPanelID = try #require(workspace.focusedPanelId) + let secondPanel = try #require( + workspace.newTerminalSplit( + from: firstPanelID, + orientation: .horizontal, + focus: false + ) + ) + let paneIDs = workspace.spatiallyOrderedPaneIds + let previousManager = TerminalController.shared.activeTabManagerForCallerNotification() + TerminalController.shared.setActiveTabManager(manager) + defer { TerminalController.shared.setActiveTabManager(previousManager) } + + let result = TerminalController.shared.v2MobileWorkspacePaneReorder(params: [ + "workspace_id": workspace.id.uuidString, + "ordered_pane_ids": paneIDs.reversed().map(\.uuidString), + ]) + + guard case .ok(let payload) = result, + let object = payload as? [String: Any], + let returnedWorkspaces = object["workspaces"] as? [[String: Any]] else { + return #expect(Bool(false), "pane reorder should return an authoritative workspace list") + } + #expect(workspace.orderedPanelIds == [secondPanel.id, firstPanelID]) + #expect( + returnedWorkspaces.contains { + $0["id"] as? String == workspace.id.uuidString + } + ) + } + + /// Slot IDs stay stable across content reorders, so the RPC's pane-id set + /// check alone cannot detect that another reorder landed after the phone + /// captured its snapshot. The phone's observed `base_layout_version` is the + /// precondition that makes the stale request fail closed as a conflict + /// instead of silently permuting the wrong panes. + @Test func mobilePaneReorderRejectsStaleBaseLayoutVersion() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let firstPanelID = try #require(workspace.focusedPanelId) + let secondPanel = try #require( + workspace.newTerminalSplit( + from: firstPanelID, + orientation: .horizontal, + focus: false + ) + ) + let paneIDs = workspace.spatiallyOrderedPaneIds + let previousManager = TerminalController.shared.activeTabManagerForCallerNotification() + TerminalController.shared.setActiveTabManager(manager) + defer { TerminalController.shared.setActiveTabManager(previousManager) } + + let staleVersion = workspace.paneLayoutVersion + let firstResult = TerminalController.shared.v2MobileWorkspacePaneReorder(params: [ + "workspace_id": workspace.id.uuidString, + "ordered_pane_ids": paneIDs.reversed().map(\.uuidString), + ]) + guard case .ok = firstResult else { + return #expect(Bool(false), "the first reorder should succeed and bump the layout version") + } + #expect(workspace.paneLayoutVersion != staleVersion) + let orderAfterFirstReorder = workspace.orderedPanelIds + #expect(orderAfterFirstReorder == [secondPanel.id, firstPanelID]) + + let secondResult = TerminalController.shared.v2MobileWorkspacePaneReorder(params: [ + "workspace_id": workspace.id.uuidString, + "ordered_pane_ids": paneIDs.reversed().map(\.uuidString), + "base_layout_version": staleVersion, + ]) + guard case .err(let code, _, _) = secondResult else { + return #expect(Bool(false), "a reorder carrying a stale base_layout_version must be rejected") + } + #expect(code == "conflict") + #expect( + workspace.orderedPanelIds == orderAfterFirstReorder, + "a conflicted reorder must not mutate the pane order" + ) + } + + @Test func mobilePaneReorderMatchingBaseLayoutVersionSucceeds() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let firstPanelID = try #require(workspace.focusedPanelId) + let secondPanel = try #require( + workspace.newTerminalSplit( + from: firstPanelID, + orientation: .horizontal, + focus: false + ) + ) + let paneIDs = workspace.spatiallyOrderedPaneIds + let previousManager = TerminalController.shared.activeTabManagerForCallerNotification() + TerminalController.shared.setActiveTabManager(manager) + defer { TerminalController.shared.setActiveTabManager(previousManager) } + + let result = TerminalController.shared.v2MobileWorkspacePaneReorder(params: [ + "workspace_id": workspace.id.uuidString, + "ordered_pane_ids": paneIDs.reversed().map(\.uuidString), + "base_layout_version": workspace.paneLayoutVersion, + ]) + + guard case .ok = result else { + return #expect(Bool(false), "a reorder carrying the current layout version must succeed") + } + #expect(workspace.orderedPanelIds == [secondPanel.id, firstPanelID]) + } + + /// The phone's snapshot can carry the window the workspace lived in before + /// it moved windows. Honoring that `window_id` verbatim resolved the wrong + /// TabManager and rejected the reorder as not_found; the mutation must + /// route to the workspace's owning window first. + @Test func mobilePaneReorderRoutesToOwnerDespiteStaleWindowID() throws { + let previousAppDelegate = AppDelegate.shared + let appDelegate = AppDelegate() + AppDelegate.shared = appDelegate + defer { AppDelegate.shared = previousAppDelegate } + + let ownerManager = TabManager() + let otherManager = TabManager() + let ownerWindowID = appDelegate.registerMainWindowContextForTesting(tabManager: ownerManager) + let staleWindowID = appDelegate.registerMainWindowContextForTesting(tabManager: otherManager) + defer { + appDelegate.unregisterMainWindowContextForTesting(windowId: ownerWindowID) + appDelegate.unregisterMainWindowContextForTesting(windowId: staleWindowID) + } + + let workspace = try #require(ownerManager.selectedWorkspace) + let firstPanelID = try #require(workspace.focusedPanelId) + let secondPanel = try #require( + workspace.newTerminalSplit( + from: firstPanelID, + orientation: .horizontal, + focus: false + ) + ) + let paneIDs = workspace.spatiallyOrderedPaneIds + + let result = TerminalController.shared.v2MobileWorkspacePaneReorder(params: [ + "workspace_id": workspace.id.uuidString, + "window_id": staleWindowID.uuidString, + "ordered_pane_ids": paneIDs.reversed().map(\.uuidString), + ]) + + guard case .ok = result else { + return #expect(Bool(false), "a stale window_id must not misroute the reorder away from the owner") + } + #expect(workspace.orderedPanelIds == [secondPanel.id, firstPanelID]) + } + @Test func reorderingTerminalsChangesObserverHashAndBumpsLayoutVersion() throws { // Tabs in one pane so a within-pane reorder genuinely changes their order. let (workspace, ordered) = try makeWorkspaceWithTabTerminals(count: 3) #expect(ordered.count == 3) + let selectedTabID = try #require(workspace.surfaceIdFromPanelId(ordered[0])) + workspace.bonsplitController.selectTab(selectedTabID) let versionBefore = workspace.paneLayoutVersion let before = MobileWorkspaceListObserver.summaryHashForTesting( tabs: [workspace], @@ -114,6 +503,7 @@ struct MobileWorkspaceListFidelityTests { // Move the first terminal to the end. Same panel set, different spatial order. let firstTabId = try #require(workspace.surfaceIdFromPanelId(ordered[0])) #expect(workspace.bonsplitController.reorderTab(firstTabId, toIndex: 2)) + workspace.bonsplitController.selectTab(selectedTabID) // Sanity: the id set is unchanged, but the order changed. let afterOrder = workspace.orderedPanelIds @@ -134,6 +524,129 @@ struct MobileWorkspaceListFidelityTests { #expect(before != after, "a pure reorder must change the mobile summary hash") } + @Test func changingPaneSelectedTabChangesObserverHash() throws { + let (workspace, ordered) = try makeWorkspaceWithTabTerminals(count: 2) + let firstTabID = try #require(workspace.surfaceIdFromPanelId(ordered[0])) + let secondTabID = try #require(workspace.surfaceIdFromPanelId(ordered[1])) + workspace.bonsplitController.selectTab(firstTabID) + let before = MobileWorkspaceListObserver.summaryHashForTesting( + tabs: [workspace], + selectedTabID: workspace.id + ) + + workspace.bonsplitController.selectTab(secondTabID) + let snapshot = workspace.bonsplitController.treeSnapshot() + guard case .pane(let pane) = snapshot else { + Issue.record("expected a single pane") + return + } + #expect(pane.selectedTabId == secondTabID.uuid.uuidString) + + let after = MobileWorkspaceListObserver.summaryHashForTesting( + tabs: [workspace], + selectedTabID: workspace.id + ) + #expect(before != after, "changing only a pane's selected tab must change the mobile summary hash") + } + + @Test func changingPaneSelectedTabPublishesLayoutRevision() throws { + let (workspace, ordered) = try makeWorkspaceWithTabTerminals(count: 2) + let firstTabID = try #require(workspace.surfaceIdFromPanelId(ordered[0])) + let secondTabID = try #require(workspace.surfaceIdFromPanelId(ordered[1])) + workspace.bonsplitController.selectTab(firstTabID) + let versionBefore = workspace.paneLayoutVersion + + workspace.bonsplitController.selectTab(secondTabID) + + #expect( + workspace.paneLayoutVersion == versionBefore + 1, + "a pane-local selection must publish one layout revision" + ) + let versionAfterChange = workspace.paneLayoutVersion + workspace.bonsplitController.selectTab(secondTabID) + #expect( + workspace.paneLayoutVersion == versionAfterChange, + "reselecting the current surface must not publish a no-op revision" + ) + } + + @Test func focusingPaneChangesObserverHashAndPublishesLayoutRevision() throws { + let (workspace, _) = try makeWorkspaceWithSplitTerminals(count: 2) + let focusedPane = try #require(workspace.bonsplitController.focusedPaneId) + let destinationPane = try #require( + workspace.bonsplitController.allPaneIds.first(where: { $0 != focusedPane }) + ) + let hashBefore = MobileWorkspaceListObserver.summaryHashForTesting( + tabs: [workspace], + selectedTabID: workspace.id + ) + let versionBefore = workspace.paneLayoutVersion + + workspace.bonsplitController.focusPane(destinationPane) + + let hashAfter = MobileWorkspaceListObserver.summaryHashForTesting( + tabs: [workspace], + selectedTabID: workspace.id + ) + #expect(hashAfter != hashBefore, "focused pane is part of the mobile layout snapshot") + #expect( + workspace.paneLayoutVersion == versionBefore + 1, + "a focus-only pane change must publish one layout revision" + ) + } + + @Test func crossPaneMoveWithStableFlatOrderPublishesLayoutRevision() throws { + let manager = TabManager() + let workspace = try #require(manager.selectedWorkspace) + let firstPanelID = try #require(workspace.focusedPanelId) + let secondPanel = try #require(workspace.newTerminalSurfaceInFocusedPane(focus: false)) + let thirdPanel = try #require( + workspace.newTerminalSplit(from: secondPanel.id, orientation: .horizontal, focus: false) + ) + let secondTabID = try #require(workspace.surfaceIdFromPanelId(secondPanel.id)) + let destinationPane = try #require(workspace.paneId(forPanelId: thirdPanel.id)) + let orderBefore = workspace.orderedPanelIds + #expect(orderBefore == [firstPanelID, secondPanel.id, thirdPanel.id]) + let versionBefore = workspace.paneLayoutVersion + + #expect(workspace.bonsplitController.moveTab(secondTabID, toPane: destinationPane, atIndex: 0)) + + #expect( + workspace.orderedPanelIds == orderBefore, + "the regression needs pane membership to change without changing the flat surface order" + ) + #expect( + workspace.paneLayoutVersion == versionBefore + 1, + "pane membership changes must publish even when the flat surface order stays stable" + ) + } + + @Test func changingOnlyDividerRatioDoesNotChangeObserverHash() throws { + let (workspace, _) = try makeWorkspaceWithSplitTerminals(count: 2) + guard case .split(let splitBefore) = workspace.bonsplitController.treeSnapshot() else { + Issue.record("expected a root split") + return + } + let before = MobileWorkspaceListObserver.summaryHashForTesting( + tabs: [workspace], + selectedTabID: workspace.id + ) + let changedRatio = splitBefore.dividerPosition < 0.5 ? 0.75 : 0.25 + let splitID = try #require(UUID(uuidString: splitBefore.id)) + #expect(workspace.bonsplitController.setDividerPosition(CGFloat(changedRatio), forSplit: splitID)) + + guard case .split(let splitAfter) = workspace.bonsplitController.treeSnapshot() else { + Issue.record("expected a root split after resizing") + return + } + #expect(abs(splitAfter.dividerPosition - changedRatio) < 0.000_1) + let after = MobileWorkspaceListObserver.summaryHashForTesting( + tabs: [workspace], + selectedTabID: workspace.id + ) + #expect(before == after, "divider-only changes must not change the mobile summary hash") + } + @Test func renamingTerminalChangesObserverHashAndDisplayedTitle() throws { let (workspace, ordered) = try makeWorkspaceWithTabTerminals(count: 2) let panelId = try #require(ordered.first) diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index ead0d6ad251a..c6af68f1693d 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -8671,6 +8671,20 @@ } } }, + "mobile.agent.status.needsInput": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Agent needs input" } }, + "ja": { "stringUnit": { "state": "translated", "value": "エージェントが入力を待っています" } } + } + }, + "mobile.agent.status.working": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Agent working" } }, + "ja": { "stringUnit": { "state": "translated", "value": "エージェントが作業中です" } } + } + }, "mobile.altScreenNotice.explanation": { "extractionState": "manual", "localizations": { @@ -8705,6 +8719,174 @@ } } }, + "mobile.paneMap.count.onePane.oneTab": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "1 pane · 1 tab" } }, + "ja": { "stringUnit": { "state": "translated", "value": "1ペイン・1タブ" } } + } + }, + "mobile.paneMap.count.onePane.otherTabs": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "1 pane · %d tabs" } }, + "ja": { "stringUnit": { "state": "translated", "value": "1ペイン・%dタブ" } } + } + }, + "mobile.paneMap.count.otherPanes.oneTab": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%d panes · 1 tab" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%dペイン・1タブ" } } + } + }, + "mobile.paneMap.count.otherPanes.otherTabs": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%d panes · %d tabs" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%dペイン・%dタブ" } } + } + }, + "mobile.paneMap.done": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Done" } }, + "ja": { "stringUnit": { "state": "translated", "value": "完了" } } + } + }, + "mobile.paneMap.focusedOnMac": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Focused on Mac" } }, + "ja": { "stringUnit": { "state": "translated", "value": "Macでフォーカス中" } } + } + }, + "mobile.paneMap.focusedOnMac.short": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Mac" } }, + "ja": { "stringUnit": { "state": "translated", "value": "Mac" } } + } + }, + "mobile.paneMap.more.bottom": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "More panes below" } }, + "ja": { "stringUnit": { "state": "translated", "value": "下にさらにペインがあります" } } + } + }, + "mobile.paneMap.more.leading": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "More panes to the left" } }, + "ja": { "stringUnit": { "state": "translated", "value": "左にさらにペインがあります" } } + } + }, + "mobile.paneMap.more.top": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "More panes above" } }, + "ja": { "stringUnit": { "state": "translated", "value": "上にさらにペインがあります" } } + } + }, + "mobile.paneMap.more.trailing": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "More panes to the right" } }, + "ja": { "stringUnit": { "state": "translated", "value": "右にさらにペインがあります" } } + } + }, + "mobile.paneMap.openNamedTerminal": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Open terminal: %@" } }, + "ja": { "stringUnit": { "state": "translated", "value": "ターミナルを開く:%@" } } + } + }, + "mobile.paneMap.panePosition": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Pane %d of %d" } }, + "ja": { "stringUnit": { "state": "translated", "value": "ペイン%d/%d" } } + } + }, + "mobile.paneMap.refresh": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Refresh" } }, + "ja": { "stringUnit": { "state": "translated", "value": "更新" } } + } + }, + "mobile.paneMap.reorderFailed": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Couldn’t rearrange panes on your Mac." } }, + "ja": { "stringUnit": { "state": "translated", "value": "Mac上のペインを並べ替えられませんでした。" } } + } + }, + "mobile.paneMap.unavailableOnPhone": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Unavailable on iPhone" } }, + "ja": { "stringUnit": { "state": "translated", "value": "iPhoneでは利用できません" } } + } + }, + "mobile.surfaceDeck.add": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Add Surface" } }, + "ja": { "stringUnit": { "state": "translated", "value": "サーフェスを追加" } } + } + }, + "mobile.surfaceDeck.chip.terminal": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%@, terminal" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%@、ターミナル" } } + } + }, + "mobile.surfaceDeck.chip.terminalInPane": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%@, terminal, pane %d of %d" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%@、ターミナル、ペイン%d/%d" } } + } + }, + "mobile.surfaceDeck.chip.unavailable": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%@, unavailable on iPhone" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%@、iPhoneでは利用できません" } } + } + }, + "mobile.surfaceDeck.chip.unavailableInPane": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%@, unavailable on iPhone, pane %d of %d" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%@、iPhoneでは利用できません、ペイン%d/%d" } } + } + }, + "mobile.surfaceDeck.label": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Workspace surfaces" } }, + "ja": { "stringUnit": { "state": "translated", "value": "ワークスペースのサーフェス" } } + } + }, + "mobile.surfaceDeck.paneMap": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Pane Map" } }, + "ja": { "stringUnit": { "state": "translated", "value": "ペインマップ" } } + } + }, + "mobile.surfaceDeck.terminalsOnly": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Terminals only on iPhone for now" } }, + "ja": { "stringUnit": { "state": "translated", "value": "現在、iPhoneではターミナルのみ利用できます" } } + } + }, "mobile.terminal.action.alt": { "extractionState": "manual", "localizations": { @@ -13196,6 +13378,13 @@ } } }, + "mobile.workspace.utilitiesMenu": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Workspace Utilities" } }, + "ja": { "stringUnit": { "state": "translated", "value": "ワークスペースユーティリティ" } } + } + }, "mobile.workspace.unpin": { "extractionState": "manual", "localizations": { diff --git a/ios/cmuxUITests/TerminalThemeParityUITests.swift b/ios/cmuxUITests/TerminalThemeParityUITests.swift index 05728acf52a3..d6744777c450 100644 --- a/ios/cmuxUITests/TerminalThemeParityUITests.swift +++ b/ios/cmuxUITests/TerminalThemeParityUITests.swift @@ -24,6 +24,30 @@ final class TerminalThemeParityUITests: XCTestCase { try capture(app, name: "custom-theme-live-reload", expectedBackground: (6, 63, 70)) } + @MainActor + func testPanePreviewPaddingUsesTheSurfaceEffectiveBackground() throws { + let app = XCUIApplication() + app.launchEnvironment["CMUX_UITEST_MOCK_DATA"] = "0" + app.launchEnvironment["CMUX_UITEST_PANES_PREVIEW"] = "1" + app.launch() + defer { app.terminate() } + + XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) + app.buttons["MobileSurfaceDeckPaneMap"].tap() + let tile = app.buttons["MobilePaneMapTile-preview-claude"] + XCTAssertTrue(tile.waitForExistence(timeout: 4)) + + let screenshot = app.screenshot() + let pixels = try ScreenshotPixels(image: screenshot.image) + let sample = pixels.color( + xUnit: (tile.frame.maxX - 8) / app.frame.width, + yUnit: tile.frame.midY / app.frame.height + ) + XCTAssertEqual(sample.red, 18, accuracy: 2) + XCTAssertEqual(sample.green, 52, accuracy: 2) + XCTAssertEqual(sample.blue, 86, accuracy: 2) + } + @MainActor private func waitForStage(_ stage: String, in app: XCUIApplication) throws { XCTAssertTrue( diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index b6ec1c084a3c..ecad2ab67feb 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -2683,6 +2683,22 @@ final class cmuxUITests: XCTestCase { assertTerminalMenuItemExists("workspace-3-terminal-1", in: app) } + @MainActor + private func assertTerminalMenuItemExists( + _ terminalID: String, + in app: XCUIApplication, + file: StaticString = #filePath, + line: UInt = #line + ) { + let item = app.buttons["MobileTerminalMenuItem-\(terminalID)"] + XCTAssertTrue( + item.waitForExistence(timeout: 4), + "Expected terminal menu to contain \(terminalID).", + file: file, + line: line + ) + } + /// Regression: preparation must durably save the exact retry identity /// before routing starts, while Cancel remains available until the create /// boundary is committed. @@ -2905,6 +2921,341 @@ final class cmuxUITests: XCTestCase { assertTerminalRenderBottomAttachedToViewport(dock, context: "synthetic keyboard preview") } + @MainActor + func testPanesPreviewCorrelatesDeckGroupsWithMapRegionsAndSwitchesTabs() throws { + let app = launchApp(mockData: false, environment: [ + "CMUX_UITEST_PANES_PREVIEW": "1", + ]) + defer { app.terminate() } + + XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) + let backButton = app.buttons["MobileWorkspaceBackButton"] + let titleMenu = workspaceTitleElement(in: app) + let terminalUtilities = app.buttons["MobileWorkspaceUtilitiesMenu"] + XCTAssertTrue(backButton.waitForExistence(timeout: 4)) + XCTAssertTrue(titleMenu.waitForExistence(timeout: 4)) + XCTAssertTrue(terminalUtilities.waitForExistence(timeout: 4)) + let terminalBackFrame = try XCTUnwrap(waitForToolbarFrame(of: backButton, timeout: 4)) + let terminalTitleFrame = try XCTUnwrap(waitForToolbarFrame(of: titleMenu, timeout: 4)) + let terminalUtilitiesFrame = try XCTUnwrap( + waitForToolbarFrame(of: terminalUtilities, timeout: 4) + ) + XCTAssertFalse( + waitForPaneMap( + app.otherElements["MobilePaneMapOverlay"], + in: app, + toBeActive: true, + timeout: 0.3 + ), + "Opening a workspace must present its restored terminal directly" + ) + + let leftTopDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-left-top" + ] + let leftBottomDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-left-bottom" + ] + let testsDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-tests" + ] + let serverDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-server" + ] + XCTAssertTrue(leftTopDeckGroup.exists) + XCTAssertTrue(leftBottomDeckGroup.exists) + XCTAssertTrue(testsDeckGroup.exists) + XCTAssertTrue(serverDeckGroup.exists) + XCTAssertFalse( + app.descendants(matching: .any)[ + "MobileSurfaceDeckPaneNumber-preview-pane-left-top" + ].exists + ) + XCTAssertEqual( + app.buttons["MobileSurfaceDeckChip-preview-claude"].value as? String, + "Agent working" + ) + + tap(app.buttons["MobileWorkspaceUtilitiesMenu"], in: app) + tapMenuItem(app.buttons["MobilePaneMapMenuItem"], in: app) + + let overlay = app.otherElements["MobilePaneMapOverlay"] + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) + XCTAssertTrue( + backButton.exists, + "The shared workspace back button must remain present in pane-layout mode" + ) + assertToolbarFrame( + try XCTUnwrap(waitForToolbarFrame(of: backButton, timeout: 4)), + matches: terminalBackFrame, + context: "workspace back button" + ) + assertToolbarFrame( + try XCTUnwrap(waitForToolbarFrame(of: titleMenu, timeout: 4)), + matches: terminalTitleFrame, + context: "workspace title" + ) + let refreshFrame = try XCTUnwrap( + waitForToolbarFrame(of: app.buttons["MobilePaneMapRefresh"], timeout: 4) + ) + let doneFrame = try XCTUnwrap( + waitForToolbarFrame(of: app.buttons["MobilePaneMapDone"], timeout: 4) + ) + XCTAssertEqual( + doneFrame.maxX, + terminalUtilitiesFrame.maxX, + accuracy: 1, + "Pane-map trailing controls must stay pinned to the same right toolbar edge" + ) + XCTAssertEqual( + refreshFrame.height, + terminalUtilitiesFrame.height, + accuracy: 1, + "Pane-map refresh control must keep the native compact toolbar height" + ) + XCTAssertLessThanOrEqual( + refreshFrame.maxX, + doneFrame.minX + 1, + "Pane-map refresh and done controls must occupy deterministic adjacent slots" + ) + let leftTopPane = app.descendants(matching: .any)[ + "MobilePaneMapPane-preview-pane-left-top" + ] + let leftBottomPane = app.descendants(matching: .any)[ + "MobilePaneMapPane-preview-pane-left-bottom" + ] + let testsPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-tests"] + let serverPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-server"] + XCTAssertTrue(leftTopPane.waitForExistence(timeout: 2)) + XCTAssertTrue(leftBottomPane.exists) + XCTAssertTrue(testsPane.exists) + XCTAssertTrue(serverPane.exists) + XCTAssertLessThan(leftTopPane.frame.midX, testsPane.frame.midX) + XCTAssertLessThan(leftTopPane.frame.midY, leftBottomPane.frame.midY) + XCTAssertLessThan(testsPane.frame.midY, serverPane.frame.midY) + XCTAssertEqual(leftTopPane.value as? String, "Focused on Mac") + XCTAssertFalse( + app.descendants(matching: .any)[ + "MobilePaneMapPaneNumber-preview-pane-left-top" + ].exists + ) + let leftTopTabStrip = app.descendants(matching: .any)[ + "MobilePaneMapTabStrip-preview-pane-left-top" + ] + XCTAssertTrue(leftTopTabStrip.waitForExistence(timeout: 2)) + XCTAssertEqual(leftTopTabStrip.frame.width, 64, accuracy: 2) + + tap(app.buttons["MobilePaneMapDone"], in: app) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: false)) + + tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) + assertFramesRemainStable( + [leftTopPane, leftBottomPane, testsPane, serverPane], + for: 0.45, + accuracy: 1, + context: "pane-map return endpoint" + ) + tap(app.buttons["MobilePaneMapTab-preview-zsh"], in: app) + let zshTile = app.buttons["MobilePaneMapTile-preview-zsh"] + XCTAssertTrue(zshTile.waitForExistence(timeout: 2)) + XCTAssertTrue(app.staticTexts["MobilePaneMapCaption-preview-zsh"].exists) + XCTAssertTrue(overlay.exists, "Switching tabs must stay inside the pane map") + tap(zshTile, in: app) + + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: false)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-zsh"].isSelected) + } + + @MainActor + func testPanesPreviewReordersCardsAndZoomsTerminalInBothDirections() throws { + let app = launchApp(mockData: false, environment: [ + "CMUX_UITEST_PANES_PREVIEW": "1", + ]) + defer { app.terminate() } + + XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) + tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) + + let overlay = app.otherElements["MobilePaneMapOverlay"] + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) + let leftTopPane = app.descendants(matching: .any)[ + "MobilePaneMapPane-preview-pane-left-top" + ] + let testsPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-tests"] + XCTAssertTrue(leftTopPane.waitForExistence(timeout: 2)) + XCTAssertTrue(testsPane.exists) + + tap(app.buttons["MobilePaneMapTab-preview-claude"], in: app) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: true), + "Switching the preview tab must not focus its pane" + ) + let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] + XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) + let originalClaudeFrame = claudeTile.frame + let originalTestsFrame = testsPane.frame + + let swipeStart = overlay.coordinate(withNormalizedOffset: CGVector(dx: 0.7, dy: 0.72)) + let swipeEnd = overlay.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.28)) + swipeStart.press(forDuration: 0.05, thenDragTo: swipeEnd) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: true), + "A pane-layout swipe must be absorbed by scrolling instead of focusing a pane" + ) + + let dragStart = leftTopPane.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) + let dragEnd = testsPane.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) + dragStart.press( + forDuration: 0.8, + thenDragTo: dragEnd, + withVelocity: .slow, + thenHoldForDuration: 0.5 + ) + let reordered = XCTNSPredicateExpectation( + predicate: NSPredicate( + block: { _, _ in + abs(claudeTile.frame.midX - originalTestsFrame.midX) < 24 + && abs(claudeTile.frame.midX - originalClaudeFrame.midX) > 20 + } + ), + object: claudeTile + ) + XCTAssertEqual( + XCTWaiter.wait(for: [reordered], timeout: 4), + .completed, + "Dragging a pane card must move its contents into the authoritative destination slot" + ) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: true), + "A pane relayout drag must not also focus the dragged pane" + ) + + tap(claudeTile, in: app) + + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: false)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-claude"].isSelected) + + let interruptedSwipeStart = app.coordinate( + withNormalizedOffset: CGVector(dx: 0.01, dy: 0.5) + ) + let interruptedSwipeEnd = app.coordinate( + withNormalizedOffset: CGVector(dx: 0.18, dy: 0.5) + ) + interruptedSwipeStart.press( + forDuration: 0.05, + thenDragTo: interruptedSwipeEnd, + withVelocity: .slow, + thenHoldForDuration: 0 + ) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: false), + "A cancelled interactive return must leave the terminal fully focused" + ) + + tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: true), + "The opened terminal must fluidly return to its pane-map source" + ) + XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) + + tap(claudeTile, in: app) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: false), + "The same source must zoom back into the opened terminal" + ) + } + + /// P0 regression for the real-shell pane-layout crash + /// (https://github.com/manaflow-ai/cmux/pull/8188): a workspace that syncs + /// a pane layout mounted a second typed `NavigationStack` inside the + /// compact shell stack's pushed destination. Both stacks join the window's + /// shared NavigationAuthority, whose queue then reconciles one stack's + /// bound path against the other stack's column and dies in + /// `NavigationColumnState.boundPathChange` with + /// `SwiftUI.AnyNavigationPath.Error.comparisonTypeMismatch`. The panes + /// fixture (`CMUX_UITEST_PANES_PREVIEW`) hosts the pane-zoom pair + /// standalone, so only a mock-host launch of the production shell + /// reproduces this. The drive-through covers every on-device trigger: + /// the initial workspace push, pane-map round-trips, popping back to the + /// list, and pushing a layout-free workspace afterwards (which crashed + /// against the stale pane column even after the pane workspace was + /// popped). + @MainActor + func testWorkspacePaneLayoutNavigationSurvivesInRealShell() async throws { + let server = try MobileSyncMockHostServer(mainWorkspacePaneLayout: true) + let port = try await server.start() + defer { server.stop() } + + let app = try launchConnectedApp(port: port, assertStatusRows: false) + // The on-device crash landed within seconds of the push with no + // further interaction; give the authority's queued updates a window. + try await Task.sleep(for: .seconds(3)) + XCTAssertEqual( + app.state, + .runningForeground, + "Opening a pane-layout workspace must not crash the shell" + ) + + let overlay = app.otherElements["MobilePaneMapOverlay"] + let deckPaneMapButton = app.buttons["MobileSurfaceDeckPaneMap"] + for cycle in 1...2 { + tap(deckPaneMapButton, in: app) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: true), + "Pane map must open from the surface deck (cycle \(cycle))" + ) + XCTAssertEqual(app.state, .runningForeground) + tap(app.buttons["MobilePaneMapTile-terminal-build"], in: app) + // The deck lives inside the terminal's presentation, so its + // reappearance proves the round trip completed. This is a + // liveness check, not a latency one: the cover re-presentation + // rebuilds the terminal subtree and takes 15+ seconds on a + // saturated CI runner. + XCTAssertTrue( + deckPaneMapButton.waitForExistence(timeout: 30), + "Tapping a tile must return to the terminal (cycle \(cycle))" + ) + XCTAssertEqual(app.state, .runningForeground) + } + + // Pop to the list and push a workspace WITHOUT a layout: before the + // fix, this push was compared against the popped pane stack's stale + // column and crashed even though the nested stack was already gone. + tap(app.buttons["MobileWorkspaceBackButton"], in: app) + let docsRow = app.descendants(matching: .any)["MobileWorkspaceRow-workspace-docs"] + XCTAssertTrue(docsRow.waitForExistence(timeout: 20)) + docsRow.tap() + let docsTerminal = app.otherElements["MobileTerminalSurface"] + if !docsTerminal.waitForExistence(timeout: 20), docsRow.exists { + // The list can reshuffle under the first tap while the popped + // workspace's cover finishes tearing down on a slow runner; + // retry once if we are demonstrably still on the list. + docsRow.tap() + } + let docsTerminalAppeared = docsTerminal.waitForExistence(timeout: 20) + if !docsTerminalAppeared { + // Name the screen that swallowed both pushes; the xcresult with + // the failure snapshot is not uploaded from CI. + print( + """ + docs workspace push produced no terminal; docsRow.exists=\(docsRow.exists) + AX tree: + \(app.debugDescription) + """ + ) + } + XCTAssertTrue(docsTerminalAppeared) + try await Task.sleep(for: .seconds(3)) + XCTAssertEqual( + app.state, + .runningForeground, + "Pushing a plain workspace after a pane-layout workspace must not crash the shell" + ) + app.terminate() + } + @MainActor func testBottomScrollStaysPinnedAcrossComposerViewportShrink() throws { let app = launchApp(mockData: false, environment: [ @@ -2928,7 +3279,7 @@ final class cmuxUITests: XCTestCase { } @MainActor - func testWorkspaceToolbarCreatesWorkspaceAndTerminal() async throws { + func testSurfaceDeckCreatesTerminalAndWorkspace() async throws { let server = try MobileSyncMockHostServer(createdWorkspaceTerminalDelay: 1.5) let port = try await server.start() defer { server.stop() } @@ -2945,50 +3296,40 @@ final class cmuxUITests: XCTestCase { XCTAssertFalse(app.buttons["MobileNewTerminalMenuItem"].exists) dismissOpenMenu(in: app) - tap(app.buttons["MobileTerminalNewWorkspaceButton"], in: app) - let freshBackButton = app.buttons["MobileWorkspaceBackButton"] - let freshTitleMenu = workspaceTitleElement(in: app) - let freshTerminalDropdown = app.buttons["MobileTerminalDropdown"] - assertWorkspaceToolbarVisible( - backButton: freshBackButton, - titleMenu: freshTitleMenu, - terminalDropdown: freshTerminalDropdown, - in: app, - context: "fresh no-agent workspace immediately after create" + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-terminal-build"].exists) + XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-terminal-tui"].exists) + + tap(app.buttons["MobileSurfaceDeckAdd"], in: app) + tapMenuItem(app.buttons["MobileNewTerminalMenuItem"], in: app) + await assertHostSelection( + workspaceID: "workspace-main", + terminalID: "workspace-main-terminal-3", + server: server ) - assertMenuButtonDoesNotExist("MobileWorkspaceSettingsMenu", in: app) - assertToolbarOverflowButtonDoesNotExist(in: app) + assertSurfaceDeckChipExists("workspace-main-terminal-3", in: app) + + tap(app.buttons["MobileSurfaceDeckAdd"], in: app) + tapMenuItem(app.buttons["MobileNewWorkspaceMenuItem"], in: app) RunLoop.current.run(until: Date().addingTimeInterval(5)) await assertHostSelection( workspaceID: "workspace-3", terminalID: "workspace-3-terminal-1", server: server ) + let freshBackButton = app.buttons["MobileWorkspaceBackButton"] + let freshTitleMenu = workspaceTitleElement(in: app) + let freshUtilitiesMenu = app.buttons["MobileWorkspaceUtilitiesMenu"] assertWorkspaceToolbarVisible( backButton: freshBackButton, titleMenu: freshTitleMenu, - terminalDropdown: freshTerminalDropdown, + utilitiesMenu: freshUtilitiesMenu, in: app, - context: "fresh no-agent workspace after 5s" + context: "fresh single-terminal workspace after create" ) - assertMenuButtonDoesNotExist("MobileWorkspaceSettingsMenu", in: app) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].exists) assertToolbarOverflowButtonDoesNotExist(in: app) - assertBackButtonFrameStaysCompactAroundPress(freshBackButton, in: app) - - tap(app.buttons["MobileTerminalDropdown"], in: app) - assertTerminalMenuItemExists("workspace-3-terminal-1", in: app) - assertMenuButtonDoesNotExist("MobileWorkspaceTitleRenameMenuItem", in: app) - assertMenuButtonDoesNotExist("MobileWorkspaceTitleReadStateMenuItem", in: app) - assertMenuButtonDoesNotExist("MobileWorkspaceTitleCloseMenuItem", in: app) - tapMenuItem(app.buttons["MobileNewTerminalMenuItem"], in: app) - await assertHostSelection( - workspaceID: "workspace-3", - terminalID: "workspace-3-terminal-2", - server: server - ) - - tap(app.buttons["MobileTerminalDropdown"], in: app) - assertTerminalMenuItemExists("workspace-3-terminal-2", in: app) } @MainActor @@ -2996,12 +3337,12 @@ final class cmuxUITests: XCTestCase { let app = launchWorkspaceDetailDelayedTerminalPreviewApp() let backButton = app.buttons["MobileWorkspaceBackButton"] let titleMenu = workspaceTitleElement(in: app) - let terminalDropdown = app.buttons["MobileTerminalDropdown"] + let utilitiesMenu = app.buttons["MobileWorkspaceUtilitiesMenu"] assertWorkspaceToolbarVisible( backButton: backButton, titleMenu: titleMenu, - terminalDropdown: terminalDropdown, + utilitiesMenu: utilitiesMenu, in: app, context: "fresh no-agent workspace before delayed terminal" ) @@ -3012,7 +3353,7 @@ final class cmuxUITests: XCTestCase { assertWorkspaceToolbarVisible( backButton: backButton, titleMenu: titleMenu, - terminalDropdown: terminalDropdown, + utilitiesMenu: utilitiesMenu, in: app, context: "fresh no-agent workspace after delayed terminal appears" ) @@ -3020,35 +3361,35 @@ final class cmuxUITests: XCTestCase { assertToolbarOverflowButtonDoesNotExist(in: app) assertBackButtonFrameStaysCompactAroundPress(backButton, in: app) - tap(terminalDropdown, in: app) - assertTerminalMenuItemExists("terminal-delayed", in: app) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].exists) } @MainActor - func testWorkspaceDetailToolbarKeepsTerminalPickerVisibleWithLongTitle() throws { + func testWorkspaceDetailToolbarKeepsUtilitiesMenuVisibleWithLongTitle() throws { let app = launchWorkspaceDetailDelayedTerminalPreviewApp(environment: [ "CMUX_UITEST_WORKSPACE_DETAIL_LONG_TITLE": "1", ]) let backButton = app.buttons["MobileWorkspaceBackButton"] let titleMenu = workspaceTitleElement(in: app) - let terminalDropdown = app.buttons["MobileTerminalDropdown"] + let utilitiesMenu = app.buttons["MobileWorkspaceUtilitiesMenu"] RunLoop.current.run(until: Date().addingTimeInterval(2.5)) assertWorkspaceToolbarVisible( backButton: backButton, titleMenu: titleMenu, - terminalDropdown: terminalDropdown, + utilitiesMenu: utilitiesMenu, in: app, context: "long workspace title without chat toggle" ) XCTAssertFalse(app.buttons["MobileWorkspaceAgentChatButton"].exists) assertToolbarOverflowButtonDoesNotExist(in: app) - tap(terminalDropdown, in: app) - assertTerminalMenuItemExists("terminal-delayed", in: app) + tap(utilitiesMenu, in: app) + XCTAssertTrue(app.buttons["MobileViewAsTextMenuItem"].waitForExistence(timeout: 4)) } @MainActor - func testWorkspaceDetailToolbarKeepsTerminalPickerVisibleWithLongTitleAndChatToggle() throws { + func testWorkspaceDetailToolbarKeepsUtilitiesMenuVisibleWithLongTitleAndChatToggle() throws { let app = launchWorkspaceDetailDelayedTerminalPreviewApp(environment: [ "CMUX_UITEST_WORKSPACE_DETAIL_LONG_TITLE": "1", "CMUX_UITEST_WORKSPACE_DETAIL_CHAT_TOGGLE": "1", @@ -3056,38 +3397,36 @@ final class cmuxUITests: XCTestCase { let backButton = app.buttons["MobileWorkspaceBackButton"] let titleMenu = workspaceTitleElement(in: app) let chatButton = app.buttons["MobileWorkspaceAgentChatButton"] - let terminalDropdown = app.buttons["MobileTerminalDropdown"] + let utilitiesMenu = app.buttons["MobileWorkspaceUtilitiesMenu"] RunLoop.current.run(until: Date().addingTimeInterval(2.5)) assertWorkspaceToolbarVisible( backButton: backButton, titleMenu: titleMenu, - terminalDropdown: terminalDropdown, + utilitiesMenu: utilitiesMenu, in: app, context: "long workspace title with chat toggle" ) XCTAssertTrue(chatButton.waitForExistence(timeout: 4)) XCTAssertTrue(chatButton.isHittable) assertToolbarOverflowButtonDoesNotExist(in: app) - tap(terminalDropdown, in: app) - assertTerminalMenuItemExists("terminal-delayed", in: app) + XCTAssertTrue(utilitiesMenu.isHittable) } @MainActor func testWorkspaceDetailToolbarSurvivesCreateWorkspaceDelayedTerminalLifecycle() throws { let app = launchWorkspaceDetailCreateDelayedTerminalPreviewApp() - let initialTerminalDropdown = app.buttons["MobileTerminalDropdown"] - tap(initialTerminalDropdown, in: app) + tap(app.buttons["MobileSurfaceDeckAdd"], in: app) tapMenuItem(app.buttons["MobileNewWorkspaceMenuItem"], in: app) let backButton = app.buttons["MobileWorkspaceBackButton"] let titleMenu = workspaceTitleElement(in: app) - let terminalDropdown = app.buttons["MobileTerminalDropdown"] + let utilitiesMenu = app.buttons["MobileWorkspaceUtilitiesMenu"] assertWorkspaceToolbarVisible( backButton: backButton, titleMenu: titleMenu, - terminalDropdown: terminalDropdown, + utilitiesMenu: utilitiesMenu, in: app, context: "created no-agent workspace before delayed terminal" ) @@ -3098,7 +3437,7 @@ final class cmuxUITests: XCTestCase { assertWorkspaceToolbarVisible( backButton: backButton, titleMenu: titleMenu, - terminalDropdown: terminalDropdown, + utilitiesMenu: utilitiesMenu, in: app, context: "created no-agent workspace after delayed terminal appears" ) @@ -3106,12 +3445,12 @@ final class cmuxUITests: XCTestCase { assertToolbarOverflowButtonDoesNotExist(in: app) assertBackButtonFrameStaysCompactAroundPress(backButton, in: app) - tap(terminalDropdown, in: app) - assertTerminalMenuItemExists("workspace-3-terminal-1", in: app) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].exists) } @MainActor - func testTerminalDropdownScrollsLongTerminalList() async throws { + func testSurfaceDeckScrollsLongTerminalList() async throws { let server = try MobileSyncMockHostServer(additionalMainTerminalCount: 24) let port = try await server.start() defer { server.stop() } @@ -3119,24 +3458,22 @@ final class cmuxUITests: XCTestCase { let app = try launchConnectedApp(port: port) try openSelectedWorkspaceIfNeeded(app) - tap(app.buttons["MobileTerminalDropdown"], in: app) - assertTerminalMenuItemExists("terminal-build", in: app) - let target = scrollTerminalMenuToItem("terminal-extra-24", in: app) - tapMenuItem(target, in: app) + assertSurfaceDeckChipExists("terminal-build", in: app) + let target = scrollSurfaceDeckToChip("terminal-extra-24", in: app) + tap(target, in: app) await assertHostSelection(workspaceID: "workspace-main", terminalID: "terminal-extra-24", server: server) await assertTerminalReplay(terminalID: "terminal-extra-24", server: server) } @MainActor - func testTerminalDropdownKeepsBottomScrollDuringWorkspaceRefresh() throws { + func testSurfaceDeckKeepsBottomScrollDuringWorkspaceRefresh() throws { let app = launchWorkspaceDetailRefreshingTerminalMenuPreviewApp() - tap(app.buttons["MobileTerminalDropdown"], in: app) - assertTerminalMenuItemExists("terminal-build", in: app) - let target = scrollTerminalMenuToItem("terminal-extra-24", in: app) + assertSurfaceDeckChipExists("terminal-build", in: app) + let target = scrollSurfaceDeckToChip("terminal-extra-24", in: app) XCTAssertTrue(target.isHittable, "Bottom terminal must be visible before refresh pulses start.") - let refreshedTarget = app.buttons["MobileTerminalMenuItem-terminal-extra-24"] + let refreshedTarget = app.buttons["MobileSurfaceDeckChip-terminal-extra-24"] let deadline = Date().addingTimeInterval(3.0) while Date() < deadline { XCTAssertTrue( @@ -3145,16 +3482,12 @@ final class cmuxUITests: XCTestCase { ) RunLoop.current.run(until: Date().addingTimeInterval(0.1)) } - tapMenuItem(refreshedTarget, in: app) - let selectedValue = app.buttons["MobileTerminalDropdown"].value as? String ?? "" - XCTAssertTrue( - selectedValue.contains("Terminal 24"), - "Selecting the bottom terminal should update the picker value. value=\(selectedValue)" - ) + tap(refreshedTarget, in: app) + XCTAssertTrue(refreshedTarget.isSelected, "Selecting the bottom surface should mark its deck chip selected.") } @MainActor - func testTerminalDropdownSwitchesToAlternateScreenSnapshot() async throws { + func testSurfaceDeckSwitchesToAlternateScreenSnapshot() async throws { let server = try MobileSyncMockHostServer() let port = try await server.start() defer { server.stop() } @@ -3162,8 +3495,7 @@ final class cmuxUITests: XCTestCase { let app = try launchConnectedApp(port: port) try openSelectedWorkspaceIfNeeded(app) - tap(app.buttons["MobileTerminalDropdown"], in: app) - tapMenuItem(app.buttons["MobileTerminalMenuItem-terminal-tui"], in: app) + tap(app.buttons["MobileSurfaceDeckChip-terminal-tui"], in: app) await assertHostSelection(workspaceID: "workspace-main", terminalID: "terminal-tui", server: server) await assertTerminalReplay(terminalID: "terminal-tui", server: server) @@ -4669,7 +5001,7 @@ final class cmuxUITests: XCTestCase { "CMUX_MOBILE_SOAK_OPEN_SELECTED_WORKSPACE": "1", ]) XCTAssertTrue(workspaceTitleElement(in: app).waitForExistence(timeout: 8)) - XCTAssertTrue(app.buttons["MobileTerminalDropdown"].waitForExistence(timeout: 8)) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 8)) return app } @@ -4685,7 +5017,7 @@ final class cmuxUITests: XCTestCase { row.tap() } XCTAssertTrue(workspaceTitleElement(in: app).waitForExistence(timeout: 8)) - XCTAssertTrue(app.buttons["MobileTerminalDropdown"].waitForExistence(timeout: 8)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].waitForExistence(timeout: 8)) return app } @@ -4805,8 +5137,7 @@ final class cmuxUITests: XCTestCase { file: StaticString = #filePath, line: UInt = #line ) async throws { - tap(app.buttons["MobileTerminalDropdown"], in: app, file: file, line: line) - tapMenuItem(app.buttons["MobileTerminalMenuItem-terminal-tui"], in: app, file: file, line: line) + tap(app.buttons["MobileSurfaceDeckChip-terminal-tui"], in: app, file: file, line: line) await assertHostSelection( workspaceID: "workspace-main", terminalID: "terminal-tui", @@ -4850,16 +5181,16 @@ final class cmuxUITests: XCTestCase { } @MainActor - private func assertTerminalMenuItemExists( + private func assertSurfaceDeckChipExists( _ terminalID: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line ) { - let item = app.buttons["MobileTerminalMenuItem-\(terminalID)"] + let item = app.buttons["MobileSurfaceDeckChip-\(terminalID)"] XCTAssertTrue( item.waitForExistence(timeout: 4), - "Expected terminal menu to contain \(terminalID).", + "Expected surface deck to contain \(terminalID).", file: file, line: line ) @@ -4896,22 +5227,23 @@ final class cmuxUITests: XCTestCase { } @MainActor - private func scrollTerminalMenuToItem( + private func scrollSurfaceDeckToChip( _ terminalID: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line ) -> XCUIElement { - let item = app.buttons["MobileTerminalMenuItem-\(terminalID)"] + let item = app.buttons["MobileSurfaceDeckChip-\(terminalID)"] + let deck = app.descendants(matching: .any)["MobileSurfaceDeck"].firstMatch let deadline = Date().addingTimeInterval(8) while Date() < deadline { if item.exists, item.isHittable { return item } - app.swipeUp(velocity: .slow) + deck.swipeLeft(velocity: .slow) RunLoop.current.run(until: Date().addingTimeInterval(0.15)) } - XCTFail("Expected terminal menu to scroll to \(terminalID).", file: file, line: line) + XCTFail("Expected surface deck to scroll to \(terminalID).", file: file, line: line) return item } @@ -5146,6 +5478,58 @@ final class cmuxUITests: XCTestCase { element.identifier.hasPrefix("MobileAddDevice") } + private func waitForPaneMap( + _ overlay: XCUIElement, + in app: XCUIApplication, + toBeActive isActive: Bool, + // Returning to the terminal re-presents its full-screen cover and + // rebuilds the terminal subtree, which takes 15+ seconds on a + // saturated CI runner (the old stack pop restored a retained view + // instantly). Presence waits are wait-until, so fast runs are + // unaffected; negative checks pass explicit short timeouts. + timeout: TimeInterval = 20 + ) -> Bool { + // The background marker spans the pane map but is intentionally behind + // every card. Its XCUI `isHittable` value therefore depends on whether + // the current device's center point lands on a card after relayout. + // Use the mode-specific shared-toolbar item as the stable presentation + // endpoint, while still requiring the pane-map subtree to exist. + // Hittability is only required on the active (pane-map) side: the + // terminal's toolbar lives in a full-screen cover, and toolbar items + // inside a presented cover never report hittable to XCUI on the CI + // simulator runtime even though real taps land (the shared tap helper + // falls back to frame coordinates for exactly that reason). + let modeControl = app.buttons[ + isActive ? "MobilePaneMapRefresh" : "MobileWorkspaceUtilitiesMenu" + ] + let expectation = XCTNSPredicateExpectation( + predicate: NSPredicate( + block: { _, _ in + modeControl.exists + && (!isActive || modeControl.isHittable) + && (isActive ? overlay.exists : !overlay.exists) + && (isActive || !app.buttons["MobilePaneMapRefresh"].exists) + } + ), + object: modeControl + ) + let completed = XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed + if !completed { + // The failed condition is invisible in CI logs (the xcresult is + // not uploaded); dump the tree so the blocking element is named. + print( + """ + waitForPaneMap(toBeActive: \(isActive)) timed out after \(timeout)s + modeControl.exists=\(modeControl.exists) overlay.exists=\(overlay.exists) \ + refresh.exists=\(app.buttons["MobilePaneMapRefresh"].exists) + AX tree: + \(app.debugDescription) + """ + ) + } + return completed + } + @MainActor private func tap( _ element: XCUIElement, @@ -5397,7 +5781,7 @@ final class cmuxUITests: XCTestCase { private func assertWorkspaceToolbarVisible( backButton: XCUIElement, titleMenu: XCUIElement, - terminalDropdown: XCUIElement, + utilitiesMenu: XCUIElement, in app: XCUIApplication, context: String, file: StaticString = #filePath, @@ -5405,12 +5789,12 @@ final class cmuxUITests: XCTestCase { ) { XCTAssertTrue(backButton.waitForExistence(timeout: 4), "\(context): missing back button", file: file, line: line) XCTAssertTrue(titleMenu.waitForExistence(timeout: 4), "\(context): missing title menu", file: file, line: line) - XCTAssertTrue(terminalDropdown.waitForExistence(timeout: 4), "\(context): missing terminal dropdown", file: file, line: line) + XCTAssertTrue(utilitiesMenu.waitForExistence(timeout: 4), "\(context): missing utilities menu", file: file, line: line) XCTAssertTrue( waitForCompactToolbarHeightsToMatch( titleMenu: titleMenu, backButton: backButton, - surfacePicker: terminalDropdown, + surfacePicker: utilitiesMenu, tolerance: 2, timeout: 4, file: file, @@ -5500,6 +5884,66 @@ final class cmuxUITests: XCTestCase { return waitForUsableFrame(of: element, timeout: 0.1) } + private func assertToolbarFrame( + _ frame: CGRect, + matches expected: CGRect, + accuracy: CGFloat = 1, + context: String, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + frame.minX, expected.minX, accuracy: accuracy, + "\(context) x shifted", file: file, line: line + ) + XCTAssertEqual( + frame.minY, expected.minY, accuracy: accuracy, + "\(context) y shifted", file: file, line: line + ) + XCTAssertEqual( + frame.width, expected.width, accuracy: accuracy, + "\(context) width changed", file: file, line: line + ) + XCTAssertEqual( + frame.height, expected.height, accuracy: accuracy, + "\(context) height changed", file: file, line: line + ) + } + + private func assertFramesRemainStable( + _ elements: [XCUIElement], + for duration: TimeInterval, + accuracy: CGFloat, + context: String, + file: StaticString = #filePath, + line: UInt = #line + ) { + let expectedFrames = elements.map(\.frame) + let movement = XCTNSPredicateExpectation( + predicate: NSPredicate( + block: { _, _ in + zip(elements, expectedFrames).contains { pair in + let (element, expected) = pair + let frame = element.frame + return abs(frame.minX - expected.minX) > accuracy + || abs(frame.minY - expected.minY) > accuracy + || abs(frame.width - expected.width) > accuracy + || abs(frame.height - expected.height) > accuracy + } + } + ), + object: elements + ) + movement.isInverted = true + XCTAssertEqual( + XCTWaiter.wait(for: [movement], timeout: duration), + .completed, + "\(context) moved after the transition endpoint. initial=\(expectedFrames) current=\(elements.map(\.frame))", + file: file, + line: line + ) + } + @MainActor private func waitForWorkspaceTitleCenteredAndSeparated( titleMenu: XCUIElement, @@ -7167,6 +7611,9 @@ private final class MobileSyncMockHostServer: @unchecked Sendable { private let supportsManualAttachTicket: Bool private let workspaceCreateSelectsCreatedWorkspace: Bool private let macInstanceTag: String + /// When set, `workspace-main` syncs a two-pane split layout so the + /// production shell mounts the pane-zoom presentation for it. + private let mainWorkspacePaneLayout: Bool private var readyContinuation: CheckedContinuation? private var connections: [NWConnection] = [] private var selectedWorkspaceID = "workspace-main" @@ -7230,13 +7677,15 @@ private final class MobileSyncMockHostServer: @unchecked Sendable { createdWorkspaceTerminalDelay: TimeInterval? = nil, supportsManualAttachTicket: Bool = false, workspaceCreateSelectsCreatedWorkspace: Bool = true, - macInstanceTag: String = mockHostInstanceTag() + macInstanceTag: String = mockHostInstanceTag(), + mainWorkspacePaneLayout: Bool = false ) throws { listener = try NWListener(using: .tcp, on: .any) self.createdWorkspaceTerminalDelay = createdWorkspaceTerminalDelay self.supportsManualAttachTicket = supportsManualAttachTicket self.workspaceCreateSelectsCreatedWorkspace = workspaceCreateSelectsCreatedWorkspace self.macInstanceTag = macInstanceTag + self.mainWorkspacePaneLayout = mainWorkspacePaneLayout appendMainTerminals(count: additionalMainTerminalCount) // Optionally replace the selected terminal's content (used by the // color-band render test so the bands stream on attach without a flaky @@ -7749,7 +8198,7 @@ private final class MobileSyncMockHostServer: @unchecked Sendable { private func workspaceListResult() -> [String: Any] { [ "workspaces": workspaces.map { workspace in - [ + var entry: [String: Any] = [ "id": workspace.id, "title": workspace.title, "current_directory": workspace.currentDirectory, @@ -7762,11 +8211,55 @@ private final class MobileSyncMockHostServer: @unchecked Sendable { "is_focused": terminal.id == selectedTerminalID, ] as [String: Any] }, - ] as [String: Any] + ] + if mainWorkspacePaneLayout, workspace.id == "workspace-main" { + entry["layout"] = Self.mainWorkspacePaneLayoutPayload() + } + return entry }, ] } + /// The `layout` wire payload for `workspace-main`: a horizontal split of + /// two single-surface panes matching the fixture terminals, in the same + /// `kind`-discriminated snake_case shape the Mac emits. + private static func mainWorkspacePaneLayoutPayload() -> [String: Any] { + [ + "version": 1, + "focused_pane_id": "pane-main-left", + "root": [ + "kind": "split", + "id": "split-main-root", + "orientation": "horizontal", + "ratio": 0.5, + "first": [ + "kind": "pane", + "id": "pane-main-left", + "selected_surface_id": "terminal-build", + "surfaces": [ + [ + "id": "terminal-build", + "type": "terminal", + "title": "Build", + ] as [String: Any], + ], + ] as [String: Any], + "second": [ + "kind": "pane", + "id": "pane-main-right", + "selected_surface_id": "terminal-tui", + "surfaces": [ + [ + "id": "terminal-tui", + "type": "terminal", + "title": "TUI", + ] as [String: Any], + ], + ] as [String: Any], + ] as [String: Any], + ] + } + func overrideCursor(workspaceID: String, terminalID: String, row: Int, column: Int, isVisible: Bool) { queue.async { [weak self] in self?.cursorOverrides["\(workspaceID)/\(terminalID)"] = CursorOverride(row: row, column: column, isVisible: isVisible)