From b6b780e5396da335339599923d2dd9ca04e5ddb8 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 15 Jul 2026 14:00:49 -0700 Subject: [PATCH 01/78] Serialize bonsplit pane layout into mobile workspace list (layout.v1) Adds a layout object per workspace to mobile.workspace.list: the recursive bonsplit split tree (orientation + divider ratio) and per-pane surface tabs (panel UUID, panelType, title, selected tab), gated by the new workspace.layout.v1 capability. The list observer's summary hash now covers pane topology (pane ids, per-pane tab order, selected tab) while still excluding split ratios and focus-only changes. Co-Authored-By: Claude Fable 5 --- .../MobileHostService+Capabilities.swift | 1 + .../Mobile/MobileWorkspaceListObserver.swift | 17 +- ...rminalController+MobileWorkspaceList.swift | 118 +++++++++++++ .../MobileWorkspaceListFidelityTests.swift | 165 +++++++++++++++++- 4 files changed, 295 insertions(+), 6 deletions(-) diff --git a/Sources/Mobile/MobileHostService+Capabilities.swift b/Sources/Mobile/MobileHostService+Capabilities.swift index 6303d0d6a008..27d7adaea71b 100644 --- a/Sources/Mobile/MobileHostService+Capabilities.swift +++ b/Sources/Mobile/MobileHostService+Capabilities.swift @@ -40,6 +40,7 @@ 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", ] #if DEBUG // Lets a dev Mac impersonate an older host while dogfooding the iOS update hint. diff --git a/Sources/Mobile/MobileWorkspaceListObserver.swift b/Sources/Mobile/MobileWorkspaceListObserver.swift index 96dd34ad9297..1c206137218b 100644 --- a/Sources/Mobile/MobileWorkspaceListObserver.swift +++ b/Sources/Mobile/MobileWorkspaceListObserver.swift @@ -234,9 +234,11 @@ final class MobileWorkspaceListObserver { /// 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 `layout.v1` pane topology. The topology hashes pane ids in + /// DFS order, each pane's surface-id order, and each pane's selected tab. It + /// deliberately excludes split ratios, so divider drags don't spam events, + /// and keeps excluding `focusedPanelId` itself. Scrollback content and focus + /// changes with no other list-facing effect also remain 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, @@ -289,6 +291,15 @@ final class MobileWorkspaceListObserver { hasher.combine(workspace.panelTitle(panelId: id)) hasher.combine(workspace.reportedPanelDirectory(panelId: id)) } + let paneTopology = MobileWorkspaceLayoutSerializer.paneTopology( + in: workspace.bonsplitController.treeSnapshot() + ) + hasher.combine(paneTopology.count) + for pane in paneTopology { + hasher.combine(pane.id) + hasher.combine(pane.surfaceIDs) + hasher.combine(pane.selectedSurfaceID) + } 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 cc1e6ca6754d..c1038a9bcd78 100644 --- a/Sources/TerminalController+MobileWorkspaceList.swift +++ b/Sources/TerminalController+MobileWorkspaceList.swift @@ -1,4 +1,5 @@ import AppKit +import Bonsplit import CmuxWorkspaces import Foundation @@ -8,6 +9,102 @@ 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. + +/// Pure serialization of bonsplit's external tree into the mobile `layout.v1` +/// dictionary shape. +struct MobileWorkspaceLayoutSerializer { + struct SurfaceMetadata { + let id: String + let type: String + let title: String + } + + struct PaneTopology { + let id: String + let surfaceIDs: [String] + let selectedSurfaceID: String? + } + + static func payload( + tree: ExternalTreeNode, + version: Int, + focusedPaneID: String?, + surfacesByTabID: [String: SurfaceMetadata] + ) -> [String: Any] { + [ + "version": version, + "focused_pane_id": jsonValue(focusedPaneID), + "root": nodePayload(tree, surfacesByTabID: surfacesByTabID), + ] + } + + static func tabs(in tree: ExternalTreeNode) -> [ExternalTab] { + switch tree { + case .pane(let pane): + return pane.tabs + case .split(let split): + return tabs(in: split.first) + tabs(in: split.second) + } + } + + static func paneTopology(in tree: ExternalTreeNode) -> [PaneTopology] { + switch tree { + case .pane(let pane): + return [PaneTopology( + id: pane.id, + surfaceIDs: pane.tabs.map(\.id), + selectedSurfaceID: pane.selectedTabId + )] + case .split(let split): + return paneTopology(in: split.first) + paneTopology(in: split.second) + } + } + + private static func nodePayload( + _ node: ExternalTreeNode, + surfacesByTabID: [String: SurfaceMetadata] + ) -> [String: Any] { + switch node { + case .pane(let pane): + let surfaces = pane.tabs.map { tab -> [String: Any] in + let metadata = surfacesByTabID[tab.id] ?? SurfaceMetadata( + id: tab.id, + type: PanelType.terminal.rawValue, + title: tab.title + ) + return [ + "id": metadata.id, + "type": metadata.type, + "title": metadata.title, + ] + } + let selectedSurfaceID = pane.selectedTabId.map { tabID in + surfacesByTabID[tabID]?.id ?? tabID + } + return [ + "kind": "pane", + "id": pane.id, + "selected_surface_id": jsonValue(selectedSurfaceID), + "surfaces": surfaces, + ] + case .split(let split): + return [ + "kind": "split", + "id": split.id, + "orientation": split.orientation, + "ratio": split.dividerPosition, + "first": nodePayload(split.first, surfacesByTabID: surfacesByTabID), + "second": nodePayload(split.second, surfacesByTabID: surfacesByTabID), + ] + } + } + + private static func jsonValue(_ value: String?) -> Any { + guard let value else { return NSNull() } + return value + } +} + extension TerminalController { /// Mobile-gated collapse/expand of a workspace group. P1 group support on /// iOS is display-only: the phone renders collapsible group sections and can @@ -209,6 +306,26 @@ extension TerminalController { ] } + let layoutTree = workspace.bonsplitController.treeSnapshot() + var layoutSurfacesByTabID: [String: MobileWorkspaceLayoutSerializer.SurfaceMetadata] = [:] + for tab in MobileWorkspaceLayoutSerializer.tabs(in: layoutTree) { + let panelID = UUID(uuidString: tab.id).flatMap { workspace.panelId(forSurfaceId: $0) } + let panel = panelID.flatMap { workspace.panels[$0] } + layoutSurfacesByTabID[tab.id] = MobileWorkspaceLayoutSerializer.SurfaceMetadata( + id: panelID?.uuidString ?? tab.id, + type: panel?.panelType.rawValue ?? PanelType.terminal.rawValue, + title: panelID.flatMap { workspace.panelTitle(panelId: $0) } + ?? panel?.displayTitle + ?? tab.title + ) + } + let layout = MobileWorkspaceLayoutSerializer.payload( + tree: layoutTree, + version: workspace.paneLayoutVersion, + focusedPaneID: workspace.bonsplitController.focusedPaneId?.id.uuidString, + surfacesByTabID: layoutSurfacesByTabID + ) + let store = notificationStore ?? AppDelegate.shared?.notificationStore let latestNotification = store?.latestNotification(forTabId: workspace.id) let preview = Self.mobileWorkspacePreview(latestNotification: latestNotification) @@ -237,6 +354,7 @@ extension TerminalController { // unread + manual/panel-derived/restored indicators) so the phone can // show an iMessage-style unread dot. "has_unread": store?.workspaceIsUnread(forTabId: workspace.id) ?? false, + "layout": layout, "terminals": terminals ] } diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index 5412621dd059..b7713213a7bd 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -2,6 +2,7 @@ import Testing import AppKit import Bonsplit import CmuxCore +import Foundation #if canImport(cmux_DEV) @testable import cmux_DEV @@ -9,9 +10,8 @@ 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. @@ -51,6 +51,111 @@ 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")) + } + @Test func orderedPanelIdsMatchesBonsplitSpatialOrder() throws { let (workspace, createdOrder) = try makeWorkspaceWithSplitTerminals(count: 3) @@ -71,6 +176,8 @@ struct MobileWorkspaceListFidelityTests { 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], @@ -80,6 +187,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 @@ -100,6 +208,57 @@ 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 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) From c76eb706a513edcd6a5a2ed4115d841755fbb6cd Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 15 Jul 2026 14:04:17 -0700 Subject: [PATCH 02/78] Decode mobile pane layout into iOS value models MobilePaneLayout mirrors the layout.v1 wire shape: recursive split/pane nodes with per-pane surfaces (type-aware, forward-compatible other case), plus pure helpers for DFS pane order, surface lookup, and unit-space pane rectangles. Decoding is tolerant: a malformed or missing layout leaves the workspace usable with layout nil. Co-Authored-By: Claude Fable 5 --- .../MobileSyncWorkspaceListResponse.swift | 118 ++++++++++++ ...MobileWorkspacePreview+RemoteMapping.swift | 86 ++++++++- .../MobilePaneLayoutDecodeTests.swift | 175 ++++++++++++++++++ .../MobilePaneLayout.swift | 115 ++++++++++++ .../CmuxMobileShellModel/MobilePaneNode.swift | 20 ++ .../MobilePaneSplit.swift | 34 ++++ .../MobilePaneSplitOrientation.swift | 7 + .../MobilePaneSurface.swift | 20 ++ .../MobilePaneSurfaceType.swift | 35 ++++ .../MobileWorkspacePreview.swift | 15 +- .../MobilePaneLayoutTests.swift | 115 ++++++++++++ 11 files changed, 734 insertions(+), 6 deletions(-) create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneLayout.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneNode.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplitOrientation.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurface.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSurfaceType.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift index 73a2da2ca417..47c98e91710f 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift @@ -41,6 +41,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: Layout? private enum CodingKeys: String, CodingKey { case id @@ -55,6 +57,122 @@ 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) + 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(Layout.self, forKey: .layout) + } + } + + /// A wire-level workspace pane layout snapshot. + public struct Layout: Decodable, Sendable { + /// A recursively decoded layout node. + public indirect enum Node: Decodable, Sendable { + /// A split branch with two child nodes. + case split(Split) + /// A leaf pane containing surface tabs. + case pane(Pane) + + private enum CodingKeys: String, CodingKey { + case kind + } + + private enum Kind: String, Decodable { + case split + case pane + } + + /// Decodes a layout node based on its `kind` discriminator. + /// - Parameter decoder: The decoder for one layout node. + /// - Throws: A decoding error for unknown kinds or malformed node data. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let kind = try container.decode(Kind.self, forKey: .kind) + switch kind { + case .split: + self = try .split(Split(from: decoder)) + case .pane: + self = try .pane(Pane(from: decoder)) + } + } + } + + /// A wire-level split branch. + public struct Split: Decodable, Sendable { + /// A split orientation emitted by bonsplit. + public enum Orientation: String, Decodable, Sendable { + /// Places children side by side. + case horizontal + /// Stacks children vertically. + case vertical + } + + /// The stable split identifier. + public let id: String + /// The axis along which this split divides its rectangle. + public let orientation: Orientation + /// The first child's proportional share. + public let ratio: Double + /// The first child node. + public let first: Node + /// The second child node. + public let second: Node + } + + /// A wire-level leaf pane. + public struct Pane: Decodable, Sendable { + /// The stable pane identifier. + public let id: String + /// The selected surface identifier, when one is selected. + public let selectedSurfaceID: String? + /// The pane's surfaces in tab order. + public let surfaces: [Surface] + + private enum CodingKeys: String, CodingKey { + case id + case selectedSurfaceID = "selected_surface_id" + case surfaces + } + } + + /// A wire-level surface tab. + public struct Surface: Decodable, Sendable { + /// The stable surface identifier. + public let id: String + /// The raw panel type emitted by the Mac. + public let type: String + /// The surface's display title. + public let title: String + } + + /// The Mac-side pane layout version. + public let version: Int + /// The focused pane identifier, when one is focused. + public let focusedPaneID: String? + /// The root of the recursive layout tree. + public let root: Node + + private enum CodingKeys: String, CodingKey { + case version + case focusedPaneID = "focused_pane_id" + case root } } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift index 9576d4c2270a..eec09d8b3d2e 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift @@ -17,11 +17,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: MobileSyncWorkspaceListResponse.Layout) { + self.init( + version: remote.version, + focusedPaneID: remote.focusedPaneID, + root: Node(remote: remote.root) + ) + } +} + +private extension MobilePaneLayout.Node { + init(remote: MobileSyncWorkspaceListResponse.Layout.Node) { + 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: MobileSyncWorkspaceListResponse.Layout.Split) { + self.init( + id: remote.id, + orientation: MobilePaneSplitOrientation(remote: remote.orientation), + ratio: min(max(remote.ratio, 0.05), 0.95), + first: MobilePaneLayout.Node(remote: remote.first), + second: MobilePaneLayout.Node(remote: remote.second) + ) + } +} + +private extension MobilePaneSplitOrientation { + init(remote: MobileSyncWorkspaceListResponse.Layout.Split.Orientation) { + switch remote { + case .horizontal: + self = .horizontal + case .vertical: + self = .vertical + } + } +} + +private extension MobilePaneNode { + init(remote: MobileSyncWorkspaceListResponse.Layout.Pane) { + self.init( + id: remote.id, + selectedSurfaceID: remote.selectedSurfaceID, + surfaces: remote.surfaces.map(MobilePaneSurface.init(remote:)) + ) + } +} + +private extension MobilePaneSurface { + init(remote: MobileSyncWorkspaceListResponse.Layout.Surface) { + 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..4621e7fea25f --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift @@ -0,0 +1,175 @@ +import CmuxMobileShellModel +import Foundation +import Testing + +@testable import CmuxMobileRPC + +@Suite struct MobilePaneLayoutDecodeTests { + @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/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..edf9a2230dd9 --- /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` by RPC mapping. + 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 + 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/MobileWorkspacePreview.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspacePreview.swift index 1a0fbfac6c0b..9cfddc8f3564 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 { @@ -75,6 +75,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` @@ -113,6 +115,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, @@ -125,7 +128,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 @@ -140,5 +144,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..bd36b9204a35 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift @@ -0,0 +1,115 @@ +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 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 surface( + _ id: String, + type: MobilePaneSurfaceType + ) -> MobilePaneSurface { + MobilePaneSurface(id: id, type: type, title: id) + } +} From 27db84d2ce8ae55e9102321bc5290a8da76292fa Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 15 Jul 2026 14:23:59 -0700 Subject: [PATCH 03/78] Replace iOS terminal picker menu with pane-grouped surface deck The top-right terminal dropdown is gone. A persistent bottom deck now shows every surface in the workspace, chips grouped by Mac pane (from layout.v1), with type icons, agent-status dots (working/needs-input via chat sessions), one-tap stream switching, a + menu (terminal/browser/workspace), and a pane-map button. Remaining utilities (View as Text, Copy Debug Logs, Send Feedback) move to a slim ellipsis menu. Deck visibility branches inside the safe-area inset so the terminal/chat/browser subtree keeps stable structural identity; keyboard covers the deck instead of lifting it. All new strings localized en+ja; XCUITest coverage ported from the dropdown to the deck. Co-Authored-By: Claude Fable 5 --- .../ChatAgentStateKind.swift | 5 + .../CmuxMobileShellUI/PaneMapOverlay.swift | 38 +++ .../SurfaceDeckActions.swift | 10 + .../CmuxMobileShellUI/SurfaceDeckBar.swift | 253 ++++++++++++++++++ .../CmuxMobileShellUI/SurfaceDeckValue.swift | 63 +++++ .../TerminalPickerMenu.swift | 114 -------- .../TerminalPickerMenuActions.swift | 12 - .../TerminalPickerMenuDiagnostics.swift | 41 --- .../TerminalPickerMenuValue.swift | 30 --- ...tailCreateDelayedTerminalPreviewView.swift | 1 + .../WorkspaceDetailView+AgentChat.swift | 2 +- .../WorkspaceDetailView+MenuState.swift | 67 ----- .../WorkspaceDetailView.swift | 118 +++++--- .../WorkspaceUtilitiesMenu.swift | 49 ++++ .../SurfaceDeckValueTests.swift | 117 ++++++++ .../TerminalPickerMenuValueTests.swift | 92 ------- ios/cmux/Resources/Localizable.xcstrings | 91 +++++++ ios/cmuxUITests/cmuxUITests.swift | 152 +++++------ 18 files changed, 773 insertions(+), 482 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/ChatAgentStateKind.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckActions.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift delete mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift delete mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuActions.swift delete mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuDiagnostics.swift delete mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuValue.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift delete mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalPickerMenuValueTests.swift 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/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift new file mode 100644 index 000000000000..30189a4df27a --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -0,0 +1,38 @@ +import CmuxMobileSupport +import SwiftUI + +/// Slice 3's pane-map shell; Slice 4 supplies the proportional pane canvas. +struct PaneMapOverlay: View { + let workspaceName: String + let dismiss: () -> Void + + var body: some View { + VStack(spacing: 0) { + HStack { + Text(workspaceName) + .font(.headline) + .foregroundStyle(TerminalPalette.foreground) + .lineLimit(1) + + Spacer(minLength: 12) + + Button(action: dismiss) { + Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(TerminalPalette.foreground) + .padding(.horizontal, 14) + .frame(height: 34) + .mobileGlassPill() + } + .buttonStyle(.plain) + .accessibilityIdentifier("MobilePaneMapDone") + } + .padding(16) + + Spacer() + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(TerminalPalette.background.ignoresSafeArea()) + .accessibilityIdentifier("MobilePaneMapOverlay") + } +} 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..85966da6801c --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -0,0 +1,253 @@ +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 + var clock: any Clock = ContinuousClock() + + @State private var unavailableHintID: UUID? + + nonisolated static func == (lhs: Self, rhs: Self) -> Bool { + lhs.value == rhs.value + } + + 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(TerminalPalette.foreground) + .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) + .accessibilityElement(children: .contain) + .accessibilityLabel(L10n.string("mobile.surfaceDeck.label", defaultValue: "Workspace surfaces")) + .accessibilityIdentifier("MobileSurfaceDeck") + } + + @ViewBuilder + private var deckSurface: some View { + if #available(iOS 26.0, *) { + GlassEffectContainer(spacing: 8) { + deckContent + } + } else { + deckContent + .background(.bar) + } + } + + 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) + } + } + .padding(2) + .frame(height: 36) + .mobileGlassPill() + } + + private func surfaceChip(_ chip: SurfaceDeckValue.Chip) -> 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(.system(size: 12, weight: .medium)) + + Text(chip.title) + .font(.system(size: 13, weight: .medium)) + .lineLimit(1) + .frame(maxWidth: 96) + } + .foregroundStyle( + isSelected + ? TerminalPalette.foreground + : TerminalPalette.foreground.opacity(0.72) + ) + .padding(.horizontal, 9) + .frame(height: 32) + .background { + if isSelected { + Capsule().fill(TerminalPalette.foreground.opacity(0.16)) + } + } + .contentShape(Capsule()) + } + .buttonStyle(.plain) + .opacity(chip.isTerminal ? 1 : 0.5) + .id(chip.id) + .accessibilityLabel(chipAccessibilityLabel(chip)) + .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)) + .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)) + .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) -> String { + if chip.isTerminal { + return String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.terminal", + defaultValue: "%@, terminal" + ), + chip.title + ) + } + return String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.unavailable", + defaultValue: "%@, unavailable on iPhone" + ), + chip.title + ) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift new file mode 100644 index 000000000000..20b063472b15 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift @@ -0,0 +1,63 @@ +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 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 { + groups = layout.orderedPanes.map { pane in + PaneGroup( + id: pane.id, + chips: pane.surfaces.map { surface in + Chip(id: surface.id, title: surface.title, type: surface.type) + } + ) + } + } else { + groups = [ + PaneGroup( + id: workspace.id.rawValue, + 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 + } + + var shouldShow: Bool { + let surfaceCount = groups.reduce(into: 0) { count, group in + count += group.chips.count + } + return surfaceCount > 1 || groups.count > 1 + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift deleted file mode 100644 index b53aa71988d2..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenu.swift +++ /dev/null @@ -1,114 +0,0 @@ -import CmuxMobileSupport -import SwiftUI - -/// Snapshot-isolated native menu for switching the active workspace surface. -struct TerminalPickerMenu: View, Equatable { - let value: TerminalPickerMenuValue - let actions: TerminalPickerMenuActions - #if DEBUG - private let diagnostics = TerminalPickerMenuDiagnostics() - #endif - - nonisolated static func == (lhs: Self, rhs: Self) -> Bool { - lhs.value == rhs.value - } - - var body: some View { - Menu { - instrumentedMenuContent - } label: { - Label( - value.selectedName ?? L10n.string("mobile.terminal.select", defaultValue: "Terminal"), - systemImage: "rectangle.stack" - ) - .labelStyle(.iconOnly) - } - .foregroundStyle(TerminalPalette.foreground) - .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 - ? "checkmark.circle.fill" - : "terminal" - ) - } - .accessibilityIdentifier("MobileTerminalMenuItem-\(terminal.id.rawValue)") - } - } - - 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 d067993e9e70..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuActions.swift +++ /dev/null @@ -1,12 +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 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 caf7497ad87b..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/TerminalPickerMenuValue.swift +++ /dev/null @@ -1,30 +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 - - init( - liveTerminals: [MobileTerminalPreview], - snapshotRows: [TerminalPickerMenuRow], - selectedID: MobileTerminalPreview.ID?, - canCreateWorkspace: Bool, - hasActiveBrowser: Bool, - isChatMode: Bool - ) { - 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 - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift index ddd7a9d00b6e..e38337935b63 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailCreateDelayedTerminalPreviewView.swift @@ -18,6 +18,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 beea8b180b0e..99be7feeadeb 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 { workspace.actionCapabilities.supportsWorkspaceActions || workspace.actionCapabilities.supportsReadStateActions diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 147b90cee246..c41b6783a61d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -43,7 +43,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 = "" @@ -51,7 +51,7 @@ 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] = [] + @State private var isPaneMapPresented = 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 @@ -92,7 +92,30 @@ struct WorkspaceDetailView: View { let content = Group { detailSurfaceContent } #if os(iOS) - content + let deckValue = surfaceDeckValue + // Deck visibility must not change the content subtree's structural + // identity: branching around `content` would remount the terminal + // surface (and the chat/browser ZStack) every time the deck toggles. + // The branch lives inside the inset builder instead, and the + // keyboard-region parameter is data, not structure. + let showDeck = activeSurface == .terminal && deckValue.shouldShow + let contentWithSurfaceDeck = content + .safeAreaInset(edge: .bottom, spacing: 0) { + if showDeck { + SurfaceDeckBar( + value: deckValue, + actions: surfaceDeckActions + ) + .equatable() + } + } + // The terminal owns keyboard geometry. Ignoring keyboard avoidance + // while the deck shows keeps the deck at the physical bottom so the + // keyboard covers it instead of lifting it; chat/browser modes keep + // normal avoidance. + .ignoresSafeArea(showDeck ? .keyboard : [], edges: .bottom) + + contentWithSurfaceDeck .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(systemNavigationTitle) .mobileTerminalNavigationChrome() @@ -102,7 +125,6 @@ struct WorkspaceDetailView: View { .onChange(of: selectedTerminalID) { _, _ in visibleArtifactCount = 0 refreshCachedChatToggleAnchor() - syncTerminalPickerRows(includeTitleChanges: true) } .onChange(of: store.supportsTerminalArtifacts) { _, supportsArtifacts in visibleArtifactCount = 0 @@ -120,6 +142,11 @@ struct WorkspaceDetailView: View { .sheet(isPresented: $isTextSheetPresented) { TerminalTextSheetView(surfaceID: textSheetSurfaceID) } + .fullScreenCover(isPresented: $isPaneMapPresented) { + PaneMapOverlay(workspaceName: workspace.name) { + isPaneMapPresented = false + } + } .workspaceRenameDialog( isPresented: $isRenamePresented, text: $renameText, @@ -324,7 +351,6 @@ struct WorkspaceDetailView: View { @ViewBuilder private var terminalToolbarButtons: some View { newWorkspaceToolbarButton - terminalPickerToolbarButton } #if os(iOS) @@ -364,36 +390,52 @@ 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 - ), - actions: TerminalPickerMenuActions( - selectTerminal: selectTerminalFromPicker, - createWorkspace: createWorkspaceFromToolbar, - createTerminal: createTerminalFromToolbar, - openBrowser: openBrowserFromToolbar, - openTextSheet: openTextSheetFromMenu, - copyDebugLogs: { - #if DEBUG - copyDebugLogsFromMenu() - #endif - }, - sendFeedback: openFeedbackComposerFromMenu - ) + var workspaceUtilitiesToolbarButton: some View { + WorkspaceUtilitiesMenu( + showsViewAsText: activeBrowser == nil && !isChatMode, + openTextSheet: openTextSheetFromMenu, + copyDebugLogs: { + #if DEBUG + copyDebugLogsFromMenu() + #endif + }, + sendFeedback: openFeedbackComposerFromMenu + ) + } + + private var surfaceDeckValue: SurfaceDeckValue { + SurfaceDeckValue( + workspace: workspace, + selectedSurfaceID: selectedTerminal?.id.rawValue, + agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds, + canCreateWorkspace: canCreateWorkspace + ) + } + + private var surfaceDeckActions: SurfaceDeckActions { + SurfaceDeckActions( + selectTerminal: selectTerminalFromDeck, + presentPaneMap: { isPaneMapPresented = true }, + createTerminal: createTerminalFromToolbar, + openBrowser: openBrowserFromToolbar, + createWorkspace: createWorkspaceFromToolbar ) - .equatable() - .simultaneousGesture(TapGesture().onEnded { syncTerminalPickerRows(includeTitleChanges: true) }) - .onAppear { syncTerminalPickerRows(includeTitleChanges: true) } - .onChange(of: terminalPickerLiveMembership) { _, _ in syncTerminalPickerRows() } + } + + 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 } #if canImport(UIKit) @@ -572,7 +614,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 @@ -610,16 +652,16 @@ 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) } - 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) - // 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/WorkspaceUtilitiesMenu.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift new file mode 100644 index 000000000000..0e090af8f3f0 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift @@ -0,0 +1,49 @@ +import CmuxMobileSupport +import SwiftUI + +/// Workspace-level utilities that remain in the top-right toolbar. +struct WorkspaceUtilitiesMenu: View { + let showsViewAsText: Bool + let openTextSheet: () -> Void + let copyDebugLogs: () -> Void + let sendFeedback: () -> Void + + var body: some View { + Menu { + 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(TerminalPalette.foreground) + .accessibilityLabel( + L10n.string("mobile.workspace.utilitiesMenu", defaultValue: "Workspace Utilities") + ) + .accessibilityIdentifier("MobileWorkspaceUtilitiesMenu") + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift new file mode 100644 index 000000000000..40e73b85356c --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift @@ -0,0 +1,117 @@ +import CmuxMobileShellModel +import Testing +@testable import CmuxMobileShellUI + +@Suite struct SurfaceDeckValueTests { + @Test func olderMacUsesOneTerminalGroupAndOnlyShowsForMultipleSurfaces() { + 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.shouldShow == false) + #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[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) + } + + 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/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 65c940eeae51..2f88d5c19fc8 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -6087,6 +6087,90 @@ } } }, + "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.refresh": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Refresh" } }, + "ja": { "stringUnit": { "state": "translated", "value": "更新" } } + } + }, + "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.unavailable": { + "extractionState": "manual", + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "%@, unavailable on iPhone" } }, + "ja": { "stringUnit": { "state": "translated", "value": "%@、iPhoneでは利用できません" } } + } + }, + "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": { @@ -7804,6 +7888,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/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 16bb31d40633..95b8ff02c5cc 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -324,7 +324,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() } @@ -341,50 +341,39 @@ 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) + XCTAssertFalse(app.otherElements["MobileSurfaceDeck"].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 @@ -392,12 +381,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" ) @@ -408,7 +397,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" ) @@ -416,35 +405,34 @@ final class cmuxUITests: XCTestCase { assertToolbarOverflowButtonDoesNotExist(in: app) assertBackButtonFrameStaysCompactAroundPress(backButton, in: app) - tap(terminalDropdown, in: app) - assertTerminalMenuItemExists("terminal-delayed", in: app) + XCTAssertFalse(app.otherElements["MobileSurfaceDeck"].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", @@ -452,38 +440,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" ) @@ -494,7 +480,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" ) @@ -502,12 +488,11 @@ final class cmuxUITests: XCTestCase { assertToolbarOverflowButtonDoesNotExist(in: app) assertBackButtonFrameStaysCompactAroundPress(backButton, in: app) - tap(terminalDropdown, in: app) - assertTerminalMenuItemExists("workspace-3-terminal-1", in: app) + XCTAssertFalse(app.otherElements["MobileSurfaceDeck"].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() } @@ -515,24 +500,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( @@ -541,16 +524,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() } @@ -558,8 +537,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) @@ -1969,7 +1947,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 } @@ -1985,7 +1963,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 } @@ -2103,8 +2081,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", @@ -2148,16 +2125,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 ) @@ -2194,22 +2171,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 } @@ -2535,7 +2513,7 @@ final class cmuxUITests: XCTestCase { private func assertWorkspaceToolbarVisible( backButton: XCUIElement, titleMenu: XCUIElement, - terminalDropdown: XCUIElement, + utilitiesMenu: XCUIElement, in app: XCUIApplication, context: String, file: StaticString = #filePath, @@ -2543,12 +2521,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, From bb707a7771e2cc5523302c7d7a841ed0cae5cf98 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 15 Jul 2026 14:41:08 -0700 Subject: [PATCH 04/78] Add iOS pane map overlay with live terminal previews Full-screen map of the Mac workspace's real split geometry: proportional tiles from the layout.v1 tree on an aspect-fit 16:10 canvas, live render-grid text previews per terminal (one-shot mobile.terminal.replay side channel that omits viewport params so previewing can never resize the shared grid, capped at 4 concurrent fetches, selected tabs first), mini tab pills on multi-tab panes, agent-status dots, phone-selected accent border, and tap-to-jump. Non-terminal surfaces render disabled at 50% opacity. Co-Authored-By: Claude Fable 5 --- ...MobileShellComposite+PaneMapPreviews.swift | 91 ++++++++ .../CmuxMobileShellUI/PaneMapOverlay.swift | 213 ++++++++++++++++-- .../PaneMapPreviewRenderer.swift | 49 ++++ .../CmuxMobileShellUI/PaneMapTileView.swift | 212 +++++++++++++++++ .../CmuxMobileShellUI/PaneMapValue.swift | 33 +++ .../WorkspaceDetailView.swift | 20 +- .../PaneMapPreviewRendererTests.swift | 40 ++++ 7 files changed, 637 insertions(+), 21 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift 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..ccc07e4596ad --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift @@ -0,0 +1,91 @@ +public import CMUXMobileCore +internal import CmuxMobileRPC + +extension MobileShellComposite { + /// 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, + ] + ) + let data = try await client.sendRequest(request) + guard remoteClient === client else { return nil } + return try MobileTerminalReplayResponse.decode(data).renderGrid + } catch { + 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] { + var seenSurfaceIDs: Set = [] + let orderedSurfaceIDs = (selectedSurfaceIDs + remainingSurfaceIDs).filter { + seenSurfaceIDs.insert($0).inserted + } + guard !orderedSurfaceIDs.isEmpty else { return [:] } + + return await withTaskGroup( + of: (String, MobileTerminalRenderGridFrame?).self, + returning: [String: MobileTerminalRenderGridFrame].self + ) { group in + var nextIndex = 0 + + func enqueueNext() { + guard nextIndex < orderedSurfaceIDs.count else { return } + let surfaceID = orderedSurfaceIDs[nextIndex] + nextIndex += 1 + group.addTask { [weak self] in + let grid = await self?.fetchPaneMapPreviewGrid( + remoteWorkspaceID: remoteWorkspaceID, + surfaceID: surfaceID + ) + return (surfaceID, grid) + } + } + + for _ in 0.. [String: MobileTerminalRenderGridFrame] + let selectTerminal: (MobileTerminalPreview.ID) -> Void let dismiss: () -> Void + @State private var selectedSurfaceIDsByPaneID: [String: String] + @State private var previewGridsBySurfaceID: [String: MobileTerminalRenderGridFrame] = [:] + @State private var isRefreshing = false + + init( + value: PaneMapValue, + fetchPreviews: @escaping ([String], [String]) async -> [String: MobileTerminalRenderGridFrame], + selectTerminal: @escaping (MobileTerminalPreview.ID) -> Void, + dismiss: @escaping () -> Void + ) { + self.value = value + self.fetchPreviews = fetchPreviews + self.selectTerminal = selectTerminal + self.dismiss = dismiss + _selectedSurfaceIDsByPaneID = State(initialValue: value.initialSurfaceIDsByPaneID) + } + var body: some View { VStack(spacing: 0) { - HStack { - Text(workspaceName) + header + paneCanvas + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(TerminalPalette.background.ignoresSafeArea()) + .task { + await refreshAllPreviews() + } + .accessibilityIdentifier("MobilePaneMapOverlay") + } + + private var header: some View { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(value.workspaceName) .font(.headline) .foregroundStyle(TerminalPalette.foreground) .lineLimit(1) - Spacer(minLength: 12) + Text(countSubtitle) + .font(.subheadline) + .foregroundStyle(TerminalPalette.foreground.opacity(0.7)) + .lineLimit(1) + } + + Spacer(minLength: 0) - Button(action: dismiss) { - Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(TerminalPalette.foreground) - .padding(.horizontal, 14) - .frame(height: 34) - .mobileGlassPill() + Button { + Task { await refreshAllPreviews() } + } label: { + HStack(spacing: 5) { + if isRefreshing { + ProgressView() + .controlSize(.mini) + .tint(TerminalPalette.foreground) + } else { + Image(systemName: "arrow.clockwise") + } + Text(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) } - .buttonStyle(.plain) - .accessibilityIdentifier("MobilePaneMapDone") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(TerminalPalette.foreground) + .padding(.horizontal, 12) + .frame(height: 34) + .mobileGlassPill() } - .padding(16) + .buttonStyle(.plain) + .disabled(isRefreshing) + .accessibilityIdentifier("MobilePaneMapRefresh") - Spacer() + Button(action: dismiss) { + Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(TerminalPalette.foreground) + .padding(.horizontal, 14) + .frame(height: 34) + .mobileGlassPill() + } + .buttonStyle(.plain) + .accessibilityIdentifier("MobilePaneMapDone") } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(TerminalPalette.background.ignoresSafeArea()) - .accessibilityIdentifier("MobilePaneMapOverlay") + .padding(16) + } + + private var paneCanvas: some View { + GeometryReader { geometry in + let canvasRect = aspectFitCanvas(in: geometry.size) + let normalizedRects = value.layout.normalizedRects() + + ZStack(alignment: .topLeading) { + ForEach(value.panes, id: \.id) { pane in + if let normalizedRect = normalizedRects[pane.id] { + let tileRect = scaledTileRect(normalizedRect, in: canvasRect) + let surfaceID = selectedSurfaceIDsByPaneID[pane.id] + + PaneMapTileView( + pane: pane, + selectedSurfaceID: surfaceID, + phoneSelectedSurfaceID: value.phoneSelectedSurfaceID, + previewGrid: surfaceID.flatMap { previewGridsBySurfaceID[$0] }, + isLoadingPreview: isRefreshing, + agentStateKind: surfaceID.flatMap { value.agentStateKindsBySurfaceID[$0] }, + selectPreviewSurface: { selectedSurfaceIDsByPaneID[pane.id] = $0 }, + jumpToTerminal: jumpToTerminal + ) + .frame(width: tileRect.width, height: tileRect.height) + .position(x: tileRect.midX, y: tileRect.midY) + } + } + } + .frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading) + } + } + + private var countSubtitle: String { + let paneCount = value.panes.count + let tabCount = value.tabCount + switch (paneCount == 1, tabCount == 1) { + case (true, true): + return L10n.string( + "mobile.paneMap.count.onePane.oneTab", + defaultValue: "1 pane · 1 tab" + ) + case (true, false): + return String( + format: L10n.string( + "mobile.paneMap.count.onePane.otherTabs", + defaultValue: "1 pane · %d tabs" + ), + tabCount + ) + case (false, true): + return String( + format: L10n.string( + "mobile.paneMap.count.otherPanes.oneTab", + defaultValue: "%d panes · 1 tab" + ), + paneCount + ) + case (false, false): + return String( + format: L10n.string( + "mobile.paneMap.count.otherPanes.otherTabs", + defaultValue: "%d panes · %d tabs" + ), + paneCount, + tabCount + ) + } + } + + private func aspectFitCanvas(in size: CGSize) -> CGRect { + let availableWidth = max(0, size.width - 32) + let availableHeight = max(0, size.height - 32) + let targetAspectRatio: CGFloat = 16 / 10 + let width = min(availableWidth, availableHeight * targetAspectRatio) + let height = min(availableHeight, availableWidth / targetAspectRatio) + return CGRect( + x: (size.width - width) / 2, + y: (size.height - height) / 2, + width: width, + height: height + ) + } + + private func scaledTileRect(_ normalizedRect: CGRect, in canvasRect: CGRect) -> CGRect { + CGRect( + x: canvasRect.minX + normalizedRect.minX * canvasRect.width, + y: canvasRect.minY + normalizedRect.minY * canvasRect.height, + width: normalizedRect.width * canvasRect.width, + height: normalizedRect.height * canvasRect.height + ) + .insetBy(dx: 3, dy: 3) + } + + private func jumpToTerminal(_ surfaceID: String) { + selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) + dismiss() + } + + private func refreshAllPreviews() async { + guard !isRefreshing else { return } + isRefreshing = true + defer { isRefreshing = 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 + } + previewGridsBySurfaceID = await fetchPreviews( + selectedTerminalSurfaceIDs, + remainingTerminalSurfaceIDs + ) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift new file mode 100644 index 000000000000..026030989ab2 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift @@ -0,0 +1,49 @@ +import CMUXMobileCore + +/// Assembles compact plain-text terminal rows for pane-map previews. +struct PaneMapPreviewRenderer { + /// Renders the last visible rows of a render-grid frame as fixed-width text. + /// + /// Spans are applied in their source order, so a later overlapping span wins. + /// Text that reaches beyond the grid's final column is truncated. + /// + /// - Parameters: + /// - frame: The render-grid snapshot to assemble. + /// - maximumRows: The maximum number of trailing grid rows to return. + /// - Returns: Fixed-width strings ordered from the first included row to the last. + static func rows( + in frame: MobileTerminalRenderGridFrame, + maximumRows: Int = 20 + ) -> [String] { + rows( + columns: frame.columns, + rowCount: frame.rows, + rowSpans: frame.rowSpans, + maximumRows: maximumRows + ) + } + + /// Pure assembly seam used by focused unit tests and the frame renderer. + static func rows( + columns: Int, + rowCount: Int, + rowSpans: [MobileTerminalRenderGridFrame.RowSpan], + maximumRows: Int = 20 + ) -> [String] { + guard columns > 0, rowCount > 0, maximumRows > 0 else { return [] } + + let firstRow = max(0, rowCount - maximumRows) + return (firstRow..= 0, span.column < columns else { continue } + for (offset, character) in span.text.enumerated() { + let column = span.column + offset + guard column < columns else { break } + characters[column] = character + } + } + return String(characters) + } + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift new file mode 100644 index 000000000000..cd7fbdc567b9 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -0,0 +1,212 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import SwiftUI + +/// One proportional pane tile rendered from immutable layout and preview snapshots. +struct PaneMapTileView: View { + let pane: MobilePaneNode + let selectedSurfaceID: String? + let phoneSelectedSurfaceID: String? + let previewGrid: MobileTerminalRenderGridFrame? + let isLoadingPreview: Bool + let agentStateKind: ChatAgentStateKind? + let selectPreviewSurface: (String) -> Void + let jumpToTerminal: (String) -> Void + + private var selectedSurface: MobilePaneSurface? { + guard let selectedSurfaceID else { return pane.surfaces.first } + return pane.surfaces.first { $0.id == selectedSurfaceID } ?? pane.surfaces.first + } + + private var isPhoneSelected: Bool { + selectedSurface?.id == phoneSelectedSurfaceID + } + + var body: some View { + let shape = RoundedRectangle(cornerRadius: 12, style: .continuous) + + VStack(spacing: 0) { + if let selectedSurface { + tileContent(for: selectedSurface) + .opacity(selectedSurface.type.isTerminal ? 1 : 0.5) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(TerminalPalette.background, in: shape) + .overlay { + shape.stroke(.white.opacity(0.12), lineWidth: 1) + } + .overlay { + if isPhoneSelected { + shape.stroke(Color.accentColor, lineWidth: 2) + } + } + .clipShape(shape) + .accessibilityElement(children: .contain) + } + + private func tileContent(for surface: MobilePaneSurface) -> some View { + VStack(spacing: 0) { + header(for: surface) + + if pane.surfaces.count > 1 { + miniTabStrip + } + + bodyContent(for: surface) + } + } + + private func header(for surface: MobilePaneSurface) -> some View { + HStack(spacing: 4) { + Image(systemName: systemImage(for: surface.type)) + .font(.system(size: 10, weight: .medium)) + + Text(surface.title) + .font(.system(size: 11, weight: .medium)) + .lineLimit(1) + .truncationMode(.tail) + + Spacer(minLength: 2) + + if let agentStateKind { + Circle() + .fill(statusColor(agentStateKind)) + .frame(width: 6, height: 6) + } + } + .foregroundStyle(TerminalPalette.foreground) + .padding(6) + } + + private var miniTabStrip: some View { + ScrollView(.horizontal) { + HStack(spacing: 3) { + ForEach(pane.surfaces, id: \.id) { surface in + Button { + selectPreviewSurface(surface.id) + } label: { + Capsule() + .fill( + surface.id == selectedSurface?.id + ? TerminalPalette.foreground.opacity(0.72) + : .clear + ) + .overlay { + Capsule().stroke(TerminalPalette.foreground.opacity(0.28), lineWidth: 1) + } + .frame(width: 16, height: 5) + .frame(width: 24, height: 14) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(surface.title) + .accessibilityAddTraits(surface.id == selectedSurface?.id ? .isSelected : []) + } + } + .padding(.horizontal, 6) + } + .scrollIndicators(.hidden) + .frame(height: 14) + } + + @ViewBuilder + private func bodyContent(for surface: MobilePaneSurface) -> some View { + if surface.type.isTerminal { + terminalPreview(surfaceID: surface.id) + .contentShape(Rectangle()) + .onTapGesture { + jumpToTerminal(surface.id) + } + .accessibilityAddTraits(.isButton) + } else { + VStack(spacing: 5) { + Image(systemName: systemImage(for: surface.type)) + .font(.system(size: 20, weight: .medium)) + Text(surface.title) + .font(.caption.weight(.medium)) + .lineLimit(2) + .multilineTextAlignment(.center) + } + .foregroundStyle(TerminalPalette.foreground) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(8) + } + } + + @ViewBuilder + private func terminalPreview(surfaceID: String) -> some View { + if let previewGrid, previewGrid.surfaceID == surfaceID { + GeometryReader { geometry in + let lines = PaneMapPreviewRenderer.rows(in: previewGrid) + let fontSize = previewFontSize( + availableSize: geometry.size, + columns: previewGrid.columns, + lineCount: lines.count + ) + + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(lines.enumerated()), id: \.offset) { _, line in + Text(line) + .font(.system(size: fontSize, weight: .regular, design: .monospaced)) + .lineLimit(1) + .fixedSize(horizontal: true, vertical: false) + } + } + .foregroundStyle(TerminalPalette.foreground) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) + .clipped() + } + .padding(.horizontal, 6) + .padding(.bottom, 6) + } else if isLoadingPreview { + ProgressView() + .controlSize(.mini) + .tint(TerminalPalette.foreground.opacity(0.5)) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + Color.clear + } + } + + private func previewFontSize( + availableSize: CGSize, + columns: Int, + lineCount: Int + ) -> CGFloat { + guard columns > 0, lineCount > 0 else { return 5 } + let widthFit = availableSize.width / (CGFloat(columns) * 0.62) + let heightFit = availableSize.height / (CGFloat(lineCount) * 1.12) + return min(7, max(5, min(widthFit, heightFit))) + } + + 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" + } + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift new file mode 100644 index 000000000000..ecc8da7af866 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift @@ -0,0 +1,33 @@ +import CmuxMobileShellModel + +/// Immutable workspace and status state rendered by ``PaneMapOverlay``. +struct PaneMapValue: Equatable { + let workspaceName: String + 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 initialSurfaceIDsByPaneID: [String: String] { + var result: [String: String] = [:] + for pane in panes { + 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/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index c41b6783a61d..ab81d755fee9 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -143,8 +143,24 @@ struct WorkspaceDetailView: View { TerminalTextSheetView(surfaceID: textSheetSurfaceID) } .fullScreenCover(isPresented: $isPaneMapPresented) { - PaneMapOverlay(workspaceName: workspace.name) { - isPaneMapPresented = false + if let layout = workspace.layout { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + layout: layout, + phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, + agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds + ), + fetchPreviews: { selectedSurfaceIDs, remainingSurfaceIDs in + await store.fetchPaneMapPreviewGrids( + remoteWorkspaceID: workspace.rpcWorkspaceID.rawValue, + selectedSurfaceIDs: selectedSurfaceIDs, + remainingSurfaceIDs: remainingSurfaceIDs + ) + }, + selectTerminal: selectTerminalFromDeck, + dismiss: { isPaneMapPresented = false } + ) } } .workspaceRenameDialog( diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift new file mode 100644 index 000000000000..45623738a556 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift @@ -0,0 +1,40 @@ +import CMUXMobileCore +import Testing +@testable import CmuxMobileShellUI + +@Suite struct PaneMapPreviewRendererTests { + @Test func emptyGridProducesSpaceCanvas() { + let rows = PaneMapPreviewRenderer.rows( + columns: 4, + rowCount: 2, + rowSpans: [] + ) + + #expect(rows == [" ", " "]) + } + + @Test func laterOverlappingSpanWinsInSourceOrder() { + let rows = PaneMapPreviewRenderer.rows( + columns: 4, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 0, text: "abcd"), + .init(row: 0, column: 1, text: "XY"), + ] + ) + + #expect(rows == ["aXYd"]) + } + + @Test func textIsTruncatedAtFinalGridColumn() { + let rows = PaneMapPreviewRenderer.rows( + columns: 4, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 2, text: "WXYZ"), + ] + ) + + #expect(rows == [" WX"]) + } +} From 2d287150f2a39867ed778406e493cfaf8c6a125a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 15 Jul 2026 14:54:24 -0700 Subject: [PATCH 05/78] Add DEBUG panes-and-tabs fixture preview route CMUX_UITEST_PANES_PREVIEW=1 mounts the production SurfaceDeckBar and PaneMapOverlay against a realistic 3-pane fixture workspace (multi-tab panes, agent statuses, canned render-grid previews) so the panes/tabs UI can be exercised and screenshotted without sign-in or a paired Mac. Also tightens accessibility labels/identifiers on the pane map controls. Co-Authored-By: Claude Fable 5 --- .../CMUXMobileRootView.swift | 18 ++ .../CmuxMobileShellUI/PaneMapOverlay.swift | 2 + .../CmuxMobileShellUI/PaneMapTileView.swift | 25 ++- .../PanesTabsPreviewHost.swift | 212 ++++++++++++++++++ .../CmuxMobileSupport/UITestConfig.swift | 13 ++ .../xcshareddata/swiftpm/Package.resolved | 11 +- 6 files changed, 274 insertions(+), 7 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 4020956e3317..279a578802eb 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -70,6 +70,14 @@ struct CMUXMobileRootView: View { #endif } + private var shouldShowPanesTabsPreview: Bool { + #if os(iOS) && DEBUG + return UITestConfig.panesPreviewEnabled + #else + return false + #endif + } + private var shouldShowWorkspaceListLayoutPreview: Bool { #if os(iOS) && DEBUG return UITestConfig.workspaceListLayoutPreviewEnabled @@ -102,6 +110,14 @@ struct CMUXMobileRootView: View { #endif } + @ViewBuilder private var panesTabsPreview: some View { + #if os(iOS) && DEBUG + PanesTabsPreviewHost() + #else + EmptyView() + #endif + } + @ViewBuilder private var workspaceListLayoutPreview: some View { #if os(iOS) && DEBUG WorkspaceListLayoutPreviewView() @@ -210,6 +226,8 @@ struct CMUXMobileRootView: View { agentChatDemoPreview } else if shouldShowTerminalLayoutPreview { terminalLayoutPreview + } else if shouldShowPanesTabsPreview { + panesTabsPreview } else if shouldShowWorkspaceListLayoutPreview { workspaceListLayoutPreview } else if shouldShowStreamingChatPreview { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index 30dd65c76a43..c39bb7eebd50 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -77,6 +77,7 @@ struct PaneMapOverlay: View { } .buttonStyle(.plain) .disabled(isRefreshing) + .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) .accessibilityIdentifier("MobilePaneMapRefresh") Button(action: dismiss) { @@ -88,6 +89,7 @@ struct PaneMapOverlay: View { .mobileGlassPill() } .buttonStyle(.plain) + .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) .accessibilityIdentifier("MobilePaneMapDone") } .padding(16) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index cd7fbdc567b9..eeb5c0d70886 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -1,5 +1,6 @@ import CMUXMobileCore import CmuxMobileShellModel +import CmuxMobileSupport import SwiftUI /// One proportional pane tile rendered from immutable layout and preview snapshots. @@ -102,6 +103,7 @@ struct PaneMapTileView: View { .buttonStyle(.plain) .accessibilityLabel(surface.title) .accessibilityAddTraits(surface.id == selectedSurface?.id ? .isSelected : []) + .accessibilityIdentifier("MobilePaneMapTab-\(surface.id)") } } .padding(.horizontal, 6) @@ -113,12 +115,23 @@ struct PaneMapTileView: View { @ViewBuilder private func bodyContent(for surface: MobilePaneSurface) -> some View { if surface.type.isTerminal { - terminalPreview(surfaceID: surface.id) - .contentShape(Rectangle()) - .onTapGesture { - jumpToTerminal(surface.id) - } - .accessibilityAddTraits(.isButton) + Button { + jumpToTerminal(surface.id) + } label: { + terminalPreview(surfaceID: surface.id) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel( + String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.terminal", + defaultValue: "%@, terminal" + ), + surface.title + ) + ) + .accessibilityIdentifier("MobilePaneMapTile-\(surface.id)") } else { VStack(spacing: 5) { Image(systemName: systemImage(for: surface.type)) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift new file mode 100644 index 000000000000..71e5e981cf2d --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift @@ -0,0 +1,212 @@ +#if canImport(UIKit) && DEBUG +import CMUXMobileCore +import CmuxMobileShellModel +import SwiftUI + +/// Fixture-driven host for exercising the production panes-and-tabs UI without a paired Mac. +struct PanesTabsPreviewHost: View { + 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" + + @State private var selectedSurfaceID = Self.claudeSurfaceID + @State private var isPaneMapPresented = false + + 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" + ), + ], + layout: MobilePaneLayout( + version: 12, + focusedPaneID: "preview-pane-left", + root: .split( + MobilePaneSplit( + id: "preview-split-root", + orientation: .horizontal, + ratio: 0.55, + first: .pane( + MobilePaneNode( + id: "preview-pane-left", + selectedSurfaceID: Self.claudeSurfaceID, + surfaces: [ + MobilePaneSurface( + id: Self.claudeSurfaceID, + type: .terminal, + title: "claude" + ), + MobilePaneSurface( + id: Self.zshSurfaceID, + type: .terminal, + title: "zsh" + ), + ] + ) + ), + second: .split( + MobilePaneSplit( + id: "preview-split-right", + orientation: .vertical, + ratio: 0.5, + 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, + ] + + var body: some View { + TerminalPalette.background + .frame(maxWidth: .infinity, maxHeight: .infinity) + .safeAreaInset(edge: .bottom, spacing: 0) { + SurfaceDeckBar(value: deckValue, actions: deckActions) + .equatable() + } + .ignoresSafeArea(.keyboard, edges: .bottom) + .fullScreenCover(isPresented: $isPaneMapPresented) { + if let layout = workspace.layout { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + layout: layout, + phoneSelectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID + ), + fetchPreviews: Self.fetchFixturePreviews, + selectTerminal: { selectedSurfaceID = $0.rawValue }, + dismiss: { isPaneMapPresented = false } + ) + } + } + .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: { isPaneMapPresented = true }, + createTerminal: {}, + openBrowser: {}, + createWorkspace: {} + ) + } + + 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 + """, + ] + + var previews: [String: MobileTerminalRenderGridFrame] = [:] + for surfaceID in selectedSurfaceIDs + remainingSurfaceIDs where previews[surfaceID] == nil { + guard let text = textBySurfaceID[surfaceID], + let frame = try? MobileTerminalRenderGridFrame.fromPlainRows( + surfaceID: surfaceID, + stateSeq: 1, + columns: 50, + rows: 7, + text: text + ) else { + continue + } + previews[surfaceID] = frame + } + return previews + } +} +#endif diff --git a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift index 11b594834b5e..aea71dad902b 100644 --- a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift +++ b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift @@ -79,6 +79,19 @@ public struct UITestConfig { #endif } + /// Whether the standalone panes-and-tabs preview is enabled. + /// + /// When `CMUX_UITEST_PANES_PREVIEW=1`, the root view renders fixture-driven + /// production surface-deck and pane-map views without sign-in or Mac pairing. + /// DEBUG-only. + public static var panesPreviewEnabled: Bool { + #if DEBUG + return ProcessInfo.processInfo.environment["CMUX_UITEST_PANES_PREVIEW"] == "1" + #else + return false + #endif + } + /// Whether the standalone workspace-list layout preview is enabled. /// /// When `CMUX_UITEST_WORKSPACE_LIST_PREVIEW=1`, the root view renders a diff --git a/ios/cmux.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/cmux.xcworkspace/xcshareddata/swiftpm/Package.resolved index d61053e7e034..505700b66295 100644 --- a/ios/cmux.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ios/cmux.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,6 +1,15 @@ { - "originHash" : "6104d2cb8b5660da4a5b51b4e654037e3bc623e8e169544d7f9c329f6afe6789", + "originHash" : "d9134cf84862c709f8ed0ba2bf6030fe66ea77a67fec9d41b789ed6c8eaf10a0", "pins" : [ + { + "identity" : "iroh-ffi", + "kind" : "remoteSourceControl", + "location" : "https://github.com/manaflow-ai/iroh-ffi.git", + "state" : { + "revision" : "31ec35c931028937db1910b6d623a3e078eb91da", + "version" : "1.0.2-cmux.2" + } + }, { "identity" : "sentry-cocoa", "kind" : "remoteSourceControl", From ce3e3a6c9de63b8694e237b8fd918dbcc1af4b48 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 15 Jul 2026 15:10:25 -0700 Subject: [PATCH 06/78] Polish surface deck and pane map from live simulator verification Deck: themed opaque backdrop extending into the home-indicator region (theme foreground was invisible on the system background), no shared GlassEffectContainer (its glass layer composited scrolled-away chips above the scroll clip, bleeding under the fixed controls), explicit theme foreground on the pane-map and add buttons (accent-blue tint mismatch). Pane map: labeled mini tab pills instead of anonymous dot capsules, canvas fills the available rect instead of forcing 16:10 (split ratios carry the structure; bigger previews read better on a portrait phone), preview font cap raised to 9pt. Co-Authored-By: Claude Fable 5 --- .../CmuxMobileShellUI/PaneMapOverlay.swift | 19 +++++----- .../CmuxMobileShellUI/PaneMapTileView.swift | 38 ++++++++++++------- .../CmuxMobileShellUI/SurfaceDeckBar.swift | 23 ++++++----- 3 files changed, 47 insertions(+), 33 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index c39bb7eebd50..fb5b912b009f 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -163,16 +163,15 @@ struct PaneMapOverlay: View { } private func aspectFitCanvas(in size: CGSize) -> CGRect { - let availableWidth = max(0, size.width - 32) - let availableHeight = max(0, size.height - 32) - let targetAspectRatio: CGFloat = 16 / 10 - let width = min(availableWidth, availableHeight * targetAspectRatio) - let height = min(availableHeight, availableWidth / targetAspectRatio) - return CGRect( - x: (size.width - width) / 2, - y: (size.height - height) / 2, - width: width, - height: height + // Fill the available space rather than forcing the Mac window's + // landscape aspect: the split RATIOS carry the structural mental + // model, and on a portrait phone larger tiles (more readable + // previews) are worth more than aspect fidelity. + CGRect( + x: 16, + y: 8, + width: max(0, size.width - 32), + height: max(0, size.height - 24) ) } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index eeb5c0d70886..8f67c52fe925 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -84,32 +84,42 @@ struct PaneMapTileView: View { ScrollView(.horizontal) { HStack(spacing: 3) { ForEach(pane.surfaces, id: \.id) { surface in + let isSelectedTab = surface.id == selectedSurface?.id Button { selectPreviewSurface(surface.id) } label: { - Capsule() - .fill( - surface.id == selectedSurface?.id - ? TerminalPalette.foreground.opacity(0.72) - : .clear + Text(surface.title) + .font(.system(size: 9, weight: .semibold)) + .lineLimit(1) + .truncationMode(.tail) + .foregroundStyle( + isSelectedTab + ? TerminalPalette.background + : TerminalPalette.foreground.opacity(0.85) + ) + .padding(.horizontal, 7) + .frame(height: 14) + .frame(minWidth: 22, maxWidth: 88) + .background( + Capsule().fill( + isSelectedTab + ? TerminalPalette.foreground.opacity(0.85) + : TerminalPalette.foreground.opacity(0.10) + ) ) - .overlay { - Capsule().stroke(TerminalPalette.foreground.opacity(0.28), lineWidth: 1) - } - .frame(width: 16, height: 5) - .frame(width: 24, height: 14) - .contentShape(Rectangle()) + .contentShape(Capsule()) } .buttonStyle(.plain) .accessibilityLabel(surface.title) - .accessibilityAddTraits(surface.id == selectedSurface?.id ? .isSelected : []) + .accessibilityAddTraits(isSelectedTab ? .isSelected : []) .accessibilityIdentifier("MobilePaneMapTab-\(surface.id)") } } .padding(.horizontal, 6) } .scrollIndicators(.hidden) - .frame(height: 14) + .frame(height: 16) + .padding(.bottom, 2) } @ViewBuilder @@ -190,7 +200,7 @@ struct PaneMapTileView: View { guard columns > 0, lineCount > 0 else { return 5 } let widthFit = availableSize.width / (CGFloat(columns) * 0.62) let heightFit = availableSize.height / (CGFloat(lineCount) * 1.12) - return min(7, max(5, min(widthFit, heightFit))) + return min(9, max(5, min(widthFit, heightFit))) } private func statusColor(_ kind: ChatAgentStateKind) -> Color { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift index 85966da6801c..3def517e88cf 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -45,21 +45,24 @@ struct SurfaceDeckBar: View, Equatable { .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( + TerminalPalette.background + .ignoresSafeArea(edges: .bottom) + ) .accessibilityElement(children: .contain) .accessibilityLabel(L10n.string("mobile.surfaceDeck.label", defaultValue: "Workspace surfaces")) .accessibilityIdentifier("MobileSurfaceDeck") } - @ViewBuilder + // 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 { - if #available(iOS 26.0, *) { - GlassEffectContainer(spacing: 8) { - deckContent - } - } else { - deckContent - .background(.bar) - } + deckContent } private var deckContent: some View { @@ -153,6 +156,7 @@ struct SurfaceDeckBar: View, Equatable { Button(action: actions.presentPaneMap) { Image(systemName: "rectangle.split.2x2") .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(TerminalPalette.foreground) .frame(width: 32, height: 32) .mobileGlassCircle() } @@ -183,6 +187,7 @@ struct SurfaceDeckBar: View, Equatable { } label: { Image(systemName: "plus") .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(TerminalPalette.foreground) .frame(width: 32, height: 32) .mobileGlassCircle() } From 29e9f20a0bf5957de7cd2cb124c80ff0db87d42a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 00:52:49 -0700 Subject: [PATCH 07/78] Fix escaping-closure capture in sidebar slot view tint The NSImage drawing handler is escaping, so referencing the enclosing view's color without an explicit capture fails to compile; capture the color by value. Unbreaks clean Debug builds of current main carried into this branch. Co-Authored-By: Claude Fable 5 --- .../Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift index 659d7dc50925..3d858b3208b7 100644 --- a/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift +++ b/Sources/Sidebar/AppKitList/Cells/SidebarWorkspaceRowSlotViews.swift @@ -96,7 +96,7 @@ final class SidebarRowPullRequestIconView: NSView { ) // Tint inside the image first: .sourceAtop against the view's // transparent backing draws nothing (no destination pixels). - let tinted = NSImage(size: image.size, flipped: false) { drawRect in + let tinted = NSImage(size: image.size, flipped: false) { [color] drawRect in image.draw(in: drawRect, from: .zero, operation: .sourceOver, fraction: 1) color.set() drawRect.fill(using: .sourceAtop) From 0891f8baa843bf261b4363a0c35c207aa7a3dfc1 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 03:35:33 -0700 Subject: [PATCH 08/78] Anchor pane-map preview window to content and migrate to live themes The preview renderer showed the last 20 grid rows, which is blank for a tall phone-attached grid whose content sits at the top after a clear; the window now ends at the last content-bearing row (or cursor). Deck, pane map, and preview host take the live TerminalTheme (TerminalPalette was removed on main by PR 7919); preview rows use the theme's true terminal foreground while chrome uses the readable chrome color. Adds fetch diagnostics to the pane-map replay side channel and regression tests for top-anchored and bottom-anchored preview windows. Co-Authored-By: Claude Fable 5 --- ...MobileShellComposite+PaneMapPreviews.swift | 9 +++++- .../CmuxMobileShellUI/PaneMapOverlay.swift | 16 ++++++---- .../PaneMapPreviewRenderer.swift | 19 ++++++++--- .../CmuxMobileShellUI/PaneMapTileView.swift | 21 ++++++------ .../PanesTabsPreviewHost.swift | 6 ++-- .../CmuxMobileShellUI/SurfaceDeckBar.swift | 18 ++++++----- .../WorkspaceDetailView.swift | 4 ++- .../PaneMapPreviewRendererTests.swift | 32 +++++++++++++++++++ 8 files changed, 94 insertions(+), 31 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift index ccc07e4596ad..9421d83c30b0 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift @@ -1,4 +1,5 @@ public import CMUXMobileCore +internal import CmuxMobileDiagnostics internal import CmuxMobileRPC extension MobileShellComposite { @@ -28,8 +29,14 @@ extension MobileShellComposite { ) let data = try await client.sendRequest(request) guard remoteClient === client else { return nil } - return try MobileTerminalReplayResponse.decode(data).renderGrid + let payload = try MobileTerminalReplayResponse.decode(data) + 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)" + ) + return grid } catch { + MobileDebugLog.anchormux("CMUX_PANEMAP preview surface=\(surfaceID) error=\(error)") return nil } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index fb5b912b009f..2deacb72fadf 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -6,6 +6,7 @@ import SwiftUI /// Full-screen proportional map of a workspace's Mac pane layout. struct PaneMapOverlay: View { let value: PaneMapValue + let terminalTheme: TerminalTheme let fetchPreviews: ([String], [String]) async -> [String: MobileTerminalRenderGridFrame] let selectTerminal: (MobileTerminalPreview.ID) -> Void let dismiss: () -> Void @@ -16,11 +17,13 @@ struct PaneMapOverlay: View { init( value: PaneMapValue, + terminalTheme: TerminalTheme, fetchPreviews: @escaping ([String], [String]) async -> [String: MobileTerminalRenderGridFrame], selectTerminal: @escaping (MobileTerminalPreview.ID) -> Void, dismiss: @escaping () -> Void ) { self.value = value + self.terminalTheme = terminalTheme self.fetchPreviews = fetchPreviews self.selectTerminal = selectTerminal self.dismiss = dismiss @@ -33,7 +36,7 @@ struct PaneMapOverlay: View { paneCanvas } .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(TerminalPalette.background.ignoresSafeArea()) + .background(terminalTheme.terminalBackgroundColor.ignoresSafeArea()) .task { await refreshAllPreviews() } @@ -45,12 +48,12 @@ struct PaneMapOverlay: View { VStack(alignment: .leading, spacing: 2) { Text(value.workspaceName) .font(.headline) - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .lineLimit(1) Text(countSubtitle) .font(.subheadline) - .foregroundStyle(TerminalPalette.foreground.opacity(0.7)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.7)) .lineLimit(1) } @@ -63,14 +66,14 @@ struct PaneMapOverlay: View { if isRefreshing { ProgressView() .controlSize(.mini) - .tint(TerminalPalette.foreground) + .tint(terminalTheme.terminalChromeForegroundColor) } else { Image(systemName: "arrow.clockwise") } Text(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) } .font(.subheadline.weight(.semibold)) - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .padding(.horizontal, 12) .frame(height: 34) .mobileGlassPill() @@ -83,7 +86,7 @@ struct PaneMapOverlay: View { Button(action: dismiss) { Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) .font(.subheadline.weight(.semibold)) - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .padding(.horizontal, 14) .frame(height: 34) .mobileGlassPill() @@ -108,6 +111,7 @@ struct PaneMapOverlay: View { PaneMapTileView( pane: pane, + terminalTheme: terminalTheme, selectedSurfaceID: surfaceID, phoneSelectedSurfaceID: value.phoneSelectedSurfaceID, previewGrid: surfaceID.flatMap { previewGridsBySurfaceID[$0] }, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift index 026030989ab2..e07fc9609093 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift @@ -2,14 +2,14 @@ import CMUXMobileCore /// Assembles compact plain-text terminal rows for pane-map previews. struct PaneMapPreviewRenderer { - /// Renders the last visible rows of a render-grid frame as fixed-width text. + /// Renders the content-bearing tail of a render-grid frame as fixed-width text. /// /// Spans are applied in their source order, so a later overlapping span wins. /// Text that reaches beyond the grid's final column is truncated. /// /// - Parameters: /// - frame: The render-grid snapshot to assemble. - /// - maximumRows: The maximum number of trailing grid rows to return. + /// - maximumRows: The maximum number of grid rows to return. /// - Returns: Fixed-width strings ordered from the first included row to the last. static func rows( in frame: MobileTerminalRenderGridFrame, @@ -19,21 +19,32 @@ struct PaneMapPreviewRenderer { columns: frame.columns, rowCount: frame.rows, rowSpans: frame.rowSpans, + cursorRow: frame.cursor?.row, maximumRows: maximumRows ) } /// Pure assembly seam used by focused unit tests and the frame renderer. + /// + /// The window ends at the last row that has content (or the cursor row, + /// whichever is lower), not at the grid's bottom: a cleared tall grid keeps + /// its content at the top, and a bottom-anchored window would show only + /// blank rows for it (this is exactly what a phone-attached surface's + /// phone-sized grid looks like right after `clear`). static func rows( columns: Int, rowCount: Int, rowSpans: [MobileTerminalRenderGridFrame.RowSpan], + cursorRow: Int? = nil, maximumRows: Int = 20 ) -> [String] { guard columns > 0, rowCount > 0, maximumRows > 0 else { return [] } - let firstRow = max(0, rowCount - maximumRows) - return (firstRow..= 0, span.column < columns else { continue } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index 8f67c52fe925..26b1020d74ae 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -6,6 +6,7 @@ import SwiftUI /// One proportional pane tile rendered from immutable layout and preview snapshots. struct PaneMapTileView: View { let pane: MobilePaneNode + let terminalTheme: TerminalTheme let selectedSurfaceID: String? let phoneSelectedSurfaceID: String? let previewGrid: MobileTerminalRenderGridFrame? @@ -33,7 +34,7 @@ struct PaneMapTileView: View { } } .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(TerminalPalette.background, in: shape) + .background(terminalTheme.terminalBackgroundColor, in: shape) .overlay { shape.stroke(.white.opacity(0.12), lineWidth: 1) } @@ -76,7 +77,7 @@ struct PaneMapTileView: View { .frame(width: 6, height: 6) } } - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .padding(6) } @@ -94,8 +95,8 @@ struct PaneMapTileView: View { .truncationMode(.tail) .foregroundStyle( isSelectedTab - ? TerminalPalette.background - : TerminalPalette.foreground.opacity(0.85) + ? terminalTheme.terminalBackgroundColor + : terminalTheme.terminalChromeForegroundColor.opacity(0.85) ) .padding(.horizontal, 7) .frame(height: 14) @@ -103,8 +104,8 @@ struct PaneMapTileView: View { .background( Capsule().fill( isSelectedTab - ? TerminalPalette.foreground.opacity(0.85) - : TerminalPalette.foreground.opacity(0.10) + ? terminalTheme.terminalChromeForegroundColor.opacity(0.85) + : terminalTheme.terminalChromeForegroundColor.opacity(0.10) ) ) .contentShape(Capsule()) @@ -151,7 +152,7 @@ struct PaneMapTileView: View { .lineLimit(2) .multilineTextAlignment(.center) } - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .frame(maxWidth: .infinity, maxHeight: .infinity) .padding(8) } @@ -176,7 +177,9 @@ struct PaneMapTileView: View { .fixedSize(horizontal: true, vertical: false) } } - .foregroundStyle(TerminalPalette.foreground) + // Preview rows are terminal content, so they use the theme's + // true foreground rather than the chrome-readable color. + .foregroundStyle(terminalTheme.terminalForegroundColor) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) .clipped() } @@ -185,7 +188,7 @@ struct PaneMapTileView: View { } else if isLoadingPreview { ProgressView() .controlSize(.mini) - .tint(TerminalPalette.foreground.opacity(0.5)) + .tint(terminalTheme.terminalChromeForegroundColor.opacity(0.5)) .frame(maxWidth: .infinity, maxHeight: .infinity) } else { Color.clear diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift index 71e5e981cf2d..f4a5047910cc 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift @@ -13,6 +13,7 @@ struct PanesTabsPreviewHost: View { @State private var selectedSurfaceID = Self.claudeSurfaceID @State private var isPaneMapPresented = false + private let terminalTheme = TerminalTheme.monokai private let workspace = MobileWorkspacePreview( id: "preview-api-server", @@ -111,10 +112,10 @@ struct PanesTabsPreviewHost: View { ] var body: some View { - TerminalPalette.background + terminalTheme.terminalBackgroundColor .frame(maxWidth: .infinity, maxHeight: .infinity) .safeAreaInset(edge: .bottom, spacing: 0) { - SurfaceDeckBar(value: deckValue, actions: deckActions) + SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) .equatable() } .ignoresSafeArea(.keyboard, edges: .bottom) @@ -127,6 +128,7 @@ struct PanesTabsPreviewHost: View { phoneSelectedSurfaceID: selectedSurfaceID, agentStateKindsBySurfaceID: agentStateKindsBySurfaceID ), + terminalTheme: terminalTheme, fetchPreviews: Self.fetchFixturePreviews, selectTerminal: { selectedSurfaceID = $0.rawValue }, dismiss: { isPaneMapPresented = false } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift index 3def517e88cf..11129997aafc 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import CmuxMobileShellModel import CmuxMobileSupport import SwiftUI @@ -6,12 +7,13 @@ import SwiftUI 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.value == rhs.value && lhs.terminalTheme == rhs.terminalTheme } var body: some View { @@ -24,7 +26,7 @@ struct SurfaceDeckBar: View, Equatable { ) ) .font(.caption) - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .padding(.horizontal, 12) .frame(height: 28) .mobileGlassPill() @@ -50,7 +52,7 @@ struct SurfaceDeckBar: View, Equatable { // region), so the light theme foreground stays readable instead of // landing on the system background. .background( - TerminalPalette.background + terminalTheme.terminalBackgroundColor .ignoresSafeArea(edges: .bottom) ) .accessibilityElement(children: .contain) @@ -130,14 +132,14 @@ struct SurfaceDeckBar: View, Equatable { } .foregroundStyle( isSelected - ? TerminalPalette.foreground - : TerminalPalette.foreground.opacity(0.72) + ? terminalTheme.terminalChromeForegroundColor + : terminalTheme.terminalChromeForegroundColor.opacity(0.72) ) .padding(.horizontal, 9) .frame(height: 32) .background { if isSelected { - Capsule().fill(TerminalPalette.foreground.opacity(0.16)) + Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.16)) } } .contentShape(Capsule()) @@ -156,7 +158,7 @@ struct SurfaceDeckBar: View, Equatable { Button(action: actions.presentPaneMap) { Image(systemName: "rectangle.split.2x2") .font(.system(size: 14, weight: .semibold)) - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .frame(width: 32, height: 32) .mobileGlassCircle() } @@ -187,7 +189,7 @@ struct SurfaceDeckBar: View, Equatable { } label: { Image(systemName: "plus") .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(TerminalPalette.foreground) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) .frame(width: 32, height: 32) .mobileGlassCircle() } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index ea517ff8ce67..9cf4e7c16e02 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -104,7 +104,8 @@ struct WorkspaceDetailView: View { if showDeck { SurfaceDeckBar( value: deckValue, - actions: surfaceDeckActions + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme ) .equatable() } @@ -151,6 +152,7 @@ struct WorkspaceDetailView: View { phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds ), + terminalTheme: store.activeTerminalTheme, fetchPreviews: { selectedSurfaceIDs, remainingSurfaceIDs in await store.fetchPaneMapPreviewGrids( remoteWorkspaceID: workspace.rpcWorkspaceID.rawValue, diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift index 45623738a556..01d68e970efd 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift @@ -37,4 +37,36 @@ import Testing #expect(rows == [" WX"]) } + + @Test func windowFollowsTopAnchoredContentOnTallGrid() { + // A cleared tall grid (like a phone-attached surface right after + // `clear`) keeps content at the top; the window must include it + // instead of showing the grid's blank bottom rows. + let rows = PaneMapPreviewRenderer.rows( + columns: 3, + rowCount: 40, + rowSpans: [ + .init(row: 0, column: 0, text: "top"), + .init(row: 2, column: 0, text: "cat"), + ], + cursorRow: 3 + ) + + #expect(rows.count == 20) + #expect(rows[0] == "top") + #expect(rows[2] == "cat") + } + + @Test func windowStaysBottomAnchoredWhenContentFillsTail() { + let rows = PaneMapPreviewRenderer.rows( + columns: 3, + rowCount: 40, + rowSpans: [ + .init(row: 39, column: 0, text: "end"), + ] + ) + + #expect(rows.count == 20) + #expect(rows.last == "end") + } } From 8c26feff718a520ff09c3c40fdb9e5b2faf0a941 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:37:16 -0700 Subject: [PATCH 09/78] Test state sync pane layout projection --- .../MobileShellStateSyncTests.swift | 80 +++++++++++++++++++ .../SurfaceDeckValueTests.swift | 26 +++++- 2 files changed, 104 insertions(+), 2 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift index c5e19acf4837..6ee13cffd80d 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellStateSyncTests.swift @@ -59,6 +59,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, @@ -93,6 +153,26 @@ private func workspaceUpdatedEventFrame() throws -> Data { @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 router = LivenessHostRouter() await router.scriptSyncFetchResult( diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift index 40e73b85356c..2ea5302fe6ac 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift @@ -3,7 +3,30 @@ import Testing @testable import CmuxMobileShellUI @Suite struct SurfaceDeckValueTests { - @Test func olderMacUsesOneTerminalGroupAndOnlyShowsForMultipleSurfaces() { + @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", @@ -23,7 +46,6 @@ import Testing #expect(oneValue.groups.count == 1) #expect(oneValue.groups[0].chips.map(\.id) == ["terminal-1"]) - #expect(oneValue.shouldShow == false) #expect(oneValue.showsPaneMap == false) #expect(twoValue.groups[0].chips.map(\.id) == ["terminal-1", "terminal-2"]) #expect(twoValue.shouldShow) From 03bf4496de46437c5e850f924b8e4df7879e1deb Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:37:56 -0700 Subject: [PATCH 10/78] Test pane layout observer invalidation gaps --- .../MobileWorkspaceListFidelityTests.swift | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index 78823c0a1c2d..d28eee86f485 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -266,6 +266,78 @@ struct MobileWorkspaceListFidelityTests { #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 { From 305e785d7e8ae05437573d7c19d0242889fb529f Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:39:41 -0700 Subject: [PATCH 11/78] Test pane preview rendering and fetch scheduling --- ...leShellRenderGridLivenessTestSupport.swift | 20 ++- .../PaneMapPreviewFetchTests.swift | 156 ++++++++++++++++++ .../PaneMapPreviewRendererTests.swift | 26 +++ 3 files changed, 199 insertions(+), 3 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 89deffa87fae..e61d4e927494 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? } private var recorded: [RecordedRequest] = [] @@ -78,11 +79,17 @@ actor LivenessHostRouter { syncFetchResults.append(["__transient_error__": true]) } - func record(method: String?, topics: [String]?, workspaceID: String? = nil) { + func record( + method: String?, + topics: [String]?, + workspaceID: String? = nil, + surfaceID: String? = nil + ) { recorded.append(RecordedRequest( method: method, topics: topics, - workspaceID: workspaceID + workspaceID: workspaceID, + surfaceID: surfaceID )) resumeSatisfiedCountWaiters() } @@ -180,6 +187,12 @@ actor LivenessHostRouter { recorded.filter { $0.method == method }.map(\.workspaceID) } + func surfaceIDs(for method: String) -> [String] { + recorded + .filter { $0.method == method } + .compactMap(\.surfaceID) + } + func setCapabilities(_ capabilities: [String]) { self.capabilities = capabilities } @@ -520,7 +533,8 @@ actor LivenessTransport: CmxByteTransport { await router.record( method: method, topics: topics, - workspaceID: params?["workspace_id"] as? String + workspaceID: params?["workspace_id"] as? String, + surfaceID: params?["surface_id"] as? String ) // Answer each request concurrently so one held response cannot // head-of-line block later RPCs, matching the Mac host's diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift new file mode 100644 index 000000000000..8e9135b8ac66 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift @@ -0,0 +1,156 @@ +import CMUXMobileCore +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct PaneMapPreviewFetchTests { + @Test func selectedSurfacesLeadDeduplicatedFourRequestWindow() 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 = ["selected-2", "selected-1", "selected-3", "selected-4", "other-1", "other-2"] + 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: ["selected-2", "selected-1", "selected-2", "selected-3", "selected-4"], + remainingSurfaceIDs: ["other-1", "selected-1", "other-2"] + ) + } + let filledWindow = await router.waitForCount( + of: "mobile.terminal.replay", + atLeast: 4, + recordIssueOnTimeout: false + ) + let firstWindow = await router.surfaceIDs(for: "mobile.terminal.replay") + let requestCountBeforeRelease = await router.count(of: "mobile.terminal.replay") + await router.releaseAllHeld() + let grids = await fetch.value + let allRequestedSurfaceIDs = await router.surfaceIDs(for: "mobile.terminal.replay") + + #expect(filledWindow) + #expect(requestCountBeforeRelease == 4) + #expect(Set(firstWindow) == Set(["selected-2", "selected-1", "selected-3", "selected-4"])) + #expect(allRequestedSurfaceIDs.count == surfaceIDs.count) + #expect(Set(allRequestedSurfaceIDs) == Set(surfaceIDs)) + #expect(Set(grids.keys) == Set(surfaceIDs)) + await store.remoteClient?.disconnect() + } + + @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() + _ = await fetch.value + try await Task.sleep(nanoseconds: 50_000_000) + 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() + } + + 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)] + ) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift index 01d68e970efd..788038256e95 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift @@ -26,6 +26,32 @@ import Testing #expect(rows == ["aXYd"]) } + @Test func wideGlyphKeepsFollowingSpansInProducerColumns() { + let rows = PaneMapPreviewRenderer.rows( + columns: 6, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 0, text: "界A", cellWidth: 3), + .init(row: 0, column: 4, text: "Z"), + ] + ) + + #expect(rows == ["界A Z "]) + } + + @Test func laterSpanClearsWideGlyphWhoseContinuationItOverlaps() { + let rows = PaneMapPreviewRenderer.rows( + columns: 4, + rowCount: 1, + rowSpans: [ + .init(row: 0, column: 0, text: "界A", cellWidth: 3), + .init(row: 0, column: 1, text: "XY"), + ] + ) + + #expect(rows == [" XY "]) + } + @Test func textIsTruncatedAtFinalGridColumn() { let rows = PaneMapPreviewRenderer.rows( columns: 4, From b3c77412779e9134b210f80ba6c2239ec9570cb6 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:42:24 -0700 Subject: [PATCH 12/78] Run pane layout packages in iOS CI --- .github/workflows/test-ios.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/test-ios.yml b/.github/workflows/test-ios.yml index 93e39c589e27..1f5d12e26576 100644 --- a/.github/workflows/test-ios.yml +++ b/.github/workflows/test-ios.yml @@ -162,6 +162,14 @@ jobs: run: | swift test --package-path Packages/iOS/CmuxMobilePairedMac + - name: Run CmuxMobileRPC package tests + run: | + swift test --package-path Packages/iOS/CmuxMobileRPC + + - name: Run CmuxMobileShellModel package tests + run: | + swift test --package-path Packages/iOS/CmuxMobileShellModel + - name: Run CmuxMobileShell package tests run: | # iOS shell replay/liveness regressions live in this package target. From f441a45c01c245ae1d0f265d43f2c668df2c0e66 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:42:53 -0700 Subject: [PATCH 13/78] test(ios): constrain pane split ratios --- .../MobilePaneLayoutTests.swift | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift index bd36b9204a35..9e81bc2c8950 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobilePaneLayoutTests.swift @@ -58,6 +58,17 @@ import Testing #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", @@ -106,6 +117,16 @@ import Testing 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 From b33638d6681c799bf91e9872c6f5777911c6a3cb Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:53:56 -0700 Subject: [PATCH 14/78] Fix pane preview rendering and cancellation --- ...ileTerminalRenderGridFrame+CellWidth.swift | 50 +++++++++++ ...rminalRenderGridFrame+PaneMapPreview.swift | 90 +++++++++++++++++++ .../MobileTerminalRenderGridReplay.swift | 55 +----------- ...rminalRenderGridPaneMapPreviewTests.swift} | 70 +++++++++------ ...MobileShellComposite+PaneMapPreviews.swift | 69 +++++++------- .../PaneMapPreviewFetcher.swift | 75 ++++++++++++++++ .../PaneMapPreviewRenderer.swift | 60 ------------- 7 files changed, 289 insertions(+), 180 deletions(-) create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift rename Packages/{iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift => Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift} (51%) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PaneMapPreviewFetcher.swift delete mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift index 244638499c2a..d3eecc993e5e 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift @@ -28,6 +28,56 @@ 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 + } + var remaining = gridCellWidth - 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 > gridCellWidth { + var excess = total - gridCellWidth + 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 + } } 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..b3e20462e7e7 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift @@ -0,0 +1,90 @@ +private struct PaneMapPreviewCell { + var text = " " + var glyphID: Int? +} + +public extension MobileTerminalRenderGridFrame { + /// Renders the content-bearing tail of this frame as terminal-width text. + /// + /// Each span uses the same producer-width resolution as VT replay. A wide + /// grapheme occupies one string element followed by an empty continuation, + /// so later content remains in its original terminal column. Spans are + /// applied in source order; a later span that touches any cell of an older + /// grapheme clears that whole grapheme before painting its replacement. + /// + /// - Parameter maximumRows: The maximum number of grid rows to return. + /// - Returns: Preview rows ordered from the first included row to the last. + func paneMapPreviewRows(maximumRows: Int = 20) -> [String] { + guard columns > 0, rows > 0, maximumRows > 0 else { return [] } + + var spansByRow: [Int: [RowSpan]] = [:] + var lastSpanRow: Int? + for span in rowSpans where !span.text.isEmpty { + spansByRow[span.row, default: []].append(span) + lastSpanRow = max(lastSpanRow ?? span.row, span.row) + } + + let lastContentRow = max(lastSpanRow ?? 0, cursor?.row ?? 0) + let minimumEndRow = min(rows, maximumRows) + let endRow = min(rows, max(lastContentRow + 1, minimumEndRow)) + let firstRow = max(0, endRow - maximumRows) + return (firstRow.. String { + var cells = Array(repeating: PaneMapPreviewCell(), 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] = PaneMapPreviewCell() + } + } + + func place(_ text: String, at column: Int, width: 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) + column += width + } + } + + return cells.map(\.text).joined() + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift index 3c67b12d8524..168e8da725d8 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridReplay.swift @@ -316,7 +316,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)) @@ -349,59 +349,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/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift similarity index 51% rename from Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift rename to Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift index 788038256e95..c9710f512f86 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapPreviewRendererTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift @@ -1,74 +1,70 @@ -import CMUXMobileCore import Testing -@testable import CmuxMobileShellUI +@testable import CMUXMobileCore -@Suite struct PaneMapPreviewRendererTests { - @Test func emptyGridProducesSpaceCanvas() { - let rows = PaneMapPreviewRenderer.rows( +@Suite struct MobileTerminalRenderGridPaneMapPreviewTests { + @Test func emptyGridProducesSpaceCanvas() throws { + let rows = try Self.frame( columns: 4, rowCount: 2, rowSpans: [] - ) + ).paneMapPreviewRows() #expect(rows == [" ", " "]) } - @Test func laterOverlappingSpanWinsInSourceOrder() { - let rows = PaneMapPreviewRenderer.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() { - let rows = PaneMapPreviewRenderer.rows( + @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() { - let rows = PaneMapPreviewRenderer.rows( + @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 textIsTruncatedAtFinalGridColumn() { - let rows = PaneMapPreviewRenderer.rows( + @Test func spanAtFinalGridColumnFitsCanvas() throws { + let rows = try Self.frame( columns: 4, rowCount: 1, rowSpans: [ - .init(row: 0, column: 2, text: "WXYZ"), + .init(row: 0, column: 2, text: "WX"), ] - ) + ).paneMapPreviewRows() #expect(rows == [" WX"]) } - @Test func windowFollowsTopAnchoredContentOnTallGrid() { - // A cleared tall grid (like a phone-attached surface right after - // `clear`) keeps content at the top; the window must include it - // instead of showing the grid's blank bottom rows. - let rows = PaneMapPreviewRenderer.rows( + @Test func windowFollowsTopAnchoredContentOnTallGrid() throws { + let rows = try Self.frame( columns: 3, rowCount: 40, rowSpans: [ @@ -76,23 +72,41 @@ import Testing .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() { - let rows = PaneMapPreviewRenderer.rows( + @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") } + + private static func frame( + columns: Int, + rowCount: Int, + rowSpans: [MobileTerminalRenderGridFrame.RowSpan], + cursorRow: Int? = nil + ) throws -> MobileTerminalRenderGridFrame { + try MobileTerminalRenderGridFrame( + surfaceID: "terminal-preview", + stateSeq: 1, + columns: columns, + rows: rowCount, + cursor: cursorRow.map { + MobileTerminalRenderGridFrame.Cursor(row: $0, column: 0) + }, + rowSpans: rowSpans + ) + } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift index 9421d83c30b0..10679ccea069 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift @@ -1,8 +1,25 @@ 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 @@ -28,13 +45,18 @@ extension MobileShellComposite { ] ) 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 payload = try MobileTerminalReplayResponse.decode(data) 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)" ) return grid + } catch is CancellationError { + return nil } catch { MobileDebugLog.anchormux("CMUX_PANEMAP preview surface=\(surfaceID) error=\(error)") return nil @@ -56,43 +78,14 @@ extension MobileShellComposite { selectedSurfaceIDs: [String], remainingSurfaceIDs: [String] ) async -> [String: MobileTerminalRenderGridFrame] { - var seenSurfaceIDs: Set = [] - let orderedSurfaceIDs = (selectedSurfaceIDs + remainingSurfaceIDs).filter { - seenSurfaceIDs.insert($0).inserted - } - guard !orderedSurfaceIDs.isEmpty else { return [:] } - - return await withTaskGroup( - of: (String, MobileTerminalRenderGridFrame?).self, - returning: [String: MobileTerminalRenderGridFrame].self - ) { group in - var nextIndex = 0 - - func enqueueNext() { - guard nextIndex < orderedSurfaceIDs.count else { return } - let surfaceID = orderedSurfaceIDs[nextIndex] - nextIndex += 1 - group.addTask { [weak self] in - let grid = await self?.fetchPaneMapPreviewGrid( - remoteWorkspaceID: remoteWorkspaceID, - surfaceID: surfaceID - ) - return (surfaceID, grid) - } - } - - for _ in 0.. 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/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift deleted file mode 100644 index e07fc9609093..000000000000 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapPreviewRenderer.swift +++ /dev/null @@ -1,60 +0,0 @@ -import CMUXMobileCore - -/// Assembles compact plain-text terminal rows for pane-map previews. -struct PaneMapPreviewRenderer { - /// Renders the content-bearing tail of a render-grid frame as fixed-width text. - /// - /// Spans are applied in their source order, so a later overlapping span wins. - /// Text that reaches beyond the grid's final column is truncated. - /// - /// - Parameters: - /// - frame: The render-grid snapshot to assemble. - /// - maximumRows: The maximum number of grid rows to return. - /// - Returns: Fixed-width strings ordered from the first included row to the last. - static func rows( - in frame: MobileTerminalRenderGridFrame, - maximumRows: Int = 20 - ) -> [String] { - rows( - columns: frame.columns, - rowCount: frame.rows, - rowSpans: frame.rowSpans, - cursorRow: frame.cursor?.row, - maximumRows: maximumRows - ) - } - - /// Pure assembly seam used by focused unit tests and the frame renderer. - /// - /// The window ends at the last row that has content (or the cursor row, - /// whichever is lower), not at the grid's bottom: a cleared tall grid keeps - /// its content at the top, and a bottom-anchored window would show only - /// blank rows for it (this is exactly what a phone-attached surface's - /// phone-sized grid looks like right after `clear`). - static func rows( - columns: Int, - rowCount: Int, - rowSpans: [MobileTerminalRenderGridFrame.RowSpan], - cursorRow: Int? = nil, - maximumRows: Int = 20 - ) -> [String] { - guard columns > 0, rowCount > 0, maximumRows > 0 else { return [] } - - let lastSpanRow = rowSpans.map(\.row).max() - let lastContentRow = max(lastSpanRow ?? 0, cursorRow ?? 0) - let endRow = min(rowCount, max(lastContentRow + 1, min(rowCount, maximumRows))) - let firstRow = max(0, endRow - maximumRows) - return (firstRow..= 0, span.column < columns else { continue } - for (offset, character) in span.text.enumerated() { - let column = span.column + offset - guard column < columns else { break } - characters[column] = character - } - } - return String(characters) - } - } -} From 51d30bf2a7618d73a2f32c18e59e09d21b451d5e Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 15:58:12 -0700 Subject: [PATCH 15/78] Share pane layouts across mobile sync transports --- .../MobileStateSyncRecords.swift | 7 +- .../MobileWorkspaceLayout.swift | 42 ++++++ .../MobileWorkspaceLayoutNode.swift | 63 +++++++++ .../MobileWorkspaceLayoutOrientation.swift | 8 ++ .../MobileWorkspaceLayoutPane.swift | 33 +++++ .../MobileWorkspaceLayoutSplit.swift | 39 ++++++ .../MobileWorkspaceLayoutSurface.swift | 23 ++++ .../MobileStateSyncFrameCodingTests.swift | 25 +++- .../MobileStateSyncStoreTests.swift | 39 +++++- .../MobileWorkspaceLayoutTests.swift | 100 ++++++++++++++ .../MobileSyncWorkspaceListResponse.swift | 127 ++++------------- ...MobileWorkspacePreview+RemoteMapping.swift | 15 +- .../MobilePaneLayoutDecodeTests.swift | 44 ++++++ .../MobileShellComposite+StateSync.swift | 3 +- Packages/macOS/CmuxWorkspaces/Package.swift | 4 + .../MobileWorkspaceLayoutSerializer.swift | 130 ++++++++++++++++++ ...MobileWorkspaceLayoutSurfaceMetadata.swift | 23 ++++ .../Mobile/MobileWorkspacePaneTopology.swift | 23 ++++ ...MobileWorkspaceLayoutSerializerTests.swift | 94 +++++++++++++ Sources/Mobile/MobileStateSync.swift | 3 +- ...rminalController+MobileWorkspaceList.swift | 125 +---------------- .../Workspace+MobilePaneLayoutSnapshot.swift | 29 ++++ cmux.xcodeproj/project.pbxproj | 4 + 23 files changed, 770 insertions(+), 233 deletions(-) create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayout.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutNode.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutOrientation.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutPane.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSplit.swift create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileWorkspaceLayoutSurface.swift create mode 100644 Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileWorkspaceLayoutTests.swift create mode 100644 Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSerializer.swift create mode 100644 Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspaceLayoutSurfaceMetadata.swift create mode 100644 Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Mobile/MobileWorkspacePaneTopology.swift create mode 100644 Packages/macOS/CmuxWorkspaces/Tests/CmuxWorkspacesTests/MobileWorkspaceLayoutSerializerTests.swift create mode 100644 Sources/Workspace+MobilePaneLayoutSnapshot.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift index 1e9a83f23d3f..5ceb0b61c563 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift @@ -98,6 +98,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 } @@ -118,7 +120,8 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { lastActivityAt: Double, hasUnread: Bool, sortIndex: Int, - terminals: [Terminal] + terminals: [Terminal], + layout: MobileWorkspaceLayout? = nil ) { self.id = id self.windowID = windowID @@ -133,6 +136,7 @@ public struct WorkspaceSyncRecord: MobileSyncRecord { self.hasUnread = hasUnread self.sortIndex = sortIndex self.terminals = terminals + self.layout = layout } private enum CodingKeys: String, CodingKey { @@ -149,6 +153,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/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 100141b1f31f..55e6ca72b422 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", @@ -26,7 +42,8 @@ struct MobileStateSyncFrameCodingTests { isReady: true, isFocused: false ) - ] + ], + layout: layout ) } @@ -45,6 +62,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 deltaEventRoundTripsThroughJSONObject() 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/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 0be5c95e679b..fba8846a4949 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. @@ -42,7 +46,7 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { /// Terminals belonging to this workspace. public let terminals: [Terminal] /// The workspace's pane layout, or `nil` when absent or malformed. - public let layout: Layout? + public let layout: MobileWorkspaceLayout? private enum CodingKeys: String, CodingKey { case id @@ -77,107 +81,25 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { 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(Layout.self, forKey: .layout) - } - } - - /// A wire-level workspace pane layout snapshot. - public struct Layout: Decodable, Sendable { - /// A recursively decoded layout node. - public indirect enum Node: Decodable, Sendable { - /// A split branch with two child nodes. - case split(Split) - /// A leaf pane containing surface tabs. - case pane(Pane) - - private enum CodingKeys: String, CodingKey { - case kind - } - - private enum Kind: String, Decodable { - case split - case pane - } - - /// Decodes a layout node based on its `kind` discriminator. - /// - Parameter decoder: The decoder for one layout node. - /// - Throws: A decoding error for unknown kinds or malformed node data. - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let kind = try container.decode(Kind.self, forKey: .kind) - switch kind { - case .split: - self = try .split(Split(from: decoder)) - case .pane: - self = try .pane(Pane(from: decoder)) - } - } - } - - /// A wire-level split branch. - public struct Split: Decodable, Sendable { - /// A split orientation emitted by bonsplit. - public enum Orientation: String, Decodable, Sendable { - /// Places children side by side. - case horizontal - /// Stacks children vertically. - case vertical - } - - /// The stable split identifier. - public let id: String - /// The axis along which this split divides its rectangle. - public let orientation: Orientation - /// The first child's proportional share. - public let ratio: Double - /// The first child node. - public let first: Node - /// The second child node. - public let second: Node + layout = try? container.decode(MobileWorkspaceLayout.self, forKey: .layout) } - /// A wire-level leaf pane. - public struct Pane: Decodable, Sendable { - /// The stable pane identifier. - public let id: String - /// The selected surface identifier, when one is selected. - public let selectedSurfaceID: String? - /// The pane's surfaces in tab order. - public let surfaces: [Surface] - - private enum CodingKeys: String, CodingKey { - case id - case selectedSurfaceID = "selected_surface_id" - case surfaces - } - } - - /// A wire-level surface tab. - public struct Surface: Decodable, Sendable { - /// The stable surface identifier. - public let id: String - /// The raw panel type emitted by the Mac. - public let type: String - /// The surface's display title. - public let title: String - } - - /// The Mac-side pane layout version. - public let version: Int - /// The focused pane identifier, when one is focused. - public let focusedPaneID: String? - /// The root of the recursive layout tree. - public let root: Node - - private enum CodingKeys: String, CodingKey { - case version - case focusedPaneID = "focused_pane_id" - case root - } - - /// 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. + /// - 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?, @@ -190,7 +112,8 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { previewAt: Double?, lastActivityAt: Double?, hasUnread: Bool?, - terminals: [Terminal] + terminals: [Terminal], + layout: MobileWorkspaceLayout? ) { self.id = id self.windowID = windowID @@ -204,6 +127,7 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { self.lastActivityAt = lastActivityAt self.hasUnread = hasUnread self.terminals = terminals + self.layout = layout } } @@ -348,4 +272,3 @@ extension MobileSyncWorkspaceListResponse { } - diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileWorkspacePreview+RemoteMapping.swift index 21985d9a1ad6..eacbc729bfe2 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 @@ -25,7 +26,7 @@ extension MobileWorkspacePreview { } private extension MobilePaneLayout { - init(remote: MobileSyncWorkspaceListResponse.Layout) { + init(remote: MobileWorkspaceLayout) { self.init( version: remote.version, focusedPaneID: remote.focusedPaneID, @@ -35,7 +36,7 @@ private extension MobilePaneLayout { } private extension MobilePaneLayout.Node { - init(remote: MobileSyncWorkspaceListResponse.Layout.Node) { + init(remote: MobileWorkspaceLayoutNode) { switch remote { case let .split(split): self = .split(MobilePaneSplit(remote: split)) @@ -46,11 +47,11 @@ private extension MobilePaneLayout.Node { } private extension MobilePaneSplit { - init(remote: MobileSyncWorkspaceListResponse.Layout.Split) { + init(remote: MobileWorkspaceLayoutSplit) { self.init( id: remote.id, orientation: MobilePaneSplitOrientation(remote: remote.orientation), - ratio: min(max(remote.ratio, 0.05), 0.95), + ratio: remote.ratio, first: MobilePaneLayout.Node(remote: remote.first), second: MobilePaneLayout.Node(remote: remote.second) ) @@ -58,7 +59,7 @@ private extension MobilePaneSplit { } private extension MobilePaneSplitOrientation { - init(remote: MobileSyncWorkspaceListResponse.Layout.Split.Orientation) { + init(remote: MobileWorkspaceLayoutOrientation) { switch remote { case .horizontal: self = .horizontal @@ -69,7 +70,7 @@ private extension MobilePaneSplitOrientation { } private extension MobilePaneNode { - init(remote: MobileSyncWorkspaceListResponse.Layout.Pane) { + init(remote: MobileWorkspaceLayoutPane) { self.init( id: remote.id, selectedSurfaceID: remote.selectedSurfaceID, @@ -79,7 +80,7 @@ private extension MobilePaneNode { } private extension MobilePaneSurface { - init(remote: MobileSyncWorkspaceListResponse.Layout.Surface) { + init(remote: MobileWorkspaceLayoutSurface) { self.init( id: remote.id, type: MobilePaneSurfaceType(remoteRawValue: remote.type), diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift index 4621e7fea25f..0718da06ea86 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobilePaneLayoutDecodeTests.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import CmuxMobileShellModel import Foundation import Testing @@ -5,6 +6,49 @@ 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(""" { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift index 170138209fb1..ffc8b42ca999 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+StateSync.swift @@ -333,7 +333,8 @@ extension MobileShellComposite { isFocused: terminal.isFocused, isReady: terminal.isReady ) - } + }, + layout: record.layout ) } let groups = stateSyncMirror.groups.orderedRecords.map { record in 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/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/Sources/Mobile/MobileStateSync.swift b/Sources/Mobile/MobileStateSync.swift index b8804563f1e6..8d5a3eb4d9e8 100644 --- a/Sources/Mobile/MobileStateSync.swift +++ b/Sources/Mobile/MobileStateSync.swift @@ -179,7 +179,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/TerminalController+MobileWorkspaceList.swift b/Sources/TerminalController+MobileWorkspaceList.swift index c1038a9bcd78..2552fdd8e905 100644 --- a/Sources/TerminalController+MobileWorkspaceList.swift +++ b/Sources/TerminalController+MobileWorkspaceList.swift @@ -1,6 +1,5 @@ import AppKit -import Bonsplit -import CmuxWorkspaces +import CMUXMobileCore import Foundation // MARK: - Mobile workspace list (iOS-facing payloads) @@ -10,101 +9,6 @@ import Foundation // group collapse/expand handler. Lives in its own file so the mobile list // payload code stays together without growing TerminalController.swift. -/// Pure serialization of bonsplit's external tree into the mobile `layout.v1` -/// dictionary shape. -struct MobileWorkspaceLayoutSerializer { - struct SurfaceMetadata { - let id: String - let type: String - let title: String - } - - struct PaneTopology { - let id: String - let surfaceIDs: [String] - let selectedSurfaceID: String? - } - - static func payload( - tree: ExternalTreeNode, - version: Int, - focusedPaneID: String?, - surfacesByTabID: [String: SurfaceMetadata] - ) -> [String: Any] { - [ - "version": version, - "focused_pane_id": jsonValue(focusedPaneID), - "root": nodePayload(tree, surfacesByTabID: surfacesByTabID), - ] - } - - static func tabs(in tree: ExternalTreeNode) -> [ExternalTab] { - switch tree { - case .pane(let pane): - return pane.tabs - case .split(let split): - return tabs(in: split.first) + tabs(in: split.second) - } - } - - static func paneTopology(in tree: ExternalTreeNode) -> [PaneTopology] { - switch tree { - case .pane(let pane): - return [PaneTopology( - id: pane.id, - surfaceIDs: pane.tabs.map(\.id), - selectedSurfaceID: pane.selectedTabId - )] - case .split(let split): - return paneTopology(in: split.first) + paneTopology(in: split.second) - } - } - - private static func nodePayload( - _ node: ExternalTreeNode, - surfacesByTabID: [String: SurfaceMetadata] - ) -> [String: Any] { - switch node { - case .pane(let pane): - let surfaces = pane.tabs.map { tab -> [String: Any] in - let metadata = surfacesByTabID[tab.id] ?? SurfaceMetadata( - id: tab.id, - type: PanelType.terminal.rawValue, - title: tab.title - ) - return [ - "id": metadata.id, - "type": metadata.type, - "title": metadata.title, - ] - } - let selectedSurfaceID = pane.selectedTabId.map { tabID in - surfacesByTabID[tabID]?.id ?? tabID - } - return [ - "kind": "pane", - "id": pane.id, - "selected_surface_id": jsonValue(selectedSurfaceID), - "surfaces": surfaces, - ] - case .split(let split): - return [ - "kind": "split", - "id": split.id, - "orientation": split.orientation, - "ratio": split.dividerPosition, - "first": nodePayload(split.first, surfacesByTabID: surfacesByTabID), - "second": nodePayload(split.second, surfacesByTabID: surfacesByTabID), - ] - } - } - - private static func jsonValue(_ value: String?) -> Any { - guard let value else { return NSNull() } - return value - } -} - extension TerminalController { /// Mobile-gated collapse/expand of a workspace group. P1 group support on /// iOS is display-only: the phone renders collapsible group sections and can @@ -306,30 +210,12 @@ extension TerminalController { ] } - let layoutTree = workspace.bonsplitController.treeSnapshot() - var layoutSurfacesByTabID: [String: MobileWorkspaceLayoutSerializer.SurfaceMetadata] = [:] - for tab in MobileWorkspaceLayoutSerializer.tabs(in: layoutTree) { - let panelID = UUID(uuidString: tab.id).flatMap { workspace.panelId(forSurfaceId: $0) } - let panel = panelID.flatMap { workspace.panels[$0] } - layoutSurfacesByTabID[tab.id] = MobileWorkspaceLayoutSerializer.SurfaceMetadata( - id: panelID?.uuidString ?? tab.id, - type: panel?.panelType.rawValue ?? PanelType.terminal.rawValue, - title: panelID.flatMap { workspace.panelTitle(panelId: $0) } - ?? panel?.displayTitle - ?? tab.title - ) - } - let layout = MobileWorkspaceLayoutSerializer.payload( - tree: layoutTree, - version: workspace.paneLayoutVersion, - focusedPaneID: workspace.bonsplitController.focusedPaneId?.id.uuidString, - surfacesByTabID: layoutSurfacesByTabID - ) + let layout = workspace.mobileWorkspaceLayoutSnapshot() let store = notificationStore ?? AppDelegate.shared?.notificationStore let latestNotification = store?.latestNotification(forTabId: workspace.id) let preview = Self.mobileWorkspacePreview(latestNotification: latestNotification) - return [ + var payload: [String: Any] = [ "id": workspace.id.uuidString, "window_id": v2OrNull(windowID?.uuidString), "title": workspace.title, @@ -354,9 +240,12 @@ extension TerminalController { // unread + manual/panel-derived/restored indicators) so the phone can // show an iMessage-style unread dot. "has_unread": store?.workspaceIsUnread(forTabId: workspace.id) ?? false, - "layout": layout, "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/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/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 370c0cfbad1e..72ed8ba29402 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -2016,6 +2016,7 @@ 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 */; }; 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 */; }; @@ -4120,6 +4121,7 @@ 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 = ""; }; 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 = ""; }; @@ -5139,6 +5141,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C0DE00000000000000000C55 /* TerminalController+ControlPaneContext.swift */, C7A50B000000000000000001 /* TerminalControllerV2ParamParsingSupport.swift */, C7A50B000000000000000011 /* TerminalController+MobileWorkspaceList.swift */, + A18F4D6C1A2B3C4D5E6F7001 /* Workspace+MobilePaneLayoutSnapshot.swift */, C7A505000000000000000001 /* TerminalControllerTopSupport.swift */, C7A501000000000000000001 /* CmuxTopSnapshot.swift */, C7A510000000000000000001 /* CmuxTopMemoryDiagnostics.swift */, @@ -8200,6 +8203,7 @@ 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 */, C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */, 797800030000000000000001 /* Workspace+PersistentRemotePTYReattach.swift in Sources */, 791100010000000000000001 /* Workspace+RemoteDisconnectPlaceholder.swift in Sources */, From bdddcf2644c65bbff0e3dfdffbb232461425efc8 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 16:07:43 -0700 Subject: [PATCH 16/78] feat(ios): complete pane-aware workspace navigation --- .../MobilePaneSplit.swift | 4 +- .../{ => Debug}/PanesTabsPreviewHost.swift | 67 ++++++---- .../CmuxMobileShellUI/PaneMapOverlay.swift | 72 ++++++++--- .../CmuxMobileShellUI/PaneMapTileView.swift | 120 +++++++++++++++--- .../CmuxMobileShellUI/PaneMapValue.swift | 12 ++ .../CmuxMobileShellUI/SurfaceDeckBar.swift | 89 +++++++++++-- .../CmuxMobileShellUI/SurfaceDeckValue.swift | 16 ++- .../WorkspaceDetailView.swift | 14 +- .../WorkspaceUtilitiesMenu.swift | 12 ++ .../SurfaceDeckValueTests.swift | 36 ++++++ ios/cmux/Resources/Localizable.xcstrings | 49 +++++++ ios/cmuxUITests/cmuxUITests.swift | 75 ++++++++++- 12 files changed, 486 insertions(+), 80 deletions(-) rename Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/{ => Debug}/PanesTabsPreviewHost.swift (81%) diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift index edf9a2230dd9..19cfc9a484bd 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobilePaneSplit.swift @@ -4,7 +4,7 @@ public struct MobilePaneSplit: Sendable, Equatable { 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` by RPC mapping. + /// 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 @@ -27,7 +27,7 @@ public struct MobilePaneSplit: Sendable, Equatable { ) { self.id = id self.orientation = orientation - self.ratio = ratio + self.ratio = ratio.isFinite ? min(max(ratio, 0.05), 0.95) : 0.5 self.first = first self.second = second } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift similarity index 81% rename from Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift rename to Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index f4a5047910cc..0e3ef69d2e3d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -112,30 +112,45 @@ struct PanesTabsPreviewHost: View { ] var body: some View { - terminalTheme.terminalBackgroundColor - .frame(maxWidth: .infinity, maxHeight: .infinity) - .safeAreaInset(edge: .bottom, spacing: 0) { - SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) - .equatable() - } - .ignoresSafeArea(.keyboard, edges: .bottom) - .fullScreenCover(isPresented: $isPaneMapPresented) { - if let layout = workspace.layout { - PaneMapOverlay( - value: PaneMapValue( - workspaceName: workspace.name, - layout: layout, - phoneSelectedSurfaceID: selectedSurfaceID, - agentStateKindsBySurfaceID: agentStateKindsBySurfaceID - ), - terminalTheme: terminalTheme, - fetchPreviews: Self.fetchFixturePreviews, - selectTerminal: { selectedSurfaceID = $0.rawValue }, - dismiss: { isPaneMapPresented = false } - ) - } + ZStack(alignment: .topTrailing) { + terminalTheme.terminalBackgroundColor + .frame(maxWidth: .infinity, maxHeight: .infinity) + + WorkspaceUtilitiesMenu( + showsViewAsText: false, + showsPaneMap: true, + terminalTheme: terminalTheme, + presentPaneMap: presentPaneMap, + openTextSheet: {}, + copyDebugLogs: {}, + sendFeedback: {} + ) + .frame(width: 44, height: 44) + .padding() + } + .safeAreaInset(edge: .bottom, spacing: 0) { + SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) + .equatable() + } + .ignoresSafeArea(.keyboard, edges: .bottom) + .fullScreenCover(isPresented: $isPaneMapPresented) { + if let layout = workspace.layout { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + layout: layout, + phoneSelectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID + ), + terminalTheme: terminalTheme, + fetchPreviews: Self.fetchFixturePreviews, + selectTerminal: { selectedSurfaceID = $0.rawValue }, + dismiss: { isPaneMapPresented = false } + ) } - .accessibilityIdentifier("PanesTabsPreviewHost") + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("PanesTabsPreviewHost") } private var deckValue: SurfaceDeckValue { @@ -150,13 +165,17 @@ struct PanesTabsPreviewHost: View { private var deckActions: SurfaceDeckActions { SurfaceDeckActions( selectTerminal: { selectedSurfaceID = $0.rawValue }, - presentPaneMap: { isPaneMapPresented = true }, + presentPaneMap: presentPaneMap, createTerminal: {}, openBrowser: {}, createWorkspace: {} ) } + private func presentPaneMap() { + isPaneMapPresented = true + } + private static func fetchFixturePreviews( selectedSurfaceIDs: [String], remainingSurfaceIDs: [String] diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index 2deacb72fadf..3b9de2c11cea 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -14,6 +14,8 @@ struct PaneMapOverlay: View { @State private var selectedSurfaceIDsByPaneID: [String: String] @State private var previewGridsBySurfaceID: [String: MobileTerminalRenderGridFrame] = [:] @State private var isRefreshing = false + @State private var refreshTask: Task? + @State private var refreshGeneration: UUID? init( value: PaneMapValue, @@ -37,8 +39,16 @@ struct PaneMapOverlay: View { } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(terminalTheme.terminalBackgroundColor.ignoresSafeArea()) - .task { - await refreshAllPreviews() + .onAppear { + startPreviewRefresh() + } + .onDisappear { + cancelPreviewRefresh() + } + .onChange(of: value.layout) { _, _ in + selectedSurfaceIDsByPaneID = value.reconciledSurfaceIDs( + current: selectedSurfaceIDsByPaneID + ) } .accessibilityIdentifier("MobilePaneMapOverlay") } @@ -59,9 +69,7 @@ struct PaneMapOverlay: View { Spacer(minLength: 0) - Button { - Task { await refreshAllPreviews() } - } label: { + Button(action: startPreviewRefresh) { HStack(spacing: 5) { if isRefreshing { ProgressView() @@ -83,7 +91,7 @@ struct PaneMapOverlay: View { .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) .accessibilityIdentifier("MobilePaneMapRefresh") - Button(action: dismiss) { + Button(action: dismissPaneMap) { Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) .font(.subheadline.weight(.semibold)) .foregroundStyle(terminalTheme.terminalChromeForegroundColor) @@ -104,13 +112,16 @@ struct PaneMapOverlay: View { let normalizedRects = value.layout.normalizedRects() ZStack(alignment: .topLeading) { - ForEach(value.panes, id: \.id) { pane in + ForEach(value.panes.enumerated(), id: \.element.id) { index, pane in if let normalizedRect = normalizedRects[pane.id] { let tileRect = scaledTileRect(normalizedRect, in: canvasRect) let surfaceID = selectedSurfaceIDsByPaneID[pane.id] PaneMapTileView( pane: pane, + paneNumber: index + 1, + paneCount: value.panes.count, + isFocusedOnMac: value.layout.focusedPaneID == pane.id, terminalTheme: terminalTheme, selectedSurfaceID: surfaceID, phoneSelectedSurfaceID: value.phoneSelectedSurfaceID, @@ -139,24 +150,24 @@ struct PaneMapOverlay: View { defaultValue: "1 pane · 1 tab" ) case (true, false): - return String( - format: L10n.string( + return String.localizedStringWithFormat( + L10n.string( "mobile.paneMap.count.onePane.otherTabs", defaultValue: "1 pane · %d tabs" ), tabCount ) case (false, true): - return String( - format: L10n.string( + return String.localizedStringWithFormat( + L10n.string( "mobile.paneMap.count.otherPanes.oneTab", defaultValue: "%d panes · 1 tab" ), paneCount ) case (false, false): - return String( - format: L10n.string( + return String.localizedStringWithFormat( + L10n.string( "mobile.paneMap.count.otherPanes.otherTabs", defaultValue: "%d panes · %d tabs" ), @@ -191,13 +202,40 @@ struct PaneMapOverlay: View { private func jumpToTerminal(_ surfaceID: String) { selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) + dismissPaneMap() + } + + private func dismissPaneMap() { + cancelPreviewRefresh() dismiss() } - private func refreshAllPreviews() async { + 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 + } + + private func refreshAllPreviews(generation: UUID) async { guard !isRefreshing else { return } isRefreshing = true - defer { isRefreshing = false } + defer { + if refreshGeneration == generation { + isRefreshing = false + } + } let selectedTerminalSurfaceIDs = value.panes.compactMap { pane -> String? in guard let surfaceID = selectedSurfaceIDsByPaneID[pane.id], @@ -210,9 +248,11 @@ struct PaneMapOverlay: View { let remainingTerminalSurfaceIDs = value.panes.flatMap(\.surfaces).compactMap { surface in surface.type.isTerminal && !selectedSet.contains(surface.id) ? surface.id : nil } - previewGridsBySurfaceID = await fetchPreviews( + let previews = await fetchPreviews( selectedTerminalSurfaceIDs, remainingTerminalSurfaceIDs ) + guard !Task.isCancelled, refreshGeneration == generation else { return } + previewGridsBySurfaceID = previews } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index 26b1020d74ae..8dd68f776a68 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -6,6 +6,9 @@ import SwiftUI /// One proportional pane tile rendered from immutable layout and preview snapshots. struct PaneMapTileView: View { let pane: MobilePaneNode + let paneNumber: Int + let paneCount: Int + let isFocusedOnMac: Bool let terminalTheme: TerminalTheme let selectedSurfaceID: String? let phoneSelectedSurfaceID: String? @@ -17,7 +20,7 @@ struct PaneMapTileView: View { private var selectedSurface: MobilePaneSurface? { guard let selectedSurfaceID else { return pane.surfaces.first } - return pane.surfaces.first { $0.id == selectedSurfaceID } ?? pane.surfaces.first + return pane.surfaces.first { $0.id == selectedSurfaceID } } private var isPhoneSelected: Bool { @@ -45,6 +48,13 @@ struct PaneMapTileView: View { } .clipShape(shape) .accessibilityElement(children: .contain) + .accessibilityLabel(paneAccessibilityLabel) + .accessibilityValue( + isFocusedOnMac + ? L10n.string("mobile.paneMap.focusedOnMac", defaultValue: "Focused on Mac") + : "" + ) + .accessibilityIdentifier("MobilePaneMapPane-\(pane.id)") } private func tileContent(for surface: MobilePaneSurface) -> some View { @@ -61,20 +71,49 @@ struct PaneMapTileView: View { private func header(for surface: MobilePaneSurface) -> some View { HStack(spacing: 4) { + Text(paneNumber, format: .number) + .font(.caption2.weight(.bold)) + .padding(.horizontal, 6) + .padding(.vertical, 3) + .background( + Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.12)) + ) + .accessibilityLabel(paneAccessibilityLabel) + .accessibilityIdentifier("MobilePaneMapPaneNumber-\(pane.id)") + Image(systemName: systemImage(for: surface.type)) - .font(.system(size: 10, weight: .medium)) + .font(.caption2.weight(.medium)) Text(surface.title) - .font(.system(size: 11, weight: .medium)) + .font(.caption.weight(.medium)) .lineLimit(1) .truncationMode(.tail) Spacer(minLength: 2) + if isFocusedOnMac { + Label( + L10n.string("mobile.paneMap.focusedOnMac.short", defaultValue: "Mac"), + systemImage: "macwindow" + ) + .font(.caption2.weight(.semibold)) + .labelStyle(.titleAndIcon) + .lineLimit(1) + .padding(.horizontal, 5) + .padding(.vertical, 3) + .background( + Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.12)) + ) + .accessibilityLabel( + L10n.string("mobile.paneMap.focusedOnMac", defaultValue: "Focused on Mac") + ) + } + if let agentStateKind { Circle() .fill(statusColor(agentStateKind)) .frame(width: 6, height: 6) + .accessibilityLabel(statusAccessibilityValue(agentStateKind)) } } .foregroundStyle(terminalTheme.terminalChromeForegroundColor) @@ -90,7 +129,7 @@ struct PaneMapTileView: View { selectPreviewSurface(surface.id) } label: { Text(surface.title) - .font(.system(size: 9, weight: .semibold)) + .font(.caption2.weight(.semibold)) .lineLimit(1) .truncationMode(.tail) .foregroundStyle( @@ -98,9 +137,9 @@ struct PaneMapTileView: View { ? terminalTheme.terminalBackgroundColor : terminalTheme.terminalChromeForegroundColor.opacity(0.85) ) - .padding(.horizontal, 7) - .frame(height: 14) - .frame(minWidth: 22, maxWidth: 88) + .padding(.horizontal, 8) + .padding(.vertical, 5) + .frame(minWidth: 44, maxWidth: 96) .background( Capsule().fill( isSelectedTab @@ -111,7 +150,9 @@ struct PaneMapTileView: View { .contentShape(Capsule()) } .buttonStyle(.plain) - .accessibilityLabel(surface.title) + .frame(minHeight: 44) + .contentShape(Rectangle()) + .accessibilityLabel(surfaceAccessibilityLabel(surface)) .accessibilityAddTraits(isSelectedTab ? .isSelected : []) .accessibilityIdentifier("MobilePaneMapTab-\(surface.id)") } @@ -119,7 +160,6 @@ struct PaneMapTileView: View { .padding(.horizontal, 6) } .scrollIndicators(.hidden) - .frame(height: 16) .padding(.bottom, 2) } @@ -134,14 +174,9 @@ struct PaneMapTileView: View { } .buttonStyle(.plain) .accessibilityLabel( - String.localizedStringWithFormat( - L10n.string( - "mobile.surfaceDeck.chip.terminal", - defaultValue: "%@, terminal" - ), - surface.title - ) + surfaceAccessibilityLabel(surface) ) + .accessibilityValue(statusAccessibilityValue(agentStateKind)) .accessibilityIdentifier("MobilePaneMapTile-\(surface.id)") } else { VStack(spacing: 5) { @@ -162,7 +197,7 @@ struct PaneMapTileView: View { private func terminalPreview(surfaceID: String) -> some View { if let previewGrid, previewGrid.surfaceID == surfaceID { GeometryReader { geometry in - let lines = PaneMapPreviewRenderer.rows(in: previewGrid) + let lines = previewGrid.paneMapPreviewRows() let fontSize = previewFontSize( availableSize: geometry.size, columns: previewGrid.columns, @@ -235,4 +270,55 @@ struct PaneMapTileView: View { return "rectangle" } } + + private var paneAccessibilityLabel: String { + String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.panePosition", + defaultValue: "Pane %d of %d" + ), + paneNumber, + paneCount + ) + } + + private func surfaceAccessibilityLabel(_ surface: MobilePaneSurface) -> String { + if surface.type.isTerminal { + return String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.terminalInPane", + defaultValue: "%@, terminal, pane %d of %d" + ), + surface.title, + paneNumber, + paneCount + ) + } + return String.localizedStringWithFormat( + L10n.string( + "mobile.surfaceDeck.chip.unavailableInPane", + defaultValue: "%@, unavailable on iPhone, pane %d of %d" + ), + surface.title, + paneNumber, + paneCount + ) + } + + 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 "" + } + } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift index ecc8da7af866..12f270131756 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift @@ -16,8 +16,20 @@ struct PaneMapValue: Equatable { } 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 } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift index 11129997aafc..84606362f7d4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -94,16 +94,38 @@ struct SurfaceDeckBar: View, Equatable { private func paneGroup(_ group: SurfaceDeckValue.PaneGroup) -> some View { HStack(spacing: 2) { + Text(group.number, format: .number) + .font(.caption2.weight(.bold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.8)) + .padding(.horizontal, 7) + .padding(.vertical, 5) + .background( + Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.10)) + ) + .accessibilityLabel( + paneAccessibilityLabel(number: group.number, totalCount: group.totalCount) + ) + .accessibilityIdentifier("MobileSurfaceDeckPaneNumber-\(group.id)") + ForEach(group.chips) { chip in - surfaceChip(chip) + 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) -> some View { + 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 { @@ -123,10 +145,10 @@ struct SurfaceDeckBar: View, Equatable { } Image(systemName: systemImage(for: chip.type)) - .font(.system(size: 12, weight: .medium)) + .font(.caption.weight(.medium)) Text(chip.title) - .font(.system(size: 13, weight: .medium)) + .font(.caption.weight(.medium)) .lineLimit(1) .frame(maxWidth: 96) } @@ -147,7 +169,14 @@ struct SurfaceDeckBar: View, Equatable { .buttonStyle(.plain) .opacity(chip.isTerminal ? 1 : 0.5) .id(chip.id) - .accessibilityLabel(chipAccessibilityLabel(chip)) + .accessibilityLabel( + chipAccessibilityLabel( + chip, + paneNumber: paneNumber, + paneCount: paneCount + ) + ) + .accessibilityValue(statusAccessibilityValue(statusKind)) .accessibilityAddTraits(isSelected ? .isSelected : []) .accessibilityIdentifier("MobileSurfaceDeckChip-\(chip.id)") } @@ -239,22 +268,58 @@ struct SurfaceDeckBar: View, Equatable { } } - private func chipAccessibilityLabel(_ chip: SurfaceDeckValue.Chip) -> String { + private func chipAccessibilityLabel( + _ chip: SurfaceDeckValue.Chip, + paneNumber: Int, + paneCount: Int + ) -> String { if chip.isTerminal { return String.localizedStringWithFormat( L10n.string( - "mobile.surfaceDeck.chip.terminal", - defaultValue: "%@, terminal" + "mobile.surfaceDeck.chip.terminalInPane", + defaultValue: "%@, terminal, pane %d of %d" ), - chip.title + chip.title, + paneNumber, + paneCount ) } return String.localizedStringWithFormat( L10n.string( - "mobile.surfaceDeck.chip.unavailable", - defaultValue: "%@, unavailable on iPhone" + "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" ), - chip.title + 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 "" + } + } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift index 20b063472b15..7d7ad9fa5373 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckValue.swift @@ -5,6 +5,8 @@ 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] } @@ -30,9 +32,12 @@ struct SurfaceDeckValue: Equatable { canCreateWorkspace: Bool ) { if let layout = workspace.layout { - groups = layout.orderedPanes.map { pane in + 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) } @@ -42,6 +47,8 @@ struct SurfaceDeckValue: Equatable { 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) } @@ -54,10 +61,9 @@ struct SurfaceDeckValue: Equatable { 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 { - let surfaceCount = groups.reduce(into: 0) { count, group in - count += group.chips.count - } - return surfaceCount > 1 || groups.count > 1 + true } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index e81f9dacfa9f..ecbb89d70873 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -142,6 +142,11 @@ struct WorkspaceDetailView: View { .onChange(of: store.supportsChatArtifactGallery) { _, _ in visibleArtifactCount = 0 } + .onChange(of: workspace.layout == nil) { _, layoutIsMissing in + if layoutIsMissing { + isPaneMapPresented = false + } + } .closeWorkspaceConfirmation( isPresented: $isConfirmingClose, confirm: confirmCloseWorkspaceFromMenu @@ -471,7 +476,9 @@ struct WorkspaceDetailView: View { var workspaceUtilitiesToolbarButton: some View { WorkspaceUtilitiesMenu( showsViewAsText: activeBrowser == nil && !isChatMode, + showsPaneMap: workspace.layout != nil, terminalTheme: store.activeTerminalTheme, + presentPaneMap: presentPaneMap, openTextSheet: openTextSheetFromMenu, copyDebugLogs: { #if DEBUG @@ -494,7 +501,7 @@ struct WorkspaceDetailView: View { private var surfaceDeckActions: SurfaceDeckActions { SurfaceDeckActions( selectTerminal: selectTerminalFromDeck, - presentPaneMap: { isPaneMapPresented = true }, + presentPaneMap: presentPaneMap, createTerminal: createTerminalFromToolbar, openBrowser: openBrowserFromToolbar, createWorkspace: createWorkspaceFromToolbar @@ -517,6 +524,11 @@ struct WorkspaceDetailView: View { return result } + private func presentPaneMap() { + guard workspace.layout != nil else { return } + isPaneMapPresented = true + } + #if canImport(UIKit) #if DEBUG private func copyDebugLogsFromMenu() { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift index 7a4e439ca05f..e140c6e9bce4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceUtilitiesMenu.swift @@ -5,13 +5,25 @@ import SwiftUI /// Workspace-level utilities that remain in the top-right toolbar. struct WorkspaceUtilitiesMenu: View { let showsViewAsText: Bool + let showsPaneMap: Bool let terminalTheme: TerminalTheme + 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 showsViewAsText { Button(action: openTextSheet) { Label( diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift index 2ea5302fe6ac..a616e7d75ad2 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift @@ -92,6 +92,8 @@ import Testing 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) @@ -125,6 +127,40 @@ import Testing #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( + workspaceName: "Workspace", + 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? diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 17231a4fe4ac..96c6193cab7a 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -6961,6 +6961,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": { @@ -7030,6 +7044,27 @@ "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.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": { @@ -7051,6 +7086,13 @@ "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": { @@ -7058,6 +7100,13 @@ "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": { diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 35440719e4a1..54b406d08aad 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1392,6 +1392,72 @@ 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)) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + + let leftDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-left" + ] + let testsDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-tests" + ] + let serverDeckGroup = app.descendants(matching: .any)[ + "MobileSurfaceDeckPane-preview-pane-server" + ] + XCTAssertTrue(leftDeckGroup.exists) + XCTAssertTrue(testsDeckGroup.exists) + XCTAssertTrue(serverDeckGroup.exists) + XCTAssertTrue( + app.descendants(matching: .any)[ + "MobileSurfaceDeckPaneNumber-preview-pane-left" + ].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(overlay.waitForExistence(timeout: 4)) + let leftPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-left"] + let testsPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-tests"] + let serverPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-server"] + XCTAssertTrue(leftPane.waitForExistence(timeout: 2)) + XCTAssertTrue(testsPane.exists) + XCTAssertTrue(serverPane.exists) + XCTAssertLessThan(leftPane.frame.midX, testsPane.frame.midX) + XCTAssertLessThan(testsPane.frame.midY, serverPane.frame.midY) + XCTAssertEqual(leftPane.value as? String, "Focused on Mac") + XCTAssertTrue( + app.descendants(matching: .any)[ + "MobilePaneMapPaneNumber-preview-pane-left" + ].exists + ) + + tap(app.buttons["MobilePaneMapDone"], in: app) + XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) + + tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) + XCTAssertTrue(overlay.waitForExistence(timeout: 4)) + tap(app.buttons["MobilePaneMapTab-preview-zsh"], in: app) + let zshTile = app.buttons["MobilePaneMapTile-preview-zsh"] + XCTAssertTrue(zshTile.waitForExistence(timeout: 2)) + tap(zshTile, in: app) + + XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-zsh"].isSelected) + } + @MainActor func testBottomScrollStaysPinnedAcrossComposerViewportShrink() throws { let app = launchApp(mockData: false, environment: [ @@ -1463,7 +1529,8 @@ final class cmuxUITests: XCTestCase { in: app, context: "fresh single-terminal workspace after create" ) - XCTAssertFalse(app.otherElements["MobileSurfaceDeck"].exists) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].exists) assertToolbarOverflowButtonDoesNotExist(in: app) } @@ -1496,7 +1563,8 @@ final class cmuxUITests: XCTestCase { assertToolbarOverflowButtonDoesNotExist(in: app) assertBackButtonFrameStaysCompactAroundPress(backButton, in: app) - XCTAssertFalse(app.otherElements["MobileSurfaceDeck"].exists) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].exists) } @MainActor @@ -1579,7 +1647,8 @@ final class cmuxUITests: XCTestCase { assertToolbarOverflowButtonDoesNotExist(in: app) assertBackButtonFrameStaysCompactAroundPress(backButton, in: app) - XCTAssertFalse(app.otherElements["MobileSurfaceDeck"].exists) + XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckAdd"].exists) } @MainActor From 75fc3a327eae0c8a274a53a5aaad0744f71d47ee Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 16:18:53 -0700 Subject: [PATCH 17/78] Fix actor initializer for Swift 6.3 --- .../CmuxGit/Probe/GitHubPullRequestRequestCoordinator.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxGit/Sources/CmuxGit/Probe/GitHubPullRequestRequestCoordinator.swift b/Packages/macOS/CmuxGit/Sources/CmuxGit/Probe/GitHubPullRequestRequestCoordinator.swift index a6aaf921d328..db608983fe0c 100644 --- a/Packages/macOS/CmuxGit/Sources/CmuxGit/Probe/GitHubPullRequestRequestCoordinator.swift +++ b/Packages/macOS/CmuxGit/Sources/CmuxGit/Probe/GitHubPullRequestRequestCoordinator.swift @@ -60,7 +60,7 @@ public actor GitHubPullRequestRequestCoordinator { /// `PullRequestProbeService(requestCoordinator:)`. The session and cache /// tuning knobs stay internal (tests reach that initializer through /// `@testable import`), keeping the public surface to a plain default. - public convenience init() { + public init() { self.init(session: nil) } From bd307f69a6be63c22b4a234daff9d01fc52b9e9d Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 16:21:27 -0700 Subject: [PATCH 18/78] Stabilize pane preview scheduler test --- .../PaneMapPreviewFetchTests.swift | 106 ++++++++++++------ 1 file changed, 72 insertions(+), 34 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift index 8e9135b8ac66..72942cbd3584 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift @@ -6,50 +6,37 @@ import Testing @MainActor @Suite struct PaneMapPreviewFetchTests { @Test func selectedSurfacesLeadDeduplicatedFourRequestWindow() 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 = ["selected-2", "selected-1", "selected-3", "selected-4", "other-1", "other-2"] - for (index, surfaceID) in surfaceIDs.enumerated() { - await router.enqueueReplayRenderGrid(try Self.frame( - surfaceID: surfaceID, - stateSeq: UInt64(index + 1) - )) - } - await router.holdNextReplayResponses(count: 4) + 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 { @MainActor in - await store.fetchPaneMapPreviewGrids( - remoteWorkspaceID: "workspace", + 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) + } } - let filledWindow = await router.waitForCount( - of: "mobile.terminal.replay", - atLeast: 4, - recordIssueOnTimeout: false - ) - let firstWindow = await router.surfaceIDs(for: "mobile.terminal.replay") - let requestCountBeforeRelease = await router.count(of: "mobile.terminal.replay") - await router.releaseAllHeld() - let grids = await fetch.value - let allRequestedSurfaceIDs = await router.surfaceIDs(for: "mobile.terminal.replay") + await gate.waitUntilStarted(count: 4) + let firstWindow = await gate.startedSurfaceIDs() - #expect(filledWindow) - #expect(requestCountBeforeRelease == 4) + #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)) - await store.remoteClient?.disconnect() } @Test func cancellationDoesNotStartQueuedRequests() async throws { @@ -154,3 +141,54 @@ import Testing ) } } + +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] + } + + func waitUntilStarted(count: Int) async { + guard started.count < count else { return } + startedCountTarget = count + await withCheckedContinuation { continuation in + startedCountContinuation = continuation + } + } + + func startedSurfaceIDs() -> [String] { + started + } + + func release() { + isReleased = true + let continuations = releaseContinuations + releaseContinuations.removeAll() + for continuation in continuations { + continuation.resume() + } + } +} From 8e3613f6f7c133a4bd36af5c495897e622414d95 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 17:50:16 -0700 Subject: [PATCH 19/78] Fix mobile pane layout invalidation --- .../Mobile/MobileWorkspaceListObserver.swift | 23 ++++----- ...rminalController+MobileWorkspaceList.swift | 1 + ...orkspace+WorkspaceSurfaceTreeReading.swift | 16 +++++++ Sources/Workspace.swift | 47 +++++++++++-------- .../MobileWorkspaceListFidelityTests.swift | 24 ++++++++++ 5 files changed, 78 insertions(+), 33 deletions(-) diff --git a/Sources/Mobile/MobileWorkspaceListObserver.swift b/Sources/Mobile/MobileWorkspaceListObserver.swift index 8579b8ac6268..d6385158d7d4 100644 --- a/Sources/Mobile/MobileWorkspaceListObserver.swift +++ b/Sources/Mobile/MobileWorkspaceListObserver.swift @@ -41,6 +41,7 @@ final class MobileWorkspaceListObserver { /// mobile subscriber. static var subscriberPresenceOverrideForTesting: Bool? var pipelinesAttachedForTesting: Bool { pipelinesAttached } + private(set) var emittedUpdateCountForTesting = 0 #endif /// Whether any mobile client currently subscribes to `workspace.updated`. @@ -287,6 +288,9 @@ final class MobileWorkspaceListObserver { return } lastSummaryHash = hash + #if DEBUG + emittedUpdateCountForTesting += 1 + #endif mobileWorkspaceObserverLog.debug("emitting workspace.updated (hash=\(hash, privacy: .public))") #if DEBUG cmuxDebugLog("mobile.observer EMIT workspace.updated hash=\(hash) tabs=\(tabManager.tabs.count) force=\(force)") @@ -300,11 +304,10 @@ final class MobileWorkspaceListObserver { /// Stable hash of the iOS-facing shape: workspace ids + titles + their /// panels in spatial order + each panel's displayed (custom-aware) title and - /// directory + the `layout.v1` pane topology. The topology hashes pane ids in - /// DFS order, each pane's surface-id order, and each pane's selected tab. It - /// deliberately excludes split ratios, so divider drags don't spam events, - /// and keeps excluding `focusedPanelId` itself. Scrollback content and focus - /// changes with no other list-facing effect also remain excluded. + /// 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, @@ -357,15 +360,7 @@ final class MobileWorkspaceListObserver { hasher.combine(workspace.panelTitle(panelId: id)) hasher.combine(workspace.reportedPanelDirectory(panelId: id)) } - let paneTopology = MobileWorkspaceLayoutSerializer.paneTopology( - in: workspace.bonsplitController.treeSnapshot() - ) - hasher.combine(paneTopology.count) - for pane in paneTopology { - hasher.combine(pane.id) - hasher.combine(pane.surfaceIDs) - hasher.combine(pane.selectedSurfaceID) - } + 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 2552fdd8e905..ecad5d6d78a0 100644 --- a/Sources/TerminalController+MobileWorkspaceList.swift +++ b/Sources/TerminalController+MobileWorkspaceList.swift @@ -1,5 +1,6 @@ import AppKit import CMUXMobileCore +import CmuxWorkspaces import Foundation // MARK: - Mobile workspace list (iOS-facing payloads) diff --git a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift index d7e3b22eee4a..4a00dd537545 100644 --- a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift +++ b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift @@ -83,4 +83,20 @@ extension Workspace: WorkspaceSurfaceTreeReading { func bumpPaneLayoutVersion() { paneLayoutVersion &+= 1 } + + /// 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 { + 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 8119c8aa7e40..189ff7be828b 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2152,20 +2152,20 @@ 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? + /// 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 } @@ -11972,8 +11972,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 { @@ -12051,15 +12055,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), @@ -12590,13 +12602,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/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index d28eee86f485..bbe19d8895ab 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -189,6 +189,30 @@ 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 observer = MobileWorkspaceListObserver(tabManager: manager) + #expect(observer.emittedUpdateCountForTesting == 1, "attachment emits the initial snapshot") + + workspace.bonsplitController.selectTab(secondTabID) + try await Task.sleep(for: .milliseconds(200)) + #expect(observer.emittedUpdateCountForTesting == 2, "selection publishes through the observer") + + workspace.bonsplitController.selectTab(secondTabID) + try await Task.sleep(for: .milliseconds(200)) + #expect(observer.emittedUpdateCountForTesting == 2, "a no-op selection stays suppressed") + } + @Test func orderedPanelIdsMatchesBonsplitSpatialOrder() throws { let (workspace, createdOrder) = try makeWorkspaceWithSplitTerminals(count: 3) From 682fe047dc3127e29fe92c9107a2dcd133c29a34 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 18:34:16 -0700 Subject: [PATCH 20/78] Stabilize pane observer emission assertion --- cmuxTests/MobileWorkspaceListFidelityTests.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index bbe19d8895ab..a5c9916e7dbb 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -206,11 +206,15 @@ struct MobileWorkspaceListFidelityTests { workspace.bonsplitController.selectTab(secondTabID) try await Task.sleep(for: .milliseconds(200)) - #expect(observer.emittedUpdateCountForTesting == 2, "selection publishes through the observer") + let countAfterSelection = observer.emittedUpdateCountForTesting + #expect(countAfterSelection > 1, "selection publishes through the observer") workspace.bonsplitController.selectTab(secondTabID) try await Task.sleep(for: .milliseconds(200)) - #expect(observer.emittedUpdateCountForTesting == 2, "a no-op selection stays suppressed") + #expect( + observer.emittedUpdateCountForTesting == countAfterSelection, + "a no-op selection stays suppressed" + ) } @Test func orderedPanelIdsMatchesBonsplitSpatialOrder() throws { From f4dbc09f64957d50adea7fd58528c8fc0c1358f4 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 19:33:05 -0700 Subject: [PATCH 21/78] Align window reference state with current main --- Sources/ContentView.swift | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 87f051412939..c3ed1f2e8d4c 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -110,6 +110,15 @@ private func debugCommandPaletteResponderSummary(_ responder: NSResponder?) -> S } #endif +@MainActor +final class WeakWindowReference { + weak var window: NSWindow? + + init(_ window: NSWindow? = nil) { + self.window = window + } +} + @MainActor private final class WindowCommandPaletteOverlayController: NSObject { private weak var window: NSWindow? @@ -848,7 +857,8 @@ struct ContentView: View { @State private var lastSidebarSelectionIndex: Int? = nil @State private var titlebarText: String = "" @State private var isFullScreen: Bool = false - @State private var observedWindow: NSWindow? + @State private var observedWindowReference = WeakWindowReference() + private var observedWindow: NSWindow? { observedWindowReference.window } @State private var sidebarRenderWorkerClient: RenderWorkerClient? @StateObject private var fullscreenControlsViewModel = TitlebarControlsViewModel() @StateObject private var fileExplorerStore = FileExplorerStore() @@ -1684,7 +1694,7 @@ struct ContentView: View { debugSource: "titlebar.hiddenNewWorkspace" ) }, - observedWindow: observedWindow, + observedWindowReference: observedWindowReference, selection: $sidebarSelectionState.selection, selectedTabIds: $selectedTabIds, lastSidebarSelectionIndex: $lastSidebarSelectionIndex, sidebarRenderWorkerClient: $sidebarRenderWorkerClient ) @@ -3252,7 +3262,7 @@ struct ContentView: View { // Track this window for fullscreen notifications if observedWindow !== window { DispatchQueue.main.async { - observedWindow = window + observedWindowReference = WeakWindowReference(window) isFullScreen = window.styleMask.contains(.fullScreen) let availableWidth = window.contentView?.bounds.width ?? window.contentLayoutRect.width clampSidebarWidthIfNeeded(availableWidth: availableWidth) @@ -10401,7 +10411,7 @@ struct VerticalTabsSidebar: View, Equatable { // precedent. static func == (lhs: VerticalTabsSidebar, rhs: VerticalTabsSidebar) -> Bool { lhs.windowId == rhs.windowId - && lhs.observedWindow === rhs.observedWindow + && lhs.observedWindowReference.window === rhs.observedWindowReference.window && lhs.updateViewModel === rhs.updateViewModel && lhs.fileExplorerState === rhs.fileExplorerState } @@ -10412,7 +10422,8 @@ struct VerticalTabsSidebar: View, Equatable { let onSendFeedback: () -> Void let onToggleSidebar: () -> Void let onNewTab: () -> Void - let observedWindow: NSWindow? + let observedWindowReference: WeakWindowReference + var observedWindow: NSWindow? { observedWindowReference.window } @EnvironmentObject var tabManager: TabManager // Observe the coalesced unread projection instead of the notification store // so notification churn (terminal/agent activity) no longer reconstructs From 3b2a8e1d33c0e2dcdb2ceacfecf3eb94dbffc0f2 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 20:01:52 -0700 Subject: [PATCH 22/78] Isolate panes preview behind debug route --- .../CMUXMobileRootView.swift | 18 +++-------- .../CMUXMobileRootView+DebugPreview.swift | 32 +++++++++++++++++++ .../MobileRootDebugPreviewRouteTests.swift | 21 ++++++++++++ .../CmuxMobileSupport/UITestConfig.swift | 13 -------- 4 files changed, 58 insertions(+), 26 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootDebugPreviewRouteTests.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 5280090a51b1..9e7d85c63abf 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -75,11 +75,11 @@ struct CMUXMobileRootView: View { #endif } - private var shouldShowPanesTabsPreview: Bool { + private var debugPreview: AnyView? { #if os(iOS) && DEBUG - return UITestConfig.panesPreviewEnabled + return configuredDebugPreview #else - return false + return nil #endif } @@ -123,14 +123,6 @@ struct CMUXMobileRootView: View { #endif } - @ViewBuilder private var panesTabsPreview: some View { - #if os(iOS) && DEBUG - PanesTabsPreviewHost() - #else - EmptyView() - #endif - } - @ViewBuilder private var workspaceListLayoutPreview: some View { #if os(iOS) && DEBUG WorkspaceListLayoutPreviewView() @@ -249,8 +241,8 @@ struct CMUXMobileRootView: View { agentChatDemoPreview } else if shouldShowTerminalLayoutPreview { terminalLayoutPreview - } else if shouldShowPanesTabsPreview { - panesTabsPreview + } else if let debugPreview { + debugPreview } else if shouldShowWorkspaceListLayoutPreview { workspaceListLayoutPreview } else if shouldShowStreamingChatPreview { 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..925d0483e5b8 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift @@ -0,0 +1,32 @@ +#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(PanesTabsPreviewHost()) + } + } +} +#endif +#endif 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/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift index 578acb7f8733..44394af74313 100644 --- a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift +++ b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift @@ -79,19 +79,6 @@ public struct UITestConfig { #endif } - /// Whether the standalone panes-and-tabs preview is enabled. - /// - /// When `CMUX_UITEST_PANES_PREVIEW=1`, the root view renders fixture-driven - /// production surface-deck and pane-map views without sign-in or Mac pairing. - /// DEBUG-only. - public static var panesPreviewEnabled: Bool { - #if DEBUG - return ProcessInfo.processInfo.environment["CMUX_UITEST_PANES_PREVIEW"] == "1" - #else - return false - #endif - } - /// Whether the standalone workspace-list layout preview is enabled. /// /// When `CMUX_UITEST_WORKSPACE_LIST_PREVIEW=1`, the root view renders a From bc666eb129576b9cd815f83633cc17472e5baed4 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 20:50:21 -0700 Subject: [PATCH 23/78] Fix pane map on iOS 18 --- .../Sources/CmuxMobileShellUI/PaneMapOverlay.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index 3b9de2c11cea..e928a8c84e30 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -112,7 +112,7 @@ struct PaneMapOverlay: View { let normalizedRects = value.layout.normalizedRects() ZStack(alignment: .topLeading) { - ForEach(value.panes.enumerated(), id: \.element.id) { index, pane in + ForEach(Array(value.panes.enumerated()), id: \.element.id) { index, pane in if let normalizedRect = normalizedRects[pane.id] { let tileRect = scaledTileRect(normalizedRect, in: canvasRect) let surfaceID = selectedSurfaceIDsByPaneID[pane.id] From 35934fca0fdb2dde4670bc5d7e3cb51722709e90 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 21:58:50 -0700 Subject: [PATCH 24/78] Remove mobile observer test counter --- Sources/Mobile/MobileWorkspaceListObserver.swift | 6 +----- cmuxTests/MobileWorkspaceListFidelityTests.swift | 8 ++++---- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/Sources/Mobile/MobileWorkspaceListObserver.swift b/Sources/Mobile/MobileWorkspaceListObserver.swift index d6385158d7d4..8f24cd237b38 100644 --- a/Sources/Mobile/MobileWorkspaceListObserver.swift +++ b/Sources/Mobile/MobileWorkspaceListObserver.swift @@ -27,7 +27,7 @@ final class MobileWorkspaceListObserver { private var perWorkspaceCancellables: [UUID: AnyCancellable] = [:] private var subscriptionsChangeObserver: NSObjectProtocol? private var pipelinesAttached = false - private var lastSummaryHash: Int = 0 + private(set) var lastSummaryHash: Int = 0 /// 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 @@ -41,7 +41,6 @@ final class MobileWorkspaceListObserver { /// mobile subscriber. static var subscriberPresenceOverrideForTesting: Bool? var pipelinesAttachedForTesting: Bool { pipelinesAttached } - private(set) var emittedUpdateCountForTesting = 0 #endif /// Whether any mobile client currently subscribes to `workspace.updated`. @@ -288,9 +287,6 @@ final class MobileWorkspaceListObserver { return } lastSummaryHash = hash - #if DEBUG - emittedUpdateCountForTesting += 1 - #endif mobileWorkspaceObserverLog.debug("emitting workspace.updated (hash=\(hash, privacy: .public))") #if DEBUG cmuxDebugLog("mobile.observer EMIT workspace.updated hash=\(hash) tabs=\(tabManager.tabs.count) force=\(force)") diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index a5c9916e7dbb..435e658d489b 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -202,17 +202,17 @@ struct MobileWorkspaceListFidelityTests { let secondTabID = try #require(workspace.surfaceIdFromPanelId(secondPanel.id)) workspace.bonsplitController.selectTab(firstTabID) let observer = MobileWorkspaceListObserver(tabManager: manager) - #expect(observer.emittedUpdateCountForTesting == 1, "attachment emits the initial snapshot") + let initialSummaryHash = observer.lastSummaryHash workspace.bonsplitController.selectTab(secondTabID) try await Task.sleep(for: .milliseconds(200)) - let countAfterSelection = observer.emittedUpdateCountForTesting - #expect(countAfterSelection > 1, "selection publishes through the observer") + let hashAfterSelection = observer.lastSummaryHash + #expect(hashAfterSelection != initialSummaryHash, "selection publishes through the observer") workspace.bonsplitController.selectTab(secondTabID) try await Task.sleep(for: .milliseconds(200)) #expect( - observer.emittedUpdateCountForTesting == countAfterSelection, + observer.lastSummaryHash == hashAfterSelection, "a no-op selection stays suppressed" ) } From d85a5673bc3c221cfbb45e6d8915d628d3fd087a Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Tue, 21 Jul 2026 23:00:03 -0700 Subject: [PATCH 25/78] Test mobile observer via emitted updates --- .../Mobile/MobileWorkspaceListObserver.swift | 25 +++++--- .../MobileWorkspaceListFidelityTests.swift | 58 ++++++++++++++++--- 2 files changed, 67 insertions(+), 16 deletions(-) diff --git a/Sources/Mobile/MobileWorkspaceListObserver.swift b/Sources/Mobile/MobileWorkspaceListObserver.swift index 8f24cd237b38..7a7e463d735f 100644 --- a/Sources/Mobile/MobileWorkspaceListObserver.swift +++ b/Sources/Mobile/MobileWorkspaceListObserver.swift @@ -27,7 +27,11 @@ final class MobileWorkspaceListObserver { private var perWorkspaceCancellables: [UUID: AnyCancellable] = [:] private var subscriptionsChangeObserver: NSObjectProtocol? private var pipelinesAttached = false - private(set) var lastSummaryHash: Int = 0 + 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 @@ -56,9 +60,20 @@ final class MobileWorkspaceListObserver { return MobileHostService.hasEventSubscribers(topic: "workspace.updated") } - init(tabManager: TabManager, notificationStore: TerminalNotificationStore? = nil) { + init( + tabManager: TabManager, + notificationStore: TerminalNotificationStore? = nil, + workspaceUpdateEmitter: (@MainActor () -> Void)? = 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() + } #if DEBUG cmuxDebugLog("mobile.observer init tabs=\(tabManager.tabs.count)") #endif @@ -291,11 +306,7 @@ 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 diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index 435e658d489b..bdf08805cb66 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -18,6 +18,25 @@ import Foundation @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. @@ -201,20 +220,41 @@ struct MobileWorkspaceListFidelityTests { let firstTabID = try #require(workspace.surfaceIdFromPanelId(firstPanelID)) let secondTabID = try #require(workspace.surfaceIdFromPanelId(secondPanel.id)) workspace.bonsplitController.selectTab(firstTabID) - let observer = MobileWorkspaceListObserver(tabManager: manager) - let initialSummaryHash = observer.lastSummaryHash + 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) - try await Task.sleep(for: .milliseconds(200)) - let hashAfterSelection = observer.lastSummaryHash - #expect(hashAfterSelection != initialSummaryHash, "selection publishes through the observer") + 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) - try await Task.sleep(for: .milliseconds(200)) - #expect( - observer.lastSummaryHash == hashAfterSelection, - "a no-op selection stays suppressed" + 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 { From 7488cf047d8c1b33015101ad3304e22f0d6acc82 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Wed, 22 Jul 2026 14:50:11 -0700 Subject: [PATCH 26/78] Test constrained iOS pane previews --- ...erminalRenderGridPaneMapPreviewTests.swift | 48 +++++++++ .../PaneMapCollectionLayoutEngineTests.swift | 102 ++++++++++++++++++ ios/cmuxUITests/cmuxUITests.swift | 79 ++++++++++++-- 3 files changed, 220 insertions(+), 9 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift index c9710f512f86..c1d337571bbc 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift @@ -92,6 +92,54 @@ import Testing #expect(rows.last == "end") } + @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) + } + private static func frame( columns: Int, rowCount: Int, diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift new file mode 100644 index 000000000000..e7dc0e7b1cf0 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -0,0 +1,102 @@ +import CoreGraphics +import CmuxMobileShellModel +import Testing +@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 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 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: []) + } +} diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index cb8543e4fce6..718407aaacab 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1561,8 +1561,11 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) - let leftDeckGroup = app.descendants(matching: .any)[ - "MobileSurfaceDeckPane-preview-pane-left" + 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" @@ -1570,12 +1573,13 @@ final class cmuxUITests: XCTestCase { let serverDeckGroup = app.descendants(matching: .any)[ "MobileSurfaceDeckPane-preview-pane-server" ] - XCTAssertTrue(leftDeckGroup.exists) + XCTAssertTrue(leftTopDeckGroup.exists) + XCTAssertTrue(leftBottomDeckGroup.exists) XCTAssertTrue(testsDeckGroup.exists) XCTAssertTrue(serverDeckGroup.exists) XCTAssertTrue( app.descendants(matching: .any)[ - "MobileSurfaceDeckPaneNumber-preview-pane-left" + "MobileSurfaceDeckPaneNumber-preview-pane-left-top" ].exists ) XCTAssertEqual( @@ -1588,18 +1592,25 @@ final class cmuxUITests: XCTestCase { let overlay = app.otherElements["MobilePaneMapOverlay"] XCTAssertTrue(overlay.waitForExistence(timeout: 4)) - let leftPane = app.descendants(matching: .any)["MobilePaneMapPane-preview-pane-left"] + 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(leftPane.waitForExistence(timeout: 2)) + XCTAssertTrue(leftTopPane.waitForExistence(timeout: 2)) + XCTAssertTrue(leftBottomPane.exists) XCTAssertTrue(testsPane.exists) XCTAssertTrue(serverPane.exists) - XCTAssertLessThan(leftPane.frame.midX, testsPane.frame.midX) + XCTAssertLessThan(leftTopPane.frame.midX, testsPane.frame.midX) + XCTAssertLessThan(leftTopPane.frame.midY, leftBottomPane.frame.midY) XCTAssertLessThan(testsPane.frame.midY, serverPane.frame.midY) - XCTAssertEqual(leftPane.value as? String, "Focused on Mac") + XCTAssertEqual(leftTopPane.value as? String, "Focused on Mac") XCTAssertTrue( app.descendants(matching: .any)[ - "MobilePaneMapPaneNumber-preview-pane-left" + "MobilePaneMapPaneNumber-preview-pane-left-top" ].exists ) @@ -1611,12 +1622,62 @@ final class cmuxUITests: XCTestCase { 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(overlay.waitForNonExistence(timeout: 4)) XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-zsh"].isSelected) } + @MainActor + func testPanesPreviewReordersCardsAndPinchZoomsTerminal() 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(overlay.waitForExistence(timeout: 4)) + 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) + + let originalLeftTopFrame = leftTopPane.frame + 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 leftTopPane.frame.midX > originalLeftTopFrame.midX + 20 } + ), + object: leftTopPane + ) + XCTAssertEqual( + XCTWaiter.wait(for: [reordered], timeout: 4), + .completed, + "Dragging a pane card must move it into the destination layout slot" + ) + + let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] + XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) + claudeTile.pinch(withScale: 2, velocity: 2) + + XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-claude"].isSelected) + } + @MainActor func testBottomScrollStaysPinnedAcrossComposerViewportShrink() throws { let app = launchApp(mockData: false, environment: [ From a37d8b3b9ab7dd048250744ba86796e56c966827 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 22 Jul 2026 15:19:48 -0700 Subject: [PATCH 27/78] Build Safari-style iOS pane map --- ...rminalRenderGridFrame+PaneMapPreview.swift | 176 ++++- .../Debug/PanesTabsPreviewHost.swift | 115 +++- .../PaneMapCollectionLayout.swift | 231 +++++++ .../PaneMapCollectionView.swift | 604 +++++++++++++++++ .../CmuxMobileShellUI/PaneMapOverlay.swift | 241 +++---- .../CmuxMobileShellUI/PaneMapTileView.swift | 633 ++++++++++++------ .../TerminalSurfaceMountOwnershipTests.swift | 2 + ios/cmux/Resources/Localizable.xcstrings | 42 ++ 8 files changed, 1659 insertions(+), 385 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionLayout.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift index b3e20462e7e7..e64cc9ebfb0d 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift @@ -1,9 +1,131 @@ -private struct PaneMapPreviewCell { +/// 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]] + + fileprivate init( + surfaceID: String, + columns: Int, + sourceRows: Int, + firstSourceRow: Int, + styles: [MobileTerminalRenderGridFrame.Style], + 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.rows = rows + } + + /// Plain terminal-width rows retained for text-only consumers and tests. + public var textRows: [String] { + rows.map { $0.map(\.text).joined() } + } +} + +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 visible terminal grid. A finite limit + /// preserves the previous tail-window behavior for text-only callers. + func paneMapPreview( + maximumRows: Int? = nil + ) -> MobileTerminalPaneMapPreview { + guard columns > 0, rows > 0 else { + return MobileTerminalPaneMapPreview( + surfaceID: surfaceID, + columns: max(0, columns), + sourceRows: max(0, rows), + firstSourceRow: 0, + styles: styles, + rows: [] + ) + } + + var spansByRow: [Int: [RowSpan]] = [:] + var lastSpanRow: Int? + for span in rowSpans where !span.text.isEmpty { + spansByRow[span.row, default: []].append(span) + lastSpanRow = max(lastSpanRow ?? span.row, span.row) + } + + let rowRange: Range + if let maximumRows { + guard maximumRows > 0 else { + return MobileTerminalPaneMapPreview( + surfaceID: surfaceID, + columns: columns, + sourceRows: rows, + firstSourceRow: 0, + styles: styles, + rows: [] + ) + } + let boundedMaximumRows = min(rows, maximumRows) + let lastContentRow = max(lastSpanRow ?? 0, cursor?.row ?? 0) + let endRow = min(rows, max(lastContentRow + 1, boundedMaximumRows)) + let firstRow = max(0, endRow - boundedMaximumRows) + rowRange = firstRow.. [String] { - guard columns > 0, rows > 0, maximumRows > 0 else { return [] } - - var spansByRow: [Int: [RowSpan]] = [:] - var lastSpanRow: Int? - for span in rowSpans where !span.text.isEmpty { - spansByRow[span.row, default: []].append(span) - lastSpanRow = max(lastSpanRow ?? span.row, span.row) - } - - let lastContentRow = max(lastSpanRow ?? 0, cursor?.row ?? 0) - let minimumEndRow = min(rows, maximumRows) - let endRow = min(rows, max(lastContentRow + 1, minimumEndRow)) - let firstRow = max(0, endRow - maximumRows) - return (firstRow.. String { - var cells = Array(repeating: PaneMapPreviewCell(), count: columns) + 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] = PaneMapPreviewCell() + cells[column] = MutablePaneMapPreviewCell() } } - func place(_ text: String, at column: Int, width: Int) { + 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.. MobileTerminalRenderGridFrame { + 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…"), + ] + ) + } } #endif 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..514a1148efaf --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -0,0 +1,604 @@ +import CMUXMobileCore +import CmuxMobileShellModel +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 } + } +} + +struct PaneMapOverflowLabels { + let leading: String + let trailing: String + let top: String + let bottom: String +} + +/// UIKit collection surface for native interactive movement and continuous zoom. +struct PaneMapCollectionView: UIViewRepresentable { + let items: [PaneMapCollectionItem] + let layout: MobilePaneLayout + let terminalTheme: TerminalTheme + let overflowLabels: PaneMapOverflowLabels + let selectPreviewSurface: (_ paneID: String, _ surfaceID: String) -> Void + let jumpToTerminal: (_ surfaceID: String) -> Void + + 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 + ) + 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.configure( + terminalTheme: terminalTheme, + labels: overflowLabels, + scrollStep: context.coordinator.scrollOneViewport + ) + 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 zoomSession: ZoomSession? + + init(parent: PaneMapCollectionView) { + self.parent = parent + } + + func attach( + collectionView: UICollectionView, + container: PaneMapCollectionContainerView + ) { + self.collectionView = collectionView + self.container = container + collectionView.dragInteractionEnabled = true + collectionView.reorderingCadence = .immediate + collectionView.dragDelegate = self + collectionView.dropDelegate = self + + let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:))) + pinch.delegate = self + collectionView.addGestureRecognizer(pinch) + } + + func reconcile(items: [PaneMapCollectionItem]) { + guard !isMovingItem else { + pendingItems = items + return + } + + let itemsByID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) }) + let retainedIDs = orderedItems.map(\.id).filter { itemsByID[$0] != nil } + let retainedIDSet = Set(retainedIDs) + let newIDs = items.map(\.id).filter { !retainedIDSet.contains($0) } + orderedItems = (retainedIDs + newIDs).compactMap { itemsByID[$0] } + collectionView?.reloadData() + collectionView?.collectionViewLayout.invalidateLayout() + container?.setNeedsLayout() + } + + 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, + selectPreviewSurface: { [weak self] surfaceID in + self?.parent.selectPreviewSurface(item.pane.id, surfaceID) + }, + jumpToTerminal: { [weak self] surfaceID in + self?.zoomToTerminal(paneID: item.pane.id, surfaceID: surfaceID) + } + ) + } + .margins(.all, 0) + .background(.clear) + return cell + } + + func collectionView( + _ collectionView: UICollectionView, + itemsForBeginning session: UIDragSession, + at indexPath: IndexPath + ) -> [UIDragItem] { + guard zoomSession == nil, + orderedItems.indices.contains(indexPath.item), + orderedItems.count > 1 else { return [] } + isMovingItem = true + 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) + + 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) + } + + func collectionView( + _ collectionView: UICollectionView, + dragSessionDidEnd session: UIDragSession + ) { + finishInteractiveMovement() + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + container?.updateOverflowIndicators() + } + + func gestureRecognizer( + _ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer + ) -> Bool { + gestureRecognizer is UIPinchGestureRecognizer + || otherGestureRecognizer is UIPinchGestureRecognizer + } + + @objc private func handlePinch(_ gesture: UIPinchGestureRecognizer) { + guard let collectionView else { return } + switch gesture.state { + case .began: + let location = gesture.location(in: collectionView) + guard let indexPath = collectionView.indexPathForItem(at: location), + startZoom(at: indexPath) else { return } + collectionView.isScrollEnabled = false + case .changed: + guard zoomSession != nil else { return } + let progress = min(1, max(0, (gesture.scale - 1) / 1.15)) + updateZoom(progress: progress) + case .ended: + guard let session = zoomSession else { return } + let shouldCommit = session.progress > 0.32 || gesture.velocity > 1.4 + shouldCommit ? commitZoom() : cancelZoom() + default: + guard zoomSession != nil else { return } + cancelZoom() + } + } + + private func finishInteractiveMovement() { + isMovingItem = false + collectionView?.collectionViewLayout.invalidateLayout() + if let pendingItems { + self.pendingItems = nil + reconcile(items: pendingItems) + } + } + + private func zoomToTerminal(paneID: String, surfaceID: String) { + guard zoomSession == nil, + let itemIndex = orderedItems.firstIndex(where: { $0.id == paneID }), + orderedItems[itemIndex].selectedSurface?.id == surfaceID, + startZoom(at: IndexPath(item: itemIndex, section: 0)) else { + return + } + commitZoom() + } + + private func startZoom(at indexPath: IndexPath) -> Bool { + guard zoomSession == nil, + orderedItems.indices.contains(indexPath.item), + let surface = orderedItems[indexPath.item].selectedSurface, + surface.type.isTerminal, + let collectionView, + let cell = collectionView.cellForItem(at: indexPath), + let window = cell.window else { + return false + } + + let previewBounds = CGRect( + x: 0, + y: 0, + width: cell.bounds.width, + height: max(0, cell.bounds.height - PaneMapTileMetrics.captionHeight) + ) + guard let snapshot = cell.resizableSnapshotView( + from: previewBounds, + afterScreenUpdates: true, + withCapInsets: .zero + ) else { + return false + } + let initialFrame = cell.convert(previewBounds, to: window) + let backdrop = UIView(frame: window.bounds) + backdrop.backgroundColor = UIColor(terminalHex: parent.terminalTheme.background) + backdrop.alpha = 0 + backdrop.isUserInteractionEnabled = false + + let wrapper = UIView(frame: initialFrame) + wrapper.backgroundColor = UIColor(terminalHex: parent.terminalTheme.background) + wrapper.clipsToBounds = true + wrapper.layer.cornerCurve = .continuous + wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius + wrapper.isUserInteractionEnabled = false + snapshot.frame = CGRect(origin: .zero, size: previewBounds.size) + wrapper.addSubview(snapshot) + + window.addSubview(backdrop) + window.addSubview(wrapper) + cell.alpha = 0 + zoomSession = ZoomSession( + surfaceID: surface.id, + cell: cell, + snapshot: snapshot, + wrapper: wrapper, + backdrop: backdrop, + initialFrame: initialFrame, + targetFrame: window.bounds, + progress: 0 + ) + return true + } + + private func updateZoom(progress: CGFloat) { + guard var session = zoomSession else { return } + session.progress = progress + session.wrapper.frame = interpolate( + from: session.initialFrame, + to: session.targetFrame, + progress: progress + ) + session.snapshot.frame = session.wrapper.bounds + session.wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius * (1 - progress) + session.backdrop.alpha = progress + zoomSession = session + } + + private func commitZoom() { + guard let session = zoomSession else { return } + let remaining = max(0.16, 0.34 * (1 - session.progress)) + UIView.animate( + withDuration: remaining, + delay: 0, + usingSpringWithDamping: 0.92, + initialSpringVelocity: 0.2, + options: [.beginFromCurrentState, .curveEaseOut] + ) { [weak self] in + self?.updateZoom(progress: 1) + } completion: { [weak self] _ in + guard let self, let committedSession = self.zoomSession else { return } + self.parent.jumpToTerminal(committedSession.surfaceID) + Task { @MainActor [weak self] in + await Task.yield() + self?.finishZoom() + } + } + } + + private func cancelZoom() { + guard let session = zoomSession else { return } + let remaining = max(0.16, 0.26 * session.progress) + UIView.animate( + withDuration: remaining, + delay: 0, + usingSpringWithDamping: 0.9, + initialSpringVelocity: 0, + options: [.beginFromCurrentState, .curveEaseOut] + ) { [weak self] in + self?.updateZoom(progress: 0) + } completion: { [weak self] _ in + self?.finishZoom() + } + } + + private func finishZoom() { + guard let session = zoomSession else { return } + session.cell.alpha = 1 + session.wrapper.removeFromSuperview() + session.backdrop.removeFromSuperview() + collectionView?.isScrollEnabled = true + zoomSession = nil + } + + private func interpolate(from start: CGRect, to end: CGRect, progress: CGFloat) -> CGRect { + CGRect( + x: start.minX + (end.minX - start.minX) * progress, + y: start.minY + (end.minY - start.minY) * progress, + width: start.width + (end.width - start.width) * progress, + height: start.height + (end.height - start.height) * progress + ) + } + + 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) + } + + private struct ZoomSession { + let surfaceID: String + let cell: UICollectionViewCell + let snapshot: UIView + let wrapper: UIView + let backdrop: UIView + let initialFrame: CGRect + let targetFrame: CGRect + var progress: CGFloat + } + } +} + +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 = UIColor(terminalHex: terminalTheme.background) + self.scrollStep = scrollStep + for button in buttons.values { + button.tintColor = UIColor(terminalHex: terminalTheme.foreground) + } + 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() + } + + 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 + } +} + +private extension UIColor { + convenience init(terminalHex: String) { + guard let rgb = TerminalTheme.rgbComponents(terminalHex) else { + self.init(white: 0, alpha: 1) + return + } + self.init( + red: CGFloat(rgb.red) / 255, + green: CGFloat(rgb.green) / 255, + blue: CGFloat(rgb.blue) / 255, + alpha: 1 + ) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index e928a8c84e30..9433d6033384 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -3,7 +3,7 @@ import CmuxMobileShellModel import CmuxMobileSupport import SwiftUI -/// Full-screen proportional map of a workspace's Mac pane layout. +/// Full-screen interactive map of a workspace's Mac pane layout. struct PaneMapOverlay: View { let value: PaneMapValue let terminalTheme: TerminalTheme @@ -12,7 +12,7 @@ struct PaneMapOverlay: View { let dismiss: () -> Void @State private var selectedSurfaceIDsByPaneID: [String: String] - @State private var previewGridsBySurfaceID: [String: MobileTerminalRenderGridFrame] = [:] + @State private var previewsBySurfaceID: [String: MobileTerminalPaneMapPreview] = [:] @State private var isRefreshing = false @State private var refreshTask: Task? @State private var refreshGeneration: UUID? @@ -34,11 +34,30 @@ struct PaneMapOverlay: View { var body: some View { VStack(spacing: 0) { - header - paneCanvas + PaneMapHeader( + workspaceName: value.workspaceName, + countSubtitle: countSubtitle, + isRefreshing: isRefreshing, + terminalTheme: terminalTheme, + refresh: startPreviewRefresh, + dismiss: dismissPaneMap + ) + PaneMapCollectionView( + items: collectionItems, + layout: value.layout, + terminalTheme: terminalTheme, + overflowLabels: overflowLabels, + selectPreviewSurface: selectPreviewSurface, + jumpToTerminal: jumpToTerminal + ) } .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(terminalTheme.terminalBackgroundColor.ignoresSafeArea()) + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + .accessibilityElement() + .accessibilityIdentifier("MobilePaneMapOverlay") + } .onAppear { startPreviewRefresh() } @@ -50,94 +69,46 @@ struct PaneMapOverlay: View { current: selectedSurfaceIDsByPaneID ) } - .accessibilityIdentifier("MobilePaneMapOverlay") } - private var header: some View { - HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(value.workspaceName) - .font(.headline) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .lineLimit(1) - - Text(countSubtitle) - .font(.subheadline) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.7)) - .lineLimit(1) - } - - Spacer(minLength: 0) - - Button(action: startPreviewRefresh) { - HStack(spacing: 5) { - if isRefreshing { - ProgressView() - .controlSize(.mini) - .tint(terminalTheme.terminalChromeForegroundColor) - } else { - Image(systemName: "arrow.clockwise") - } - Text(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) + 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] } - .font(.subheadline.weight(.semibold)) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .padding(.horizontal, 12) - .frame(height: 34) - .mobileGlassPill() - } - .buttonStyle(.plain) - .disabled(isRefreshing) - .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) - .accessibilityIdentifier("MobilePaneMapRefresh") - - Button(action: dismissPaneMap) { - Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .padding(.horizontal, 14) - .frame(height: 34) - .mobileGlassPill() - } - .buttonStyle(.plain) - .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .accessibilityIdentifier("MobilePaneMapDone") + ) } - .padding(16) } - private var paneCanvas: some View { - GeometryReader { geometry in - let canvasRect = aspectFitCanvas(in: geometry.size) - let normalizedRects = value.layout.normalizedRects() - - ZStack(alignment: .topLeading) { - ForEach(Array(value.panes.enumerated()), id: \.element.id) { index, pane in - if let normalizedRect = normalizedRects[pane.id] { - let tileRect = scaledTileRect(normalizedRect, in: canvasRect) - let surfaceID = selectedSurfaceIDsByPaneID[pane.id] - - PaneMapTileView( - pane: pane, - paneNumber: index + 1, - paneCount: value.panes.count, - isFocusedOnMac: value.layout.focusedPaneID == pane.id, - terminalTheme: terminalTheme, - selectedSurfaceID: surfaceID, - phoneSelectedSurfaceID: value.phoneSelectedSurfaceID, - previewGrid: surfaceID.flatMap { previewGridsBySurfaceID[$0] }, - isLoadingPreview: isRefreshing, - agentStateKind: surfaceID.flatMap { value.agentStateKindsBySurfaceID[$0] }, - selectPreviewSurface: { selectedSurfaceIDsByPaneID[pane.id] = $0 }, - jumpToTerminal: jumpToTerminal - ) - .frame(width: tileRect.width, height: tileRect.height) - .position(x: tileRect.midX, y: tileRect.midY) - } - } - } - .frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading) - } + 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 var countSubtitle: String { @@ -177,32 +148,17 @@ struct PaneMapOverlay: View { } } - private func aspectFitCanvas(in size: CGSize) -> CGRect { - // Fill the available space rather than forcing the Mac window's - // landscape aspect: the split RATIOS carry the structural mental - // model, and on a portrait phone larger tiles (more readable - // previews) are worth more than aspect fidelity. - CGRect( - x: 16, - y: 8, - width: max(0, size.width - 32), - height: max(0, size.height - 24) - ) - } - - private func scaledTileRect(_ normalizedRect: CGRect, in canvasRect: CGRect) -> CGRect { - CGRect( - x: canvasRect.minX + normalizedRect.minX * canvasRect.width, - y: canvasRect.minY + normalizedRect.minY * canvasRect.height, - width: normalizedRect.width * canvasRect.width, - height: normalizedRect.height * canvasRect.height - ) - .insetBy(dx: 3, dy: 3) + private func selectPreviewSurface(paneID: String, surfaceID: String) { + selectedSurfaceIDsByPaneID[paneID] = surfaceID } private func jumpToTerminal(_ surfaceID: String) { - selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) - dismissPaneMap() + var transaction = Transaction(animation: nil) + transaction.disablesAnimations = true + withTransaction(transaction) { + selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) + dismissPaneMap() + } } private func dismissPaneMap() { @@ -248,11 +204,72 @@ struct PaneMapOverlay: View { let remainingTerminalSurfaceIDs = value.panes.flatMap(\.surfaces).compactMap { surface in surface.type.isTerminal && !selectedSet.contains(surface.id) ? surface.id : nil } - let previews = await fetchPreviews( + let frames = await fetchPreviews( selectedTerminalSurfaceIDs, remainingTerminalSurfaceIDs ) guard !Task.isCancelled, refreshGeneration == generation else { return } - previewGridsBySurfaceID = previews + previewsBySurfaceID = frames.mapValues { $0.paneMapPreview() } + } +} + +private struct PaneMapHeader: View { + let workspaceName: String + let countSubtitle: String + let isRefreshing: Bool + let terminalTheme: TerminalTheme + let refresh: () -> Void + let dismiss: () -> Void + + var body: some View { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(workspaceName) + .font(.headline) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .lineLimit(1) + Text(countSubtitle) + .font(.subheadline) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.7)) + .lineLimit(1) + } + + Spacer(minLength: 0) + + Button(action: refresh) { + HStack(spacing: 5) { + if isRefreshing { + ProgressView() + .controlSize(.mini) + .tint(terminalTheme.terminalChromeForegroundColor) + } else { + Image(systemName: "arrow.clockwise") + } + Text(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) + } + .font(.subheadline.weight(.semibold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .padding(.horizontal, 12) + .frame(height: 34) + .mobileGlassPill() + } + .buttonStyle(.plain) + .disabled(isRefreshing) + .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) + .accessibilityIdentifier("MobilePaneMapRefresh") + + Button(action: dismiss) { + Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .padding(.horizontal, 14) + .frame(height: 34) + .mobileGlassPill() + } + .buttonStyle(.plain) + .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .accessibilityIdentifier("MobilePaneMapDone") + } + .padding(16) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index 8dd68f776a68..5be0e54ab60b 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -3,255 +3,481 @@ import CmuxMobileShellModel import CmuxMobileSupport import SwiftUI -/// One proportional pane tile rendered from immutable layout and preview snapshots. +enum PaneMapTileMetrics { + static let captionHeight: CGFloat = 38 + static let cornerRadius: CGFloat = 16 +} + +/// One floating Safari-style pane card rendered from immutable snapshots. struct PaneMapTileView: View { - let pane: MobilePaneNode - let paneNumber: Int - let paneCount: Int - let isFocusedOnMac: Bool + let item: PaneMapCollectionItem let terminalTheme: TerminalTheme - let selectedSurfaceID: String? - let phoneSelectedSurfaceID: String? - let previewGrid: MobileTerminalRenderGridFrame? - let isLoadingPreview: Bool - let agentStateKind: ChatAgentStateKind? let selectPreviewSurface: (String) -> Void let jumpToTerminal: (String) -> Void - private var selectedSurface: MobilePaneSurface? { - guard let selectedSurfaceID else { return pane.surfaces.first } - return pane.surfaces.first { $0.id == selectedSurfaceID } + var body: some View { + VStack(spacing: 0) { + PaneMapPreviewCard( + item: item, + terminalTheme: terminalTheme, + selectPreviewSurface: selectPreviewSurface, + jumpToTerminal: jumpToTerminal + ) + PaneMapTileCaption(item: item, terminalTheme: terminalTheme) + .frame(height: PaneMapTileMetrics.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 selectedSurface: MobilePaneSurface? { item.selectedSurface } private var isPhoneSelected: Bool { - selectedSurface?.id == phoneSelectedSurfaceID + selectedSurface?.id == item.phoneSelectedSurfaceID } var body: some View { - let shape = RoundedRectangle(cornerRadius: 12, style: .continuous) + let shape = RoundedRectangle( + cornerRadius: PaneMapTileMetrics.cornerRadius, + style: .continuous + ) + + ZStack { + terminalTheme.terminalBackgroundColor - VStack(spacing: 0) { if let selectedSurface { - tileContent(for: selectedSurface) - .opacity(selectedSurface.type.isTerminal ? 1 : 0.5) + PaneMapSurfacePreview( + surface: selectedSurface, + preview: item.preview, + isLoadingPreview: item.isLoadingPreview, + terminalTheme: terminalTheme, + jumpToTerminal: jumpToTerminal + ) } + + VStack { + HStack(alignment: .top) { + PaneMapPaneNumberBadge( + paneID: item.pane.id, + paneNumber: item.paneNumber, + terminalTheme: terminalTheme + ) + 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(terminalTheme.terminalBackgroundColor, in: shape) + .background(terminalTheme.terminalBackgroundColor) .overlay { - shape.stroke(.white.opacity(0.12), lineWidth: 1) + shape.stroke(.white.opacity(0.16), lineWidth: 1) } .overlay { if isPhoneSelected { - shape.stroke(Color.accentColor, lineWidth: 2) + shape.stroke(Color.accentColor, lineWidth: 2.5) } } .clipShape(shape) - .accessibilityElement(children: .contain) - .accessibilityLabel(paneAccessibilityLabel) - .accessibilityValue( - isFocusedOnMac - ? L10n.string("mobile.paneMap.focusedOnMac", defaultValue: "Focused on Mac") - : "" - ) - .accessibilityIdentifier("MobilePaneMapPane-\(pane.id)") + .shadow(color: .black.opacity(0.28), radius: 9, y: 5) } +} - private func tileContent(for surface: MobilePaneSurface) -> some View { - VStack(spacing: 0) { - header(for: surface) +private struct PaneMapSurfacePreview: View { + let surface: MobilePaneSurface + let preview: MobileTerminalPaneMapPreview? + let isLoadingPreview: Bool + let terminalTheme: TerminalTheme + let jumpToTerminal: (String) -> Void - if pane.surfaces.count > 1 { - miniTabStrip + var body: some View { + ZStack { + if surface.type.isTerminal { + Button { + jumpToTerminal(surface.id) + } label: { + PaneMapTerminalPreview( + preview: preview, + isLoadingPreview: isLoadingPreview, + terminalTheme: terminalTheme + ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(surfaceAccessibilityLabel) + .accessibilityIdentifier("MobilePaneMapTile-\(surface.id)") + } else { + PaneMapUnavailableSurfacePreview( + surface: surface, + terminalTheme: terminalTheme + ) } - - bodyContent(for: surface) } + .frame(maxWidth: .infinity, maxHeight: .infinity) } - private func header(for surface: MobilePaneSurface) -> some View { - HStack(spacing: 4) { - Text(paneNumber, format: .number) - .font(.caption2.weight(.bold)) - .padding(.horizontal, 6) - .padding(.vertical, 3) - .background( - Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.12)) - ) - .accessibilityLabel(paneAccessibilityLabel) - .accessibilityIdentifier("MobilePaneMapPaneNumber-\(pane.id)") + private var surfaceAccessibilityLabel: String { + String.localizedStringWithFormat( + L10n.string( + "mobile.paneMap.openNamedTerminal", + defaultValue: "Open terminal: %@" + ), + surface.title + ) + } +} - Image(systemName: systemImage(for: surface.type)) - .font(.caption2.weight(.medium)) +private struct PaneMapTerminalPreview: View { + let preview: MobileTerminalPaneMapPreview? + let isLoadingPreview: Bool + let terminalTheme: TerminalTheme - Text(surface.title) - .font(.caption.weight(.medium)) - .lineLimit(1) - .truncationMode(.tail) + var body: some View { + ZStack(alignment: .topLeading) { + terminalTheme.terminalBackgroundColor + if let preview { + PaneMapTerminalCanvas(preview: preview, terminalTheme: terminalTheme) + } 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() + } +} - Spacer(minLength: 2) +private struct PaneMapTerminalCanvas: View { + let preview: MobileTerminalPaneMapPreview + let terminalTheme: TerminalTheme - if isFocusedOnMac { - Label( - L10n.string("mobile.paneMap.focusedOnMac.short", defaultValue: "Mac"), - systemImage: "macwindow" + 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 lineHeightRatio: CGFloat = 1.82 + let widthCell = size.width / CGFloat(preview.columns) + let heightCell = size.height / (CGFloat(preview.rows.count) * lineHeightRatio) + let cellWidth = max(0.1, min(widthCell, heightCell)) + let lineHeight = cellWidth * lineHeightRatio + let fontSize = max(0.5, cellWidth / 0.61) + + for (rowIndex, row) in preview.rows.enumerated() { + drawBackgrounds( + row, + rowIndex: rowIndex, + cellWidth: cellWidth, + lineHeight: lineHeight, + context: &context ) - .font(.caption2.weight(.semibold)) - .labelStyle(.titleAndIcon) - .lineLimit(1) - .padding(.horizontal, 5) - .padding(.vertical, 3) - .background( - Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.12)) + drawGlyphs( + row, + rowIndex: rowIndex, + cellWidth: cellWidth, + lineHeight: lineHeight, + fontSize: fontSize, + context: &context ) - .accessibilityLabel( - L10n.string("mobile.paneMap.focusedOnMac", defaultValue: "Focused on Mac") + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private func drawBackgrounds( + _ row: [MobileTerminalPaneMapPreview.Cell], + rowIndex: Int, + 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: CGFloat(startColumn) * cellWidth, + y: CGFloat(rowIndex) * lineHeight, + width: CGFloat(endColumn - startColumn) * cellWidth, + height: lineHeight + )), + with: .color(background) ) } + startColumn = endColumn + } + } - if let agentStateKind { - Circle() - .fill(statusColor(agentStateKind)) - .frame(width: 6, height: 6) - .accessibilityLabel(statusAccessibilityValue(agentStateKind)) + private func drawGlyphs( + _ row: [MobileTerminalPaneMapPreview.Cell], + rowIndex: Int, + 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: CGFloat(column) * cellWidth, + y: CGFloat(rowIndex) * lineHeight + ), + anchor: .topLeading + ) + if style.isOverlined { + let width = CGFloat(max(1, cell.columnSpan)) * cellWidth + context.stroke( + Path(CGRect( + x: CGFloat(column) * cellWidth, + y: CGFloat(rowIndex) * lineHeight, + width: width, + height: 0.5 + )), + with: .color(style.foreground), + lineWidth: max(0.35, fontSize * 0.06) + ) } } - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .padding(6) } - private var miniTabStrip: some View { + 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 PaneMapPaneNumberBadge: View { + let paneID: String + let paneNumber: Int + let terminalTheme: TerminalTheme + + var body: some View { + Text(paneNumber, format: .number) + .font(.caption2.weight(.bold)) + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .frame(width: 26, height: 26) + .mobileGlassCircle() + .accessibilityIdentifier("MobilePaneMapPaneNumber-\(paneID)") + } +} + +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 + + var body: some View { ScrollView(.horizontal) { - HStack(spacing: 3) { + HStack(spacing: 2) { ForEach(pane.surfaces, id: \.id) { surface in - let isSelectedTab = surface.id == selectedSurface?.id + let isSelected = surface.id == selectedSurfaceID Button { selectPreviewSurface(surface.id) } label: { - Text(surface.title) - .font(.caption2.weight(.semibold)) - .lineLimit(1) - .truncationMode(.tail) + Image(systemName: surface.type.paneMapSystemImage) + .font(.system(size: 10, weight: .semibold)) .foregroundStyle( - isSelectedTab + isSelected ? terminalTheme.terminalBackgroundColor - : terminalTheme.terminalChromeForegroundColor.opacity(0.85) + : terminalTheme.terminalChromeForegroundColor.opacity(0.82) ) - .padding(.horizontal, 8) - .padding(.vertical, 5) - .frame(minWidth: 44, maxWidth: 96) + .frame(width: 28, height: 28) .background( - Capsule().fill( - isSelectedTab - ? terminalTheme.terminalChromeForegroundColor.opacity(0.85) - : terminalTheme.terminalChromeForegroundColor.opacity(0.10) - ) + isSelected + ? terminalTheme.terminalChromeForegroundColor.opacity(0.9) + : .clear, + in: Circle() ) - .contentShape(Capsule()) + .contentShape(Circle()) } .buttonStyle(.plain) - .frame(minHeight: 44) - .contentShape(Rectangle()) - .accessibilityLabel(surfaceAccessibilityLabel(surface)) - .accessibilityAddTraits(isSelectedTab ? .isSelected : []) + .accessibilityLabel(surface.title) + .accessibilityAddTraits(isSelected ? .isSelected : []) .accessibilityIdentifier("MobilePaneMapTab-\(surface.id)") } } - .padding(.horizontal, 6) + .padding(3) } .scrollIndicators(.hidden) - .padding(.bottom, 2) + .fixedSize(horizontal: true, vertical: true) + .frame(maxWidth: 132) + .mobileGlassPill() } +} - @ViewBuilder - private func bodyContent(for surface: MobilePaneSurface) -> some View { - if surface.type.isTerminal { - Button { - jumpToTerminal(surface.id) - } label: { - terminalPreview(surfaceID: surface.id) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityLabel( - surfaceAccessibilityLabel(surface) - ) - .accessibilityValue(statusAccessibilityValue(agentStateKind)) - .accessibilityIdentifier("MobilePaneMapTile-\(surface.id)") - } else { - VStack(spacing: 5) { - Image(systemName: systemImage(for: surface.type)) - .font(.system(size: 20, weight: .medium)) +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(.medium)) - .lineLimit(2) - .multilineTextAlignment(.center) + .font(.caption.weight(.semibold)) + .lineLimit(1) + .truncationMode(.tail) + .accessibilityIdentifier("MobilePaneMapCaption-\(surface.id)") } - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(8) - } - } - - @ViewBuilder - private func terminalPreview(surfaceID: String) -> some View { - if let previewGrid, previewGrid.surfaceID == surfaceID { - GeometryReader { geometry in - let lines = previewGrid.paneMapPreviewRows() - let fontSize = previewFontSize( - availableSize: geometry.size, - columns: previewGrid.columns, - lineCount: lines.count - ) - - VStack(alignment: .leading, spacing: 0) { - ForEach(Array(lines.enumerated()), id: \.offset) { _, line in - Text(line) - .font(.system(size: fontSize, weight: .regular, design: .monospaced)) - .lineLimit(1) - .fixedSize(horizontal: true, vertical: false) - } - } - // Preview rows are terminal content, so they use the theme's - // true foreground rather than the chrome-readable color. - .foregroundStyle(terminalTheme.terminalForegroundColor) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) - .clipped() + Spacer(minLength: 0) + if let agentStateKind = item.agentStateKind { + Circle() + .fill(agentStateKind == .working ? Color.green : Color.orange) + .frame(width: 7, height: 7) + .accessibilityLabel(statusAccessibilityValue(agentStateKind)) } - .padding(.horizontal, 6) - .padding(.bottom, 6) - } else if isLoadingPreview { - ProgressView() - .controlSize(.mini) - .tint(terminalTheme.terminalChromeForegroundColor.opacity(0.5)) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } else { - Color.clear } + .foregroundStyle(terminalTheme.terminalChromeForegroundColor) + .padding(.horizontal, 4) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .combine) } - private func previewFontSize( - availableSize: CGSize, - columns: Int, - lineCount: Int - ) -> CGFloat { - guard columns > 0, lineCount > 0 else { return 5 } - let widthFit = availableSize.width / (CGFloat(columns) * 0.62) - let heightFit = availableSize.height / (CGFloat(lineCount) * 1.12) - return min(9, max(5, min(widthFit, heightFit))) - } - - private func statusColor(_ kind: ChatAgentStateKind) -> Color { + private func statusAccessibilityValue(_ kind: ChatAgentStateKind) -> String { switch kind { case .working: - return .green + return L10n.string("mobile.agent.status.working", defaultValue: "Agent working") case .needsInput: - return .orange + return L10n.string("mobile.agent.status.needsInput", defaultValue: "Agent needs input") } } +} - private func systemImage(for type: MobilePaneSurfaceType) -> String { - switch type { +private extension MobilePaneSurfaceType { + var paneMapSystemImage: String { + switch self { case .terminal: return "terminal" case .browser: @@ -270,55 +496,18 @@ struct PaneMapTileView: View { return "rectangle" } } +} - private var paneAccessibilityLabel: String { - String.localizedStringWithFormat( - L10n.string( - "mobile.paneMap.panePosition", - defaultValue: "Pane %d of %d" - ), - paneNumber, - paneCount - ) - } - - private func surfaceAccessibilityLabel(_ surface: MobilePaneSurface) -> String { - if surface.type.isTerminal { - return String.localizedStringWithFormat( - L10n.string( - "mobile.surfaceDeck.chip.terminalInPane", - defaultValue: "%@, terminal, pane %d of %d" - ), - surface.title, - paneNumber, - paneCount - ) +private extension Color { + init(terminalHex: String) { + guard let rgb = TerminalTheme.rgbComponents(terminalHex) else { + self = .primary + return } - return String.localizedStringWithFormat( - L10n.string( - "mobile.surfaceDeck.chip.unavailableInPane", - defaultValue: "%@, unavailable on iPhone, pane %d of %d" - ), - surface.title, - paneNumber, - paneCount + self.init( + red: Double(rgb.red) / 255, + green: Double(rgb.green) / 255, + blue: Double(rgb.blue) / 255 ) } - - 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 "" - } - } } diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalSurfaceMountOwnershipTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalSurfaceMountOwnershipTests.swift index 550a3789f5dc..aa6bf548dfaa 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalSurfaceMountOwnershipTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/TerminalSurfaceMountOwnershipTests.swift @@ -20,6 +20,7 @@ struct TerminalSurfaceMountOwnershipTests { surfaceID: surfaceID, store: store, artifactFilesEnabled: false, + terminalFolderTapEnabled: true, terminalFilesChipEnabled: false, sessionArtifactCountEnabled: false, visibleArtifactCount: 0, @@ -58,6 +59,7 @@ struct TerminalSurfaceMountOwnershipTests { surfaceID: surfaceID, store: store, artifactFilesEnabled: false, + terminalFolderTapEnabled: true, terminalFilesChipEnabled: false, sessionArtifactCountEnabled: false, visibleArtifactCount: 0, diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index dc19eb90994d..905f621870c2 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -7714,6 +7714,41 @@ "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": { @@ -7728,6 +7763,13 @@ "ja": { "stringUnit": { "state": "translated", "value": "更新" } } } }, + "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": { From 24a2c4921b38523ad6553d8c19e78db001fe5bf9 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 22 Jul 2026 16:21:04 -0700 Subject: [PATCH 28/78] Test reversible pane map zoom --- .../PaneMapCollectionLayoutEngineTests.swift | 44 +++++++++++++++++++ ios/cmuxUITests/cmuxUITests.swift | 21 +++++++++ 2 files changed, 65 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index e7dc0e7b1cf0..88c044193ccf 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -36,6 +36,35 @@ import Testing } } + @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() @@ -70,6 +99,21 @@ import Testing 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, diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 1eaa14393aa9..77de9b0f143c 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1688,6 +1688,27 @@ final class cmuxUITests: XCTestCase { let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) + let originalClaudeFrame = claudeTile.frame + claudeTile.pinch(withScale: 1.3, velocity: 0.35) + + XCTAssertTrue(overlay.exists, "A reversed pane zoom must stay inside the pane map") + let returnedToSource = XCTNSPredicateExpectation( + predicate: NSPredicate( + block: { _, _ in + abs(claudeTile.frame.midX - originalClaudeFrame.midX) < 2 + && abs(claudeTile.frame.midY - originalClaudeFrame.midY) < 2 + && abs(claudeTile.frame.width - originalClaudeFrame.width) < 2 + && abs(claudeTile.frame.height - originalClaudeFrame.height) < 2 + } + ), + object: claudeTile + ) + XCTAssertEqual( + XCTWaiter.wait(for: [returnedToSource], timeout: 4), + .completed, + "A cancelled pane zoom must return to the exact source card" + ) + claudeTile.pinch(withScale: 2, velocity: 2) XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) From c0a6fae14e9700824db6921331127fc56956481b Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 22 Jul 2026 19:30:21 -0700 Subject: [PATCH 29/78] Anchor iOS pane zoom to pinch --- .../PaneMapCollectionView.swift | 119 ++++++++++++++--- .../PaneMapCollectionLayoutEngineTests.swift | 124 ++++++++++++++++++ 2 files changed, 225 insertions(+), 18 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index 514a1148efaf..62dca09ab979 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -29,6 +29,50 @@ struct PaneMapOverflowLabels { let bottom: String } +struct PaneMapInteractiveZoomGeometry { + static func progress(forPinchScale scale: CGFloat) -> CGFloat { + min(1, max(0, (scale - 1) / 1.15)) + } + + static func frame( + initialFrame: CGRect, + targetFrame: CGRect, + normalizedAnchor: CGPoint, + gestureLocation: CGPoint, + progress: CGFloat + ) -> CGRect { + let progress = min(1, max(0, progress)) + let size = CGSize( + width: interpolate(initialFrame.width, targetFrame.width, progress: progress), + height: interpolate(initialFrame.height, targetFrame.height, progress: progress) + ) + return CGRect( + x: gestureLocation.x - normalizedAnchor.x * size.width, + y: gestureLocation.y - normalizedAnchor.y * size.height, + width: size.width, + height: size.height + ) + } + + static func settledFrame( + from initialFrame: CGRect, + to targetFrame: CGRect, + progress: CGFloat + ) -> CGRect { + let progress = min(1, max(0, progress)) + return CGRect( + x: interpolate(initialFrame.minX, targetFrame.minX, progress: progress), + y: interpolate(initialFrame.minY, targetFrame.minY, progress: progress), + width: interpolate(initialFrame.width, targetFrame.width, progress: progress), + height: interpolate(initialFrame.height, targetFrame.height, progress: progress) + ) + } + + private static func interpolate(_ start: CGFloat, _ end: CGFloat, progress: CGFloat) -> CGFloat { + start + (end - start) * progress + } +} + /// UIKit collection surface for native interactive movement and continuous zoom. struct PaneMapCollectionView: UIViewRepresentable { let items: [PaneMapCollectionItem] @@ -124,7 +168,7 @@ struct PaneMapCollectionView: UIViewRepresentable { } func reconcile(items: [PaneMapCollectionItem]) { - guard !isMovingItem else { + guard !isMovingItem, zoomSession == nil else { pendingItems = items return } @@ -255,12 +299,19 @@ struct PaneMapCollectionView: UIViewRepresentable { case .began: let location = gesture.location(in: collectionView) guard let indexPath = collectionView.indexPathForItem(at: location), - startZoom(at: indexPath) else { return } + startZoom(at: indexPath, gestureLocationInCollectionView: location) else { return } collectionView.isScrollEnabled = false case .changed: - guard zoomSession != nil else { return } - let progress = min(1, max(0, (gesture.scale - 1) / 1.15)) - updateZoom(progress: progress) + guard let session = zoomSession else { return } + guard session.wrapper.window?.bounds == session.targetFrame else { + finishZoom() + return + } + let progress = PaneMapInteractiveZoomGeometry.progress( + forPinchScale: gesture.scale + ) + let gestureLocation = gesture.location(in: session.wrapper.superview) + updateInteractiveZoom(progress: progress, gestureLocation: gestureLocation) case .ended: guard let session = zoomSession else { return } let shouldCommit = session.progress > 0.32 || gesture.velocity > 1.4 @@ -290,8 +341,12 @@ struct PaneMapCollectionView: UIViewRepresentable { commitZoom() } - private func startZoom(at indexPath: IndexPath) -> Bool { + private func startZoom( + at indexPath: IndexPath, + gestureLocationInCollectionView: CGPoint? = nil + ) -> Bool { guard zoomSession == nil, + !isMovingItem, orderedItems.indices.contains(indexPath.item), let surface = orderedItems[indexPath.item].selectedSurface, surface.type.isTerminal, @@ -307,6 +362,10 @@ struct PaneMapCollectionView: UIViewRepresentable { width: cell.bounds.width, height: max(0, cell.bounds.height - PaneMapTileMetrics.captionHeight) ) + if let gestureLocationInCollectionView { + let locationInCell = collectionView.convert(gestureLocationInCollectionView, to: cell) + guard previewBounds.contains(locationInCell) else { return false } + } guard let snapshot = cell.resizableSnapshotView( from: previewBounds, afterScreenUpdates: true, @@ -315,6 +374,17 @@ struct PaneMapCollectionView: UIViewRepresentable { return false } let initialFrame = cell.convert(previewBounds, to: window) + let gestureLocation = gestureLocationInCollectionView.map { + collectionView.convert($0, to: window) + } ?? CGPoint(x: initialFrame.midX, y: initialFrame.midY) + let normalizedAnchor = CGPoint( + x: initialFrame.width > 0 + ? (gestureLocation.x - initialFrame.minX) / initialFrame.width + : 0.5, + y: initialFrame.height > 0 + ? (gestureLocation.y - initialFrame.minY) / initialFrame.height + : 0.5 + ) let backdrop = UIView(frame: window.bounds) backdrop.backgroundColor = UIColor(terminalHex: parent.terminalTheme.background) backdrop.alpha = 0 @@ -340,15 +410,32 @@ struct PaneMapCollectionView: UIViewRepresentable { backdrop: backdrop, initialFrame: initialFrame, targetFrame: window.bounds, + normalizedAnchor: normalizedAnchor, progress: 0 ) return true } + private func updateInteractiveZoom(progress: CGFloat, gestureLocation: CGPoint) { + guard var session = zoomSession else { return } + session.progress = progress + session.wrapper.frame = PaneMapInteractiveZoomGeometry.frame( + initialFrame: session.initialFrame, + targetFrame: session.targetFrame, + normalizedAnchor: session.normalizedAnchor, + gestureLocation: gestureLocation, + progress: progress + ) + session.snapshot.frame = session.wrapper.bounds + session.wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius * (1 - progress) + session.backdrop.alpha = progress + zoomSession = session + } + private func updateZoom(progress: CGFloat) { guard var session = zoomSession else { return } session.progress = progress - session.wrapper.frame = interpolate( + session.wrapper.frame = PaneMapInteractiveZoomGeometry.settledFrame( from: session.initialFrame, to: session.targetFrame, progress: progress @@ -373,9 +460,9 @@ struct PaneMapCollectionView: UIViewRepresentable { } completion: { [weak self] _ in guard let self, let committedSession = self.zoomSession else { return } self.parent.jumpToTerminal(committedSession.surfaceID) - Task { @MainActor [weak self] in + Task { @MainActor [self] in await Task.yield() - self?.finishZoom() + finishZoom() } } } @@ -403,15 +490,10 @@ struct PaneMapCollectionView: UIViewRepresentable { session.backdrop.removeFromSuperview() collectionView?.isScrollEnabled = true zoomSession = nil - } - - private func interpolate(from start: CGRect, to end: CGRect, progress: CGFloat) -> CGRect { - CGRect( - x: start.minX + (end.minX - start.minX) * progress, - y: start.minY + (end.minY - start.minY) * progress, - width: start.width + (end.width - start.width) * progress, - height: start.height + (end.height - start.height) * progress - ) + if let pendingItems { + self.pendingItems = nil + reconcile(items: pendingItems) + } } func scrollOneViewport(_ direction: PaneMapOverflowDirection) { @@ -446,6 +528,7 @@ struct PaneMapCollectionView: UIViewRepresentable { let backdrop: UIView let initialFrame: CGRect let targetFrame: CGRect + let normalizedAnchor: CGPoint var progress: CGFloat } } diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 88c044193ccf..184b51ac14af 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -144,3 +144,127 @@ import Testing MobilePaneNode(id: id, selectedSurfaceID: nil, surfaces: []) } } + +@Suite struct PaneMapInteractiveZoomGeometryTests { + private let initialFrame = CGRect(x: 100, y: 200, width: 120, height: 240) + private let targetFrame = CGRect(x: 0, y: 0, width: 390, height: 844) + private let anchor = CGPoint(x: 0.25, y: 0.75) + + @Test func zeroProgressPreservesTheSourceFrame() { + let sourceAnchor = CGPoint( + x: initialFrame.minX + initialFrame.width * anchor.x, + y: initialFrame.minY + initialFrame.height * anchor.y + ) + + let frame = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: sourceAnchor, + progress: 0 + ) + + #expect(frame == initialFrame) + } + + @Test func intermediateProgressTracksTheGestureCenter() { + let progress: CGFloat = 0.4 + let gestureLocation = CGPoint(x: 250, y: 500) + + let frame = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: gestureLocation, + progress: progress + ) + + let renderedAnchor = CGPoint( + x: frame.minX + frame.width * anchor.x, + y: frame.minY + frame.height * anchor.y + ) + + #expect(abs(frame.width - 228) < 0.001) + #expect(abs(frame.height - 481.6) < 0.001) + #expect(abs(renderedAnchor.x - gestureLocation.x) < 0.001) + #expect(abs(renderedAnchor.y - gestureLocation.y) < 0.001) + } + + @Test func movingTheGestureCenterMovesTheFrameOneForOne() { + let first = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: CGPoint(x: 200, y: 400), + progress: 0.5 + ) + let second = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: CGPoint(x: 237, y: 381), + progress: 0.5 + ) + + #expect(abs(second.minX - first.minX - 37) < 0.001) + #expect(abs(second.minY - first.minY + 19) < 0.001) + #expect(second.size == first.size) + } + + @Test func settlementUsesExactSourceAndTargetFrames() { + let source = PaneMapInteractiveZoomGeometry.settledFrame( + from: initialFrame, + to: targetFrame, + progress: 0 + ) + let target = PaneMapInteractiveZoomGeometry.settledFrame( + from: initialFrame, + to: targetFrame, + progress: 1 + ) + + #expect(source == initialFrame) + #expect(target == targetFrame) + } + + @Test func pinchScaleProgressIsAbsoluteAndClamped() { + #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 0.5) == 0) + #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 1) == 0) + #expect(abs( + PaneMapInteractiveZoomGeometry.progress(forPinchScale: 1.575) - 0.5 + ) < 0.001) + #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 2.15) == 1) + #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 4) == 1) + } + + @Test func reversingScaleDoesNotAccumulateGeometry() { + let sourceAnchor = CGPoint( + x: initialFrame.minX + initialFrame.width * anchor.x, + y: initialFrame.minY + initialFrame.height * anchor.y + ) + let expanded = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: sourceAnchor, + progress: 0.7 + ) + let reversed = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: sourceAnchor, + progress: 0.25 + ) + let returned = PaneMapInteractiveZoomGeometry.frame( + initialFrame: initialFrame, + targetFrame: targetFrame, + normalizedAnchor: anchor, + gestureLocation: sourceAnchor, + progress: 0 + ) + + #expect(expanded.width > reversed.width) + #expect(returned == initialFrame) + } +} From e50db56dff2e35609d050fb4418a4276b1df50fa Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 11:49:33 -0700 Subject: [PATCH 30/78] Test polished iOS pane previews --- ...erminalRenderGridPaneMapPreviewTests.swift | 63 +++++++++++++++++++ .../Debug/PanesTabsPreviewHost.swift | 8 ++- .../PaneMapCollectionLayoutEngineTests.swift | 52 +++++++++++++++ .../PaneMapTerminalPreviewLayoutTests.swift | 42 +++++++++++++ .../TerminalThemeParityUITests.swift | 24 +++++++ ios/cmuxUITests/cmuxUITests.swift | 53 +++++++++++++++- 6 files changed, 239 insertions(+), 3 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift index c1d337571bbc..bd6419c456d4 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift @@ -92,6 +92,69 @@ import Testing #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, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 4a936a5e1b3a..e22484eb5360 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -268,7 +268,9 @@ struct PanesTabsPreviewHost: View { } private static func styledClaudeFrame() throws -> MobileTerminalRenderGridFrame { - try MobileTerminalRenderGridFrame( + var effectiveTheme = TerminalTheme.monokai + effectiveTheme.background = "#123456" + return try MobileTerminalRenderGridFrame( surfaceID: claudeSurfaceID, stateSeq: 1, columns: 50, @@ -291,7 +293,9 @@ struct PanesTabsPreviewHost: View { .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 ) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 184b51ac14af..015f9ff74162 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -237,6 +237,33 @@ import Testing #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 4) == 1) } + @Test func reciprocalPinchesProduceComplementaryProgress() { + let scale: CGFloat = 1.6 + let zoomedIn = PaneMapInteractiveZoomGeometry.progress( + startingAt: 0, + forPinchScale: scale + ) + let zoomedOut = PaneMapInteractiveZoomGeometry.progress( + startingAt: 1, + forPinchScale: 1 / scale + ) + + #expect(abs(zoomedIn + zoomedOut - 1) < 0.001) + } + + @Test func equalDistanceSettlesUseIdenticalTimingInBothDirections() { + let zoomInDuration = PaneMapInteractiveZoomGeometry.settlementDuration( + from: 0.25, + to: 1 + ) + let zoomOutDuration = PaneMapInteractiveZoomGeometry.settlementDuration( + from: 0.75, + to: 0 + ) + + #expect(zoomInDuration == zoomOutDuration) + } + @Test func reversingScaleDoesNotAccumulateGeometry() { let sourceAnchor = CGPoint( x: initialFrame.minX + initialFrame.width * anchor.x, @@ -268,3 +295,28 @@ import Testing #expect(returned == initialFrame) } } + +@Suite struct PaneMapZoomTransitionStateTests { + @Test func staleCommitCannotWinAfterSettlementIsReversed() { + var state = PaneMapZoomTransitionState(progress: 0) + state.beginGesture(at: 0) + state.updateGesture(pinchScale: 1.7) + let staleCommit = state.beginSettlement(toward: .terminal) + + state.interruptSettlement(at: 0.6) + state.updateGesture(pinchScale: 0.5) + let currentReturn = state.beginSettlement(toward: .map) + + #expect(state.completeSettlement(generation: staleCommit) == nil) + #expect(state.completeSettlement(generation: currentReturn) == .map) + } + + @Test func interruptedSettlementContinuesFromRenderedProgress() { + var state = PaneMapZoomTransitionState(progress: 0) + state.interruptSettlement(at: 0.63) + + #expect(abs(state.progress - 0.63) < 0.001) + state.updateGesture(pinchScale: 1) + #expect(abs(state.progress - 0.63) < 0.001) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift new file mode 100644 index 000000000000..11878091b4eb --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift @@ -0,0 +1,42 @@ +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() { + #expect(PaneMapTabStripMetrics.width(tabCount: 2) == 64) + #expect(PaneMapTabStripMetrics.width(tabCount: 3) == 94) + #expect(PaneMapTabStripMetrics.width(tabCount: 4) == 124) + #expect(PaneMapTabStripMetrics.width(tabCount: 5) == 132) + #expect(PaneMapTabStripMetrics.width(tabCount: 20) == 132) + } +} 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 77de9b0f143c..7fe65d3ec171 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1624,11 +1624,16 @@ final class cmuxUITests: XCTestCase { XCTAssertLessThan(leftTopPane.frame.midY, leftBottomPane.frame.midY) XCTAssertLessThan(testsPane.frame.midY, serverPane.frame.midY) XCTAssertEqual(leftTopPane.value as? String, "Focused on Mac") - XCTAssertTrue( + 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(overlay.waitForNonExistence(timeout: 4)) @@ -1715,6 +1720,52 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-claude"].isSelected) } + @MainActor + func testPaneZoomSettlementCanBeInterruptedBackToItsSourceCard() throws { + let app = launchApp(mockData: false, environment: [ + "CMUX_UITEST_PANES_PREVIEW": "1", + "CMUX_UITEST_PANE_ZOOM_SETTLE_DURATION": "1.2", + ]) + defer { app.terminate() } + + XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) + tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) + + let overlay = app.otherElements["MobilePaneMapOverlay"] + XCTAssertTrue(overlay.waitForExistence(timeout: 4)) + let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] + XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) + let sourceFrame = claudeTile.frame + + claudeTile.pinch(withScale: 1.4, velocity: 2) + overlay.pinch(withScale: 0.5, velocity: -2) + + XCTAssertTrue( + overlay.waitForExistence(timeout: 2), + "Reversing an active terminal settlement must keep the pane map presented" + ) + let returnedToSource = XCTNSPredicateExpectation( + predicate: NSPredicate( + block: { _, _ in + abs(claudeTile.frame.midX - sourceFrame.midX) < 2 + && abs(claudeTile.frame.midY - sourceFrame.midY) < 2 + && abs(claudeTile.frame.width - sourceFrame.width) < 2 + && abs(claudeTile.frame.height - sourceFrame.height) < 2 + } + ), + object: claudeTile + ) + XCTAssertEqual( + XCTWaiter.wait(for: [returnedToSource], timeout: 3), + .completed, + "Interrupted zoom must settle to the exact source card" + ) + XCTAssertTrue( + overlay.exists, + "A stale terminal completion must not dismiss after the reversal" + ) + } + @MainActor func testBottomScrollStaysPinnedAcrossComposerViewportShrink() throws { let app = launchApp(mockData: false, environment: [ From aad1eff77f0a85982ad6f755e9b95b952e266d47 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 12:02:03 -0700 Subject: [PATCH 31/78] Polish iOS pane previews and zoom --- ...rminalRenderGridFrame+PaneMapPreview.swift | 94 +++++- .../PaneMapCollectionView.swift | 318 +++++++++++++++--- .../CmuxMobileShellUI/PaneMapTileView.swift | 171 +++++++--- 3 files changed, 473 insertions(+), 110 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift index e64cc9ebfb0d..8a26be9acfdb 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift @@ -25,6 +25,14 @@ public struct MobileTerminalPaneMapPreview: Equatable, Sendable { 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, @@ -32,6 +40,10 @@ public struct MobileTerminalPaneMapPreview: Equatable, Sendable { sourceRows: Int, firstSourceRow: Int, styles: [MobileTerminalRenderGridFrame.Style], + terminalTheme: TerminalTheme?, + terminalForeground: String?, + terminalBackground: String?, + usesDECReverseVideo: Bool, rows: [[Cell]] ) { self.surfaceID = surfaceID @@ -42,6 +54,10 @@ public struct MobileTerminalPaneMapPreview: Equatable, Sendable { 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 } @@ -49,6 +65,29 @@ public struct MobileTerminalPaneMapPreview: Equatable, Sendable { 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 { @@ -69,11 +108,16 @@ private struct MutablePaneMapPreviewCell { public extension MobileTerminalRenderGridFrame { /// Resolves this frame into fixed terminal cells for a compact visual preview. /// - /// Passing `nil` renders the complete visible terminal grid. A finite limit - /// preserves the previous tail-window behavior for text-only callers. + /// 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 { + let usesDECReverseVideo = modes.contains { + !$0.ansi && $0.code == 5 && $0.on + } guard columns > 0, rows > 0 else { return MobileTerminalPaneMapPreview( surfaceID: surfaceID, @@ -81,15 +125,28 @@ public extension MobileTerminalRenderGridFrame { 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 { - spansByRow[span.row, default: []].append(span) - lastSpanRow = max(lastSpanRow ?? span.row, span.row) + let sourceRow = includedScrollbackRows + span.row + spansByRow[sourceRow, default: []].append(span) + lastSpanRow = max(lastSpanRow ?? sourceRow, sourceRow) } let rowRange: Range @@ -98,19 +155,28 @@ public extension MobileTerminalRenderGridFrame { return MobileTerminalPaneMapPreview( surfaceID: surfaceID, columns: columns, - sourceRows: rows, + sourceRows: sourceRows, firstSourceRow: 0, styles: styles, + terminalTheme: terminalTheme, + terminalForeground: terminalForeground, + terminalBackground: terminalBackground, + usesDECReverseVideo: usesDECReverseVideo, rows: [] ) } - let boundedMaximumRows = min(rows, maximumRows) - let lastContentRow = max(lastSpanRow ?? 0, cursor?.row ?? 0) - let endRow = min(rows, max(lastContentRow + 1, boundedMaximumRows)) - let firstRow = max(0, endRow - boundedMaximumRows) - rowRange = firstRow.. 0 { + let firstRow = sourceRows - boundedMaximumRows + rowRange = firstRow.. CGFloat { min(1, max(0, (scale - 1) / 1.15)) } + static func progress( + startingAt initialProgress: CGFloat, + forPinchScale scale: CGFloat + ) -> CGFloat { + guard scale > 0 else { return clamped(initialProgress) } + let scaleProgress = log(Double(scale)) / log(Double(fullTransitionScale)) + return clamped(initialProgress + CGFloat(scaleProgress)) + } + + static func settlementDuration( + from initialProgress: CGFloat, + to targetProgress: CGFloat + ) -> TimeInterval { + let distance = abs(clamped(targetProgress) - clamped(initialProgress)) + return max(0.08, fullSettlementDuration * TimeInterval(distance)) + } + + static func progress( + forRenderedFrame frame: CGRect, + from initialFrame: CGRect, + to targetFrame: CGRect + ) -> CGFloat { + let widthDistance = targetFrame.width - initialFrame.width + let heightDistance = targetFrame.height - initialFrame.height + if abs(widthDistance) >= abs(heightDistance), abs(widthDistance) > 0.001 { + return clamped((frame.width - initialFrame.width) / widthDistance) + } + guard abs(heightDistance) > 0.001 else { return 0 } + return clamped((frame.height - initialFrame.height) / heightDistance) + } + static func frame( initialFrame: CGRect, targetFrame: CGRect, @@ -71,6 +106,62 @@ struct PaneMapInteractiveZoomGeometry { private static func interpolate(_ start: CGFloat, _ end: CGFloat, progress: CGFloat) -> CGFloat { start + (end - start) * progress } + + private static func clamped(_ progress: CGFloat) -> CGFloat { + min(1, max(0, progress)) + } +} + +struct PaneMapZoomTransitionState { + enum Destination: Equatable { + case map + case terminal + } + + private(set) var progress: CGFloat + private(set) var generation: UInt64 = 0 + private(set) var settlingDestination: Destination? + private var gestureStartProgress: CGFloat + + init(progress: CGFloat) { + let progress = min(1, max(0, progress)) + self.progress = progress + self.gestureStartProgress = progress + } + + mutating func beginGesture(at renderedProgress: CGFloat) { + generation &+= 1 + progress = min(1, max(0, renderedProgress)) + gestureStartProgress = progress + settlingDestination = nil + } + + mutating func interruptSettlement(at renderedProgress: CGFloat) { + beginGesture(at: renderedProgress) + } + + mutating func updateGesture(pinchScale: CGFloat) { + progress = PaneMapInteractiveZoomGeometry.progress( + startingAt: gestureStartProgress, + forPinchScale: pinchScale + ) + } + + mutating func beginSettlement(toward destination: Destination) -> UInt64 { + generation &+= 1 + settlingDestination = destination + return generation + } + + mutating func completeSettlement(generation: UInt64) -> Destination? { + guard generation == self.generation, let destination = settlingDestination else { + return nil + } + progress = destination == .terminal ? 1 : 0 + gestureStartProgress = progress + settlingDestination = nil + return destination + } } /// UIKit collection surface for native interactive movement and continuous zoom. @@ -146,6 +237,8 @@ struct PaneMapCollectionView: UIViewRepresentable { private var isMovingItem = false private var pendingItems: [PaneMapCollectionItem]? private var zoomSession: ZoomSession? + private var zoomAnimator: UIViewPropertyAnimator? + private var activeZoomGestureGeneration: UInt64? init(parent: PaneMapCollectionView) { self.parent = parent @@ -298,27 +391,59 @@ struct PaneMapCollectionView: UIViewRepresentable { switch gesture.state { case .began: let location = gesture.location(in: collectionView) - guard let indexPath = collectionView.indexPathForItem(at: location), - startZoom(at: indexPath, gestureLocationInCollectionView: location) else { return } + if zoomSession != nil { + guard let window = zoomSession?.wrapper.superview, + interruptZoomSettlement( + gestureLocation: gesture.location(in: window) + ) else { + return + } + } else { + guard let indexPath = collectionView.indexPathForItem(at: location), + startZoom( + at: indexPath, + gestureLocationInCollectionView: location + ), + beginZoomGesture() else { + return + } + } collectionView.isScrollEnabled = false case .changed: - guard let session = zoomSession else { return } + guard var session = zoomSession, + activeZoomGestureGeneration == session.transition.generation else { + return + } guard session.wrapper.window?.bounds == session.targetFrame else { finishZoom() return } - let progress = PaneMapInteractiveZoomGeometry.progress( - forPinchScale: gesture.scale - ) + session.transition.updateGesture(pinchScale: gesture.scale) + let progress = session.transition.progress + zoomSession = session let gestureLocation = gesture.location(in: session.wrapper.superview) updateInteractiveZoom(progress: progress, gestureLocation: gestureLocation) case .ended: - guard let session = zoomSession else { return } - let shouldCommit = session.progress > 0.32 || gesture.velocity > 1.4 - shouldCommit ? commitZoom() : cancelZoom() + guard let session = zoomSession, + activeZoomGestureGeneration == session.transition.generation else { + return + } + activeZoomGestureGeneration = nil + let normalizedVelocity = gesture.velocity + / max(gesture.scale, 0.001) + / CGFloat(log(2.15)) + let projectedProgress = session.transition.progress + + normalizedVelocity * 0.12 + settleZoom( + toward: projectedProgress >= 0.5 ? .terminal : .map + ) default: - guard zoomSession != nil else { return } - cancelZoom() + guard let session = zoomSession, + activeZoomGestureGeneration == session.transition.generation else { + return + } + activeZoomGestureGeneration = nil + settleZoom(toward: .map) } } @@ -338,7 +463,7 @@ struct PaneMapCollectionView: UIViewRepresentable { startZoom(at: IndexPath(item: itemIndex, section: 0)) else { return } - commitZoom() + settleZoom(toward: .terminal) } private func startZoom( @@ -385,13 +510,16 @@ struct PaneMapCollectionView: UIViewRepresentable { ? (gestureLocation.y - initialFrame.minY) / initialFrame.height : 0.5 ) + let previewTheme = orderedItems[indexPath.item].preview? + .resolvedTerminalTheme(fallback: parent.terminalTheme) + ?? parent.terminalTheme let backdrop = UIView(frame: window.bounds) - backdrop.backgroundColor = UIColor(terminalHex: parent.terminalTheme.background) + backdrop.backgroundColor = UIColor(terminalHex: previewTheme.background) backdrop.alpha = 0 backdrop.isUserInteractionEnabled = false let wrapper = UIView(frame: initialFrame) - wrapper.backgroundColor = UIColor(terminalHex: parent.terminalTheme.background) + wrapper.backgroundColor = UIColor(terminalHex: previewTheme.background) wrapper.clipsToBounds = true wrapper.layer.cornerCurve = .continuous wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius @@ -411,14 +539,64 @@ struct PaneMapCollectionView: UIViewRepresentable { initialFrame: initialFrame, targetFrame: window.bounds, normalizedAnchor: normalizedAnchor, - progress: 0 + transition: PaneMapZoomTransitionState(progress: 0) + ) + return true + } + + private func beginZoomGesture() -> Bool { + guard var session = zoomSession else { return false } + session.transition.beginGesture(at: session.transition.progress) + activeZoomGestureGeneration = session.transition.generation + zoomSession = session + return true + } + + private func interruptZoomSettlement(gestureLocation: CGPoint) -> Bool { + guard var session = zoomSession, let animator = zoomAnimator else { + return false + } + + let presentationFrame = session.wrapper.layer.presentation()?.frame + ?? session.wrapper.frame + let presentationCornerRadius = session.wrapper.layer.presentation()?.cornerRadius + ?? session.wrapper.layer.cornerRadius + let presentationBackdropAlpha = session.backdrop.layer.presentation()?.opacity + ?? Float(session.backdrop.alpha) + let renderedProgress = PaneMapInteractiveZoomGeometry.progress( + forRenderedFrame: presentationFrame, + from: session.initialFrame, + to: session.targetFrame ) + + zoomAnimator = nil + animator.stopAnimation(true) + session.wrapper.layer.removeAllAnimations() + session.snapshot.layer.removeAllAnimations() + session.backdrop.layer.removeAllAnimations() + session.wrapper.frame = presentationFrame + session.snapshot.frame = session.wrapper.bounds + session.wrapper.layer.cornerRadius = presentationCornerRadius + session.backdrop.alpha = CGFloat(presentationBackdropAlpha) + + session.normalizedAnchor = CGPoint( + x: session.wrapper.bounds.width > 0 + ? (gestureLocation.x - presentationFrame.minX) / presentationFrame.width + : 0.5, + y: session.wrapper.bounds.height > 0 + ? (gestureLocation.y - presentationFrame.minY) / presentationFrame.height + : 0.5 + ) + session.normalizedAnchor.x = min(1, max(0, session.normalizedAnchor.x)) + session.normalizedAnchor.y = min(1, max(0, session.normalizedAnchor.y)) + session.transition.interruptSettlement(at: renderedProgress) + activeZoomGestureGeneration = session.transition.generation + zoomSession = session return true } private func updateInteractiveZoom(progress: CGFloat, gestureLocation: CGPoint) { - guard var session = zoomSession else { return } - session.progress = progress + guard let session = zoomSession else { return } session.wrapper.frame = PaneMapInteractiveZoomGeometry.frame( initialFrame: session.initialFrame, targetFrame: session.targetFrame, @@ -429,12 +607,10 @@ struct PaneMapCollectionView: UIViewRepresentable { session.snapshot.frame = session.wrapper.bounds session.wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius * (1 - progress) session.backdrop.alpha = progress - zoomSession = session } - private func updateZoom(progress: CGFloat) { - guard var session = zoomSession else { return } - session.progress = progress + private func renderSettledZoom(progress: CGFloat) { + guard let session = zoomSession else { return } session.wrapper.frame = PaneMapInteractiveZoomGeometry.settledFrame( from: session.initialFrame, to: session.targetFrame, @@ -443,48 +619,86 @@ struct PaneMapCollectionView: UIViewRepresentable { session.snapshot.frame = session.wrapper.bounds session.wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius * (1 - progress) session.backdrop.alpha = progress + } + + private func settleZoom(toward destination: PaneMapZoomTransitionState.Destination) { + guard var session = zoomSession else { return } + let targetProgress: CGFloat = destination == .terminal ? 1 : 0 + let initialProgress = session.transition.progress + let generation = session.transition.beginSettlement(toward: destination) zoomSession = session + + let defaultDuration = PaneMapInteractiveZoomGeometry.settlementDuration( + from: initialProgress, + to: targetProgress + ) + let duration = zoomSettlementDurationOverride ?? defaultDuration + let timing = UISpringTimingParameters(dampingRatio: 0.92) + let animator = UIViewPropertyAnimator( + duration: duration, + timingParameters: timing + ) + zoomAnimator = animator + animator.addAnimations { [weak self] in + self?.renderSettledZoom(progress: targetProgress) + } + animator.addCompletion { [weak self, weak animator] position in + guard let self, let animator, self.zoomAnimator === animator else { + return + } + self.completeZoomSettlement( + generation: generation, + position: position + ) + } + animator.startAnimation() } - private func commitZoom() { - guard let session = zoomSession else { return } - let remaining = max(0.16, 0.34 * (1 - session.progress)) - UIView.animate( - withDuration: remaining, - delay: 0, - usingSpringWithDamping: 0.92, - initialSpringVelocity: 0.2, - options: [.beginFromCurrentState, .curveEaseOut] - ) { [weak self] in - self?.updateZoom(progress: 1) - } completion: { [weak self] _ in - guard let self, let committedSession = self.zoomSession else { return } - self.parent.jumpToTerminal(committedSession.surfaceID) - Task { @MainActor [self] in + private func completeZoomSettlement( + generation: UInt64, + position: UIViewAnimatingPosition + ) { + zoomAnimator = nil + guard position == .end, var session = zoomSession else { return } + guard let destination = session.transition.completeSettlement( + generation: generation + ) else { + return + } + zoomSession = session + switch destination { + case .map: + finishZoom() + case .terminal: + parent.jumpToTerminal(session.surfaceID) + Task { @MainActor [weak self] in await Task.yield() - finishZoom() + self?.finishZoom() } } } - private func cancelZoom() { - guard let session = zoomSession else { return } - let remaining = max(0.16, 0.26 * session.progress) - UIView.animate( - withDuration: remaining, - delay: 0, - usingSpringWithDamping: 0.9, - initialSpringVelocity: 0, - options: [.beginFromCurrentState, .curveEaseOut] - ) { [weak self] in - self?.updateZoom(progress: 0) - } completion: { [weak self] _ in - self?.finishZoom() + private var zoomSettlementDurationOverride: TimeInterval? { +#if DEBUG + guard let rawValue = ProcessInfo.processInfo.environment[ + "CMUX_UITEST_PANE_ZOOM_SETTLE_DURATION" + ], + let duration = TimeInterval(rawValue), + duration > 0 else { + return nil } + return duration +#else + nil +#endif } private func finishZoom() { guard let session = zoomSession else { return } + let animator = zoomAnimator + zoomAnimator = nil + animator?.stopAnimation(true) + activeZoomGestureGeneration = nil session.cell.alpha = 1 session.wrapper.removeFromSuperview() session.backdrop.removeFromSuperview() @@ -528,8 +742,8 @@ struct PaneMapCollectionView: UIViewRepresentable { let backdrop: UIView let initialFrame: CGRect let targetFrame: CGRect - let normalizedAnchor: CGPoint - var progress: CGFloat + var normalizedAnchor: CGPoint + var transition: PaneMapZoomTransitionState } } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index 5be0e54ab60b..b44eba84996f 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -8,6 +8,85 @@ enum PaneMapTileMetrics { static 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) + } +} + +enum PaneMapTabStripMetrics { + static let tabWidth: CGFloat = 28 + static let spacing: CGFloat = 2 + static let padding: CGFloat = 3 + static let maximumWidth: CGFloat = 132 + + static 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) + } +} + /// One floating Safari-style pane card rendered from immutable snapshots. struct PaneMapTileView: View { let item: PaneMapCollectionItem @@ -66,7 +145,7 @@ private struct PaneMapPreviewCard: View { ) ZStack { - terminalTheme.terminalBackgroundColor + previewTerminalTheme.terminalBackgroundColor if let selectedSurface { PaneMapSurfacePreview( @@ -80,11 +159,6 @@ private struct PaneMapPreviewCard: View { VStack { HStack(alignment: .top) { - PaneMapPaneNumberBadge( - paneID: item.pane.id, - paneNumber: item.paneNumber, - terminalTheme: terminalTheme - ) Spacer(minLength: 0) if item.isFocusedOnMac { PaneMapMacFocusBadge(terminalTheme: terminalTheme) @@ -103,7 +177,7 @@ private struct PaneMapPreviewCard: View { .padding(8) } .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(terminalTheme.terminalBackgroundColor) + .background(previewTerminalTheme.terminalBackgroundColor) .overlay { shape.stroke(.white.opacity(0.16), lineWidth: 1) } @@ -115,6 +189,10 @@ private struct PaneMapPreviewCard: View { .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 { @@ -167,10 +245,16 @@ private struct PaneMapTerminalPreview: View { let terminalTheme: TerminalTheme var body: some View { + let resolvedTerminalTheme = + preview?.resolvedTerminalTheme(fallback: terminalTheme) ?? terminalTheme + ZStack(alignment: .topLeading) { - terminalTheme.terminalBackgroundColor + resolvedTerminalTheme.terminalBackgroundColor if let preview { - PaneMapTerminalCanvas(preview: preview, terminalTheme: terminalTheme) + PaneMapTerminalCanvas( + preview: preview, + terminalTheme: resolvedTerminalTheme + ) } else if isLoadingPreview { ProgressView() .controlSize(.mini) @@ -195,27 +279,32 @@ private struct PaneMapTerminalCanvas: View { ) guard preview.columns > 0, !preview.rows.isEmpty else { return } - let lineHeightRatio: CGFloat = 1.82 - let widthCell = size.width / CGFloat(preview.columns) - let heightCell = size.height / (CGFloat(preview.rows.count) * lineHeightRatio) - let cellWidth = max(0.1, min(widthCell, heightCell)) - let lineHeight = cellWidth * lineHeightRatio - let fontSize = max(0.5, cellWidth / 0.61) + 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 (rowIndex, row) in preview.rows.enumerated() { + for (visibleRowIndex, sourceRowIndex) in layout.visibleRowRange.enumerated() { + let row = preview.rows[sourceRowIndex] drawBackgrounds( row, - rowIndex: rowIndex, - cellWidth: cellWidth, - lineHeight: lineHeight, + rowIndex: visibleRowIndex, + origin: layout.drawOrigin, + cellWidth: layout.cellWidth, + lineHeight: layout.lineHeight, context: &context ) drawGlyphs( row, - rowIndex: rowIndex, - cellWidth: cellWidth, - lineHeight: lineHeight, - fontSize: fontSize, + rowIndex: visibleRowIndex, + origin: layout.drawOrigin, + cellWidth: layout.cellWidth, + lineHeight: layout.lineHeight, + fontSize: layout.fontSize, context: &context ) } @@ -226,6 +315,7 @@ private struct PaneMapTerminalCanvas: View { private func drawBackgrounds( _ row: [MobileTerminalPaneMapPreview.Cell], rowIndex: Int, + origin: CGPoint, cellWidth: CGFloat, lineHeight: CGFloat, context: inout GraphicsContext @@ -240,8 +330,8 @@ private struct PaneMapTerminalCanvas: View { if let background = resolvedStyle(styleID).background { context.fill( Path(CGRect( - x: CGFloat(startColumn) * cellWidth, - y: CGFloat(rowIndex) * lineHeight, + x: origin.x + (CGFloat(startColumn) * cellWidth), + y: origin.y + (CGFloat(rowIndex) * lineHeight), width: CGFloat(endColumn - startColumn) * cellWidth, height: lineHeight )), @@ -255,6 +345,7 @@ private struct PaneMapTerminalCanvas: View { private func drawGlyphs( _ row: [MobileTerminalPaneMapPreview.Cell], rowIndex: Int, + origin: CGPoint, cellWidth: CGFloat, lineHeight: CGFloat, fontSize: CGFloat, @@ -277,8 +368,8 @@ private struct PaneMapTerminalCanvas: View { context.draw( text, at: CGPoint( - x: CGFloat(column) * cellWidth, - y: CGFloat(rowIndex) * lineHeight + x: origin.x + (CGFloat(column) * cellWidth), + y: origin.y + (CGFloat(rowIndex) * lineHeight) ), anchor: .topLeading ) @@ -286,8 +377,8 @@ private struct PaneMapTerminalCanvas: View { let width = CGFloat(max(1, cell.columnSpan)) * cellWidth context.stroke( Path(CGRect( - x: CGFloat(column) * cellWidth, - y: CGFloat(rowIndex) * lineHeight, + x: origin.x + (CGFloat(column) * cellWidth), + y: origin.y + (CGFloat(rowIndex) * lineHeight), width: width, height: 0.5 )), @@ -361,21 +452,6 @@ private struct PaneMapUnavailableSurfacePreview: View { } } -private struct PaneMapPaneNumberBadge: View { - let paneID: String - let paneNumber: Int - let terminalTheme: TerminalTheme - - var body: some View { - Text(paneNumber, format: .number) - .font(.caption2.weight(.bold)) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .frame(width: 26, height: 26) - .mobileGlassCircle() - .accessibilityIdentifier("MobilePaneMapPaneNumber-\(paneID)") - } -} - private struct PaneMapMacFocusBadge: View { let terminalTheme: TerminalTheme @@ -430,9 +506,12 @@ private struct PaneMapTabSwitcher: View { .padding(3) } .scrollIndicators(.hidden) - .fixedSize(horizontal: true, vertical: true) - .frame(maxWidth: 132) + .frame( + width: PaneMapTabStripMetrics.width(tabCount: pane.surfaces.count), + height: 34 + ) .mobileGlassPill() + .accessibilityIdentifier("MobilePaneMapTabStrip-\(pane.id)") } } From 92792d4d08e33a74fdeebc5df10936f8e78b50aa Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 12:15:23 -0700 Subject: [PATCH 32/78] Verify interrupted pane zoom settlement --- .../PaneMapCollectionView.swift | 43 +++++++++++++++++++ ios/cmuxUITests/cmuxUITests.swift | 4 +- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index 2fa2bfc81e3c..c5d8ad3ca18e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -652,7 +652,50 @@ struct PaneMapCollectionView: UIViewRepresentable { ) } animator.startAnimation() +#if DEBUG + scheduleUITestZoomInterruptionIfNeeded(for: destination) +#endif + } + +#if DEBUG + private func scheduleUITestZoomInterruptionIfNeeded( + for destination: PaneMapZoomTransitionState.Destination + ) { + guard destination == .terminal, + let rawValue = ProcessInfo.processInfo.environment[ + "CMUX_UITEST_PANE_ZOOM_INTERRUPT_DELAY" + ], + let delay = TimeInterval(rawValue), + delay >= 0 else { + return + } + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + guard let self, let session = self.zoomSession, + self.zoomAnimator != nil else { + return + } + let gestureLocation = CGPoint( + x: session.wrapper.frame.midX, + y: session.wrapper.frame.midY + ) + guard self.interruptZoomSettlement(gestureLocation: gestureLocation), + var interruptedSession = self.zoomSession, + self.activeZoomGestureGeneration + == interruptedSession.transition.generation else { + return + } + interruptedSession.transition.updateGesture(pinchScale: 0.5) + let progress = interruptedSession.transition.progress + self.zoomSession = interruptedSession + self.updateInteractiveZoom( + progress: progress, + gestureLocation: gestureLocation + ) + self.activeZoomGestureGeneration = nil + self.settleZoom(toward: .map) + } } +#endif private func completeZoomSettlement( generation: UInt64, diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 7fe65d3ec171..c3484e2554bf 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1725,6 +1725,7 @@ final class cmuxUITests: XCTestCase { let app = launchApp(mockData: false, environment: [ "CMUX_UITEST_PANES_PREVIEW": "1", "CMUX_UITEST_PANE_ZOOM_SETTLE_DURATION": "1.2", + "CMUX_UITEST_PANE_ZOOM_INTERRUPT_DELAY": "0.12", ]) defer { app.terminate() } @@ -1737,8 +1738,9 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) let sourceFrame = claudeTile.frame + // Public XCUITest gestures wait for UI quiescence, so the debug host + // schedules the reversing gesture through the same coordinator path. claudeTile.pinch(withScale: 1.4, velocity: 2) - overlay.pinch(withScale: 0.5, velocity: -2) XCTAssertTrue( overlay.waitForExistence(timeout: 2), From 24985d811bf1ce48e10677803d05b052efb42ba2 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 14:19:16 -0700 Subject: [PATCH 33/78] Polish native iOS pane zoom transitions --- .../Debug/PanesTabsPreviewHost.swift | 103 +++- .../PaneMapCollectionView.swift | 534 +----------------- .../CmuxMobileShellUI/PaneMapOverlay.swift | 26 +- .../CmuxMobileShellUI/PaneMapTileView.swift | 5 + .../PaneZoomPresentationState.swift | 31 + .../WorkspaceDetailView.swift | 136 +++-- .../PaneMapCollectionLayoutEngineTests.swift | 188 +----- ios/cmuxUITests/cmuxUITests.swift | 98 +--- 8 files changed, 289 insertions(+), 832 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index e22484eb5360..4ece914dd082 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -13,7 +13,8 @@ struct PanesTabsPreviewHost: View { private static let gitSurfaceID = "preview-git" @State private var selectedSurfaceID = Self.claudeSurfaceID - @State private var isPaneMapPresented = false + @Namespace private var paneZoomNamespace + @State private var paneZoomPresentation = PaneZoomPresentationState() private let terminalTheme = TerminalTheme.monokai private let workspace = MobileWorkspacePreview( @@ -137,40 +138,62 @@ struct PanesTabsPreviewHost: View { ] var body: some View { + if let layout = workspace.layout { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + layout: layout, + phoneSelectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID + ), + terminalTheme: terminalTheme, + zoomNamespace: paneZoomNamespace, + isVisible: !paneZoomPresentation.isTerminalPresented, + fetchPreviews: Self.fetchFixturePreviews, + selectTerminal: presentTerminalFromPaneMap, + dismiss: returnToTerminalFromPaneMap + ) + .accessibilityHidden(paneZoomPresentation.isTerminalPresented) + .fullScreenCover( + isPresented: terminalPresentationBinding, + onDismiss: reconcilePaneMapAfterInteractiveDismissal + ) { + NavigationStack { + terminalPreviewEndpoint + } + .navigationTransition( + .zoom( + sourceID: paneZoomSourceSurfaceID, + in: paneZoomNamespace + ) + ) + } + } else { + terminalPreviewEndpoint + } + } + + private var terminalPreviewEndpoint: some View { ZStack(alignment: .topTrailing) { terminalTheme.terminalBackgroundColor .frame(maxWidth: .infinity, maxHeight: .infinity) - - WorkspaceUtilitiesMenu( - showsViewAsText: false, - showsPaneMap: true, - terminalTheme: terminalTheme, - presentPaneMap: presentPaneMap, - openTextSheet: {}, - copyDebugLogs: {}, - sendFeedback: {} - ) - .frame(width: 44, height: 44) - .padding() } .safeAreaInset(edge: .bottom, spacing: 0) { SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) .equatable() } .ignoresSafeArea(.keyboard, edges: .bottom) - .fullScreenCover(isPresented: $isPaneMapPresented) { - if let layout = workspace.layout { - PaneMapOverlay( - value: PaneMapValue( - workspaceName: workspace.name, - layout: layout, - phoneSelectedSurfaceID: selectedSurfaceID, - agentStateKindsBySurfaceID: agentStateKindsBySurfaceID - ), + .navigationTitle(workspace.name) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + WorkspaceUtilitiesMenu( + showsViewAsText: false, + showsPaneMap: true, terminalTheme: terminalTheme, - fetchPreviews: Self.fetchFixturePreviews, - selectTerminal: { selectedSurfaceID = $0.rawValue }, - dismiss: { isPaneMapPresented = false } + presentPaneMap: presentPaneMap, + openTextSheet: {}, + copyDebugLogs: {}, + sendFeedback: {} ) } } @@ -198,7 +221,35 @@ struct PanesTabsPreviewHost: View { } private func presentPaneMap() { - isPaneMapPresented = true + 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 var terminalPresentationBinding: Binding { + Binding( + get: { paneZoomPresentation.isTerminalPresented }, + set: { isPresented in + paneZoomPresentation.presentationDidChange( + isTerminalPresented: isPresented + ) + } + ) + } + + private func reconcilePaneMapAfterInteractiveDismissal() { + paneZoomPresentation.presentationDidChange(isTerminalPresented: false) + } + + private var paneZoomSourceSurfaceID: String { + paneZoomPresentation.sourceSurfaceID ?? selectedSurfaceID } private static func fetchFixturePreviews( diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index c5d8ad3ca18e..f82b754a6ea6 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -1,6 +1,5 @@ import CMUXMobileCore import CmuxMobileShellModel -import Foundation import SwiftUI import UIKit @@ -30,145 +29,12 @@ struct PaneMapOverflowLabels { let bottom: String } -struct PaneMapInteractiveZoomGeometry { - private static let fullTransitionScale: CGFloat = 2.15 - private static let fullSettlementDuration: TimeInterval = 0.34 - - static func progress(forPinchScale scale: CGFloat) -> CGFloat { - min(1, max(0, (scale - 1) / 1.15)) - } - - static func progress( - startingAt initialProgress: CGFloat, - forPinchScale scale: CGFloat - ) -> CGFloat { - guard scale > 0 else { return clamped(initialProgress) } - let scaleProgress = log(Double(scale)) / log(Double(fullTransitionScale)) - return clamped(initialProgress + CGFloat(scaleProgress)) - } - - static func settlementDuration( - from initialProgress: CGFloat, - to targetProgress: CGFloat - ) -> TimeInterval { - let distance = abs(clamped(targetProgress) - clamped(initialProgress)) - return max(0.08, fullSettlementDuration * TimeInterval(distance)) - } - - static func progress( - forRenderedFrame frame: CGRect, - from initialFrame: CGRect, - to targetFrame: CGRect - ) -> CGFloat { - let widthDistance = targetFrame.width - initialFrame.width - let heightDistance = targetFrame.height - initialFrame.height - if abs(widthDistance) >= abs(heightDistance), abs(widthDistance) > 0.001 { - return clamped((frame.width - initialFrame.width) / widthDistance) - } - guard abs(heightDistance) > 0.001 else { return 0 } - return clamped((frame.height - initialFrame.height) / heightDistance) - } - - static func frame( - initialFrame: CGRect, - targetFrame: CGRect, - normalizedAnchor: CGPoint, - gestureLocation: CGPoint, - progress: CGFloat - ) -> CGRect { - let progress = min(1, max(0, progress)) - let size = CGSize( - width: interpolate(initialFrame.width, targetFrame.width, progress: progress), - height: interpolate(initialFrame.height, targetFrame.height, progress: progress) - ) - return CGRect( - x: gestureLocation.x - normalizedAnchor.x * size.width, - y: gestureLocation.y - normalizedAnchor.y * size.height, - width: size.width, - height: size.height - ) - } - - static func settledFrame( - from initialFrame: CGRect, - to targetFrame: CGRect, - progress: CGFloat - ) -> CGRect { - let progress = min(1, max(0, progress)) - return CGRect( - x: interpolate(initialFrame.minX, targetFrame.minX, progress: progress), - y: interpolate(initialFrame.minY, targetFrame.minY, progress: progress), - width: interpolate(initialFrame.width, targetFrame.width, progress: progress), - height: interpolate(initialFrame.height, targetFrame.height, progress: progress) - ) - } - - private static func interpolate(_ start: CGFloat, _ end: CGFloat, progress: CGFloat) -> CGFloat { - start + (end - start) * progress - } - - private static func clamped(_ progress: CGFloat) -> CGFloat { - min(1, max(0, progress)) - } -} - -struct PaneMapZoomTransitionState { - enum Destination: Equatable { - case map - case terminal - } - - private(set) var progress: CGFloat - private(set) var generation: UInt64 = 0 - private(set) var settlingDestination: Destination? - private var gestureStartProgress: CGFloat - - init(progress: CGFloat) { - let progress = min(1, max(0, progress)) - self.progress = progress - self.gestureStartProgress = progress - } - - mutating func beginGesture(at renderedProgress: CGFloat) { - generation &+= 1 - progress = min(1, max(0, renderedProgress)) - gestureStartProgress = progress - settlingDestination = nil - } - - mutating func interruptSettlement(at renderedProgress: CGFloat) { - beginGesture(at: renderedProgress) - } - - mutating func updateGesture(pinchScale: CGFloat) { - progress = PaneMapInteractiveZoomGeometry.progress( - startingAt: gestureStartProgress, - forPinchScale: pinchScale - ) - } - - mutating func beginSettlement(toward destination: Destination) -> UInt64 { - generation &+= 1 - settlingDestination = destination - return generation - } - - mutating func completeSettlement(generation: UInt64) -> Destination? { - guard generation == self.generation, let destination = settlingDestination else { - return nil - } - progress = destination == .terminal ? 1 : 0 - gestureStartProgress = progress - settlingDestination = nil - return destination - } -} - -/// UIKit collection surface for native interactive movement and continuous zoom. +/// 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 selectPreviewSurface: (_ paneID: String, _ surfaceID: String) -> Void let jumpToTerminal: (_ surfaceID: String) -> Void @@ -225,8 +91,7 @@ struct PaneMapCollectionView: UIViewRepresentable { UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDragDelegate, - UICollectionViewDropDelegate, - UIGestureRecognizerDelegate + UICollectionViewDropDelegate { static let cellReuseIdentifier = "PaneMapCollectionCell" @@ -236,9 +101,6 @@ struct PaneMapCollectionView: UIViewRepresentable { private weak var container: PaneMapCollectionContainerView? private var isMovingItem = false private var pendingItems: [PaneMapCollectionItem]? - private var zoomSession: ZoomSession? - private var zoomAnimator: UIViewPropertyAnimator? - private var activeZoomGestureGeneration: UInt64? init(parent: PaneMapCollectionView) { self.parent = parent @@ -254,14 +116,10 @@ struct PaneMapCollectionView: UIViewRepresentable { collectionView.reorderingCadence = .immediate collectionView.dragDelegate = self collectionView.dropDelegate = self - - let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:))) - pinch.delegate = self - collectionView.addGestureRecognizer(pinch) } func reconcile(items: [PaneMapCollectionItem]) { - guard !isMovingItem, zoomSession == nil else { + guard !isMovingItem else { pendingItems = items return } @@ -301,11 +159,12 @@ struct PaneMapCollectionView: UIViewRepresentable { PaneMapTileView( item: item, terminalTheme: parent.terminalTheme, + zoomNamespace: parent.zoomNamespace, selectPreviewSurface: { [weak self] surfaceID in self?.parent.selectPreviewSurface(item.pane.id, surfaceID) }, jumpToTerminal: { [weak self] surfaceID in - self?.zoomToTerminal(paneID: item.pane.id, surfaceID: surfaceID) + self?.parent.jumpToTerminal(surfaceID) } ) } @@ -319,8 +178,7 @@ struct PaneMapCollectionView: UIViewRepresentable { itemsForBeginning session: UIDragSession, at indexPath: IndexPath ) -> [UIDragItem] { - guard zoomSession == nil, - orderedItems.indices.contains(indexPath.item), + guard orderedItems.indices.contains(indexPath.item), orderedItems.count > 1 else { return [] } isMovingItem = true let itemID = orderedItems[indexPath.item].id @@ -378,75 +236,6 @@ struct PaneMapCollectionView: UIViewRepresentable { container?.updateOverflowIndicators() } - func gestureRecognizer( - _ gestureRecognizer: UIGestureRecognizer, - shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer - ) -> Bool { - gestureRecognizer is UIPinchGestureRecognizer - || otherGestureRecognizer is UIPinchGestureRecognizer - } - - @objc private func handlePinch(_ gesture: UIPinchGestureRecognizer) { - guard let collectionView else { return } - switch gesture.state { - case .began: - let location = gesture.location(in: collectionView) - if zoomSession != nil { - guard let window = zoomSession?.wrapper.superview, - interruptZoomSettlement( - gestureLocation: gesture.location(in: window) - ) else { - return - } - } else { - guard let indexPath = collectionView.indexPathForItem(at: location), - startZoom( - at: indexPath, - gestureLocationInCollectionView: location - ), - beginZoomGesture() else { - return - } - } - collectionView.isScrollEnabled = false - case .changed: - guard var session = zoomSession, - activeZoomGestureGeneration == session.transition.generation else { - return - } - guard session.wrapper.window?.bounds == session.targetFrame else { - finishZoom() - return - } - session.transition.updateGesture(pinchScale: gesture.scale) - let progress = session.transition.progress - zoomSession = session - let gestureLocation = gesture.location(in: session.wrapper.superview) - updateInteractiveZoom(progress: progress, gestureLocation: gestureLocation) - case .ended: - guard let session = zoomSession, - activeZoomGestureGeneration == session.transition.generation else { - return - } - activeZoomGestureGeneration = nil - let normalizedVelocity = gesture.velocity - / max(gesture.scale, 0.001) - / CGFloat(log(2.15)) - let projectedProgress = session.transition.progress - + normalizedVelocity * 0.12 - settleZoom( - toward: projectedProgress >= 0.5 ? .terminal : .map - ) - default: - guard let session = zoomSession, - activeZoomGestureGeneration == session.transition.generation else { - return - } - activeZoomGestureGeneration = nil - settleZoom(toward: .map) - } - } - private func finishInteractiveMovement() { isMovingItem = false collectionView?.collectionViewLayout.invalidateLayout() @@ -456,303 +245,6 @@ struct PaneMapCollectionView: UIViewRepresentable { } } - private func zoomToTerminal(paneID: String, surfaceID: String) { - guard zoomSession == nil, - let itemIndex = orderedItems.firstIndex(where: { $0.id == paneID }), - orderedItems[itemIndex].selectedSurface?.id == surfaceID, - startZoom(at: IndexPath(item: itemIndex, section: 0)) else { - return - } - settleZoom(toward: .terminal) - } - - private func startZoom( - at indexPath: IndexPath, - gestureLocationInCollectionView: CGPoint? = nil - ) -> Bool { - guard zoomSession == nil, - !isMovingItem, - orderedItems.indices.contains(indexPath.item), - let surface = orderedItems[indexPath.item].selectedSurface, - surface.type.isTerminal, - let collectionView, - let cell = collectionView.cellForItem(at: indexPath), - let window = cell.window else { - return false - } - - let previewBounds = CGRect( - x: 0, - y: 0, - width: cell.bounds.width, - height: max(0, cell.bounds.height - PaneMapTileMetrics.captionHeight) - ) - if let gestureLocationInCollectionView { - let locationInCell = collectionView.convert(gestureLocationInCollectionView, to: cell) - guard previewBounds.contains(locationInCell) else { return false } - } - guard let snapshot = cell.resizableSnapshotView( - from: previewBounds, - afterScreenUpdates: true, - withCapInsets: .zero - ) else { - return false - } - let initialFrame = cell.convert(previewBounds, to: window) - let gestureLocation = gestureLocationInCollectionView.map { - collectionView.convert($0, to: window) - } ?? CGPoint(x: initialFrame.midX, y: initialFrame.midY) - let normalizedAnchor = CGPoint( - x: initialFrame.width > 0 - ? (gestureLocation.x - initialFrame.minX) / initialFrame.width - : 0.5, - y: initialFrame.height > 0 - ? (gestureLocation.y - initialFrame.minY) / initialFrame.height - : 0.5 - ) - let previewTheme = orderedItems[indexPath.item].preview? - .resolvedTerminalTheme(fallback: parent.terminalTheme) - ?? parent.terminalTheme - let backdrop = UIView(frame: window.bounds) - backdrop.backgroundColor = UIColor(terminalHex: previewTheme.background) - backdrop.alpha = 0 - backdrop.isUserInteractionEnabled = false - - let wrapper = UIView(frame: initialFrame) - wrapper.backgroundColor = UIColor(terminalHex: previewTheme.background) - wrapper.clipsToBounds = true - wrapper.layer.cornerCurve = .continuous - wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius - wrapper.isUserInteractionEnabled = false - snapshot.frame = CGRect(origin: .zero, size: previewBounds.size) - wrapper.addSubview(snapshot) - - window.addSubview(backdrop) - window.addSubview(wrapper) - cell.alpha = 0 - zoomSession = ZoomSession( - surfaceID: surface.id, - cell: cell, - snapshot: snapshot, - wrapper: wrapper, - backdrop: backdrop, - initialFrame: initialFrame, - targetFrame: window.bounds, - normalizedAnchor: normalizedAnchor, - transition: PaneMapZoomTransitionState(progress: 0) - ) - return true - } - - private func beginZoomGesture() -> Bool { - guard var session = zoomSession else { return false } - session.transition.beginGesture(at: session.transition.progress) - activeZoomGestureGeneration = session.transition.generation - zoomSession = session - return true - } - - private func interruptZoomSettlement(gestureLocation: CGPoint) -> Bool { - guard var session = zoomSession, let animator = zoomAnimator else { - return false - } - - let presentationFrame = session.wrapper.layer.presentation()?.frame - ?? session.wrapper.frame - let presentationCornerRadius = session.wrapper.layer.presentation()?.cornerRadius - ?? session.wrapper.layer.cornerRadius - let presentationBackdropAlpha = session.backdrop.layer.presentation()?.opacity - ?? Float(session.backdrop.alpha) - let renderedProgress = PaneMapInteractiveZoomGeometry.progress( - forRenderedFrame: presentationFrame, - from: session.initialFrame, - to: session.targetFrame - ) - - zoomAnimator = nil - animator.stopAnimation(true) - session.wrapper.layer.removeAllAnimations() - session.snapshot.layer.removeAllAnimations() - session.backdrop.layer.removeAllAnimations() - session.wrapper.frame = presentationFrame - session.snapshot.frame = session.wrapper.bounds - session.wrapper.layer.cornerRadius = presentationCornerRadius - session.backdrop.alpha = CGFloat(presentationBackdropAlpha) - - session.normalizedAnchor = CGPoint( - x: session.wrapper.bounds.width > 0 - ? (gestureLocation.x - presentationFrame.minX) / presentationFrame.width - : 0.5, - y: session.wrapper.bounds.height > 0 - ? (gestureLocation.y - presentationFrame.minY) / presentationFrame.height - : 0.5 - ) - session.normalizedAnchor.x = min(1, max(0, session.normalizedAnchor.x)) - session.normalizedAnchor.y = min(1, max(0, session.normalizedAnchor.y)) - session.transition.interruptSettlement(at: renderedProgress) - activeZoomGestureGeneration = session.transition.generation - zoomSession = session - return true - } - - private func updateInteractiveZoom(progress: CGFloat, gestureLocation: CGPoint) { - guard let session = zoomSession else { return } - session.wrapper.frame = PaneMapInteractiveZoomGeometry.frame( - initialFrame: session.initialFrame, - targetFrame: session.targetFrame, - normalizedAnchor: session.normalizedAnchor, - gestureLocation: gestureLocation, - progress: progress - ) - session.snapshot.frame = session.wrapper.bounds - session.wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius * (1 - progress) - session.backdrop.alpha = progress - } - - private func renderSettledZoom(progress: CGFloat) { - guard let session = zoomSession else { return } - session.wrapper.frame = PaneMapInteractiveZoomGeometry.settledFrame( - from: session.initialFrame, - to: session.targetFrame, - progress: progress - ) - session.snapshot.frame = session.wrapper.bounds - session.wrapper.layer.cornerRadius = PaneMapTileMetrics.cornerRadius * (1 - progress) - session.backdrop.alpha = progress - } - - private func settleZoom(toward destination: PaneMapZoomTransitionState.Destination) { - guard var session = zoomSession else { return } - let targetProgress: CGFloat = destination == .terminal ? 1 : 0 - let initialProgress = session.transition.progress - let generation = session.transition.beginSettlement(toward: destination) - zoomSession = session - - let defaultDuration = PaneMapInteractiveZoomGeometry.settlementDuration( - from: initialProgress, - to: targetProgress - ) - let duration = zoomSettlementDurationOverride ?? defaultDuration - let timing = UISpringTimingParameters(dampingRatio: 0.92) - let animator = UIViewPropertyAnimator( - duration: duration, - timingParameters: timing - ) - zoomAnimator = animator - animator.addAnimations { [weak self] in - self?.renderSettledZoom(progress: targetProgress) - } - animator.addCompletion { [weak self, weak animator] position in - guard let self, let animator, self.zoomAnimator === animator else { - return - } - self.completeZoomSettlement( - generation: generation, - position: position - ) - } - animator.startAnimation() -#if DEBUG - scheduleUITestZoomInterruptionIfNeeded(for: destination) -#endif - } - -#if DEBUG - private func scheduleUITestZoomInterruptionIfNeeded( - for destination: PaneMapZoomTransitionState.Destination - ) { - guard destination == .terminal, - let rawValue = ProcessInfo.processInfo.environment[ - "CMUX_UITEST_PANE_ZOOM_INTERRUPT_DELAY" - ], - let delay = TimeInterval(rawValue), - delay >= 0 else { - return - } - DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in - guard let self, let session = self.zoomSession, - self.zoomAnimator != nil else { - return - } - let gestureLocation = CGPoint( - x: session.wrapper.frame.midX, - y: session.wrapper.frame.midY - ) - guard self.interruptZoomSettlement(gestureLocation: gestureLocation), - var interruptedSession = self.zoomSession, - self.activeZoomGestureGeneration - == interruptedSession.transition.generation else { - return - } - interruptedSession.transition.updateGesture(pinchScale: 0.5) - let progress = interruptedSession.transition.progress - self.zoomSession = interruptedSession - self.updateInteractiveZoom( - progress: progress, - gestureLocation: gestureLocation - ) - self.activeZoomGestureGeneration = nil - self.settleZoom(toward: .map) - } - } -#endif - - private func completeZoomSettlement( - generation: UInt64, - position: UIViewAnimatingPosition - ) { - zoomAnimator = nil - guard position == .end, var session = zoomSession else { return } - guard let destination = session.transition.completeSettlement( - generation: generation - ) else { - return - } - zoomSession = session - switch destination { - case .map: - finishZoom() - case .terminal: - parent.jumpToTerminal(session.surfaceID) - Task { @MainActor [weak self] in - await Task.yield() - self?.finishZoom() - } - } - } - - private var zoomSettlementDurationOverride: TimeInterval? { -#if DEBUG - guard let rawValue = ProcessInfo.processInfo.environment[ - "CMUX_UITEST_PANE_ZOOM_SETTLE_DURATION" - ], - let duration = TimeInterval(rawValue), - duration > 0 else { - return nil - } - return duration -#else - nil -#endif - } - - private func finishZoom() { - guard let session = zoomSession else { return } - let animator = zoomAnimator - zoomAnimator = nil - animator?.stopAnimation(true) - activeZoomGestureGeneration = nil - session.cell.alpha = 1 - session.wrapper.removeFromSuperview() - session.backdrop.removeFromSuperview() - collectionView?.isScrollEnabled = true - zoomSession = nil - if let pendingItems { - self.pendingItems = nil - reconcile(items: pendingItems) - } - } - func scrollOneViewport(_ direction: PaneMapOverflowDirection) { guard let collectionView else { return } let horizontalStep = max(80, collectionView.bounds.width * 0.72) @@ -776,18 +268,6 @@ struct PaneMapCollectionView: UIViewRepresentable { offset.y = min(maximumOffset.y, max(0, offset.y)) collectionView.setContentOffset(offset, animated: true) } - - private struct ZoomSession { - let surfaceID: String - let cell: UICollectionViewCell - let snapshot: UIView - let wrapper: UIView - let backdrop: UIView - let initialFrame: CGRect - let targetFrame: CGRect - var normalizedAnchor: CGPoint - var transition: PaneMapZoomTransitionState - } } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index 9433d6033384..bbb883324b20 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -7,6 +7,8 @@ import SwiftUI struct PaneMapOverlay: View { let value: PaneMapValue let terminalTheme: TerminalTheme + let zoomNamespace: Namespace.ID + let isVisible: Bool let fetchPreviews: ([String], [String]) async -> [String: MobileTerminalRenderGridFrame] let selectTerminal: (MobileTerminalPreview.ID) -> Void let dismiss: () -> Void @@ -20,12 +22,16 @@ struct PaneMapOverlay: View { init( value: PaneMapValue, terminalTheme: TerminalTheme, + zoomNamespace: Namespace.ID, + isVisible: Bool, fetchPreviews: @escaping ([String], [String]) async -> [String: MobileTerminalRenderGridFrame], selectTerminal: @escaping (MobileTerminalPreview.ID) -> Void, dismiss: @escaping () -> Void ) { self.value = value self.terminalTheme = terminalTheme + self.zoomNamespace = zoomNamespace + self.isVisible = isVisible self.fetchPreviews = fetchPreviews self.selectTerminal = selectTerminal self.dismiss = dismiss @@ -46,6 +52,7 @@ struct PaneMapOverlay: View { items: collectionItems, layout: value.layout, terminalTheme: terminalTheme, + zoomNamespace: zoomNamespace, overflowLabels: overflowLabels, selectPreviewSurface: selectPreviewSurface, jumpToTerminal: jumpToTerminal @@ -59,11 +66,20 @@ struct PaneMapOverlay: View { .accessibilityIdentifier("MobilePaneMapOverlay") } .onAppear { - startPreviewRefresh() + if isVisible { + startPreviewRefresh() + } } .onDisappear { cancelPreviewRefresh() } + .onChange(of: isVisible) { _, isVisible in + if isVisible { + startPreviewRefresh() + } else { + cancelPreviewRefresh() + } + } .onChange(of: value.layout) { _, _ in selectedSurfaceIDsByPaneID = value.reconciledSurfaceIDs( current: selectedSurfaceIDsByPaneID @@ -153,16 +169,10 @@ struct PaneMapOverlay: View { } private func jumpToTerminal(_ surfaceID: String) { - var transaction = Transaction(animation: nil) - transaction.disablesAnimations = true - withTransaction(transaction) { - selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) - dismissPaneMap() - } + selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) } private func dismissPaneMap() { - cancelPreviewRefresh() dismiss() } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index b44eba84996f..6b63f70bf624 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -91,6 +91,7 @@ enum PaneMapTabStripMetrics { struct PaneMapTileView: View { let item: PaneMapCollectionItem let terminalTheme: TerminalTheme + let zoomNamespace: Namespace.ID let selectPreviewSurface: (String) -> Void let jumpToTerminal: (String) -> Void @@ -102,6 +103,10 @@ struct PaneMapTileView: View { selectPreviewSurface: selectPreviewSurface, jumpToTerminal: jumpToTerminal ) + .matchedTransitionSource( + id: item.selectedSurface?.id ?? item.id, + in: zoomNamespace + ) PaneMapTileCaption(item: item, terminalTheme: terminalTheme) .frame(height: PaneMapTileMetrics.captionHeight) } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift new file mode 100644 index 000000000000..5d477aaaaadf --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -0,0 +1,31 @@ +/// Stable routing state for the native pane-map zoom presentation. +struct PaneZoomPresentationState: Equatable { + enum Endpoint: Equatable { + case paneMap + case terminal + } + + private(set) var endpoint: Endpoint = .terminal + private(set) var sourceSurfaceID: String? + + var isTerminalPresented: Bool { + endpoint == .terminal + } + + mutating func presentPaneMap(from surfaceID: String?) { + if let surfaceID, !surfaceID.isEmpty { + sourceSurfaceID = surfaceID + } + endpoint = .paneMap + } + + mutating func presentTerminal(surfaceID: String) { + guard !surfaceID.isEmpty else { return } + sourceSurfaceID = surfaceID + endpoint = .terminal + } + + mutating func presentationDidChange(isTerminalPresented: Bool) { + endpoint = isTerminalPresented ? .terminal : .paneMap + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index a3571798ed83..1cd0cf5ad5a6 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -53,7 +53,8 @@ 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 private var isPaneMapPresented = false + @Namespace private var paneZoomNamespace + @State private var paneZoomPresentation = PaneZoomPresentationState() /// 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 @@ -98,10 +99,43 @@ struct WorkspaceDetailView: View { } #endif var body: some View { - let content = Group { detailSurfaceContent } - #if os(iOS) + if let layout = workspace.layout { + paneMapRoot(layout: layout) + .accessibilityHidden(paneZoomPresentation.isTerminalPresented) + .fullScreenCover( + isPresented: terminalZoomPresentationBinding, + onDismiss: reconcilePaneMapAfterInteractiveDismissal + ) { + NavigationStack { + terminalWorkspaceEndpoint + } + .navigationTransition( + .zoom( + sourceID: paneZoomSourceSurfaceID, + in: paneZoomNamespace + ) + ) + } + .toolbar(.hidden, for: .navigationBar) + .navigationBarBackButtonHidden(true) + } else { + terminalWorkspaceEndpoint + } + #else + Group { detailSurfaceContent } + .closeWorkspaceConfirmation( + isPresented: $isConfirmingClose, + confirm: confirmCloseWorkspaceFromMenu + ) + .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) + #endif + } + + #if os(iOS) + private var terminalWorkspaceEndpoint: some View { let deckValue = surfaceDeckValue + let content = Group { detailSurfaceContent } // Deck visibility must not change the content subtree's structural // identity: branching around `content` would remount the terminal // surface (and the chat/browser ZStack) every time the deck toggles. @@ -125,7 +159,7 @@ struct WorkspaceDetailView: View { // normal avoidance. .ignoresSafeArea(showDeck ? .keyboard : [], edges: .bottom) - contentWithSurfaceDeck + return contentWithSurfaceDeck .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(systemNavigationTitle) .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) @@ -144,7 +178,7 @@ struct WorkspaceDetailView: View { } .onChange(of: workspace.layout == nil) { _, layoutIsMissing in if layoutIsMissing { - isPaneMapPresented = false + paneZoomPresentation.presentationDidChange(isTerminalPresented: true) } } .closeWorkspaceConfirmation( @@ -157,45 +191,61 @@ struct WorkspaceDetailView: View { .sheet(isPresented: $isTextSheetPresented) { TerminalTextSheetView(surfaceID: textSheetSurfaceID) } - .fullScreenCover(isPresented: $isPaneMapPresented) { - if let layout = workspace.layout { - PaneMapOverlay( - value: PaneMapValue( - workspaceName: workspace.name, - layout: layout, - phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, - agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds - ), - terminalTheme: store.activeTerminalTheme, - fetchPreviews: { selectedSurfaceIDs, remainingSurfaceIDs in - await store.fetchPaneMapPreviewGrids( - remoteWorkspaceID: workspace.rpcWorkspaceID.rawValue, - selectedSurfaceIDs: selectedSurfaceIDs, - remainingSurfaceIDs: remainingSurfaceIDs - ) - }, - selectTerminal: selectTerminalFromDeck, - dismiss: { isPaneMapPresented = false } - ) - } - } .workspaceRenameDialog( isPresented: $isRenamePresented, text: $renameText, onSave: commitRenameFromDialog ) .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) - #else - content - .closeWorkspaceConfirmation( - isPresented: $isConfirmingClose, - confirm: confirmCloseWorkspaceFromMenu - ) - .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) - #endif } - #if os(iOS) + private func paneMapRoot(layout: MobilePaneLayout) -> some View { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + layout: layout, + phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, + agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds + ), + terminalTheme: store.activeTerminalTheme, + zoomNamespace: paneZoomNamespace, + isVisible: !paneZoomPresentation.isTerminalPresented, + fetchPreviews: { selectedSurfaceIDs, remainingSurfaceIDs in + await store.fetchPaneMapPreviewGrids( + remoteWorkspaceID: workspace.rpcWorkspaceID.rawValue, + selectedSurfaceIDs: selectedSurfaceIDs, + remainingSurfaceIDs: remainingSurfaceIDs + ) + }, + selectTerminal: presentTerminalFromPaneMap, + dismiss: returnToTerminalFromPaneMap + ) + } + + private var terminalZoomPresentationBinding: Binding { + Binding( + get: { paneZoomPresentation.isTerminalPresented }, + set: { isPresented in + paneZoomPresentation.presentationDidChange( + isTerminalPresented: isPresented + ) + } + ) + } + + private func reconcilePaneMapAfterInteractiveDismissal() { + paneZoomPresentation.presentationDidChange(isTerminalPresented: false) + } + + private var paneZoomSourceSurfaceID: String { + paneZoomPresentation.sourceSurfaceID + ?? selectedTerminal?.id.rawValue + ?? workspace.layout?.orderedPanes + .compactMap(\.selectedSurfaceID) + .first + ?? "" + } + @ToolbarContentBuilder private var workspaceDetailToolbar: some ToolbarContent { if backButtonConfiguration != nil { @@ -556,7 +606,19 @@ struct WorkspaceDetailView: View { private func presentPaneMap() { guard workspace.layout != nil else { return } - isPaneMapPresented = true + 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) } #if canImport(UIKit) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 015f9ff74162..461af4e0c446 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -145,178 +145,40 @@ import Testing } } -@Suite struct PaneMapInteractiveZoomGeometryTests { - private let initialFrame = CGRect(x: 100, y: 200, width: 120, height: 240) - private let targetFrame = CGRect(x: 0, y: 0, width: 390, height: 844) - private let anchor = CGPoint(x: 0.25, y: 0.75) +@Suite struct PaneZoomPresentationStateTests { + @Test func bothDirectionsKeepTheSameStableZoomSource() { + var state = PaneZoomPresentationState() - @Test func zeroProgressPreservesTheSourceFrame() { - let sourceAnchor = CGPoint( - x: initialFrame.minX + initialFrame.width * anchor.x, - y: initialFrame.minY + initialFrame.height * anchor.y - ) - - let frame = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: sourceAnchor, - progress: 0 - ) - - #expect(frame == initialFrame) - } - - @Test func intermediateProgressTracksTheGestureCenter() { - let progress: CGFloat = 0.4 - let gestureLocation = CGPoint(x: 250, y: 500) - - let frame = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: gestureLocation, - progress: progress - ) - - let renderedAnchor = CGPoint( - x: frame.minX + frame.width * anchor.x, - y: frame.minY + frame.height * anchor.y - ) + state.presentPaneMap(from: "terminal-a") + #expect(state.endpoint == .paneMap) + #expect(state.sourceSurfaceID == "terminal-a") - #expect(abs(frame.width - 228) < 0.001) - #expect(abs(frame.height - 481.6) < 0.001) - #expect(abs(renderedAnchor.x - gestureLocation.x) < 0.001) - #expect(abs(renderedAnchor.y - gestureLocation.y) < 0.001) - } - - @Test func movingTheGestureCenterMovesTheFrameOneForOne() { - let first = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: CGPoint(x: 200, y: 400), - progress: 0.5 - ) - let second = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: CGPoint(x: 237, y: 381), - progress: 0.5 - ) - - #expect(abs(second.minX - first.minX - 37) < 0.001) - #expect(abs(second.minY - first.minY + 19) < 0.001) - #expect(second.size == first.size) - } + state.presentTerminal(surfaceID: "terminal-b") + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-b") - @Test func settlementUsesExactSourceAndTargetFrames() { - let source = PaneMapInteractiveZoomGeometry.settledFrame( - from: initialFrame, - to: targetFrame, - progress: 0 - ) - let target = PaneMapInteractiveZoomGeometry.settledFrame( - from: initialFrame, - to: targetFrame, - progress: 1 - ) - - #expect(source == initialFrame) - #expect(target == targetFrame) + state.presentationDidChange(isTerminalPresented: false) + #expect(state.endpoint == .paneMap) + #expect(state.sourceSurfaceID == "terminal-b") } - @Test func pinchScaleProgressIsAbsoluteAndClamped() { - #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 0.5) == 0) - #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 1) == 0) - #expect(abs( - PaneMapInteractiveZoomGeometry.progress(forPinchScale: 1.575) - 0.5 - ) < 0.001) - #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 2.15) == 1) - #expect(PaneMapInteractiveZoomGeometry.progress(forPinchScale: 4) == 1) - } - - @Test func reciprocalPinchesProduceComplementaryProgress() { - let scale: CGFloat = 1.6 - let zoomedIn = PaneMapInteractiveZoomGeometry.progress( - startingAt: 0, - forPinchScale: scale - ) - let zoomedOut = PaneMapInteractiveZoomGeometry.progress( - startingAt: 1, - forPinchScale: 1 / scale - ) - - #expect(abs(zoomedIn + zoomedOut - 1) < 0.001) - } - - @Test func equalDistanceSettlesUseIdenticalTimingInBothDirections() { - let zoomInDuration = PaneMapInteractiveZoomGeometry.settlementDuration( - from: 0.25, - to: 1 - ) - let zoomOutDuration = PaneMapInteractiveZoomGeometry.settlementDuration( - from: 0.75, - to: 0 - ) - - #expect(zoomInDuration == zoomOutDuration) - } - - @Test func reversingScaleDoesNotAccumulateGeometry() { - let sourceAnchor = CGPoint( - x: initialFrame.minX + initialFrame.width * anchor.x, - y: initialFrame.minY + initialFrame.height * anchor.y - ) - let expanded = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: sourceAnchor, - progress: 0.7 - ) - let reversed = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: sourceAnchor, - progress: 0.25 - ) - let returned = PaneMapInteractiveZoomGeometry.frame( - initialFrame: initialFrame, - targetFrame: targetFrame, - normalizedAnchor: anchor, - gestureLocation: sourceAnchor, - progress: 0 - ) - - #expect(expanded.width > reversed.width) - #expect(returned == initialFrame) - } -} - -@Suite struct PaneMapZoomTransitionStateTests { - @Test func staleCommitCannotWinAfterSettlementIsReversed() { - var state = PaneMapZoomTransitionState(progress: 0) - state.beginGesture(at: 0) - state.updateGesture(pinchScale: 1.7) - let staleCommit = state.beginSettlement(toward: .terminal) + @Test func anInteractiveCancellationDoesNotDiscardTheSource() { + var state = PaneZoomPresentationState() + state.presentTerminal(surfaceID: "terminal-a") - state.interruptSettlement(at: 0.6) - state.updateGesture(pinchScale: 0.5) - let currentReturn = state.beginSettlement(toward: .map) + state.presentationDidChange(isTerminalPresented: false) + state.presentationDidChange(isTerminalPresented: true) - #expect(state.completeSettlement(generation: staleCommit) == nil) - #expect(state.completeSettlement(generation: currentReturn) == .map) + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-a") } - @Test func interruptedSettlementContinuesFromRenderedProgress() { - var state = PaneMapZoomTransitionState(progress: 0) - state.interruptSettlement(at: 0.63) + @Test func anEmptyTerminalIDCannotBreakTheMatchedSource() { + var state = PaneZoomPresentationState() + state.presentTerminal(surfaceID: "terminal-a") + state.presentTerminal(surfaceID: "") - #expect(abs(state.progress - 0.63) < 0.001) - state.updateGesture(pinchScale: 1) - #expect(abs(state.progress - 0.63) < 0.001) + #expect(state.endpoint == .terminal) + #expect(state.sourceSurfaceID == "terminal-a") } } diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 918d069444b1..1876c7d17a0a 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1705,7 +1705,7 @@ final class cmuxUITests: XCTestCase { tapMenuItem(app.buttons["MobilePaneMapMenuItem"], in: app) let overlay = app.otherElements["MobilePaneMapOverlay"] - XCTAssertTrue(overlay.waitForExistence(timeout: 4)) + XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) let leftTopPane = app.descendants(matching: .any)[ "MobilePaneMapPane-preview-pane-left-top" ] @@ -1734,10 +1734,10 @@ final class cmuxUITests: XCTestCase { XCTAssertEqual(leftTopTabStrip.frame.width, 64, accuracy: 2) tap(app.buttons["MobilePaneMapDone"], in: app) - XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) + XCTAssertTrue(waitForPaneMap(overlay, toBeActive: false)) tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) - XCTAssertTrue(overlay.waitForExistence(timeout: 4)) + XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) tap(app.buttons["MobilePaneMapTab-preview-zsh"], in: app) let zshTile = app.buttons["MobilePaneMapTile-preview-zsh"] XCTAssertTrue(zshTile.waitForExistence(timeout: 2)) @@ -1745,12 +1745,12 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(overlay.exists, "Switching tabs must stay inside the pane map") tap(zshTile, in: app) - XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) + XCTAssertTrue(waitForPaneMap(overlay, toBeActive: false)) XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-zsh"].isSelected) } @MainActor - func testPanesPreviewReordersCardsAndPinchZoomsTerminal() throws { + func testPanesPreviewReordersCardsAndZoomsTerminalInBothDirections() throws { let app = launchApp(mockData: false, environment: [ "CMUX_UITEST_PANES_PREVIEW": "1", ]) @@ -1760,7 +1760,7 @@ final class cmuxUITests: XCTestCase { tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) let overlay = app.otherElements["MobilePaneMapOverlay"] - XCTAssertTrue(overlay.waitForExistence(timeout: 4)) + XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) let leftTopPane = app.descendants(matching: .any)[ "MobilePaneMapPane-preview-pane-left-top" ] @@ -1791,78 +1791,22 @@ final class cmuxUITests: XCTestCase { let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) - let originalClaudeFrame = claudeTile.frame - claudeTile.pinch(withScale: 1.3, velocity: 0.35) + tap(claudeTile, in: app) - XCTAssertTrue(overlay.exists, "A reversed pane zoom must stay inside the pane map") - let returnedToSource = XCTNSPredicateExpectation( - predicate: NSPredicate( - block: { _, _ in - abs(claudeTile.frame.midX - originalClaudeFrame.midX) < 2 - && abs(claudeTile.frame.midY - originalClaudeFrame.midY) < 2 - && abs(claudeTile.frame.width - originalClaudeFrame.width) < 2 - && abs(claudeTile.frame.height - originalClaudeFrame.height) < 2 - } - ), - object: claudeTile - ) - XCTAssertEqual( - XCTWaiter.wait(for: [returnedToSource], timeout: 4), - .completed, - "A cancelled pane zoom must return to the exact source card" - ) - - claudeTile.pinch(withScale: 2, velocity: 2) - - XCTAssertTrue(overlay.waitForNonExistence(timeout: 4)) + XCTAssertTrue(waitForPaneMap(overlay, toBeActive: false)) XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-claude"].isSelected) - } - @MainActor - func testPaneZoomSettlementCanBeInterruptedBackToItsSourceCard() throws { - let app = launchApp(mockData: false, environment: [ - "CMUX_UITEST_PANES_PREVIEW": "1", - "CMUX_UITEST_PANE_ZOOM_SETTLE_DURATION": "1.2", - "CMUX_UITEST_PANE_ZOOM_INTERRUPT_DELAY": "0.12", - ]) - defer { app.terminate() } - - XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) - - let overlay = app.otherElements["MobilePaneMapOverlay"] - XCTAssertTrue(overlay.waitForExistence(timeout: 4)) - let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] - XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) - let sourceFrame = claudeTile.frame - - // Public XCUITest gestures wait for UI quiescence, so the debug host - // schedules the reversing gesture through the same coordinator path. - claudeTile.pinch(withScale: 1.4, velocity: 2) - XCTAssertTrue( - overlay.waitForExistence(timeout: 2), - "Reversing an active terminal settlement must keep the pane map presented" - ) - let returnedToSource = XCTNSPredicateExpectation( - predicate: NSPredicate( - block: { _, _ in - abs(claudeTile.frame.midX - sourceFrame.midX) < 2 - && abs(claudeTile.frame.midY - sourceFrame.midY) < 2 - && abs(claudeTile.frame.width - sourceFrame.width) < 2 - && abs(claudeTile.frame.height - sourceFrame.height) < 2 - } - ), - object: claudeTile - ) - XCTAssertEqual( - XCTWaiter.wait(for: [returnedToSource], timeout: 3), - .completed, - "Interrupted zoom must settle to the exact source card" + waitForPaneMap(overlay, toBeActive: true), + "The opened terminal must fluidly return to its pane-map source" ) + XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) + + tap(claudeTile, in: app) XCTAssertTrue( - overlay.exists, - "A stale terminal completion must not dismiss after the reversal" + waitForPaneMap(overlay, toBeActive: false), + "The same source must zoom back into the opened terminal" ) } @@ -4040,6 +3984,18 @@ final class cmuxUITests: XCTestCase { element.identifier.hasPrefix("MobileAddDevice") } + private func waitForPaneMap( + _ overlay: XCUIElement, + toBeActive isActive: Bool, + timeout: TimeInterval = 4 + ) -> Bool { + let expectation = XCTNSPredicateExpectation( + predicate: NSPredicate(format: "isHittable == %@", NSNumber(value: isActive)), + object: overlay + ) + return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed + } + @MainActor private func tap( _ element: XCUIElement, From bb347059b046e0736e60daec2428e34352f49f44 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 15:00:21 -0700 Subject: [PATCH 34/78] test(ios): cover pane reorder reconciliation --- .../PaneMapCollectionLayoutEngineTests.swift | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 461af4e0c446..377878a2099c 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -182,3 +182,63 @@ import Testing #expect(state.sourceSurfaceID == "terminal-a") } } + +@Suite struct PaneMapReorderStateTests { + @Test func failureRollsBackToTheLatestAuthoritativeOrder() throws { + var state = PaneMapReorderState(authoritativePaneIDs: ["left", "middle", "right"]) + + let request = try #require(state.beginMove(from: 0, to: 2)) + #expect(state.visiblePaneIDs == ["middle", "right", "left"]) + + state.reconcile(authoritativePaneIDs: ["left", "right", "middle"]) + #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"]) + + let request = try #require(state.beginMove(from: 2, to: 0)) + #expect(request.orderedPaneIDs == ["three", "one", "two"]) + #expect(state.complete(requestID: request.id, succeeded: true) == .awaitingAuthority) + #expect(state.visiblePaneIDs == ["three", "one", "two"]) + #expect(state.isMutationPending) + + state.reconcile(authoritativePaneIDs: ["one", "two", "three"]) + #expect(state.visiblePaneIDs == ["one", "two", "three"]) + #expect(!state.isMutationPending) + } + + @Test func staleCompletionCannotOverwriteANewerMove() throws { + var state = PaneMapReorderState(authoritativePaneIDs: ["a", "b", "c"]) + + let first = try #require(state.beginMove(from: 0, to: 1)) + #expect(state.complete(requestID: first.id, succeeded: false) == .rolledBack) + + let second = try #require(state.beginMove(from: 2, to: 0)) + #expect(state.complete(requestID: first.id, succeeded: true) == .ignored) + #expect(state.visiblePaneIDs == second.orderedPaneIDs) + #expect(state.isMutationPending) + } + + @Test func scrollAndDragMovementDoNotResolveAsPaneSelection() { + var arbitration = PaneMapSelectionArbitration() + + arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) + arbitration.touchMoved(to: CGPoint(x: 32, y: 10)) + #expect(!arbitration.touchEnded(at: CGPoint(x: 32, y: 10))) + + arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) + arbitration.dragSessionDidBegin() + #expect(!arbitration.touchEnded(at: CGPoint(x: 10, y: 10))) + + arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) + #expect(arbitration.touchEnded(at: CGPoint(x: 11, y: 11))) + } +} From f074baad3674ed9015ee366f75cf24c38ed2edb4 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 16:21:02 -0700 Subject: [PATCH 35/78] feat(ios): synchronize Safari-style pane layout --- .../MobileShellComposite+Capabilities.swift | 4 + .../MobileShellComposite+Helpers.swift | 3 +- ...obileShellComposite+WorkspaceActions.swift | 22 +++ .../MobileShellComposite.swift | 1 + .../MobileShellWorkspaceCapabilityTests.swift | 4 + .../MobileWorkspaceActionCapabilities.swift | 6 +- .../CMUXMobileRootView+DebugPreview.swift | 6 +- .../Debug/PanesTabsPreviewHost.swift | 180 +++++++++++++++--- .../PaneMapCollectionView.swift | 158 +++++++++++++-- .../CmuxMobileShellUI/PaneMapOverlay.swift | 155 +++------------ .../PaneMapReorderState.swift | 83 ++++++++ .../PaneMapSelectionArbitration.swift | 40 ++++ .../CmuxMobileShellUI/PaneMapTileView.swift | 21 +- .../CmuxMobileShellUI/PaneMapValue.swift | 36 ++++ .../WorkspaceDetailView.swift | 131 ++++++++++--- .../PaneMapCollectionLayoutEngineTests.swift | 21 +- .../MobileHostService+Capabilities.swift | 1 + ...obileHostService+TicketAuthorization.swift | 2 +- .../TerminalController+WorkspaceMove.swift | 59 ++++++ Sources/TerminalController.swift | 2 + Sources/Workspace+MobilePaneReorder.swift | 135 +++++++++++++ ...orkspace+WorkspaceSurfaceTreeReading.swift | 3 + Sources/Workspace.swift | 6 + cmux.xcodeproj/project.pbxproj | 4 + .../MobileHostConnectionLifecycleTests.swift | 1 + ...ostWorkspaceTicketAuthorizationTests.swift | 10 + .../MobileWorkspaceListFidelityTests.swift | 96 ++++++++++ ios/cmux/Resources/Localizable.xcstrings | 7 + ios/cmuxUITests/cmuxUITests.swift | 61 +++++- 29 files changed, 1043 insertions(+), 215 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapSelectionArbitration.swift create mode 100644 Sources/Workspace+MobilePaneReorder.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift index 69c817253c31..1c152754bd1c 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Capabilities.swift @@ -12,6 +12,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+Helpers.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift index 2852888d3401..b7a23db8791a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift @@ -33,7 +33,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("workspace.pane_reorder.v1") ) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift index 8f3ec77e8df3..52a2cbe506d9 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift @@ -14,6 +14,28 @@ private let mobileShellLog = Logger( // workspace list after the request returns. That covers success, rejected // actions (e.g. attempting to close the last workspace), and dropped push events. 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] + ) 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 + return await sendWorkspaceMutation( + method: "workspace.pane.reorder", + params: params, + id: id, + actionName: "pane_reorder" + ) + } /// Rename a workspace on the Mac. /// diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 4372cea7ceb2..f0fd492626d8 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -90,6 +90,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 workspaceGroupActionsCapability = "workspace.group_actions.v1" static let workspaceCreateInGroupCapability = "workspace.create_in_group.v1", workspaceGroupCreateCapability = "workspace.group_create.v1" static let taskCreateCapability = "workspace.task_create.v1" diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift index 39224e8acb39..3d26e9eca952 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift @@ -36,6 +36,7 @@ import Testing #expect(oldMac.store.supportsWorkspaceActions) #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) @@ -47,6 +48,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", @@ -54,6 +56,7 @@ import Testing let scoped = try await connectedStore(capabilities: currentCapabilities) #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) @@ -63,6 +66,7 @@ import Testing ticketTerminalID: nil ) #expect(macWide.store.supportsWorkspaceMoveActions && macWide.store.supportsWorkspaceGroupActions) + #expect(macWide.store.supportsWorkspacePaneReorder) #expect(macWide.store.supportsWorkspaceCreateInGroup) #expect(macWide.store.supportsWorkspaceGroupCreate) } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift index d95da1c21b5a..9808966dd858 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileWorkspaceActionCapabilities.swift @@ -12,6 +12,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() @@ -23,7 +25,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.supportsReadStateActions = supportsReadStateActions @@ -31,5 +34,6 @@ public struct MobileWorkspaceActionCapabilities: Equatable, Sendable { self.supportsMoveActions = supportsMoveActions self.supportsGroupActions = supportsGroupActions self.supportsGroupCreate = supportsGroupCreate + self.supportsPaneReorder = supportsPaneReorder } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift index 925d0483e5b8..5b903e4a7ee8 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/CMUXMobileRootView+DebugPreview.swift @@ -24,7 +24,11 @@ extension CMUXMobileRootView { } switch route { case .panesTabs: - return AnyView(PanesTabsPreviewHost()) + return AnyView( + NavigationStack { + PanesTabsPreviewHost() + } + ) } } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 4ece914dd082..e72f4c98d64a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -1,6 +1,7 @@ #if canImport(UIKit) && DEBUG import CMUXMobileCore import CmuxMobileShellModel +import CmuxMobileSupport import SwiftUI /// Fixture-driven host for exercising the production panes-and-tabs UI without a paired Mac. @@ -15,6 +16,15 @@ struct PanesTabsPreviewHost: View { @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 private let terminalTheme = TerminalTheme.monokai private let workspace = MobileWorkspacePreview( @@ -138,7 +148,7 @@ struct PanesTabsPreviewHost: View { ] var body: some View { - if let layout = workspace.layout { + if let layout = fixtureLayout { PaneMapOverlay( value: PaneMapValue( workspaceName: workspace.name, @@ -149,18 +159,20 @@ struct PanesTabsPreviewHost: View { terminalTheme: terminalTheme, zoomNamespace: paneZoomNamespace, isVisible: !paneZoomPresentation.isTerminalPresented, + allowsReordering: true, + refreshTrigger: paneMapRefreshTrigger, fetchPreviews: Self.fetchFixturePreviews, selectTerminal: presentTerminalFromPaneMap, - dismiss: returnToTerminalFromPaneMap + reorderPanes: reorderFixturePanes, + refreshingChanged: { isPaneMapRefreshing = $0 } ) .accessibilityHidden(paneZoomPresentation.isTerminalPresented) - .fullScreenCover( - isPresented: terminalPresentationBinding, - onDismiss: reconcilePaneMapAfterInteractiveDismissal - ) { - NavigationStack { - terminalPreviewEndpoint - } + .navigationTitle(workspace.name) + .mobileTerminalNavigationChrome(theme: terminalTheme) + .toolbar { sharedPaneToolbar } + .navigationDestination(isPresented: terminalPresentationBinding) { + terminalPreviewEndpoint + .navigationBarBackButtonHidden(true) .navigationTransition( .zoom( sourceID: paneZoomSourceSurfaceID, @@ -168,6 +180,7 @@ struct PanesTabsPreviewHost: View { ) ) } + .navigationBarBackButtonHidden(true) } else { terminalPreviewEndpoint } @@ -184,20 +197,8 @@ struct PanesTabsPreviewHost: View { } .ignoresSafeArea(.keyboard, edges: .bottom) .navigationTitle(workspace.name) - .toolbar { - ToolbarItem(placement: .topBarTrailing) { - WorkspaceUtilitiesMenu( - showsViewAsText: false, - showsPaneMap: true, - terminalTheme: terminalTheme, - presentPaneMap: presentPaneMap, - openTextSheet: {}, - copyDebugLogs: {}, - sendFeedback: {} - ) - } - } - .accessibilityElement(children: .contain) + .mobileTerminalNavigationChrome(theme: terminalTheme) + .toolbar { sharedPaneToolbar } .accessibilityIdentifier("PanesTabsPreviewHost") } @@ -244,14 +245,139 @@ struct PanesTabsPreviewHost: View { ) } - private func reconcilePaneMapAfterInteractiveDismissal() { - paneZoomPresentation.presentationDidChange(isTerminalPresented: false) - } - private var paneZoomSourceSurfaceID: String { paneZoomPresentation.sourceSurfaceID ?? selectedSurfaceID } + @ToolbarContentBuilder + private var sharedPaneToolbar: some ToolbarContent { + ToolbarItem(placement: .topBarLeading) { + WorkspaceBackButton(unreadCount: 2, action: {}) + } + ToolbarItem(placement: .topBarTrailing) { + ZStack(alignment: .trailing) { + if paneZoomPresentation.isTerminalPresented { + WorkspaceUtilitiesMenu( + showsViewAsText: false, + showsPaneMap: true, + terminalTheme: terminalTheme, + presentPaneMap: presentPaneMap, + openTextSheet: {}, + copyDebugLogs: {}, + sendFeedback: {} + ) + .transition( + .move(edge: .trailing) + .combined(with: .opacity) + .combined(with: .scale(scale: 0.9, anchor: .trailing)) + ) + } else { + HStack(spacing: 8) { + Button { + paneMapRefreshTrigger &+= 1 + } label: { + if isPaneMapRefreshing { + ProgressView() + } else { + Image(systemName: "arrow.clockwise") + } + } + .accessibilityLabel( + L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh") + ) + .accessibilityIdentifier("MobilePaneMapRefresh") + + Button( + L10n.string("mobile.paneMap.done", defaultValue: "Done"), + action: returnToTerminalFromPaneMap + ) + .accessibilityIdentifier("MobilePaneMapDone") + } + .transition( + .move(edge: .trailing) + .combined(with: .opacity) + .combined(with: .scale(scale: 0.9, anchor: .trailing)) + ) + } + } + .animation(.snappy(duration: 0.32), value: paneZoomPresentation.endpoint) + } + } + + 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]) 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] diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index f82b754a6ea6..db38da003d74 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -36,8 +36,10 @@ struct PaneMapCollectionView: UIViewRepresentable { let terminalTheme: TerminalTheme let zoomNamespace: Namespace.ID let overflowLabels: PaneMapOverflowLabels + let allowsReordering: Bool let selectPreviewSurface: (_ paneID: String, _ surfaceID: String) -> Void let jumpToTerminal: (_ surfaceID: String) -> Void + let reorderPanes: (_ orderedPaneIDs: [String]) async -> Bool func makeCoordinator() -> Coordinator { Coordinator(parent: self) @@ -78,6 +80,7 @@ struct PaneMapCollectionView: UIViewRepresentable { as? PaneMapCollectionLayout { collectionLayout.paneLayout = layout } + container.collectionView.dragInteractionEnabled = allowsReordering container.configure( terminalTheme: terminalTheme, labels: overflowLabels, @@ -91,7 +94,8 @@ struct PaneMapCollectionView: UIViewRepresentable { UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDragDelegate, - UICollectionViewDropDelegate + UICollectionViewDropDelegate, + UIGestureRecognizerDelegate { static let cellReuseIdentifier = "PaneMapCollectionCell" @@ -101,9 +105,18 @@ struct PaneMapCollectionView: UIViewRepresentable { 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() init(parent: PaneMapCollectionView) { self.parent = parent + authoritativeItemsByID = Dictionary( + uniqueKeysWithValues: parent.items.map { ($0.id, $0) } + ) + reorderState = PaneMapReorderState( + authoritativePaneIDs: parent.items.map(\.id) + ) } func attach( @@ -112,23 +125,38 @@ struct PaneMapCollectionView: UIViewRepresentable { ) { self.collectionView = collectionView self.container = container - collectionView.dragInteractionEnabled = true + 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( + uniqueKeysWithValues: items.map { ($0.id, $0) } + ) guard !isMovingItem else { pendingItems = items return } - let itemsByID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) }) - let retainedIDs = orderedItems.map(\.id).filter { itemsByID[$0] != nil } - let retainedIDSet = Set(retainedIDs) - let newIDs = items.map(\.id).filter { !retainedIDSet.contains($0) } - orderedItems = (retainedIDs + newIDs).compactMap { itemsByID[$0] } + reorderState.reconcile(authoritativePaneIDs: items.map(\.id)) + reloadVisibleItems() + } + + private func reloadVisibleItems() { + orderedItems = reorderState.visiblePaneIDs.compactMap { + authoritativeItemsByID[$0] + } collectionView?.reloadData() collectionView?.collectionViewLayout.invalidateLayout() container?.setNeedsLayout() @@ -161,11 +189,10 @@ struct PaneMapCollectionView: UIViewRepresentable { 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?.parent.jumpToTerminal(surfaceID) - } + jumpToTerminal: { [weak self] surfaceID in self?.resolveAccessibilitySelection(surfaceID) } ) } .margins(.all, 0) @@ -178,9 +205,12 @@ struct PaneMapCollectionView: UIViewRepresentable { itemsForBeginning session: UIDragSession, at indexPath: IndexPath ) -> [UIDragItem] { - guard orderedItems.indices.contains(indexPath.item), + 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 @@ -216,6 +246,12 @@ struct PaneMapCollectionView: UIViewRepresentable { 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) @@ -223,6 +259,11 @@ struct PaneMapCollectionView: UIViewRepresentable { collectionView.moveItem(at: sourceIndexPath, to: destinationIndexPath) } coordinator.drop(droppedItem.dragItem, toItemAt: destinationIndexPath) + Task { [weak self] in + guard let self else { return } + let succeeded = await parent.reorderPanes(request.orderedPaneIDs) + completeReorder(requestID: request.id, succeeded: succeeded) + } } func collectionView( @@ -234,6 +275,13 @@ struct PaneMapCollectionView: UIViewRepresentable { func scrollViewDidScroll(_ scrollView: UIScrollView) { container?.updateOverflowIndicators() + selectionArbitration.touchMoved( + to: scrollView.panGestureRecognizer.location(in: scrollView) + ) + } + + func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + selectionArbitration.dragSessionDidBegin() } private func finishInteractiveMovement() { @@ -245,6 +293,94 @@ struct PaneMapCollectionView: UIViewRepresentable { } } + 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 previewHeight = cell.bounds.height - PaneMapTileMetrics.captionHeight + let paneControlsBand = CGRect( + x: cell.frame.minX, + y: cell.frame.minY + previewHeight - 50, + width: cell.frame.width, + height: 50 + ) + return paneControlsBand.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: PaneMapTileMetrics.cornerRadius + ) + return parameters + } + func scrollOneViewport(_ direction: PaneMapOverflowDirection) { guard let collectionView else { return } let horizontalStep = max(80, collectionView.bounds.width * 0.72) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index bbb883324b20..fa7e2e590c41 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -9,9 +9,12 @@ struct PaneMapOverlay: View { 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 dismiss: () -> Void + let reorderPanes: ([String]) async -> Bool + let refreshingChanged: (Bool) -> Void @State private var selectedSurfaceIDsByPaneID: [String: String] @State private var previewsBySurfaceID: [String: MobileTerminalPaneMapPreview] = [:] @@ -24,40 +27,38 @@ struct PaneMapOverlay: View { terminalTheme: TerminalTheme, zoomNamespace: Namespace.ID, isVisible: Bool, + allowsReordering: Bool, + refreshTrigger: Int, fetchPreviews: @escaping ([String], [String]) async -> [String: MobileTerminalRenderGridFrame], selectTerminal: @escaping (MobileTerminalPreview.ID) -> Void, - dismiss: @escaping () -> Void + reorderPanes: @escaping ([String]) 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.dismiss = dismiss + self.reorderPanes = reorderPanes + self.refreshingChanged = refreshingChanged _selectedSurfaceIDsByPaneID = State(initialValue: value.initialSurfaceIDsByPaneID) } var body: some View { - VStack(spacing: 0) { - PaneMapHeader( - workspaceName: value.workspaceName, - countSubtitle: countSubtitle, - isRefreshing: isRefreshing, - terminalTheme: terminalTheme, - refresh: startPreviewRefresh, - dismiss: dismissPaneMap - ) - PaneMapCollectionView( - items: collectionItems, - layout: value.layout, - terminalTheme: terminalTheme, - zoomNamespace: zoomNamespace, - overflowLabels: overflowLabels, - selectPreviewSurface: selectPreviewSurface, - jumpToTerminal: jumpToTerminal - ) - } + PaneMapCollectionView( + items: collectionItems, + layout: value.layout, + terminalTheme: terminalTheme, + zoomNamespace: zoomNamespace, + overflowLabels: overflowLabels, + allowsReordering: allowsReordering, + selectPreviewSurface: selectPreviewSurface, + jumpToTerminal: jumpToTerminal, + reorderPanes: reorderPanes + ) .frame(maxWidth: .infinity, maxHeight: .infinity) .background { terminalTheme.terminalBackgroundColor @@ -80,6 +81,11 @@ struct PaneMapOverlay: View { cancelPreviewRefresh() } } + .onChange(of: refreshTrigger) { _, _ in + guard isVisible else { return } + cancelPreviewRefresh() + startPreviewRefresh() + } .onChange(of: value.layout) { _, _ in selectedSurfaceIDsByPaneID = value.reconciledSurfaceIDs( current: selectedSurfaceIDsByPaneID @@ -127,43 +133,6 @@ struct PaneMapOverlay: View { ) } - private var countSubtitle: String { - let paneCount = value.panes.count - let tabCount = value.tabCount - switch (paneCount == 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" - ), - paneCount - ) - case (false, false): - return String.localizedStringWithFormat( - L10n.string( - "mobile.paneMap.count.otherPanes.otherTabs", - defaultValue: "%d panes · %d tabs" - ), - paneCount, - tabCount - ) - } - } - private func selectPreviewSurface(paneID: String, surfaceID: String) { selectedSurfaceIDsByPaneID[paneID] = surfaceID } @@ -172,10 +141,6 @@ struct PaneMapOverlay: View { selectTerminal(MobileTerminalPreview.ID(rawValue: surfaceID)) } - private func dismissPaneMap() { - dismiss() - } - private func startPreviewRefresh() { guard refreshTask == nil else { return } let generation = UUID() @@ -192,14 +157,17 @@ struct PaneMapOverlay: View { refreshTask?.cancel() refreshTask = nil isRefreshing = false + refreshingChanged(false) } private func refreshAllPreviews(generation: UUID) async { guard !isRefreshing else { return } isRefreshing = true + refreshingChanged(true) defer { if refreshGeneration == generation { isRefreshing = false + refreshingChanged(false) } } @@ -222,64 +190,3 @@ struct PaneMapOverlay: View { previewsBySurfaceID = frames.mapValues { $0.paneMapPreview() } } } - -private struct PaneMapHeader: View { - let workspaceName: String - let countSubtitle: String - let isRefreshing: Bool - let terminalTheme: TerminalTheme - let refresh: () -> Void - let dismiss: () -> Void - - var body: some View { - HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(workspaceName) - .font(.headline) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .lineLimit(1) - Text(countSubtitle) - .font(.subheadline) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.7)) - .lineLimit(1) - } - - Spacer(minLength: 0) - - Button(action: refresh) { - HStack(spacing: 5) { - if isRefreshing { - ProgressView() - .controlSize(.mini) - .tint(terminalTheme.terminalChromeForegroundColor) - } else { - Image(systemName: "arrow.clockwise") - } - Text(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) - } - .font(.subheadline.weight(.semibold)) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .padding(.horizontal, 12) - .frame(height: 34) - .mobileGlassPill() - } - .buttonStyle(.plain) - .disabled(isRefreshing) - .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) - .accessibilityIdentifier("MobilePaneMapRefresh") - - Button(action: dismiss) { - Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor) - .padding(.horizontal, 14) - .frame(height: 34) - .mobileGlassPill() - } - .buttonStyle(.plain) - .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .accessibilityIdentifier("MobilePaneMapDone") - } - .padding(16) - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift new file mode 100644 index 000000000000..83a2dd5b7c60 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift @@ -0,0 +1,83 @@ +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] + } + + enum Completion: Equatable { + case ignored + case rolledBack + case awaitingAuthority + } + + private(set) var visiblePaneIDs: [String] + private(set) var authoritativePaneIDs: [String] + private(set) var pendingRequest: Request? + private var receivedAuthorityWhilePending = false + private var pendingRequestWasAccepted = false + + var isMutationPending: Bool { + pendingRequest != nil + } + + init(authoritativePaneIDs: [String]) { + self.visiblePaneIDs = authoritativePaneIDs + self.authoritativePaneIDs = authoritativePaneIDs + } + + 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) + pendingRequest = request + receivedAuthorityWhilePending = false + pendingRequestWasAccepted = false + return request + } + + mutating func reconcile(authoritativePaneIDs: [String]) { + self.authoritativePaneIDs = authoritativePaneIDs + guard pendingRequest != nil else { + visiblePaneIDs = authoritativePaneIDs + 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 index 6b63f70bf624..c71e82fb4450 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -210,19 +210,18 @@ private struct PaneMapSurfacePreview: View { var body: some View { ZStack { if surface.type.isTerminal { - Button { - jumpToTerminal(surface.id) - } label: { - PaneMapTerminalPreview( - preview: preview, - isLoadingPreview: isLoadingPreview, - terminalTheme: terminalTheme - ) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) + 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, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift index 12f270131756..e8b9d57e152a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift @@ -1,4 +1,5 @@ import CmuxMobileShellModel +import CmuxMobileSupport /// Immutable workspace and status state rendered by ``PaneMapOverlay``. struct PaneMapValue: Equatable { @@ -15,6 +16,41 @@ struct PaneMapValue: Equatable { } } + 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: [:]) } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 1cd0cf5ad5a6..1d96d8680ece 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -55,6 +55,8 @@ struct WorkspaceDetailView: View { @State private var textSheetSurfaceID: String? @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 @@ -103,13 +105,13 @@ struct WorkspaceDetailView: View { if let layout = workspace.layout { paneMapRoot(layout: layout) .accessibilityHidden(paneZoomPresentation.isTerminalPresented) - .fullScreenCover( - isPresented: terminalZoomPresentationBinding, - onDismiss: reconcilePaneMapAfterInteractiveDismissal - ) { - NavigationStack { - terminalWorkspaceEndpoint - } + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } + .navigationTitle(systemNavigationTitle) + .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) + .toolbar { workspaceDetailToolbar } + .navigationDestination(isPresented: terminalZoomPresentationBinding) { + terminalWorkspaceEndpoint + .navigationBarBackButtonHidden(true) .navigationTransition( .zoom( sourceID: paneZoomSourceSurfaceID, @@ -117,7 +119,6 @@ struct WorkspaceDetailView: View { ) ) } - .toolbar(.hidden, for: .navigationBar) .navigationBarBackButtonHidden(true) } else { terminalWorkspaceEndpoint @@ -210,6 +211,8 @@ struct WorkspaceDetailView: View { 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, @@ -218,7 +221,8 @@ struct WorkspaceDetailView: View { ) }, selectTerminal: presentTerminalFromPaneMap, - dismiss: returnToTerminalFromPaneMap + reorderPanes: reorderPanesFromMap, + refreshingChanged: { isPaneMapRefreshing = $0 } ) } @@ -233,10 +237,6 @@ struct WorkspaceDetailView: View { ) } - private func reconcilePaneMapAfterInteractiveDismissal() { - paneZoomPresentation.presentationDidChange(isTerminalPresented: false) - } - private var paneZoomSourceSurfaceID: String { paneZoomPresentation.sourceSurfaceID ?? selectedTerminal?.id.rawValue @@ -259,17 +259,8 @@ 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 - } - } - } ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { - toolbarTrailingCluster + paneWorkspaceToolbarTrailingContent } } @@ -334,7 +325,19 @@ struct WorkspaceDetailView: View { } private var toolbarTitleLabelToken: WorkspaceTitleMenuLabelToken { - if isChatMode, + if !paneZoomPresentation.isTerminalPresented, + let layout = workspace.layout { + let paneMapValue = PaneMapValue( + workspaceName: workspace.name, + 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( @@ -350,6 +353,63 @@ struct WorkspaceDetailView: View { return .standard(title: workspace.name, subtitle: selectedToolbarSubtitle) } } + + private var paneWorkspaceToolbarTrailingContent: some View { + ZStack(alignment: .trailing) { + if paneZoomPresentation.isTerminalPresented { + HStack(spacing: 8) { + if let selectedTerminalID, + store.isAlternateScreen(surfaceID: selectedTerminalID), + displaySettings.showAltScreenNotice { + AltScreenNoticeButton { + displaySettings.showAltScreenNotice = false + } + .frame(width: 44, height: 44) + } + toolbarTrailingCluster + } + .transition( + .move(edge: .trailing) + .combined(with: .opacity) + .combined(with: .scale(scale: 0.9, anchor: .trailing)) + ) + } else { + paneMapToolbarControls + .transition( + .move(edge: .trailing) + .combined(with: .opacity) + .combined(with: .scale(scale: 0.9, anchor: .trailing)) + ) + } + } + .animation(.snappy(duration: 0.32), value: paneZoomPresentation.endpoint) + } + + private var paneMapToolbarControls: some View { + HStack(spacing: 8) { + Button(action: refreshPaneMapFromToolbar) { + Group { + if isPaneMapRefreshing { + ProgressView() + .controlSize(.small) + } else { + Image(systemName: "arrow.clockwise") + } + } + .frame(width: 24, height: 24) + } + .disabled(isPaneMapRefreshing) + .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) + .accessibilityIdentifier("MobilePaneMapRefresh") + + Button(action: returnToTerminalFromPaneMap) { + Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .font(.subheadline.weight(.semibold)) + } + .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) + .accessibilityIdentifier("MobilePaneMapDone") + } + } #endif func detailContent() -> some View { @@ -621,6 +681,29 @@ struct WorkspaceDetailView: View { paneZoomPresentation.presentTerminal(surfaceID: paneZoomSourceSurfaceID) } + private func refreshPaneMapFromToolbar() { + paneMapRefreshTrigger &+= 1 + } + + @MainActor + private func reorderPanesFromMap(_ orderedPaneIDs: [String]) async -> Bool { + let result = await store.reorderWorkspacePanes( + id: workspace.id, + orderedPaneIDs: orderedPaneIDs + ) + 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) #if DEBUG private func copyDebugLogsFromMenu() { diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 377878a2099c..a30cdebde17e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -187,7 +187,8 @@ import Testing @Test func failureRollsBackToTheLatestAuthoritativeOrder() throws { var state = PaneMapReorderState(authoritativePaneIDs: ["left", "middle", "right"]) - let request = try #require(state.beginMove(from: 0, to: 2)) + 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"]) @@ -204,7 +205,8 @@ import Testing @Test func successWaitsForAndThenUsesTheAuthoritativeMacOrder() throws { var state = PaneMapReorderState(authoritativePaneIDs: ["one", "two", "three"]) - let request = try #require(state.beginMove(from: 2, to: 0)) + let pendingRequest = state.beginMove(from: 2, to: 0) + let request = try #require(pendingRequest) #expect(request.orderedPaneIDs == ["three", "one", "two"]) #expect(state.complete(requestID: request.id, succeeded: true) == .awaitingAuthority) #expect(state.visiblePaneIDs == ["three", "one", "two"]) @@ -218,10 +220,12 @@ import Testing @Test func staleCompletionCannotOverwriteANewerMove() throws { var state = PaneMapReorderState(authoritativePaneIDs: ["a", "b", "c"]) - let first = try #require(state.beginMove(from: 0, to: 1)) + let firstPendingRequest = state.beginMove(from: 0, to: 1) + let first = try #require(firstPendingRequest) #expect(state.complete(requestID: first.id, succeeded: false) == .rolledBack) - let second = try #require(state.beginMove(from: 2, to: 0)) + 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) @@ -232,13 +236,16 @@ import Testing arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) arbitration.touchMoved(to: CGPoint(x: 32, y: 10)) - #expect(!arbitration.touchEnded(at: 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() - #expect(!arbitration.touchEnded(at: CGPoint(x: 10, y: 10))) + let dragResolvedAsTap = arbitration.touchEnded(at: CGPoint(x: 10, y: 10)) + #expect(!dragResolvedAsTap) arbitration.touchBegan(at: CGPoint(x: 10, y: 10)) - #expect(arbitration.touchEnded(at: CGPoint(x: 11, y: 11))) + let stationaryTouchResolvedAsTap = arbitration.touchEnded(at: CGPoint(x: 11, y: 11)) + #expect(stationaryTouchResolvedAsTap) } } diff --git a/Sources/Mobile/MobileHostService+Capabilities.swift b/Sources/Mobile/MobileHostService+Capabilities.swift index 03a01ef081ec..36758291734a 100644 --- a/Sources/Mobile/MobileHostService+Capabilities.swift +++ b/Sources/Mobile/MobileHostService+Capabilities.swift @@ -51,6 +51,7 @@ extension MobileHostService { // this to render collapsible groups only against a Mac that emits them. "workspace.groups.v1", "workspace.layout.v1", + "workspace.pane_reorder.v1", ] #if DEBUG // Lets a dev Mac impersonate an older host while dogfooding the iOS update hint. diff --git a/Sources/Mobile/MobileHostService+TicketAuthorization.swift b/Sources/Mobile/MobileHostService+TicketAuthorization.swift index e534e69033ec..3c48c92758a5 100644 --- a/Sources/Mobile/MobileHostService+TicketAuthorization.swift +++ b/Sources/Mobile/MobileHostService+TicketAuthorization.swift @@ -55,7 +55,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/TerminalController+WorkspaceMove.swift b/Sources/TerminalController+WorkspaceMove.swift index 526cea1734e8..7271f33ea90a 100644 --- a/Sources/TerminalController+WorkspaceMove.swift +++ b/Sources/TerminalController+WorkspaceMove.swift @@ -1,6 +1,65 @@ 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) + } + guard let tabManager = v2ResolveTabManager(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 + } + 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") + return v2MobileWorkspaceList(params: listParams, tabManager: tabManager) + } + /// Mobile-gated workspace reorder/group move. func v2MobileWorkspaceMove(params: [String: Any]) -> V2CallResult { if let error = mobileWorkspaceIDValidationError(params: params) { diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index f87eef93cd6e..407e343a7608 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -14005,6 +14005,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."): diff --git a/Sources/Workspace+MobilePaneReorder.swift b/Sources/Workspace+MobilePaneReorder.swift new file mode 100644 index 000000000000..75cfea98c908 --- /dev/null +++ b/Sources/Workspace+MobilePaneReorder.swift @@ -0,0 +1,135 @@ +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 { + _ = bonsplitController.closeTab(placeholder) + } + + 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) + } + } + mobilePaneLayoutPublicationSuppressionCount -= 1 + + guard mutationSucceeded else { return false } + + if let originallyFocusedPaneID, + let destinationIndex = requestedPaneIDs.firstIndex(of: originallyFocusedPaneID), + let focusedPane = panesByID[spatialPanes[destinationIndex]] { + bonsplitController.focusPane(focusedPane) + } + 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 4a00dd537545..bdfd56706411 100644 --- a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift +++ b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift @@ -89,6 +89,9 @@ extension Workspace: WorkspaceSurfaceTreeReading { /// 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() diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 5db0778dbaea..5900df994bd9 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2280,6 +2280,12 @@ final class Workspace: Identifiable, ObservableObject { /// 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 } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 91ecb8acc8a1..39c6fa1f0d09 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -2070,6 +2070,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources 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 */; }; @@ -4230,6 +4231,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 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 = ""; }; @@ -5279,6 +5281,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C0DE00000000000000000D35 /* TerminalController+WorkspaceCreatePreparation.swift */, C0DE00000000000000000C8A /* TerminalController+WorkspaceGroupAction.swift */, C0DE00000000000000000C88 /* TerminalController+WorkspaceMove.swift */, + C0DE00000000000000000C90 /* Workspace+MobilePaneReorder.swift */, C0DE00000000000000000C55 /* TerminalController+ControlPaneContext.swift */, C7A50B000000000000000001 /* TerminalControllerV2ParamParsingSupport.swift */, C7A50B000000000000000011 /* TerminalController+MobileWorkspaceList.swift */, @@ -8405,6 +8408,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 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 5e1cee028eac..55f67995cb08 100644 --- a/cmuxTests/MobileHostConnectionLifecycleTests.swift +++ b/cmuxTests/MobileHostConnectionLifecycleTests.swift @@ -356,6 +356,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 e02fa38efe94..b7f7ddda1305 100644 --- a/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift +++ b/cmuxTests/MobileHostWorkspaceTicketAuthorizationTests.swift @@ -298,6 +298,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 bdf08805cb66..e1cf9ffe53e5 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -173,6 +173,7 @@ struct MobileWorkspaceListFidelityTests { @Test func mobileHostAdvertisesWorkspaceLayoutV1() { #expect(MobileHostService.mobileHostCapabilities.contains("workspace.layout.v1")) + #expect(MobileHostService.mobileHostCapabilities.contains("workspace.pane_reorder.v1")) } @Test func observerPipelinesFollowSubscriberPresence() throws { @@ -272,6 +273,101 @@ 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 + } + ) + } + @Test func reorderingTerminalsChangesObserverHashAndBumpsLayoutVersion() throws { // Tabs in one pane so a within-pane reorder genuinely changes their order. let (workspace, ordered) = try makeWorkspaceWithTabTerminals(count: 3) diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index b5cba4d123ba..b190d20ce01d 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -7848,6 +7848,13 @@ "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": { diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 1876c7d17a0a..6f6c0fb14c29 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1673,7 +1673,11 @@ final class cmuxUITests: XCTestCase { defer { app.terminate() } XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) - XCTAssertTrue(app.otherElements["MobileSurfaceDeck"].waitForExistence(timeout: 4)) + XCTAssertTrue(app.buttons["MobileWorkspaceBackButton"].exists) + XCTAssertFalse( + waitForPaneMap(app.otherElements["MobilePaneMapOverlay"], 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" @@ -1706,6 +1710,10 @@ final class cmuxUITests: XCTestCase { let overlay = app.otherElements["MobilePaneMapOverlay"] XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) + XCTAssertTrue( + app.buttons["MobileWorkspaceBackButton"].exists, + "The shared workspace back button must remain present in pane-layout mode" + ) let leftTopPane = app.descendants(matching: .any)[ "MobilePaneMapPane-preview-pane-left-top" ] @@ -1768,7 +1776,24 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(leftTopPane.waitForExistence(timeout: 2)) XCTAssertTrue(testsPane.exists) - let originalLeftTopFrame = leftTopPane.frame + tap(app.buttons["MobilePaneMapTab-preview-claude"], in: app) + XCTAssertTrue( + waitForPaneMap(overlay, 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, 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( @@ -1779,23 +1804,45 @@ final class cmuxUITests: XCTestCase { ) let reordered = XCTNSPredicateExpectation( predicate: NSPredicate( - block: { _, _ in leftTopPane.frame.midX > originalLeftTopFrame.midX + 20 } + block: { _, _ in + abs(claudeTile.frame.midX - originalTestsFrame.midX) < 24 + && abs(claudeTile.frame.midX - originalClaudeFrame.midX) > 20 + } ), - object: leftTopPane + object: claudeTile ) XCTAssertEqual( XCTWaiter.wait(for: [reordered], timeout: 4), .completed, - "Dragging a pane card must move it into the destination layout slot" + "Dragging a pane card must move its contents into the authoritative destination slot" + ) + XCTAssertTrue( + waitForPaneMap(overlay, toBeActive: true), + "A pane relayout drag must not also focus the dragged pane" ) - let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] - XCTAssertTrue(claudeTile.waitForExistence(timeout: 2)) tap(claudeTile, in: app) XCTAssertTrue(waitForPaneMap(overlay, 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, toBeActive: false), + "A cancelled interactive return must leave the terminal fully focused" + ) + tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) XCTAssertTrue( waitForPaneMap(overlay, toBeActive: true), From b887b362c87f78ea8b449526efbf54526fd5cb1d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 16:41:14 -0700 Subject: [PATCH 36/78] test(ios): stabilize pane map presentation checks --- ios/cmuxUITests/cmuxUITests.swift | 50 +++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 6f6c0fb14c29..273a851bc1ec 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -1675,7 +1675,12 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) XCTAssertTrue(app.buttons["MobileWorkspaceBackButton"].exists) XCTAssertFalse( - waitForPaneMap(app.otherElements["MobilePaneMapOverlay"], toBeActive: true, timeout: 0.3), + waitForPaneMap( + app.otherElements["MobilePaneMapOverlay"], + in: app, + toBeActive: true, + timeout: 0.3 + ), "Opening a workspace must present its restored terminal directly" ) @@ -1709,7 +1714,7 @@ final class cmuxUITests: XCTestCase { tapMenuItem(app.buttons["MobilePaneMapMenuItem"], in: app) let overlay = app.otherElements["MobilePaneMapOverlay"] - XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) XCTAssertTrue( app.buttons["MobileWorkspaceBackButton"].exists, "The shared workspace back button must remain present in pane-layout mode" @@ -1742,10 +1747,10 @@ final class cmuxUITests: XCTestCase { XCTAssertEqual(leftTopTabStrip.frame.width, 64, accuracy: 2) tap(app.buttons["MobilePaneMapDone"], in: app) - XCTAssertTrue(waitForPaneMap(overlay, toBeActive: false)) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: false)) tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) - XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) tap(app.buttons["MobilePaneMapTab-preview-zsh"], in: app) let zshTile = app.buttons["MobilePaneMapTile-preview-zsh"] XCTAssertTrue(zshTile.waitForExistence(timeout: 2)) @@ -1753,7 +1758,7 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(overlay.exists, "Switching tabs must stay inside the pane map") tap(zshTile, in: app) - XCTAssertTrue(waitForPaneMap(overlay, toBeActive: false)) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: false)) XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-zsh"].isSelected) } @@ -1768,7 +1773,7 @@ final class cmuxUITests: XCTestCase { tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) let overlay = app.otherElements["MobilePaneMapOverlay"] - XCTAssertTrue(waitForPaneMap(overlay, toBeActive: true)) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) let leftTopPane = app.descendants(matching: .any)[ "MobilePaneMapPane-preview-pane-left-top" ] @@ -1778,7 +1783,7 @@ final class cmuxUITests: XCTestCase { tap(app.buttons["MobilePaneMapTab-preview-claude"], in: app) XCTAssertTrue( - waitForPaneMap(overlay, toBeActive: true), + waitForPaneMap(overlay, in: app, toBeActive: true), "Switching the preview tab must not focus its pane" ) let claudeTile = app.buttons["MobilePaneMapTile-preview-claude"] @@ -1790,7 +1795,7 @@ final class cmuxUITests: XCTestCase { let swipeEnd = overlay.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.28)) swipeStart.press(forDuration: 0.05, thenDragTo: swipeEnd) XCTAssertTrue( - waitForPaneMap(overlay, toBeActive: true), + waitForPaneMap(overlay, in: app, toBeActive: true), "A pane-layout swipe must be absorbed by scrolling instead of focusing a pane" ) @@ -1817,13 +1822,13 @@ final class cmuxUITests: XCTestCase { "Dragging a pane card must move its contents into the authoritative destination slot" ) XCTAssertTrue( - waitForPaneMap(overlay, toBeActive: true), + waitForPaneMap(overlay, in: app, toBeActive: true), "A pane relayout drag must not also focus the dragged pane" ) tap(claudeTile, in: app) - XCTAssertTrue(waitForPaneMap(overlay, toBeActive: false)) + XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: false)) XCTAssertTrue(app.buttons["MobileSurfaceDeckChip-preview-claude"].isSelected) let interruptedSwipeStart = app.coordinate( @@ -1839,20 +1844,20 @@ final class cmuxUITests: XCTestCase { thenHoldForDuration: 0 ) XCTAssertTrue( - waitForPaneMap(overlay, toBeActive: false), + 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, toBeActive: true), + 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, toBeActive: false), + waitForPaneMap(overlay, in: app, toBeActive: false), "The same source must zoom back into the opened terminal" ) } @@ -4033,12 +4038,27 @@ final class cmuxUITests: XCTestCase { private func waitForPaneMap( _ overlay: XCUIElement, + in app: XCUIApplication, toBeActive isActive: Bool, timeout: TimeInterval = 4 ) -> 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. + let modeControl = app.buttons[ + isActive ? "MobilePaneMapRefresh" : "MobileWorkspaceUtilitiesMenu" + ] let expectation = XCTNSPredicateExpectation( - predicate: NSPredicate(format: "isHittable == %@", NSNumber(value: isActive)), - object: overlay + predicate: NSPredicate( + block: { _, _ in + modeControl.exists + && modeControl.isHittable + && (!isActive || overlay.exists) + } + ), + object: modeControl ) return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed } From 2677ab8d9c3bc46f756a9b201681d7c15569eabf Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 17:19:32 -0700 Subject: [PATCH 37/78] test(ios): cover direct restored pane presentation --- .../PaneMapCollectionLayoutEngineTests.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index a30cdebde17e..cf85a27c2780 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -173,6 +173,21 @@ import Testing #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") From 387dda4ff67a4ce6519579e45d53dddaa34f41c5 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 23 Jul 2026 17:20:01 -0700 Subject: [PATCH 38/78] fix(ios): restore focused pane on workspace entry --- .../Debug/PanesTabsPreviewHost.swift | 68 ++++++++----------- .../PaneZoomPresentationState.swift | 50 ++++++++++++-- .../WorkspaceDetailView.swift | 34 ++++------ .../WorkspaceShellView.swift | 9 +++ 4 files changed, 95 insertions(+), 66 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index e72f4c98d64a..824dacb78769 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -149,38 +149,39 @@ struct PanesTabsPreviewHost: View { var body: some View { if let layout = fixtureLayout { - PaneMapOverlay( - value: PaneMapValue( - workspaceName: workspace.name, - 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) - .navigationTitle(workspace.name) - .mobileTerminalNavigationChrome(theme: terminalTheme) - .toolbar { sharedPaneToolbar } - .navigationDestination(isPresented: terminalPresentationBinding) { + PaneZoomNavigationStack(presentation: $paneZoomPresentation) { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + 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) + .navigationTitle(workspace.name) + .mobileTerminalNavigationChrome(theme: terminalTheme) + .toolbar { sharedPaneToolbar } + .navigationBarBackButtonHidden(true) + } terminal: { terminalPreviewEndpoint .navigationBarBackButtonHidden(true) - .navigationTransition( - .zoom( - sourceID: paneZoomSourceSurfaceID, - in: paneZoomNamespace + .navigationTransition( + .zoom( + sourceID: paneZoomSourceSurfaceID, + in: paneZoomNamespace + ) ) - ) } - .navigationBarBackButtonHidden(true) } else { terminalPreviewEndpoint } @@ -234,17 +235,6 @@ struct PanesTabsPreviewHost: View { paneZoomPresentation.presentTerminal(surfaceID: paneZoomSourceSurfaceID) } - private var terminalPresentationBinding: Binding { - Binding( - get: { paneZoomPresentation.isTerminalPresented }, - set: { isPresented in - paneZoomPresentation.presentationDidChange( - isTerminalPresented: isPresented - ) - } - ) - } - private var paneZoomSourceSurfaceID: String { paneZoomPresentation.sourceSurfaceID ?? selectedSurfaceID } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index 5d477aaaaadf..3c147af53520 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -1,13 +1,19 @@ +import SwiftUI + /// Stable routing state for the native pane-map zoom presentation. struct PaneZoomPresentationState: Equatable { - enum Endpoint: Equatable { + enum Endpoint: Hashable { case paneMap case terminal } - private(set) var endpoint: Endpoint = .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 } @@ -16,16 +22,50 @@ struct PaneZoomPresentationState: Equatable { if let surfaceID, !surfaceID.isEmpty { sourceSurfaceID = surfaceID } - endpoint = .paneMap + navigationPath = [] } mutating func presentTerminal(surfaceID: String) { guard !surfaceID.isEmpty else { return } sourceSurfaceID = surfaceID - endpoint = .terminal + navigationPath = [.terminal] } mutating func presentationDidChange(isTerminalPresented: Bool) { - endpoint = isTerminalPresented ? .terminal : .paneMap + navigationPath = isTerminalPresented ? [.terminal] : [] + } + + mutating func navigationPathDidChange(_ path: [Endpoint]) { + navigationPath = path.last == .terminal ? [.terminal] : [] + } +} + +/// Keeps the pane-map route local to a workspace destination. The parent stack +/// still owns workspace-list navigation and its shared back button, while this +/// path starts with the restored terminal already installed on the first frame. +struct PaneZoomNavigationStack: View { + @Binding var presentation: PaneZoomPresentationState + @ViewBuilder let root: () -> Root + @ViewBuilder let terminal: () -> Terminal + + var body: some View { + NavigationStack(path: navigationPath) { + root() + .navigationDestination(for: PaneZoomPresentationState.Endpoint.self) { endpoint in + if endpoint == .terminal { + terminal() + } + } + } + #if os(iOS) + .toolbarVisibility(.hidden, for: .tabBar) + #endif + } + + private var navigationPath: Binding<[PaneZoomPresentationState.Endpoint]> { + Binding( + get: { presentation.navigationPath }, + set: { presentation.navigationPathDidChange($0) } + ) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 1d96d8680ece..07aeb4cae732 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -103,23 +103,24 @@ struct WorkspaceDetailView: View { var body: some View { #if os(iOS) if let layout = workspace.layout { - paneMapRoot(layout: layout) - .accessibilityHidden(paneZoomPresentation.isTerminalPresented) - .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } - .navigationTitle(systemNavigationTitle) - .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) - .toolbar { workspaceDetailToolbar } - .navigationDestination(isPresented: terminalZoomPresentationBinding) { - terminalWorkspaceEndpoint - .navigationBarBackButtonHidden(true) + PaneZoomNavigationStack(presentation: $paneZoomPresentation) { + paneMapRoot(layout: layout) + .accessibilityHidden(paneZoomPresentation.isTerminalPresented) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } + .navigationTitle(systemNavigationTitle) + .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) + .toolbar { workspaceDetailToolbar } + .navigationBarBackButtonHidden(true) + } terminal: { + terminalWorkspaceEndpoint + .navigationBarBackButtonHidden(true) .navigationTransition( .zoom( sourceID: paneZoomSourceSurfaceID, in: paneZoomNamespace ) ) - } - .navigationBarBackButtonHidden(true) + } } else { terminalWorkspaceEndpoint } @@ -226,17 +227,6 @@ struct WorkspaceDetailView: View { ) } - private var terminalZoomPresentationBinding: Binding { - Binding( - get: { paneZoomPresentation.isTerminalPresented }, - set: { isPresented in - paneZoomPresentation.presentationDidChange( - isTerminalPresented: isPresented - ) - } - ) - } - private var paneZoomSourceSurfaceID: String { paneZoomPresentation.sourceSurfaceID ?? selectedTerminal?.id.rawValue diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index 11c4dd6df4aa..4d8bcda37ee6 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -219,6 +219,7 @@ struct WorkspaceShellView: View { workspaceTabContent( canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection ) + .toolbarVisibility(primaryTabBarVisibility, for: .tabBar) } notifications: { NavigationStack(path: $notificationNavigationPath) { NotificationFeedStoreView( @@ -240,6 +241,7 @@ struct WorkspaceShellView: View { .toolbarVisibility(.hidden, for: .tabBar) } } + .toolbarVisibility(primaryTabBarVisibility, for: .tabBar) } .environment(\.workspaceRootToolbarContentWidth, geometry.size.width) .environment(\.workspaceRootToolbarRenderContext, toolbarRenderContext) @@ -308,6 +310,13 @@ struct WorkspaceShellView: View { } } + #if os(iOS) + private var primaryTabBarVisibility: Visibility { + let workspaceIsPushed = usesCompactStack && !compactNavigationPath.isEmpty + return workspaceIsPushed || !notificationNavigationPath.isEmpty ? .hidden : .automatic + } + #endif + private func layoutContent(canCreateWorkspaceForSelection: Bool) -> some View { Group { if usesCompactStack { From 69ae8a56f6afa334bc9377f009b26145edc8ce97 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 24 Jul 2026 14:40:47 -0700 Subject: [PATCH 39/78] fix(ios): let pane zoom own toolbar transitions --- .../Debug/PanesTabsPreviewHost.swift | 85 +++++++++---------- .../WorkspaceDetailView.swift | 72 ++++++++-------- 2 files changed, 76 insertions(+), 81 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 824dacb78769..1b8b890c2795 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -170,7 +170,7 @@ struct PanesTabsPreviewHost: View { .accessibilityHidden(paneZoomPresentation.isTerminalPresented) .navigationTitle(workspace.name) .mobileTerminalNavigationChrome(theme: terminalTheme) - .toolbar { sharedPaneToolbar } + .toolbar { paneMapToolbar } .navigationBarBackButtonHidden(true) } terminal: { terminalPreviewEndpoint @@ -199,7 +199,7 @@ struct PanesTabsPreviewHost: View { .ignoresSafeArea(.keyboard, edges: .bottom) .navigationTitle(workspace.name) .mobileTerminalNavigationChrome(theme: terminalTheme) - .toolbar { sharedPaneToolbar } + .toolbar { terminalToolbar } .accessibilityIdentifier("PanesTabsPreviewHost") } @@ -240,57 +240,50 @@ struct PanesTabsPreviewHost: View { } @ToolbarContentBuilder - private var sharedPaneToolbar: some ToolbarContent { + private var paneMapToolbar: some ToolbarContent { ToolbarItem(placement: .topBarLeading) { WorkspaceBackButton(unreadCount: 2, action: {}) } ToolbarItem(placement: .topBarTrailing) { - ZStack(alignment: .trailing) { - if paneZoomPresentation.isTerminalPresented { - WorkspaceUtilitiesMenu( - showsViewAsText: false, - showsPaneMap: true, - terminalTheme: terminalTheme, - presentPaneMap: presentPaneMap, - openTextSheet: {}, - copyDebugLogs: {}, - sendFeedback: {} - ) - .transition( - .move(edge: .trailing) - .combined(with: .opacity) - .combined(with: .scale(scale: 0.9, anchor: .trailing)) - ) - } else { - HStack(spacing: 8) { - Button { - paneMapRefreshTrigger &+= 1 - } label: { - if isPaneMapRefreshing { - ProgressView() - } else { - Image(systemName: "arrow.clockwise") - } - } - .accessibilityLabel( - L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh") - ) - .accessibilityIdentifier("MobilePaneMapRefresh") - - Button( - L10n.string("mobile.paneMap.done", defaultValue: "Done"), - action: returnToTerminalFromPaneMap - ) - .accessibilityIdentifier("MobilePaneMapDone") + HStack(spacing: 8) { + Button { + paneMapRefreshTrigger &+= 1 + } label: { + if isPaneMapRefreshing { + ProgressView() + } else { + Image(systemName: "arrow.clockwise") } - .transition( - .move(edge: .trailing) - .combined(with: .opacity) - .combined(with: .scale(scale: 0.9, anchor: .trailing)) - ) } + .accessibilityLabel( + L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh") + ) + .accessibilityIdentifier("MobilePaneMapRefresh") + + Button( + L10n.string("mobile.paneMap.done", defaultValue: "Done"), + action: returnToTerminalFromPaneMap + ) + .accessibilityIdentifier("MobilePaneMapDone") } - .animation(.snappy(duration: 0.32), value: paneZoomPresentation.endpoint) + } + } + + @ToolbarContentBuilder + private var terminalToolbar: some ToolbarContent { + ToolbarItem(placement: .topBarLeading) { + WorkspaceBackButton(unreadCount: 2, action: {}) + } + ToolbarItem(placement: .topBarTrailing) { + WorkspaceUtilitiesMenu( + showsViewAsText: false, + showsPaneMap: true, + terminalTheme: terminalTheme, + presentPaneMap: presentPaneMap, + openTextSheet: {}, + copyDebugLogs: {}, + sendFeedback: {} + ) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 07aeb4cae732..a50a34575c48 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -109,7 +109,7 @@ struct WorkspaceDetailView: View { .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(systemNavigationTitle) .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) - .toolbar { workspaceDetailToolbar } + .toolbar { workspaceDetailToolbar(mode: .paneMap) } .navigationBarBackButtonHidden(true) } terminal: { terminalWorkspaceEndpoint @@ -165,7 +165,7 @@ struct WorkspaceDetailView: View { .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(systemNavigationTitle) .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) - .toolbar { workspaceDetailToolbar } + .toolbar { workspaceDetailToolbar(mode: .terminal) } .task(id: chatRefreshKey) { await refreshChatSessions() } .task(id: chatConversationWarmKey) { await runWarmChatConversation() } .onChange(of: selectedTerminalID) { _, _ in @@ -236,8 +236,15 @@ struct WorkspaceDetailView: View { ?? "" } + 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 @@ -247,26 +254,28 @@ struct WorkspaceDetailView: View { } } ToolbarItem(id: "workspace-title", placement: .topBarLeading) { - workspaceTitleToolbarMenu + workspaceTitleToolbarMenu(mode: mode) } ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { - paneWorkspaceToolbarTrailingContent + workspaceToolbarTrailingContent(mode: mode) } } - private var workspaceTitleToolbarMenu: some View { + private func workspaceTitleToolbarMenu( + mode: WorkspaceDetailToolbarMode + ) -> some View { let value = WorkspaceTitleMenuValue( contentWidth: contentWidth, hasBackButton: backButtonConfiguration != nil, hasTrailingCluster: true, - hasChatToggle: shouldShowChatToggle, + hasChatToggle: mode == .terminal && shouldShowChatToggle, isEnabled: hasTitleMenuActions, workspaceName: workspace.name, hasUnread: workspace.hasUnread, canRenameWorkspace: renameWorkspace != nil, canToggleReadState: setWorkspaceUnread != nil, canCloseWorkspace: closeWorkspace != nil, - labelToken: toolbarTitleLabelToken, + labelToken: toolbarTitleLabelToken(mode: mode), terminalTheme: store.activeTerminalTheme ) return WorkspaceTitleMenu( @@ -314,8 +323,10 @@ struct WorkspaceDetailView: View { .equatable() } - private var toolbarTitleLabelToken: WorkspaceTitleMenuLabelToken { - if !paneZoomPresentation.isTerminalPresented, + private func toolbarTitleLabelToken( + mode: WorkspaceDetailToolbarMode + ) -> WorkspaceTitleMenuLabelToken { + if mode == .paneMap, let layout = workspace.layout { let paneMapValue = PaneMapValue( workspaceName: workspace.name, @@ -344,35 +355,26 @@ struct WorkspaceDetailView: View { } } - private var paneWorkspaceToolbarTrailingContent: some View { - ZStack(alignment: .trailing) { - if paneZoomPresentation.isTerminalPresented { - HStack(spacing: 8) { - if let selectedTerminalID, - store.isAlternateScreen(surfaceID: selectedTerminalID), - displaySettings.showAltScreenNotice { - AltScreenNoticeButton { - displaySettings.showAltScreenNotice = false - } - .frame(width: 44, height: 44) + @ViewBuilder + private func workspaceToolbarTrailingContent( + mode: WorkspaceDetailToolbarMode + ) -> some View { + switch mode { + case .terminal: + HStack(spacing: 8) { + if let selectedTerminalID, + store.isAlternateScreen(surfaceID: selectedTerminalID), + displaySettings.showAltScreenNotice { + AltScreenNoticeButton { + displaySettings.showAltScreenNotice = false } - toolbarTrailingCluster + .frame(width: 44, height: 44) } - .transition( - .move(edge: .trailing) - .combined(with: .opacity) - .combined(with: .scale(scale: 0.9, anchor: .trailing)) - ) - } else { - paneMapToolbarControls - .transition( - .move(edge: .trailing) - .combined(with: .opacity) - .combined(with: .scale(scale: 0.9, anchor: .trailing)) - ) + toolbarTrailingCluster } + case .paneMap: + paneMapToolbarControls } - .animation(.snappy(duration: 0.32), value: paneZoomPresentation.endpoint) } private var paneMapToolbarControls: some View { From 28922560241d6a92c2ddc06dd26060b0cf495e81 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:03:19 -0700 Subject: [PATCH 40/78] fix(ios): prefer focused pane terminal on workspace entry --- .../MobileShellComposite.swift | 33 +++++++++++++++++++ .../MobileShellCompositePreviewTests.swift | 31 +++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index f0fd492626d8..655d3b3304da 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -4454,6 +4454,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 @@ -6137,6 +6138,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. @@ -8244,6 +8253,30 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } private extension MobileWorkspacePreview { + var preferredEntryTerminal: MobileTerminalPreview? { + focusedPaneTerminal ?? preferredTerminal + } + + private var focusedPaneTerminal: MobileTerminalPreview? { + guard let layout else { return nil } + 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 nil } + let terminalIDs = focusedPane.surfaces + .filter { $0.type.isTerminal } + .map(\.id) + if let selectedSurfaceID = focusedPane.selectedSurfaceID, + terminalIDs.contains(selectedSurfaceID), + let terminal = terminals.first(where: { $0.id.rawValue == selectedSurfaceID }) { + return terminal + } + return terminalIDs.compactMap { terminalID in + terminals.first { $0.id.rawValue == terminalID } + }.first + } + var preferredTerminal: MobileTerminalPreview? { terminals.first { $0.isReady && $0.isFocused } ?? terminals.first { $0.isReady } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index 83040f3fb2cd..f5b2a7f49678 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -128,6 +128,37 @@ 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 startsAtSignInWithoutConnection() { let store = MobileShellComposite.preview() From b62c281f2213836fad7a73a76b34919d90db9486 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Tue, 28 Jul 2026 21:36:31 -0700 Subject: [PATCH 41/78] test(ios): cover pane map layout loss route reset --- .../PaneMapCollectionLayoutEngineTests.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index cf85a27c2780..86045be85847 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -196,6 +196,16 @@ import Testing #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") + } } @Suite struct PaneMapReorderStateTests { From 9502fdc1e7a8d0fa398959927f7b399b0c29274b Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Tue, 28 Jul 2026 21:38:54 -0700 Subject: [PATCH 42/78] fix(ios): reset pane map route when layout disappears --- .../PaneZoomPresentationState.swift | 5 ++ .../WorkspaceDetailView.swift | 48 +++++++++---------- 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index 3c147af53520..bd039b495968 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -35,6 +35,11 @@ struct PaneZoomPresentationState: Equatable { 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] : [] } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index a50a34575c48..8e0d39ca9e9e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -102,27 +102,32 @@ struct WorkspaceDetailView: View { #endif var body: some View { #if os(iOS) - if let layout = workspace.layout { - PaneZoomNavigationStack(presentation: $paneZoomPresentation) { - 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: { - terminalWorkspaceEndpoint - .navigationBarBackButtonHidden(true) - .navigationTransition( - .zoom( - sourceID: paneZoomSourceSurfaceID, - in: paneZoomNamespace + Group { + if let layout = workspace.layout { + PaneZoomNavigationStack(presentation: $paneZoomPresentation) { + 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: { + terminalWorkspaceEndpoint + .navigationBarBackButtonHidden(true) + .navigationTransition( + .zoom( + sourceID: paneZoomSourceSurfaceID, + in: paneZoomNamespace + ) ) - ) + } + } else { + terminalWorkspaceEndpoint } - } else { - terminalWorkspaceEndpoint + } + .onChange(of: workspace.layout != nil) { _, hasLayout in + paneZoomPresentation.layoutAvailabilityDidChange(hasLayout: hasLayout) } #else Group { detailSurfaceContent } @@ -178,11 +183,6 @@ struct WorkspaceDetailView: View { .onChange(of: store.supportsChatArtifactGallery) { _, _ in visibleArtifactCount = 0 } - .onChange(of: workspace.layout == nil) { _, layoutIsMissing in - if layoutIsMissing { - paneZoomPresentation.presentationDidChange(isTerminalPresented: true) - } - } .closeWorkspaceConfirmation( isPresented: $isConfirmingClose, confirm: confirmCloseWorkspaceFromMenu From f5293f765101847afb3bdf4ceeaf142a916aaa7f Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 01:06:39 -0700 Subject: [PATCH 43/78] fix(ios): reconcile pane layout merge decoding --- .../Sources/CMUXMobileCore/MobileStateSyncRecords.swift | 1 + .../Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift index 605d527367a3..d2605bd98761 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileStateSyncRecords.swift @@ -172,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 { diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift index 6d5521f41b1e..0c7b53c69180 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileSyncWorkspaceListResponse.swift @@ -134,7 +134,7 @@ public struct MobileSyncWorkspaceListResponse: Decodable, Sendable { lastActivityAt: Double?, hasUnread: Bool?, terminals: [Terminal], - layout: MobileWorkspaceLayout? + layout: MobileWorkspaceLayout? = nil ) { self.id = id self.windowID = windowID From 2e156bb1d1f1fa8c1cfbe578bceff5d4f1150d06 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 02:56:58 -0700 Subject: [PATCH 44/78] test(ios): assert pane transition endpoint stability --- ios/cmuxUITests/cmuxUITests.swift | 85 ++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 17fa85df5c7d..124abbcc751c 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -2258,7 +2258,12 @@ final class cmuxUITests: XCTestCase { defer { app.terminate() } XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) - XCTAssertTrue(app.buttons["MobileWorkspaceBackButton"].exists) + let backButton = app.buttons["MobileWorkspaceBackButton"] + let titleMenu = app.buttons["MobileWorkspaceTitleMenu"] + XCTAssertTrue(backButton.waitForExistence(timeout: 4)) + XCTAssertTrue(titleMenu.waitForExistence(timeout: 4)) + let terminalBackFrame = try XCTUnwrap(waitForToolbarFrame(of: backButton, timeout: 4)) + let terminalTitleFrame = try XCTUnwrap(waitForToolbarFrame(of: titleMenu, timeout: 4)) XCTAssertFalse( waitForPaneMap( app.otherElements["MobilePaneMapOverlay"], @@ -2301,9 +2306,19 @@ final class cmuxUITests: XCTestCase { let overlay = app.otherElements["MobilePaneMapOverlay"] XCTAssertTrue(waitForPaneMap(overlay, in: app, toBeActive: true)) XCTAssertTrue( - app.buttons["MobileWorkspaceBackButton"].exists, + 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 leftTopPane = app.descendants(matching: .any)[ "MobilePaneMapPane-preview-pane-left-top" ] @@ -2336,6 +2351,12 @@ final class cmuxUITests: XCTestCase { 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)) @@ -4950,6 +4971,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, From 05841375d0ccc837505873256fb9911999337b9d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 03:15:56 -0700 Subject: [PATCH 45/78] refactor(ios): model pane geometry as values --- .../PaneMapCollectionView.swift | 5 +-- .../CmuxMobileShellUI/PaneMapTileView.swift | 35 ++++++++++--------- .../PaneMapTerminalPreviewLayoutTests.swift | 11 +++--- 3 files changed, 28 insertions(+), 23 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index db38da003d74..70ec7491faf7 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -108,6 +108,7 @@ struct PaneMapCollectionView: UIViewRepresentable { private var authoritativeItemsByID: [String: PaneMapCollectionItem] private var reorderState: PaneMapReorderState private var selectionArbitration = PaneMapSelectionArbitration() + private let tileMetrics = PaneMapTileMetrics() init(parent: PaneMapCollectionView) { self.parent = parent @@ -350,7 +351,7 @@ struct PaneMapCollectionView: UIViewRepresentable { let cell = collectionView.cellForItem(at: indexPath) else { return false } - let previewHeight = cell.bounds.height - PaneMapTileMetrics.captionHeight + let previewHeight = cell.bounds.height - tileMetrics.captionHeight let paneControlsBand = CGRect( x: cell.frame.minX, y: cell.frame.minY + previewHeight - 50, @@ -376,7 +377,7 @@ struct PaneMapCollectionView: UIViewRepresentable { parameters.backgroundColor = .clear parameters.visiblePath = UIBezierPath( roundedRect: cell.bounds, - cornerRadius: PaneMapTileMetrics.cornerRadius + cornerRadius: tileMetrics.cornerRadius ) return parameters } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index c71e82fb4450..c1368c612966 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -3,9 +3,9 @@ import CmuxMobileShellModel import CmuxMobileSupport import SwiftUI -enum PaneMapTileMetrics { - static let captionHeight: CGFloat = 38 - static let cornerRadius: CGFloat = 16 +struct PaneMapTileMetrics: Equatable { + let captionHeight: CGFloat = 38 + let cornerRadius: CGFloat = 16 } struct PaneMapTerminalCanvasLayout: Equatable { @@ -71,13 +71,13 @@ struct PaneMapTerminalCanvasLayout: Equatable { } } -enum PaneMapTabStripMetrics { - static let tabWidth: CGFloat = 28 - static let spacing: CGFloat = 2 - static let padding: CGFloat = 3 - static let maximumWidth: CGFloat = 132 +struct PaneMapTabStripMetrics: Equatable { + let tabWidth: CGFloat = 28 + let spacing: CGFloat = 2 + let padding: CGFloat = 3 + let maximumWidth: CGFloat = 132 - static func width(tabCount: Int) -> CGFloat { + func width(tabCount: Int) -> CGFloat { guard tabCount > 0 else { return 0 } let contentWidth = (CGFloat(tabCount) * tabWidth) @@ -94,6 +94,7 @@ struct PaneMapTileView: View { let zoomNamespace: Namespace.ID let selectPreviewSurface: (String) -> Void let jumpToTerminal: (String) -> Void + private var metrics: PaneMapTileMetrics { PaneMapTileMetrics() } var body: some View { VStack(spacing: 0) { @@ -108,7 +109,7 @@ struct PaneMapTileView: View { in: zoomNamespace ) PaneMapTileCaption(item: item, terminalTheme: terminalTheme) - .frame(height: PaneMapTileMetrics.captionHeight) + .frame(height: metrics.captionHeight) } .accessibilityElement(children: .contain) .accessibilityLabel(paneAccessibilityLabel) @@ -137,6 +138,7 @@ private struct PaneMapPreviewCard: View { 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 { @@ -145,7 +147,7 @@ private struct PaneMapPreviewCard: View { var body: some View { let shape = RoundedRectangle( - cornerRadius: PaneMapTileMetrics.cornerRadius, + cornerRadius: metrics.cornerRadius, style: .continuous ) @@ -476,10 +478,11 @@ private struct PaneMapTabSwitcher: View { let selectedSurfaceID: String? let terminalTheme: TerminalTheme let selectPreviewSurface: (String) -> Void + private var metrics: PaneMapTabStripMetrics { PaneMapTabStripMetrics() } var body: some View { ScrollView(.horizontal) { - HStack(spacing: 2) { + HStack(spacing: metrics.spacing) { ForEach(pane.surfaces, id: \.id) { surface in let isSelected = surface.id == selectedSurfaceID Button { @@ -492,7 +495,7 @@ private struct PaneMapTabSwitcher: View { ? terminalTheme.terminalBackgroundColor : terminalTheme.terminalChromeForegroundColor.opacity(0.82) ) - .frame(width: 28, height: 28) + .frame(width: metrics.tabWidth, height: metrics.tabWidth) .background( isSelected ? terminalTheme.terminalChromeForegroundColor.opacity(0.9) @@ -507,12 +510,12 @@ private struct PaneMapTabSwitcher: View { .accessibilityIdentifier("MobilePaneMapTab-\(surface.id)") } } - .padding(3) + .padding(metrics.padding) } .scrollIndicators(.hidden) .frame( - width: PaneMapTabStripMetrics.width(tabCount: pane.surfaces.count), - height: 34 + width: metrics.width(tabCount: pane.surfaces.count), + height: metrics.tabWidth + (metrics.padding * 2) ) .mobileGlassPill() .accessibilityIdentifier("MobilePaneMapTabStrip-\(pane.id)") diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift index 11878091b4eb..fca6d5d1109a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift @@ -33,10 +33,11 @@ import Testing @Suite struct PaneMapTabStripMetricsTests { @Test func stripHugsTabsUntilItsMaximumWidth() { - #expect(PaneMapTabStripMetrics.width(tabCount: 2) == 64) - #expect(PaneMapTabStripMetrics.width(tabCount: 3) == 94) - #expect(PaneMapTabStripMetrics.width(tabCount: 4) == 124) - #expect(PaneMapTabStripMetrics.width(tabCount: 5) == 132) - #expect(PaneMapTabStripMetrics.width(tabCount: 20) == 132) + 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) } } From 86f10d08ec97d8e9b56d11d893d5bb36f20c0236 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 03:37:25 -0700 Subject: [PATCH 46/78] test(ios): query inert pane title by identifier --- ios/cmuxUITests/cmuxUITests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 124abbcc751c..6bc6402b46c8 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -2259,7 +2259,7 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(app.otherElements["PanesTabsPreviewHost"].waitForExistence(timeout: 8)) let backButton = app.buttons["MobileWorkspaceBackButton"] - let titleMenu = app.buttons["MobileWorkspaceTitleMenu"] + let titleMenu = workspaceTitleElement(in: app) XCTAssertTrue(backButton.waitForExistence(timeout: 4)) XCTAssertTrue(titleMenu.waitForExistence(timeout: 4)) let terminalBackFrame = try XCTUnwrap(waitForToolbarFrame(of: backButton, timeout: 4)) From 6c2d150904a8005ff9a8e18638a938e3fd94b167 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 04:09:04 -0700 Subject: [PATCH 47/78] test(ios): mirror workspace toolbar in pane preview --- .../Debug/PanesTabsPreviewHost.swift | 104 +++++++++++++++--- 1 file changed, 90 insertions(+), 14 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 1b8b890c2795..3ae2ec46f0c4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -25,6 +25,7 @@ struct PanesTabsPreviewHost: View { @State private var paneMapRefreshTrigger = 0 @State private var fixtureLayoutRevision = 0 @State private var isPaneMapRefreshing = false + @State private var contentWidth: CGFloat = 0 private let terminalTheme = TerminalTheme.monokai private let workspace = MobileWorkspacePreview( @@ -168,9 +169,10 @@ struct PanesTabsPreviewHost: View { refreshingChanged: { isPaneMapRefreshing = $0 } ) .accessibilityHidden(paneZoomPresentation.isTerminalPresented) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(workspace.name) .mobileTerminalNavigationChrome(theme: terminalTheme) - .toolbar { paneMapToolbar } + .toolbar { previewToolbar(mode: .paneMap) } .navigationBarBackButtonHidden(true) } terminal: { terminalPreviewEndpoint @@ -197,9 +199,10 @@ struct PanesTabsPreviewHost: View { .equatable() } .ignoresSafeArea(.keyboard, edges: .bottom) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(workspace.name) .mobileTerminalNavigationChrome(theme: terminalTheme) - .toolbar { terminalToolbar } + .toolbar { previewToolbar(mode: .terminal) } .accessibilityIdentifier("PanesTabsPreviewHost") } @@ -239,12 +242,93 @@ struct PanesTabsPreviewHost: View { paneZoomPresentation.sourceSurfaceID ?? selectedSurfaceID } + private enum PreviewToolbarMode { + case paneMap + case terminal + } + @ToolbarContentBuilder - private var paneMapToolbar: some ToolbarContent { - ToolbarItem(placement: .topBarLeading) { + private func previewToolbar(mode: PreviewToolbarMode) -> some ToolbarContent { + ToolbarItem(id: "workspace-back", placement: .topBarLeading) { WorkspaceBackButton(unreadCount: 2, action: {}) } - ToolbarItem(placement: .topBarTrailing) { + if #available(iOS 26.0, *) { + ToolbarSpacer(.fixed, placement: .topBarLeading) + } + ToolbarItem(id: "workspace-title", placement: .topBarLeading) { + previewWorkspaceTitleMenu(mode: mode) + } + ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { + previewToolbarTrailingContent(mode: mode) + } + } + + private func previewWorkspaceTitleMenu(mode: PreviewToolbarMode) -> some View { + let value = WorkspaceTitleMenuValue( + contentWidth: contentWidth, + hasBackButton: true, + hasTrailingCluster: true, + hasChatToggle: false, + 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( + workspaceName: workspace.name, + layout: layout, + phoneSelectedSurfaceID: selectedSurfaceID, + agentStateKindsBySurfaceID: agentStateKindsBySurfaceID + ).countSubtitle + case .terminal: + return workspace.terminals.first { + $0.id.rawValue == selectedSurfaceID + }?.name + } + } + + @ViewBuilder + private func previewToolbarTrailingContent(mode: PreviewToolbarMode) -> some View { + switch mode { + case .paneMap: HStack(spacing: 8) { Button { paneMapRefreshTrigger &+= 1 @@ -266,15 +350,7 @@ struct PanesTabsPreviewHost: View { ) .accessibilityIdentifier("MobilePaneMapDone") } - } - } - - @ToolbarContentBuilder - private var terminalToolbar: some ToolbarContent { - ToolbarItem(placement: .topBarLeading) { - WorkspaceBackButton(unreadCount: 2, action: {}) - } - ToolbarItem(placement: .topBarTrailing) { + case .terminal: WorkspaceUtilitiesMenu( showsViewAsText: false, showsPaneMap: true, From 5562acf229627bfd5ca04816204a3220b1c9de67 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 04:47:38 -0700 Subject: [PATCH 48/78] fix(ios): stabilize shared workspace title geometry --- .../MobileLeadingToolbarTitleWidth.swift | 1 - .../CmuxMobileShellUI/WorkspaceDetailView.swift | 4 +++- .../CmuxMobileShellUI/WorkspaceTitleMenu.swift | 16 ++++------------ .../WorkspaceTitleMenuValue.swift | 9 +++++++++ .../WorkspaceTitleMenuValueTests.swift | 11 +++++++++++ 5 files changed, 27 insertions(+), 14 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift index 5188fbe0f1c8..1dc7d3258a0d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift @@ -17,7 +17,6 @@ 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 } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index be0893bd7b6e..35c7a1fa71a0 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -318,7 +318,9 @@ struct WorkspaceDetailView: View { contentWidth: contentWidth, hasBackButton: backButtonConfiguration != nil, hasTrailingCluster: true, - hasChatToggle: mode == .terminal && shouldShowChatToggle, + // Reserve the same leading-title geometry in both endpoints even + // though the chat control itself only appears in terminal mode. + hasChatToggle: shouldShowChatToggle, isEnabled: hasTitleMenuActions, workspaceName: workspace.name, hasUnread: workspace.hasUnread, 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..8ed010bf8c50 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift @@ -15,4 +15,13 @@ struct WorkspaceTitleMenuValue: Equatable { let canCloseWorkspace: Bool let labelToken: WorkspaceTitleMenuLabelToken let terminalTheme: TerminalTheme + + var titleWidth: CGFloat { + MobileLeadingToolbarTitleWidth( + contentWidth: contentWidth, + hasBackButton: hasBackButton, + hasTrailingCluster: hasTrailingCluster, + hasChatToggle: hasChatToggle + ).cap + } } diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift index cd358a6a1876..0861a219714f 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 From d129f58ccffae952798839ddc045945052453dd9 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 13:25:21 -0700 Subject: [PATCH 49/78] fix(ios): stabilize pane map toolbar geometry --- .../AgentChatDemoScreen.swift | 1 + .../Debug/PanesTabsPreviewHost.swift | 27 +++-------- .../MobileLeadingToolbarTitleWidth.swift | 7 ++- .../PaneMapToolbarControls.swift | 46 +++++++++++++++++++ .../PaneMapToolbarMetrics.swift | 12 +++++ .../WorkspaceDetailView.swift | 29 +++--------- .../WorkspaceTitleMenuValue.swift | 4 +- .../MobileLeadingToolbarTitleWidthTests.swift | 32 ++++++++++++- .../WorkspaceTitleMenuValueTests.swift | 1 + ios/cmuxUITests/cmuxUITests.swift | 28 +++++++++++ 10 files changed, 139 insertions(+), 48 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarMetrics.swift 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/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 3ae2ec46f0c4..67ce178af414 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -269,6 +269,7 @@ struct PanesTabsPreviewHost: View { hasBackButton: true, hasTrailingCluster: true, hasChatToggle: false, + reservesPaneMapControls: true, isEnabled: true, workspaceName: workspace.name, hasUnread: false, @@ -329,27 +330,11 @@ struct PanesTabsPreviewHost: View { private func previewToolbarTrailingContent(mode: PreviewToolbarMode) -> some View { switch mode { case .paneMap: - HStack(spacing: 8) { - Button { - paneMapRefreshTrigger &+= 1 - } label: { - if isPaneMapRefreshing { - ProgressView() - } else { - Image(systemName: "arrow.clockwise") - } - } - .accessibilityLabel( - L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh") - ) - .accessibilityIdentifier("MobilePaneMapRefresh") - - Button( - L10n.string("mobile.paneMap.done", defaultValue: "Done"), - action: returnToTerminalFromPaneMap - ) - .accessibilityIdentifier("MobilePaneMapDone") - } + PaneMapToolbarControls( + isRefreshing: isPaneMapRefreshing, + refresh: { paneMapRefreshTrigger &+= 1 }, + done: returnToTerminalFromPaneMap + ) case .terminal: WorkspaceUtilitiesMenu( showsViewAsText: false, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileLeadingToolbarTitleWidth.swift index 1dc7d3258a0d..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 @@ -21,9 +22,13 @@ struct MobileLeadingToolbarTitleWidth { 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/PaneMapToolbarControls.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift new file mode 100644 index 000000000000..b6d0562d1d24 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift @@ -0,0 +1,46 @@ +import CmuxMobileSupport +import SwiftUI + +struct PaneMapToolbarControls: View { + let isRefreshing: Bool + let refresh: () -> Void + let done: () -> Void + + var body: some View { + HStack(spacing: PaneMapToolbarMetrics.spacing) { + 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") + + 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") + } + .frame( + width: PaneMapToolbarMetrics.trailingClusterWidth, + height: PaneMapToolbarMetrics.height, + alignment: .trailing + ) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("MobilePaneMapToolbarControls") + } +} 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/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 35c7a1fa71a0..ff2ec6e75e53 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -321,6 +321,7 @@ struct WorkspaceDetailView: View { // 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, @@ -435,29 +436,11 @@ struct WorkspaceDetailView: View { } private var paneMapToolbarControls: some View { - HStack(spacing: 8) { - Button(action: refreshPaneMapFromToolbar) { - Group { - if isPaneMapRefreshing { - ProgressView() - .controlSize(.small) - } else { - Image(systemName: "arrow.clockwise") - } - } - .frame(width: 24, height: 24) - } - .disabled(isPaneMapRefreshing) - .accessibilityLabel(L10n.string("mobile.paneMap.refresh", defaultValue: "Refresh")) - .accessibilityIdentifier("MobilePaneMapRefresh") - - Button(action: returnToTerminalFromPaneMap) { - Text(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .font(.subheadline.weight(.semibold)) - } - .accessibilityLabel(L10n.string("mobile.paneMap.done", defaultValue: "Done")) - .accessibilityIdentifier("MobilePaneMapDone") - } + PaneMapToolbarControls( + isRefreshing: isPaneMapRefreshing, + refresh: refreshPaneMapFromToolbar, + done: returnToTerminalFromPaneMap + ) } #endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceTitleMenuValue.swift index 8ed010bf8c50..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 @@ -21,7 +22,8 @@ struct WorkspaceTitleMenuValue: Equatable { contentWidth: contentWidth, hasBackButton: hasBackButton, hasTrailingCluster: hasTrailingCluster, - hasChatToggle: hasChatToggle + hasChatToggle: hasChatToggle, + reservesPaneMapControls: reservesPaneMapControls ).cap } } 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/WorkspaceTitleMenuValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift index 0861a219714f..77c58fa8d1e6 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceTitleMenuValueTests.swift @@ -65,6 +65,7 @@ import Testing hasBackButton: true, hasTrailingCluster: true, hasChatToggle: true, + reservesPaneMapControls: true, isEnabled: true, workspaceName: "Workspace", hasUnread: false, diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 6bc6402b46c8..78b631c2edb0 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -2260,10 +2260,15 @@ final class cmuxUITests: XCTestCase { 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"], @@ -2319,6 +2324,29 @@ final class cmuxUITests: XCTestCase { 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" ] From 4811f750589241409bda6f0f797cb22e9004a93c Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 13:54:02 -0700 Subject: [PATCH 50/78] fix(ios): remove visible pane numbers from deck --- .../Sources/CmuxMobileShellUI/SurfaceDeckBar.swift | 13 ------------- ios/cmuxUITests/cmuxUITests.swift | 2 +- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift index 84606362f7d4..402d3ca6fd20 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -94,19 +94,6 @@ struct SurfaceDeckBar: View, Equatable { private func paneGroup(_ group: SurfaceDeckValue.PaneGroup) -> some View { HStack(spacing: 2) { - Text(group.number, format: .number) - .font(.caption2.weight(.bold)) - .foregroundStyle(terminalTheme.terminalChromeForegroundColor.opacity(0.8)) - .padding(.horizontal, 7) - .padding(.vertical, 5) - .background( - Capsule().fill(terminalTheme.terminalChromeForegroundColor.opacity(0.10)) - ) - .accessibilityLabel( - paneAccessibilityLabel(number: group.number, totalCount: group.totalCount) - ) - .accessibilityIdentifier("MobileSurfaceDeckPaneNumber-\(group.id)") - ForEach(group.chips) { chip in surfaceChip(chip, paneNumber: group.number, paneCount: group.totalCount) } diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 78b631c2edb0..6b7a7368b31c 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -2295,7 +2295,7 @@ final class cmuxUITests: XCTestCase { XCTAssertTrue(leftBottomDeckGroup.exists) XCTAssertTrue(testsDeckGroup.exists) XCTAssertTrue(serverDeckGroup.exists) - XCTAssertTrue( + XCTAssertFalse( app.descendants(matching: .any)[ "MobileSurfaceDeckPaneNumber-preview-pane-left-top" ].exists From 53b92bfe8faf676dc70d8dc16e077dcd3dd9a7a1 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 14:09:13 -0700 Subject: [PATCH 51/78] fix(ios): retire superseded pending connect clients --- .../MobileShellComposite.swift | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index fde4dc5f95db..d5276fe152d7 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -807,6 +807,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } } + /// RPC client currently dialing but not yet adopted as ``remoteClient``. + /// A newer connect attempt supersedes this owner and must retire it before + /// asking the shared route registry for the same physical route again. + private var pendingConnectClient: MobileCoreRPCClient? /// Whether legacy connected-but-clientless shells use local iOS workspace creation. public var usesLocalWorkspaceCreationFallback: Bool { remoteClient == nil && connectionState == .connected @@ -7678,6 +7682,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { rawTerminalInputBuffer.clear() terminalInputRPCPipeline.clear() resumeRawTerminalInputDrainWaiters() + await releasePendingConnectClientForReplacement() + guard isConnectCurrent() else { return nil } let supportedKinds = runtime?.supportedRouteKinds ?? [] let supportedRoutes = supportedRoutes( for: ticket, @@ -7918,6 +7924,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { stackTokenForceRefreshGate: stackTokenForceRefreshGate, transportConnectObserver: transportConnectDiagnosticObserver ) + registerPendingConnectClient(client) + defer { clearPendingConnectClient(client) } for workspaceListRequest in workspaceListRequests { do { let requestTimeoutNanoseconds: UInt64 @@ -8600,6 +8608,21 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { await replaceRemoteClientAwaitingTeardownRegistration(with: nil) } + func releasePendingConnectClientForReplacement() async { + guard let previous = pendingConnectClient else { return } + pendingConnectClient = nil + await previous.disconnect() + } + + func registerPendingConnectClient(_ client: MobileCoreRPCClient) { + pendingConnectClient = client + } + + func clearPendingConnectClient(_ client: MobileCoreRPCClient) { + guard pendingConnectClient === client else { return } + pendingConnectClient = nil + } + /// Publish one remote-client ownership change synchronously. Callers choose /// whether teardown registration is fire-and-forget or an awaited handoff. private func replaceRemoteClientOwnership( From dff67f96b8e003433530bc4ff71f1160842ad291 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 16:43:34 -0700 Subject: [PATCH 52/78] fix(ios): anchor pane map toolbar items natively --- .../Debug/PanesTabsPreviewHost.swift | 47 +++++++------ .../PaneMapToolbarControls.swift | 68 ++++++++++++------- .../WorkspaceDetailView.swift | 50 +++++++------- 3 files changed, 91 insertions(+), 74 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 67ce178af414..461e062b53fb 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -258,8 +258,21 @@ struct PanesTabsPreviewHost: View { ToolbarItem(id: "workspace-title", placement: .topBarLeading) { previewWorkspaceTitleMenu(mode: mode) } - ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { - previewToolbarTrailingContent(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 + } } } @@ -326,26 +339,16 @@ struct PanesTabsPreviewHost: View { } } - @ViewBuilder - private func previewToolbarTrailingContent(mode: PreviewToolbarMode) -> some View { - switch mode { - case .paneMap: - PaneMapToolbarControls( - isRefreshing: isPaneMapRefreshing, - refresh: { paneMapRefreshTrigger &+= 1 }, - done: returnToTerminalFromPaneMap - ) - case .terminal: - WorkspaceUtilitiesMenu( - showsViewAsText: false, - showsPaneMap: true, - terminalTheme: terminalTheme, - presentPaneMap: presentPaneMap, - openTextSheet: {}, - copyDebugLogs: {}, - sendFeedback: {} - ) - } + private var previewToolbarTrailingContent: some View { + WorkspaceUtilitiesMenu( + showsViewAsText: false, + showsPaneMap: true, + terminalTheme: terminalTheme, + presentPaneMap: presentPaneMap, + openTextSheet: {}, + copyDebugLogs: {}, + sendFeedback: {} + ) } private var fixtureLayout: MobilePaneLayout? { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift index b6d0562d1d24..b7ad0f1bf48a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift @@ -8,32 +8,8 @@ struct PaneMapToolbarControls: View { var body: some View { HStack(spacing: PaneMapToolbarMetrics.spacing) { - 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") - - 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") + PaneMapRefreshToolbarButton(isRefreshing: isRefreshing, refresh: refresh) + PaneMapDoneToolbarButton(done: done) } .frame( width: PaneMapToolbarMetrics.trailingClusterWidth, @@ -44,3 +20,43 @@ struct PaneMapToolbarControls: View { .accessibilityIdentifier("MobilePaneMapToolbarControls") } } + +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/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index ff2ec6e75e53..e91fdc1178f5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -306,8 +306,21 @@ struct WorkspaceDetailView: View { .environment(\.colorScheme, store.activeTerminalTheme.terminalColorScheme) } } - ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { - workspaceToolbarTrailingContent(mode: mode) + 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) + } } } @@ -414,34 +427,19 @@ struct WorkspaceDetailView: View { } @ViewBuilder - private func workspaceToolbarTrailingContent( - mode: WorkspaceDetailToolbarMode - ) -> some View { - switch mode { - case .terminal: - HStack(spacing: 8) { - if let selectedTerminalID, - store.isAlternateScreen(surfaceID: selectedTerminalID), - displaySettings.showAltScreenNotice { - AltScreenNoticeButton { - displaySettings.showAltScreenNotice = false - } - .frame(width: 44, height: 44) + private var workspaceToolbarTrailingContent: some View { + HStack(spacing: 8) { + if let selectedTerminalID, + store.isAlternateScreen(surfaceID: selectedTerminalID), + displaySettings.showAltScreenNotice { + AltScreenNoticeButton { + displaySettings.showAltScreenNotice = false } - toolbarTrailingCluster + .frame(width: 44, height: 44) } - case .paneMap: - paneMapToolbarControls + toolbarTrailingCluster } } - - private var paneMapToolbarControls: some View { - PaneMapToolbarControls( - isRefreshing: isPaneMapRefreshing, - refresh: refreshPaneMapFromToolbar, - done: returnToTerminalFromPaneMap - ) - } #endif func detailContent() -> some View { From 70a69a9f81ce62118ad70ae6f0bc0129a69d5a84 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 20:18:24 -0700 Subject: [PATCH 53/78] Fix iOS pane zoom transition background --- .../Debug/PanesTabsPreviewHost.swift | 249 +++++++++++++++--- .../PaneZoomPresentationState.swift | 93 +++++++ .../WorkspaceDetailView.swift | 57 ++-- 3 files changed, 336 insertions(+), 63 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 461e062b53fb..05629168c2f5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -2,10 +2,13 @@ import CMUXMobileCore import CmuxMobileShellModel import CmuxMobileSupport +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" @@ -26,6 +29,7 @@ struct PanesTabsPreviewHost: View { @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( @@ -149,44 +153,63 @@ struct PanesTabsPreviewHost: View { ] var body: some View { - if let layout = fixtureLayout { - PaneZoomNavigationStack(presentation: $paneZoomPresentation) { - PaneMapOverlay( - value: PaneMapValue( - workspaceName: workspace.name, - 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) - } terminal: { - terminalPreviewEndpoint + Group { + if let layout = fixtureLayout { + PaneZoomNavigationStack( + presentation: $paneZoomPresentation, + terminalTheme: terminalTheme + ) { + PaneMapOverlay( + value: PaneMapValue( + workspaceName: workspace.name, + 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) - .navigationTransition( - .zoom( - sourceID: paneZoomSourceSurfaceID, - in: paneZoomNamespace + .background { autoplayDriver(for: .paneMap) } + } terminal: { + terminalPreviewEndpoint + .navigationBarBackButtonHidden(true) + .navigationTransition( + .zoom( + sourceID: paneZoomSourceSurfaceID, + in: paneZoomNamespace + ) ) - ) + } + } else { + terminalPreviewEndpoint + } + } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + .safeAreaInset(edge: .bottom, spacing: 0) { + if paneZoomPresentation.isTerminalPresented { + SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) + .equatable() + .transition(.opacity.combined(with: .move(edge: .bottom))) } - } else { - terminalPreviewEndpoint } + .ignoresSafeArea(paneZoomPresentation.isTerminalPresented ? .keyboard : [], edges: .bottom) + .animation(.snappy(duration: 0.18), value: paneZoomPresentation.isTerminalPresented) } private var terminalPreviewEndpoint: some View { @@ -194,15 +217,15 @@ struct PanesTabsPreviewHost: View { terminalTheme.terminalBackgroundColor .frame(maxWidth: .infinity, maxHeight: .infinity) } - .safeAreaInset(edge: .bottom, spacing: 0) { - SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) - .equatable() + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea(.container, edges: [.horizontal, .top, .bottom]) } - .ignoresSafeArea(.keyboard, edges: .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") } @@ -238,6 +261,156 @@ struct PanesTabsPreviewHost: View { 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 timer: Timer? + 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)") + timer = Timer.scheduledTimer(withTimeInterval: plan.delay, repeats: false) { [weak self] _ in + MainActor.assumeIsolated { + guard 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() { + timer?.invalidate() + timer = 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 } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index bd039b495968..e9d7f20df768 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -1,4 +1,8 @@ +import CMUXMobileCore import SwiftUI +#if os(iOS) +import UIKit +#endif /// Stable routing state for the native pane-map zoom presentation. struct PaneZoomPresentationState: Equatable { @@ -50,6 +54,7 @@ struct PaneZoomPresentationState: Equatable { /// path starts with the restored terminal already installed on the first frame. struct PaneZoomNavigationStack: View { @Binding var presentation: PaneZoomPresentationState + let terminalTheme: TerminalTheme @ViewBuilder let root: () -> Root @ViewBuilder let terminal: () -> Terminal @@ -62,6 +67,17 @@ struct PaneZoomNavigationStack: View { } } } + .background { + terminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + #if os(iOS) + .background { + PaneZoomNavigationHostBackground( + color: UIColor(paneZoomTerminalBackground: terminalTheme) + ) + } + #endif #if os(iOS) .toolbarVisibility(.hidden, for: .tabBar) #endif @@ -74,3 +90,80 @@ struct PaneZoomNavigationStack: View { ) } } + +#if os(iOS) +private struct PaneZoomNavigationHostBackground: UIViewRepresentable { + let color: UIColor + + func makeUIView(context: Context) -> BackgroundBridgeView { + let view = BackgroundBridgeView() + view.color = color + return view + } + + func updateUIView(_ uiView: BackgroundBridgeView, context: Context) { + uiView.color = color + uiView.applyBackground() + } + + final class BackgroundBridgeView: UIView { + 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 { return } + + var ancestor = superview + var hops = 0 + while let view = ancestor, !(view is UIWindow), hops < 16 { + view.backgroundColor = color + ancestor = view.superview + hops += 1 + } + + var responder: UIResponder? = self + var responderHops = 0 + while let current = responder, responderHops < 32 { + if let viewController = current as? UIViewController { + viewController.view.backgroundColor = color + viewController.navigationController?.view.backgroundColor = color + } + if let navigationController = current as? UINavigationController { + navigationController.view.backgroundColor = color + } + responder = current.next + responderHops += 1 + } + } + } +} + +private extension UIColor { + convenience init(paneZoomTerminalBackground theme: TerminalTheme) { + let fallback = TerminalTheme.monokai.background + guard let rgb = TerminalTheme.rgbComponents(theme.background) + ?? TerminalTheme.rgbComponents(fallback) else { + self.init(white: 0, alpha: 1) + return + } + self.init( + red: CGFloat(rgb.red) / 255.0, + green: CGFloat(rgb.green) / 255.0, + blue: CGFloat(rgb.blue) / 255.0, + alpha: 1 + ) + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index e91fdc1178f5..7ab3befdde6f 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -120,7 +120,10 @@ struct WorkspaceDetailView: View { #if os(iOS) Group { if let layout = workspace.layout { - PaneZoomNavigationStack(presentation: $paneZoomPresentation) { + PaneZoomNavigationStack( + presentation: $paneZoomPresentation, + terminalTheme: store.activeTerminalTheme + ) { paneMapRoot(layout: layout) .accessibilityHidden(paneZoomPresentation.isTerminalPresented) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } @@ -142,6 +145,27 @@ struct WorkspaceDetailView: View { terminalWorkspaceEndpoint } } + .background { + store.activeTerminalTheme.terminalBackgroundColor + .ignoresSafeArea() + } + .safeAreaInset(edge: .bottom, spacing: 0) { + if shouldShowSurfaceDeck { + SurfaceDeckBar( + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme + ) + .equatable() + .transition(.opacity.combined(with: .move(edge: .bottom))) + } + } + // The terminal owns keyboard geometry. Ignoring keyboard avoidance + // while the deck shows keeps the deck at the physical bottom so the + // keyboard covers it instead of lifting it; chat/browser modes keep + // normal avoidance. + .ignoresSafeArea(shouldShowSurfaceDeck ? .keyboard : [], edges: .bottom) + .animation(.snappy(duration: 0.18), value: shouldShowSurfaceDeck) .onChange(of: workspace.layout != nil) { _, hasLayout in paneZoomPresentation.layoutAvailabilityDidChange(hasLayout: hasLayout) } @@ -156,33 +180,16 @@ struct WorkspaceDetailView: View { } #if os(iOS) + private var shouldShowSurfaceDeck: Bool { + activeSurface == .terminal + && paneZoomPresentation.isTerminalPresented + && surfaceDeckValue.shouldShow + } + private var terminalWorkspaceEndpoint: some View { - let deckValue = surfaceDeckValue let content = Group { detailSurfaceContent } - // Deck visibility must not change the content subtree's structural - // identity: branching around `content` would remount the terminal - // surface (and the chat/browser ZStack) every time the deck toggles. - // The branch lives inside the inset builder instead, and the - // keyboard-region parameter is data, not structure. - let showDeck = activeSurface == .terminal && deckValue.shouldShow - let contentWithSurfaceDeck = content - .safeAreaInset(edge: .bottom, spacing: 0) { - if showDeck { - SurfaceDeckBar( - value: deckValue, - actions: surfaceDeckActions, - terminalTheme: store.activeTerminalTheme - ) - .equatable() - } - } - // The terminal owns keyboard geometry. Ignoring keyboard avoidance - // while the deck shows keeps the deck at the physical bottom so the - // keyboard covers it instead of lifting it; chat/browser modes keep - // normal avoidance. - .ignoresSafeArea(showDeck ? .keyboard : [], edges: .bottom) - return contentWithSurfaceDeck + return content .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } .navigationTitle(systemNavigationTitle) .mobileTerminalNavigationChrome(theme: store.activeTerminalTheme) From 58f0bcbfab82c12f85322319891b1cb0f98aa62f Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:09:47 -0700 Subject: [PATCH 54/78] fix(ios): retain pane deck outside zoom route --- .../Debug/PanesTabsPreviewHost.swift | 21 +++++++------ .../CmuxMobileShellUI/SurfaceDeckBar.swift | 31 +++++++++++++++++++ .../WorkspaceDetailView.swift | 29 +++++++---------- 3 files changed, 55 insertions(+), 26 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 05629168c2f5..d74672514a99 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -193,23 +193,26 @@ struct PanesTabsPreviewHost: View { ) ) } + .mobileSurfaceDeckInset( + isVisible: paneZoomPresentation.isTerminalPresented, + value: deckValue, + actions: deckActions, + terminalTheme: terminalTheme + ) } else { terminalPreviewEndpoint + .mobileSurfaceDeckInset( + isVisible: paneZoomPresentation.isTerminalPresented, + value: deckValue, + actions: deckActions, + terminalTheme: terminalTheme + ) } } .background { terminalTheme.terminalBackgroundColor .ignoresSafeArea() } - .safeAreaInset(edge: .bottom, spacing: 0) { - if paneZoomPresentation.isTerminalPresented { - SurfaceDeckBar(value: deckValue, actions: deckActions, terminalTheme: terminalTheme) - .equatable() - .transition(.opacity.combined(with: .move(edge: .bottom))) - } - } - .ignoresSafeArea(paneZoomPresentation.isTerminalPresented ? .keyboard : [], edges: .bottom) - .animation(.snappy(duration: 0.18), value: paneZoomPresentation.isTerminalPresented) } private var terminalPreviewEndpoint: some View { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift index 402d3ca6fd20..697cb787d54d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -310,3 +310,34 @@ struct SurfaceDeckBar: View, Equatable { } } } + +#if os(iOS) +extension View { + /// Installs the deck on a concrete layout container so it remains outside + /// pane-map navigation transitions while still contributing a real safe-area + /// inset to the terminal viewport. Applying `safeAreaInset` to a conditional + /// `Group` drops the deck around nested navigation stacks 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/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 7ab3befdde6f..15d4f468f293 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -141,31 +141,26 @@ struct WorkspaceDetailView: View { ) ) } + .mobileSurfaceDeckInset( + isVisible: shouldShowSurfaceDeck, + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme + ) } else { terminalWorkspaceEndpoint + .mobileSurfaceDeckInset( + isVisible: shouldShowSurfaceDeck, + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme + ) } } .background { store.activeTerminalTheme.terminalBackgroundColor .ignoresSafeArea() } - .safeAreaInset(edge: .bottom, spacing: 0) { - if shouldShowSurfaceDeck { - SurfaceDeckBar( - value: surfaceDeckValue, - actions: surfaceDeckActions, - terminalTheme: store.activeTerminalTheme - ) - .equatable() - .transition(.opacity.combined(with: .move(edge: .bottom))) - } - } - // The terminal owns keyboard geometry. Ignoring keyboard avoidance - // while the deck shows keeps the deck at the physical bottom so the - // keyboard covers it instead of lifting it; chat/browser modes keep - // normal avoidance. - .ignoresSafeArea(shouldShowSurfaceDeck ? .keyboard : [], edges: .bottom) - .animation(.snappy(duration: 0.18), value: shouldShowSurfaceDeck) .onChange(of: workspace.layout != nil) { _, hasLayout in paneZoomPresentation.layoutAvailabilityDidChange(hasLayout: hasLayout) } From cac569f40760dc8582f14e2be52b2b3f847c7c17 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:08:15 -0700 Subject: [PATCH 55/78] fix(ios): reconcile pane interactions with Mac authority --- .github/workflows/test-ios.yml | 4 - ...ileTerminalRenderGridFrame+CellWidth.swift | 23 +++--- ...erminalRenderGridPaneMapPreviewTests.swift | 36 +++++++++ ...MobileShellComposite+PaneMapPreviews.swift | 6 ++ ...obileShellComposite+WorkspaceActions.swift | 76 +++++++++++++++++-- ...leShellRenderGridLivenessTestSupport.swift | 14 ++++ .../MobileShellWorkspaceCapabilityTests.swift | 67 ++++++++++++++++ .../PaneMapPreviewFetchTests.swift | 25 ++++++ .../Debug/PanesTabsPreviewHost.swift | 24 +++--- .../PaneMapCollectionView.swift | 21 +++-- .../CmuxMobileShellUI/PaneMapOverlay.swift | 11 ++- .../PaneMapReorderState.swift | 12 ++- .../CmuxMobileShellUI/PaneMapTileView.swift | 17 ++++- .../PaneMapToolbarControls.swift | 20 ----- .../PaneZoomPresentationState.swift | 67 +++++++++++----- .../WorkspaceDetailView.swift | 62 +++++++-------- .../PaneMapCollectionLayoutEngineTests.swift | 48 ++++++++++-- .../PaneMapTerminalPreviewLayoutTests.swift | 14 ++++ ...rkspaceListTableCoordinatorDropTests.swift | 3 - ...anonicalizer+PortableAgentExecutable.swift | 2 +- Sources/Workspace+MobilePaneReorder.swift | 18 +++-- ios/cmuxUITests/cmuxUITests.swift | 1 + 22 files changed, 445 insertions(+), 126 deletions(-) diff --git a/.github/workflows/test-ios.yml b/.github/workflows/test-ios.yml index dc51dee1ca93..ccbb48518245 100644 --- a/.github/workflows/test-ios.yml +++ b/.github/workflows/test-ios.yml @@ -166,10 +166,6 @@ jobs: run: | swift test --package-path Packages/iOS/CmuxMobileRPC - - name: Run CmuxMobileShellModel package tests - run: | - swift test --package-path Packages/iOS/CmuxMobileShellModel - - name: Run CmuxMobileShell package tests run: | # iOS shell replay/liveness regressions live in this package target. diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift index d3eecc993e5e..9218cdfb9c83 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+CellWidth.swift @@ -61,20 +61,25 @@ extension MobileTerminalRenderGridFrame.RowSpan { guard !hasUntrustedExpansionCandidate else { return nil } - var remaining = gridCellWidth - total - for index in widths.indices where remaining > 0 && widths[index] < 2 { - guard expandable[index] else { continue } + 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 - remaining -= 1 } - guard remaining == 0 else { return nil } } else if total > gridCellWidth { - var excess = total - gridCellWidth - for index in widths.indices.reversed() where excess > 0 && widths[index] > 1 { + 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 - excess -= 1 } - guard excess == 0 else { return nil } } return widths } diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift index bd6419c456d4..493643361996 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift @@ -203,6 +203,42 @@ import Testing #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]) + } + private static func frame( columns: Int, rowCount: Int, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift index 10679ccea069..ad1a4b2a954b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift @@ -54,6 +54,12 @@ extension MobileShellComposite { 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 diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift index 27461c7a7fce..e93c213cfe56 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift @@ -36,7 +36,8 @@ extension MobileShellComposite { method: "workspace.pane.reorder", params: params, id: id, - actionName: "pane_reorder" + actionName: "pane_reorder", + authoritativeWorkspaceListResponse: true ) } @@ -408,7 +409,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( @@ -421,7 +423,8 @@ extension MobileShellComposite { ), logID: id.rawValue, actionName: actionName, - refreshAfterMutation: refreshAfterMutation + refreshAfterMutation: refreshAfterMutation, + authoritativeWorkspaceListResponse: authoritativeWorkspaceListResponse ) } @@ -460,7 +463,8 @@ extension MobileShellComposite { hostDisplayName: String?, logID: String, actionName: String, - refreshAfterMutation: Bool = true + refreshAfterMutation: Bool = true, + authoritativeWorkspaceListResponse: Bool = false ) async -> Result { // Route the mutation to the Mac that actually OWNS this workspace. The // aggregated list can include rows from secondary Macs, whose connection is @@ -478,9 +482,22 @@ extension MobileShellComposite { return .failure(.notConnected(hostDisplayName: hostDisplayName)) } let generation = connectionGeneration + var appliedAuthoritativeWorkspaceList = false do { let request = try MobileCoreRPCClient.requestData(method: method, params: params) - _ = try await client.sendRequest(request) + let responseData = try await client.sendRequest(request) + if authoritativeWorkspaceListResponse { + let response = try MobileSyncWorkspaceListResponse.decode(responseData) + guard applyAuthoritativeWorkspaceMutationResponse( + response, + target: target, + client: client, + connectionGeneration: generation + ) else { + throw MobileShellConnectionError.invalidResponse + } + appliedAuthoritativeWorkspaceList = true + } } catch { if disconnectForAuthorizationFailureIfNeeded(error) { return .failure(.authorizationFailed(hostDisplayName: hostDisplayName)) @@ -502,12 +519,59 @@ 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) } 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) + return true + } + + guard let ownerKey = target.ownerKey, + let subscription = secondaryMacSubscriptions[ownerKey], + subscription.client === client, + !subscription.isTransitioningToFocus else { + return false + } + subscription.workspaceRefreshGeneration &+= 1 + 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/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 570411f9b194..e3d6450fe366 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -76,6 +76,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?)] = [] @@ -251,6 +252,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) } @@ -476,6 +482,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) { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift index b149e21abbd7..9cf9528bced5 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift @@ -178,6 +178,73 @@ 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() + } + 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 index 72942cbd3584..7a48557a028d 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift @@ -128,6 +128,31 @@ import Testing 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 diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index d74672514a99..d683f56d60a9 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -319,7 +319,7 @@ struct PanesTabsPreviewHost: View { @MainActor final class Coordinator { - private var timer: Timer? + private var task: Task? private var scheduledKey: String? func update(_ parent: PanesTabsAutoplayDriver) { @@ -344,20 +344,24 @@ struct PanesTabsPreviewHost: View { cancel() scheduledKey = nextKey PanesTabsPreviewHost.logger.notice("autoplay: schedule \(nextKey, privacy: .public)") - timer = Timer.scheduledTimer(withTimeInterval: plan.delay, repeats: false) { [weak self] _ in - MainActor.assumeIsolated { - guard parent.step == plan.expectedStep else { return } - PanesTabsPreviewHost.logger.notice("autoplay: fire \(nextKey, privacy: .public)") - parent.step = plan.nextStep - parent.run(plan.action) - self?.cancel() + 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() { - timer?.invalidate() - timer = nil + task?.cancel() + task = nil scheduledKey = nil } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index 70ec7491faf7..eb381a2b25d4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -109,6 +109,7 @@ struct PaneMapCollectionView: UIViewRepresentable { private var reorderState: PaneMapReorderState private var selectionArbitration = PaneMapSelectionArbitration() private let tileMetrics = PaneMapTileMetrics() + private let tabStripMetrics = PaneMapTabStripMetrics() init(parent: PaneMapCollectionView) { self.parent = parent @@ -116,7 +117,8 @@ struct PaneMapCollectionView: UIViewRepresentable { uniqueKeysWithValues: parent.items.map { ($0.id, $0) } ) reorderState = PaneMapReorderState( - authoritativePaneIDs: parent.items.map(\.id) + authoritativePaneIDs: parent.items.map(\.id), + authoritativeRevision: parent.layout.version ) } @@ -150,7 +152,10 @@ struct PaneMapCollectionView: UIViewRepresentable { return } - reorderState.reconcile(authoritativePaneIDs: items.map(\.id)) + reorderState.reconcile( + authoritativePaneIDs: items.map(\.id), + authoritativeRevision: parent.layout.version + ) reloadVisibleItems() } @@ -351,14 +356,16 @@ struct PaneMapCollectionView: UIViewRepresentable { let cell = collectionView.cellForItem(at: indexPath) else { return false } - let previewHeight = cell.bounds.height - tileMetrics.captionHeight - let paneControlsBand = CGRect( + let previewBounds = CGRect( x: cell.frame.minX, - y: cell.frame.minY + previewHeight - 50, + y: cell.frame.minY, width: cell.frame.width, - height: 50 + height: max(0, cell.bounds.height - tileMetrics.captionHeight) ) - return paneControlsBand.contains(collectionLocation) + return tabStripMetrics.frame( + in: previewBounds, + tabCount: orderedItems[indexPath.item].pane.surfaces.count + ).contains(collectionLocation) } func gestureRecognizer( diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index fa7e2e590c41..8927ee3bb151 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -90,6 +90,13 @@ struct PaneMapOverlay: View { 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() } } @@ -187,6 +194,8 @@ struct PaneMapOverlay: View { remainingTerminalSurfaceIDs ) guard !Task.isCancelled, refreshGeneration == generation else { return } - previewsBySurfaceID = frames.mapValues { $0.paneMapPreview() } + 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 index 83a2dd5b7c60..32efc5520082 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift @@ -15,6 +15,7 @@ struct PaneMapReorderState: Equatable { 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 @@ -23,9 +24,10 @@ struct PaneMapReorderState: Equatable { pendingRequest != nil } - init(authoritativePaneIDs: [String]) { + init(authoritativePaneIDs: [String], authoritativeRevision: Int) { self.visiblePaneIDs = authoritativePaneIDs self.authoritativePaneIDs = authoritativePaneIDs + self.authoritativeRevision = authoritativeRevision } mutating func beginMove(from sourceIndex: Int, to destinationIndex: Int) -> Request? { @@ -44,12 +46,18 @@ struct PaneMapReorderState: Equatable { return request } - mutating func reconcile(authoritativePaneIDs: [String]) { + mutating func reconcile( + authoritativePaneIDs: [String], + authoritativeRevision: Int + ) { + 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() diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift index c1368c612966..4ea2aa883b19 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapTileView.swift @@ -76,6 +76,11 @@ struct PaneMapTabStripMetrics: Equatable { 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 } @@ -85,6 +90,16 @@ struct PaneMapTabStripMetrics: Equatable { + (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. @@ -515,7 +530,7 @@ private struct PaneMapTabSwitcher: View { .scrollIndicators(.hidden) .frame( width: metrics.width(tabCount: pane.surfaces.count), - height: metrics.tabWidth + (metrics.padding * 2) + height: metrics.height ) .mobileGlassPill() .accessibilityIdentifier("MobilePaneMapTabStrip-\(pane.id)") diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift index b7ad0f1bf48a..18b5f5f98cc5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapToolbarControls.swift @@ -1,26 +1,6 @@ import CmuxMobileSupport import SwiftUI -struct PaneMapToolbarControls: View { - let isRefreshing: Bool - let refresh: () -> Void - let done: () -> Void - - var body: some View { - HStack(spacing: PaneMapToolbarMetrics.spacing) { - PaneMapRefreshToolbarButton(isRefreshing: isRefreshing, refresh: refresh) - PaneMapDoneToolbarButton(done: done) - } - .frame( - width: PaneMapToolbarMetrics.trailingClusterWidth, - height: PaneMapToolbarMetrics.height, - alignment: .trailing - ) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("MobilePaneMapToolbarControls") - } -} - struct PaneMapRefreshToolbarButton: View { let isRefreshing: Bool let refresh: () -> Void diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index e9d7f20df768..1b9d36b48345 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -1,4 +1,5 @@ import CMUXMobileCore +import CmuxMobileTerminal import SwiftUI #if os(iOS) import UIKit @@ -74,7 +75,7 @@ struct PaneZoomNavigationStack: View { #if os(iOS) .background { PaneZoomNavigationHostBackground( - color: UIColor(paneZoomTerminalBackground: terminalTheme) + color: terminalTheme.terminalBackgroundUIColor ) } #endif @@ -106,7 +107,24 @@ private struct PaneZoomNavigationHostBackground: UIViewRepresentable { uiView.applyBackground() } + static func dismantleUIView(_ uiView: BackgroundBridgeView, coordinator: ()) { + uiView.restoreBackgrounds() + } + final class BackgroundBridgeView: UIView { + 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() } } @@ -123,12 +141,15 @@ private struct PaneZoomNavigationHostBackground: UIViewRepresentable { func applyBackground() { backgroundColor = .clear - guard window != nil else { return } + guard window != nil else { + restoreBackgrounds() + return + } var ancestor = superview var hops = 0 while let view = ancestor, !(view is UIWindow), hops < 16 { - view.backgroundColor = color + applyColor(to: view) ancestor = view.superview hops += 1 } @@ -137,33 +158,37 @@ private struct PaneZoomNavigationHostBackground: UIViewRepresentable { var responderHops = 0 while let current = responder, responderHops < 32 { if let viewController = current as? UIViewController { - viewController.view.backgroundColor = color - viewController.navigationController?.view.backgroundColor = color + applyColor(to: viewController.view) + if let navigationView = viewController.navigationController?.view { + applyColor(to: navigationView) + } } if let navigationController = current as? UINavigationController { - navigationController.view.backgroundColor = color + applyColor(to: navigationController.view) } responder = current.next responderHops += 1 } } - } -} -private extension UIColor { - convenience init(paneZoomTerminalBackground theme: TerminalTheme) { - let fallback = TerminalTheme.monokai.background - guard let rgb = TerminalTheme.rgbComponents(theme.background) - ?? TerminalTheme.rgbComponents(fallback) else { - self.init(white: 0, alpha: 1) - return + 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 } - self.init( - red: CGFloat(rgb.red) / 255.0, - green: CGFloat(rgb.green) / 255.0, - blue: CGFloat(rgb.blue) / 255.0, - alpha: 1 - ) } } #endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 165c2510400e..fe3bc3493791 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -164,6 +164,37 @@ struct WorkspaceDetailView: View { .onChange(of: workspace.layout != nil) { _, hasLayout in paneZoomPresentation.layoutAvailabilityDidChange(hasLayout: hasLayout) } + .closeWorkspaceConfirmation( + isPresented: $isConfirmingClose, + confirm: confirmCloseWorkspaceFromMenu + ) + .sheet(isPresented: $isFeedbackComposerPresented) { + feedbackComposer + } + .sheet(isPresented: $isTextSheetPresented) { + TerminalTextSheetView(surfaceID: textSheetSurfaceID) + } + .sheet(isPresented: $isWorkspaceChangesSheetPresented) { + WorkspaceChangesSheet( + store: store, + workspaceID: workspace.rpcWorkspaceID.rawValue, + workspaceTitle: workspace.name + ) + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + } + .workspaceRenameDialog( + isPresented: $isRenamePresented, + text: $renameText, + onSave: commitRenameFromDialog + ) + .sheet(isPresented: $isCustomizationPresented) { + WorkspaceCustomizationSheet(workspace: workspace) { initialDraft, submittedDraft in + await customizeWorkspace?(workspace.id, initialDraft, submittedDraft) + ?? .failure() + } + } + .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) #else Group { detailSurfaceContent } .closeWorkspaceConfirmation( @@ -208,37 +239,6 @@ struct WorkspaceDetailView: View { .onChange(of: store.supportsChatArtifactGallery) { _, _ in visibleArtifactCount = 0 } - .closeWorkspaceConfirmation( - isPresented: $isConfirmingClose, - confirm: confirmCloseWorkspaceFromMenu - ) - .sheet(isPresented: $isFeedbackComposerPresented) { - feedbackComposer - } - .sheet(isPresented: $isTextSheetPresented) { - TerminalTextSheetView(surfaceID: textSheetSurfaceID) - } - .sheet(isPresented: $isWorkspaceChangesSheetPresented) { - WorkspaceChangesSheet( - store: store, - workspaceID: workspace.rpcWorkspaceID.rawValue, - workspaceTitle: workspace.name - ) - .presentationDetents([.large]) - .presentationDragIndicator(.visible) - } - .workspaceRenameDialog( - isPresented: $isRenamePresented, - text: $renameText, - onSave: commitRenameFromDialog - ) - .sheet(isPresented: $isCustomizationPresented) { - WorkspaceCustomizationSheet(workspace: workspace) { initialDraft, submittedDraft in - await customizeWorkspace?(workspace.id, initialDraft, submittedDraft) - ?? .failure() - } - } - .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) } private func paneMapRoot(layout: MobilePaneLayout) -> some View { diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 86045be85847..0a57f7423e85 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -210,13 +210,19 @@ import Testing @Suite struct PaneMapReorderStateTests { @Test func failureRollsBackToTheLatestAuthoritativeOrder() throws { - var state = PaneMapReorderState(authoritativePaneIDs: ["left", "middle", "right"]) + 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"]) + 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" @@ -228,22 +234,54 @@ import Testing } @Test func successWaitsForAndThenUsesTheAuthoritativeMacOrder() throws { - var state = PaneMapReorderState(authoritativePaneIDs: ["one", "two", "three"]) + 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"]) + 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 request = try #require(state.beginMove(from: 0, to: 1)) + 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"]) + var state = PaneMapReorderState( + authoritativePaneIDs: ["a", "b", "c"], + authoritativeRevision: 40 + ) let firstPendingRequest = state.beginMove(from: 0, to: 1) let first = try #require(firstPendingRequest) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift index fca6d5d1109a..0a2dea52cfb8 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapTerminalPreviewLayoutTests.swift @@ -40,4 +40,18 @@ import Testing #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/WorkspaceListTableCoordinatorDropTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceListTableCoordinatorDropTests.swift index 94b554c24e34..278ebc1b09f9 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceListTableCoordinatorDropTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/WorkspaceListTableCoordinatorDropTests.swift @@ -58,8 +58,6 @@ import UIKit workspaceChangeChipsByWorkspaceID: [:], openWorkspaceChanges: nil, connectionRequiresReauth: false, - connectionRecoveryFailed: false, - isRecoveringConnection: false, connectionError: nil, host: "Test Mac", isInitialConnectionLoading: false, @@ -90,7 +88,6 @@ import UIKit deleteWorkspaceGroup: nil, toggleGroupCollapsed: nil, showAll: {}, - retryConnectionRecovery: nil, signOut: nil, retryInitialConnection: nil, showAddDevice: nil, diff --git a/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift b/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift index b839d2bca528..f02983b1a30a 100644 --- a/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift +++ b/Sources/SurfaceResumeCommandCanonicalizer+PortableAgentExecutable.swift @@ -75,7 +75,7 @@ extension SurfaceResumeBindingSnapshot { !value.isEmpty else { return nil } - AgentRestoreCLIArgument(rawValue: value)?.rawValue + return AgentRestoreCLIArgument(rawValue: value)?.rawValue } private func resolvedStartupCommand(repairPortableAgentExecutable: Bool) -> String { diff --git a/Sources/Workspace+MobilePaneReorder.swift b/Sources/Workspace+MobilePaneReorder.swift index 75cfea98c908..1b1fd68fa1b9 100644 --- a/Sources/Workspace+MobilePaneReorder.swift +++ b/Sources/Workspace+MobilePaneReorder.swift @@ -101,16 +101,24 @@ extension Workspace { bonsplitController.focusPane(destinationPane) bonsplitController.selectTab(selectedTab) } + + 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 } - if let originallyFocusedPaneID, - let destinationIndex = requestedPaneIDs.firstIndex(of: originallyFocusedPaneID), - let focusedPane = panesByID[spatialPanes[destinationIndex]] { - bonsplitController.focusPane(focusedPane) - } publishMobilePaneLayoutRevisionIfChanged() scheduleTerminalGeometryReconcile() scheduleFocusReconcile() diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 552a1a85683d..361bc3db55d0 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -5055,6 +5055,7 @@ final class cmuxUITests: XCTestCase { modeControl.exists && modeControl.isHittable && (!isActive || overlay.exists) + && (isActive || !app.buttons["MobilePaneMapRefresh"].exists) } ), object: modeControl From 5cc12c6cb213fa8197352114bfbe86fb514ac720 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:15:54 -0700 Subject: [PATCH 56/78] test(ios): cover zoom background restoration --- .../PaneZoomPresentationState.swift | 138 +++++++++--------- .../PaneMapCollectionLayoutEngineTests.swift | 38 +++++ 2 files changed, 110 insertions(+), 66 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index 1b9d36b48345..de94320b5482 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -96,99 +96,105 @@ struct PaneZoomNavigationStack: View { private struct PaneZoomNavigationHostBackground: UIViewRepresentable { let color: UIColor - func makeUIView(context: Context) -> BackgroundBridgeView { - let view = BackgroundBridgeView() + func makeUIView(context: Context) -> PaneZoomNavigationBackgroundBridgeView { + let view = PaneZoomNavigationBackgroundBridgeView() view.color = color return view } - func updateUIView(_ uiView: BackgroundBridgeView, context: Context) { + func updateUIView( + _ uiView: PaneZoomNavigationBackgroundBridgeView, + context: Context + ) { uiView.color = color uiView.applyBackground() } - static func dismantleUIView(_ uiView: BackgroundBridgeView, coordinator: ()) { + static func dismantleUIView( + _ uiView: PaneZoomNavigationBackgroundBridgeView, + coordinator: () + ) { uiView.restoreBackgrounds() } +} - final class BackgroundBridgeView: UIView { - private final class BackgroundSnapshot { - weak var view: UIView? - let originalColor: UIColor? - var appliedColor: UIColor? +final class PaneZoomNavigationBackgroundBridgeView: UIView { + private final class BackgroundSnapshot { + weak var view: UIView? + let originalColor: UIColor? + var appliedColor: UIColor? - init(view: UIView) { - self.view = view - self.originalColor = view.backgroundColor - } + init(view: UIView) { + self.view = view + self.originalColor = view.backgroundColor } + } - private var backgroundSnapshots: [ObjectIdentifier: BackgroundSnapshot] = [:] + private var backgroundSnapshots: [ObjectIdentifier: BackgroundSnapshot] = [:] - var color: UIColor = .clear { - didSet { applyBackground() } - } + var color: UIColor = .clear { + didSet { applyBackground() } + } - override func didMoveToWindow() { - super.didMoveToWindow() - applyBackground() - } + override func didMoveToWindow() { + super.didMoveToWindow() + applyBackground() + } - override func didMoveToSuperview() { - super.didMoveToSuperview() - applyBackground() - } + override func didMoveToSuperview() { + super.didMoveToSuperview() + applyBackground() + } - func applyBackground() { - backgroundColor = .clear - guard window != nil else { - restoreBackgrounds() - return - } + 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 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) + 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) } - responder = current.next - responderHops += 1 } + 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 + func restoreBackgrounds() { + for snapshot in backgroundSnapshots.values { + guard let view = snapshot.view, + view.backgroundColor == snapshot.appliedColor else { + continue } - backgroundSnapshots.removeAll() + 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 - } + 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/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 0a57f7423e85..aaad1bff798e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -1,6 +1,9 @@ import CoreGraphics import CmuxMobileShellModel import Testing +#if os(iOS) +import UIKit +#endif @testable import CmuxMobileShellUI @Suite struct PaneMapCollectionLayoutEngineTests { @@ -208,6 +211,41 @@ import Testing } } +#if os(iOS) +@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 + @Suite struct PaneMapReorderStateTests { @Test func failureRollsBackToTheLatestAuthoritativeOrder() throws { var state = PaneMapReorderState( From 3185cdb28287dbc4e13baef09750cbd0d0f0ac59 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:37:16 -0700 Subject: [PATCH 57/78] test(ios): avoid mutating reorder state in macro --- .../PaneMapCollectionLayoutEngineTests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index aaad1bff798e..000df8fd6070 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -303,7 +303,8 @@ import UIKit authoritativeRevision: 30 ) - let request = try #require(state.beginMove(from: 0, to: 1)) + let pendingRequest = state.beginMove(from: 0, to: 1) + let request = try #require(pendingRequest) state.reconcile( authoritativePaneIDs: ["left", "right"], authoritativeRevision: 31 From 6545e29c7e6855b484ddce6b3d423c9d02f1462c Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 31 Jul 2026 22:45:51 -0700 Subject: [PATCH 58/78] fix(mac): restore pane focus after mutation snapshot --- Sources/Workspace+MobilePaneReorder.swift | 26 +++++++++++++---------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Sources/Workspace+MobilePaneReorder.swift b/Sources/Workspace+MobilePaneReorder.swift index 1b1fd68fa1b9..7c0633e4bdba 100644 --- a/Sources/Workspace+MobilePaneReorder.swift +++ b/Sources/Workspace+MobilePaneReorder.swift @@ -101,18 +101,22 @@ extension Workspace { bonsplitController.focusPane(destinationPane) bonsplitController.selectTab(selectedTab) } + } - 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) - } + // 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 From 3217729c70366f25e568078812b02ce0947f6ff4 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Sat, 1 Aug 2026 01:32:33 -0700 Subject: [PATCH 59/78] fix(ios): keep surface deck on zoom destination --- .../Debug/PanesTabsPreviewHost.swift | 12 ++++++------ .../Sources/CmuxMobileShellUI/SurfaceDeckBar.swift | 8 ++++---- .../CmuxMobileShellUI/WorkspaceDetailView.swift | 12 ++++++------ 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index d683f56d60a9..722aae136658 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -185,6 +185,12 @@ struct PanesTabsPreviewHost: View { .background { autoplayDriver(for: .paneMap) } } terminal: { terminalPreviewEndpoint + .mobileSurfaceDeckInset( + isVisible: paneZoomPresentation.isTerminalPresented, + value: deckValue, + actions: deckActions, + terminalTheme: terminalTheme + ) .navigationBarBackButtonHidden(true) .navigationTransition( .zoom( @@ -193,12 +199,6 @@ struct PanesTabsPreviewHost: View { ) ) } - .mobileSurfaceDeckInset( - isVisible: paneZoomPresentation.isTerminalPresented, - value: deckValue, - actions: deckActions, - terminalTheme: terminalTheme - ) } else { terminalPreviewEndpoint .mobileSurfaceDeckInset( diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift index 697cb787d54d..78e164d79876 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/SurfaceDeckBar.swift @@ -313,10 +313,10 @@ struct SurfaceDeckBar: View, Equatable { #if os(iOS) extension View { - /// Installs the deck on a concrete layout container so it remains outside - /// pane-map navigation transitions while still contributing a real safe-area - /// inset to the terminal viewport. Applying `safeAreaInset` to a conditional - /// `Group` drops the deck around nested navigation stacks on iOS. + /// 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, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index fe3bc3493791..c78faa5aa748 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -133,6 +133,12 @@ struct WorkspaceDetailView: View { .navigationBarBackButtonHidden(true) } terminal: { terminalWorkspaceEndpoint + .mobileSurfaceDeckInset( + isVisible: shouldShowSurfaceDeck, + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme + ) .navigationBarBackButtonHidden(true) .navigationTransition( .zoom( @@ -141,12 +147,6 @@ struct WorkspaceDetailView: View { ) ) } - .mobileSurfaceDeckInset( - isVisible: shouldShowSurfaceDeck, - value: surfaceDeckValue, - actions: surfaceDeckActions, - terminalTheme: store.activeTerminalTheme - ) } else { terminalWorkspaceEndpoint .mobileSurfaceDeckInset( From 77e66b5c7b65de84a56f0253761e8fcef93ed973 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Sat, 1 Aug 2026 04:11:28 -0700 Subject: [PATCH 60/78] fix(ios): isolate pane zoom background snapshots --- .../Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index de94320b5482..7204dbf65ef4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -119,7 +119,7 @@ private struct PaneZoomNavigationHostBackground: UIViewRepresentable { } final class PaneZoomNavigationBackgroundBridgeView: UIView { - private final class BackgroundSnapshot { + @MainActor private final class BackgroundSnapshot { weak var view: UIView? let originalColor: UIColor? var appliedColor: UIColor? From 7cbecf3b45e7dc5f10567e684e7133bff18e6bd7 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Tue, 4 Aug 2026 01:19:28 -0700 Subject: [PATCH 61/78] fix(panes): resolve Cubic review findings across reorder authority chain Mac: workspace.pane.reorder accepts an optional base_layout_version precondition (stale drags fail closed as conflict); mobile mutations resolve the owning window before honoring a stale window_id; reorder placeholders are force-closed so close-confirmation vetoes cannot leave phantom tabs; mobile.terminal.replay honors grid_only to skip unbounded VT fallbacks; dead legacy geometry-reorder API removed. iOS: reorder requests carry the observed layout revision; reorder state ignores lower-revision (stale) workspace lists; mutation responses retire in-flight list fetches and re-arm pending refresh loops on both foreground and secondary Macs; workspace entry prefers ready terminals before an unready focused-pane selection; pane-map refresh cancelled before start no longer wedges the toolbar spinner; browser streams keep the surface deck as their exit path; pane zoom no longer overrides the shell's tab-bar policy; duplicate pane IDs no longer trap; VoiceOver ordinals follow optimistic reorders; DEC reverse-video resolves from the final mode setting; sign-out retires in-flight dialing transports. Tests: PaneMapReorderState monotonicity suite, stale-list overwrite regression (verified red without the fix), entry-readiness coverage, reverse-video final-setting coverage, base-layout-version conflict coverage; removed fixed sleeps and unbounded waits from pane tests. Co-Authored-By: Claude Fable 5 --- ...rminalRenderGridFrame+PaneMapPreview.swift | 9 +- ...erminalRenderGridPaneMapPreviewTests.swift | 42 ++++++- ...ileShellComposite+ConnectionRecovery.swift | 9 ++ .../MobileShellComposite+Helpers.swift | 2 +- ...MobileShellComposite+PaneMapPreviews.swift | 4 + ...obileShellComposite+WorkspaceActions.swift | 19 ++- .../MobileShellComposite.swift | 52 ++++++-- .../MobileShellCompositePreviewTests.swift | 66 ++++++++++ .../MobileShellWorkspaceCapabilityTests.swift | 84 +++++++++++++ .../PaneMapPreviewFetchTests.swift | 21 +++- .../Debug/PanesTabsPreviewHost.swift | 7 +- .../PaneMapCollectionView.swift | 74 +++++++---- .../CmuxMobileShellUI/PaneMapOverlay.swift | 9 +- .../PaneMapReorderState.swift | 17 ++- .../CmuxMobileShellUI/PaneMapValue.swift | 1 - .../PaneZoomPresentationState.swift | 7 +- .../WorkspaceDetailView.swift | 16 ++- .../WorkspaceShellView.swift | 4 +- .../PaneMapReorderStateTests.swift | 81 ++++++++++++ .../SurfaceDeckValueTests.swift | 1 - .../CmuxPanes/Model/PaneTreeModel.swift | 11 +- .../CmuxPanesTests/PaneTreeModelTests.swift | 2 - .../WorkspaceSurfaceListModel.swift | 34 +---- .../WorkspaceSurfaceTreeReading.swift | 30 ++--- .../WorkspaceSurfaceListModelTests.swift | 30 ----- .../TerminalController+WorkspaceMove.swift | 36 +++++- Sources/TerminalController.swift | 4 + Sources/Workspace+MobilePaneReorder.swift | 13 +- ...orkspace+WorkspaceSurfaceTreeReading.swift | 9 -- .../MobileWorkspaceListFidelityTests.swift | 118 ++++++++++++++++++ ios/cmuxUITests/cmuxUITests.swift | 2 +- 31 files changed, 649 insertions(+), 165 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift index 8a26be9acfdb..dc360c5a3f44 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGridFrame+PaneMapPreview.swift @@ -115,9 +115,12 @@ public extension MobileTerminalRenderGridFrame { func paneMapPreview( maximumRows: Int? = nil ) -> MobileTerminalPaneMapPreview { - let usesDECReverseVideo = modes.contains { - !$0.ansi && $0.code == 5 && $0.on - } + // 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, diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift index 493643361996..eba9ef939aa5 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileTerminalRenderGridPaneMapPreviewTests.swift @@ -239,11 +239,48 @@ import Testing #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 + cursorRow: Int? = nil, + modes: [MobileTerminalRenderGridFrame.ModeSetting] = [] ) throws -> MobileTerminalRenderGridFrame { try MobileTerminalRenderGridFrame( surfaceID: "terminal-preview", @@ -253,7 +290,8 @@ import Testing cursor: cursorRow.map { MobileTerminalRenderGridFrame.Cursor(row: $0, column: 0) }, - rowSpans: rowSpans + rowSpans: rowSpans, + modes: modes ) } } 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 dd23f30e4402..03eed71bc1b4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Helpers.swift @@ -36,7 +36,7 @@ extension MobileShellComposite { supportsMoveActions: supportedHostCapabilities.contains("workspace.move.v1") && allowsMacScopedMutations, supportsGroupActions: supportedHostCapabilities.contains("workspace.group_actions.v1") && allowsMacScopedMutations, supportsGroupCreate: supportedHostCapabilities.contains("workspace.group_create.v1") && allowsMacScopedMutations, - supportsPaneReorder: supportedHostCapabilities.contains("workspace.pane_reorder.v1") + 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 index ad1a4b2a954b..4dcaf3b65719 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PaneMapPreviews.swift @@ -42,6 +42,10 @@ extension MobileShellComposite { 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) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift index 61fc5fc31c17..409f18f5d6b0 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift @@ -22,7 +22,8 @@ extension MobileShellComposite { @discardableResult public func reorderWorkspacePanes( id: MobileWorkspacePreview.ID, - orderedPaneIDs: [String] + orderedPaneIDs: [String], + baseLayoutRevision: Int? = nil ) async -> Result { guard workspaceActionCapabilities(for: id).supportsPaneReorder else { return .failure(.unsupported(hostDisplayName: workspaceHostDisplayName(for: id))) @@ -32,6 +33,11 @@ extension MobileShellComposite { } 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, @@ -573,6 +579,10 @@ extension MobileShellComposite { 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 } @@ -583,6 +593,13 @@ extension MobileShellComposite { 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 diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index e3268021c103..456a9ec3f178 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -982,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 = [] @@ -1600,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 @@ -12230,27 +12252,39 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private extension MobileWorkspacePreview { var preferredEntryTerminal: MobileTerminalPreview? { - focusedPaneTerminal ?? preferredTerminal + // 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 } - private var focusedPaneTerminal: MobileTerminalPreview? { - guard let layout else { return nil } + /// 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 nil } - let terminalIDs = focusedPane.surfaces + guard let focusedPane else { return [] } + var terminalIDs = focusedPane.surfaces .filter { $0.type.isTerminal } .map(\.id) if let selectedSurfaceID = focusedPane.selectedSurfaceID, - terminalIDs.contains(selectedSurfaceID), - let terminal = terminals.first(where: { $0.id.rawValue == selectedSurfaceID }) { - return terminal + 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 } - }.first + } } var preferredTerminal: MobileTerminalPreview? { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index 772b6724af59..22617e60b4d9 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -159,6 +159,72 @@ import Testing #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/MobileShellWorkspaceCapabilityTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift index a36c6ef186e9..0a75e2273f27 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellWorkspaceCapabilityTests.swift @@ -325,6 +325,90 @@ import Testing 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 index 7a48557a028d..225446845363 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PaneMapPreviewFetchTests.swift @@ -73,8 +73,10 @@ import Testing ) 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 - try await Task.sleep(nanoseconds: 50_000_000) let requestedSurfaceIDs = await router.surfaceIDs(for: "mobile.terminal.replay") #expect(filledWindow) @@ -196,12 +198,27 @@ private actor PaneMapPreviewFetchGate { return frames[surfaceID] } - func waitUntilStarted(count: Int) async { + /// 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] { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 722aae136658..f7662cfbc8ff 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -161,7 +161,6 @@ struct PanesTabsPreviewHost: View { ) { PaneMapOverlay( value: PaneMapValue( - workspaceName: workspace.name, layout: layout, phoneSelectedSurfaceID: selectedSurfaceID, agentStateKindsBySurfaceID: agentStateKindsBySurfaceID @@ -507,7 +506,6 @@ struct PanesTabsPreviewHost: View { case .paneMap: guard let layout = fixtureLayout else { return nil } return PaneMapValue( - workspaceName: workspace.name, layout: layout, phoneSelectedSurfaceID: selectedSurfaceID, agentStateKindsBySurfaceID: agentStateKindsBySurfaceID @@ -588,7 +586,10 @@ struct PanesTabsPreviewHost: View { } @MainActor - private func reorderFixturePanes(_ orderedPaneIDs: [String]) async -> Bool { + 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 { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index eb381a2b25d4..92a4527d5e0e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -1,5 +1,6 @@ import CMUXMobileCore import CmuxMobileShellModel +import CmuxMobileTerminal import SwiftUI import UIKit @@ -20,6 +21,23 @@ struct PaneMapCollectionItem: Equatable, Identifiable { 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 { @@ -39,7 +57,7 @@ struct PaneMapCollectionView: UIViewRepresentable { let allowsReordering: Bool let selectPreviewSurface: (_ paneID: String, _ surfaceID: String) -> Void let jumpToTerminal: (_ surfaceID: String) -> Void - let reorderPanes: (_ orderedPaneIDs: [String]) async -> Bool + let reorderPanes: (_ orderedPaneIDs: [String], _ baseLayoutRevision: Int) async -> Bool func makeCoordinator() -> Coordinator { Coordinator(parent: self) @@ -113,15 +131,23 @@ struct PaneMapCollectionView: UIViewRepresentable { 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( - uniqueKeysWithValues: parent.items.map { ($0.id, $0) } + parent.items.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } ) reorderState = PaneMapReorderState( - authoritativePaneIDs: parent.items.map(\.id), + 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 @@ -145,7 +171,8 @@ struct PaneMapCollectionView: UIViewRepresentable { func reconcile(items: [PaneMapCollectionItem]) { authoritativeItemsByID = Dictionary( - uniqueKeysWithValues: items.map { ($0.id, $0) } + items.map { ($0.id, $0) }, + uniquingKeysWith: { first, _ in first } ) guard !isMovingItem else { pendingItems = items @@ -153,16 +180,17 @@ struct PaneMapCollectionView: UIViewRepresentable { } reorderState.reconcile( - authoritativePaneIDs: items.map(\.id), + authoritativePaneIDs: Self.deduplicatedPaneIDs(items), authoritativeRevision: parent.layout.version ) reloadVisibleItems() } private func reloadVisibleItems() { - orderedItems = reorderState.visiblePaneIDs.compactMap { - authoritativeItemsByID[$0] - } + orderedItems = reorderState.visiblePaneIDs + .compactMap { authoritativeItemsByID[$0] } + .enumerated() + .map { index, item in item.withPanePosition(number: index + 1) } collectionView?.reloadData() collectionView?.collectionViewLayout.invalidateLayout() container?.setNeedsLayout() @@ -265,9 +293,19 @@ struct PaneMapCollectionView: UIViewRepresentable { 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) + let succeeded = await parent.reorderPanes( + request.orderedPaneIDs, + request.baseLayoutRevision + ) completeReorder(requestID: request.id, succeeded: succeeded) } } @@ -461,10 +499,10 @@ final class PaneMapCollectionContainerView: UIView { labels: PaneMapOverflowLabels, scrollStep: @escaping (PaneMapOverflowDirection) -> Void ) { - backgroundColor = UIColor(terminalHex: terminalTheme.background) + backgroundColor = terminalTheme.terminalBackgroundUIColor self.scrollStep = scrollStep for button in buttons.values { - button.tintColor = UIColor(terminalHex: terminalTheme.foreground) + button.tintColor = terminalTheme.terminalForegroundUIColor } buttons[.leading]?.accessibilityLabel = labels.leading buttons[.trailing]?.accessibilityLabel = labels.trailing @@ -552,17 +590,3 @@ private final class PaneMapOverflowButton: UIButton { } } -private extension UIColor { - convenience init(terminalHex: String) { - guard let rgb = TerminalTheme.rgbComponents(terminalHex) else { - self.init(white: 0, alpha: 1) - return - } - self.init( - red: CGFloat(rgb.red) / 255, - green: CGFloat(rgb.green) / 255, - blue: CGFloat(rgb.blue) / 255, - alpha: 1 - ) - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index 8927ee3bb151..f379f1b51828 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -13,7 +13,7 @@ struct PaneMapOverlay: View { let refreshTrigger: Int let fetchPreviews: ([String], [String]) async -> [String: MobileTerminalRenderGridFrame] let selectTerminal: (MobileTerminalPreview.ID) -> Void - let reorderPanes: ([String]) async -> Bool + let reorderPanes: ([String], Int) async -> Bool let refreshingChanged: (Bool) -> Void @State private var selectedSurfaceIDsByPaneID: [String: String] @@ -31,7 +31,7 @@ struct PaneMapOverlay: View { refreshTrigger: Int, fetchPreviews: @escaping ([String], [String]) async -> [String: MobileTerminalRenderGridFrame], selectTerminal: @escaping (MobileTerminalPreview.ID) -> Void, - reorderPanes: @escaping ([String]) async -> Bool, + reorderPanes: @escaping ([String], Int) async -> Bool, refreshingChanged: @escaping (Bool) -> Void ) { self.value = value @@ -168,6 +168,11 @@ struct PaneMapOverlay: View { } 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) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift index 32efc5520082..c9c233a65f75 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapReorderState.swift @@ -5,6 +5,10 @@ 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 { @@ -39,7 +43,11 @@ struct PaneMapReorderState: Equatable { } let movedPaneID = visiblePaneIDs.remove(at: sourceIndex) visiblePaneIDs.insert(movedPaneID, at: destinationIndex) - let request = Request(id: UUID(), orderedPaneIDs: visiblePaneIDs) + let request = Request( + id: UUID(), + orderedPaneIDs: visiblePaneIDs, + baseLayoutRevision: authoritativeRevision + ) pendingRequest = request receivedAuthorityWhilePending = false pendingRequestWasAccepted = false @@ -50,7 +58,12 @@ struct PaneMapReorderState: Equatable { authoritativePaneIDs: [String], authoritativeRevision: Int ) { - let receivedNewAuthority = authoritativeRevision != self.authoritativeRevision + // 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 { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift index e8b9d57e152a..e9f9b2a6fdbc 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapValue.swift @@ -3,7 +3,6 @@ import CmuxMobileSupport /// Immutable workspace and status state rendered by ``PaneMapOverlay``. struct PaneMapValue: Equatable { - let workspaceName: String let layout: MobilePaneLayout let phoneSelectedSurfaceID: String? let agentStateKindsBySurfaceID: [String: ChatAgentStateKind] diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index 7204dbf65ef4..5149418605fc 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -79,9 +79,10 @@ struct PaneZoomNavigationStack: View { ) } #endif - #if os(iOS) - .toolbarVisibility(.hidden, for: .tabBar) - #endif + // 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. } private var navigationPath: Binding<[PaneZoomPresentationState.Endpoint]> { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 7c55c9ee4588..35a7dc819f59 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -214,7 +214,11 @@ struct WorkspaceDetailView: View { #if os(iOS) private var shouldShowSurfaceDeck: Bool { - activeSurface == .terminal + // 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 } @@ -251,7 +255,6 @@ struct WorkspaceDetailView: View { private func paneMapRoot(layout: MobilePaneLayout) -> some View { PaneMapOverlay( value: PaneMapValue( - workspaceName: workspace.name, layout: layout, phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds @@ -407,7 +410,6 @@ struct WorkspaceDetailView: View { if mode == .paneMap, let layout = workspace.layout { let paneMapValue = PaneMapValue( - workspaceName: workspace.name, layout: layout, phoneSelectedSurfaceID: selectedTerminal?.id.rawValue, agentStateKindsBySurfaceID: surfaceDeckAgentStateKinds @@ -802,10 +804,14 @@ struct WorkspaceDetailView: View { } @MainActor - private func reorderPanesFromMap(_ orderedPaneIDs: [String]) async -> Bool { + private func reorderPanesFromMap( + _ orderedPaneIDs: [String], + baseLayoutRevision: Int + ) async -> Bool { let result = await store.reorderWorkspacePanes( id: workspace.id, - orderedPaneIDs: orderedPaneIDs + orderedPaneIDs: orderedPaneIDs, + baseLayoutRevision: baseLayoutRevision ) guard case .success = result else { toasts.present(.failure( diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index 2955d437c2d7..1159202c8603 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -421,7 +421,9 @@ struct WorkspaceShellView: View { #if os(iOS) private var primaryTabBarVisibility: Visibility { let workspaceIsPushed = usesCompactStack && !compactNavigationPath.isEmpty - return workspaceIsPushed || !notificationNavigationPath.isEmpty ? .hidden : .automatic + let notificationRouteIsPushed = !notificationNavigationPath.isEmpty + || !notificationSearchNavigationPath.isEmpty + return workspaceIsPushed || notificationRouteIsPushed ? .hidden : .automatic } #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..4aaa121f9e43 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift @@ -0,0 +1,81 @@ +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) + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift index a616e7d75ad2..ca2165e8f8dd 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/SurfaceDeckValueTests.swift @@ -143,7 +143,6 @@ import Testing ) ) let paneMap = PaneMapValue( - workspaceName: "Workspace", layout: layout, phoneSelectedSurfaceID: "terminal-new", agentStateKindsBySurfaceID: [:] 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/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/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/TerminalController+WorkspaceMove.swift b/Sources/TerminalController+WorkspaceMove.swift index 19fa1a0d52db..f612a6e575c8 100644 --- a/Sources/TerminalController+WorkspaceMove.swift +++ b/Sources/TerminalController+WorkspaceMove.swift @@ -18,7 +18,11 @@ extension TerminalController { Set(orderedPaneIDs).count == orderedPaneIDs.count else { return .err(code: "invalid_params", message: "ordered_pane_ids must be unique UUIDs", data: nil) } - guard let tabManager = v2ResolveTabManager(params: params) else { + 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) } @@ -32,6 +36,19 @@ extension TerminalController { ) 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 { @@ -57,9 +74,24 @@ extension TerminalController { 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") @@ -110,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 93beaa8f2d13..904eb0f92cdd 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -14632,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+MobilePaneReorder.swift b/Sources/Workspace+MobilePaneReorder.swift index 7c0633e4bdba..69149b7b33eb 100644 --- a/Sources/Workspace+MobilePaneReorder.swift +++ b/Sources/Workspace+MobilePaneReorder.swift @@ -87,7 +87,18 @@ extension Workspace { } for placeholder in placeholderTabsByPaneID.values { - _ = bonsplitController.closeTab(placeholder) + // 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 diff --git a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift index bdfd56706411..4e71b8f0c423 100644 --- a/Sources/Workspace+WorkspaceSurfaceTreeReading.swift +++ b/Sources/Workspace+WorkspaceSurfaceTreeReading.swift @@ -75,15 +75,6 @@ extension Workspace: WorkspaceSurfaceTreeReading { sidebarOrderedPanelIds().first } - var lastOrderedPanelIds: [UUID] { - get { paneTree.lastOrderedPanelIds } - set { paneTree.lastOrderedPanelIds = newValue } - } - - func bumpPaneLayoutVersion() { - paneLayoutVersion &+= 1 - } - /// 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. diff --git a/cmuxTests/MobileWorkspaceListFidelityTests.swift b/cmuxTests/MobileWorkspaceListFidelityTests.swift index 5da7761ddb8e..d48d042ce6fe 100644 --- a/cmuxTests/MobileWorkspaceListFidelityTests.swift +++ b/cmuxTests/MobileWorkspaceListFidelityTests.swift @@ -369,6 +369,124 @@ struct MobileWorkspaceListFidelityTests { ) } + /// 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) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index e2eb0615a1af..3e93e8096945 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -5408,7 +5408,7 @@ final class cmuxUITests: XCTestCase { block: { _, _ in modeControl.exists && modeControl.isHittable - && (!isActive || overlay.exists) + && (isActive ? overlay.exists : !overlay.exists) && (isActive || !app.buttons["MobilePaneMapRefresh"].exists) } ), From 5dbefae9f880fcedc1eb33a16fe6db70384c21f9 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 5 Aug 2026 15:58:03 -0700 Subject: [PATCH 62/78] test(panes): cold-open detached pane map must materialize zoom source cells A restored workspace mounts the pane map as a covered navigation-stack root, so UIKit never lays it out before the first terminal-to-map pop. The zoom transition's matched source tile lives in a collection cell; with no cells the first unzoom degrades to a hard cut. Red until the pre-warm fix lands in the next commit. Co-Authored-By: Claude Fable 5 --- .../PaneMapCollectionLayoutEngineTests.swift | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 000df8fd6070..275d7450d975 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -212,6 +212,92 @@ import UIKit } #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, + 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) + } +} + @MainActor @Suite struct PaneZoomNavigationBackgroundBridgeTests { @Test func restoresOwnedAncestorBackgroundsWithoutClobberingNewOwners() { From f637c36b274d049c12dcbec382b681d0b3577b7e Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 5 Aug 2026 15:59:14 -0700 Subject: [PATCH 63/78] fix(panes): pre-warm detached pane-map cells so the first unzoom matches its source The pane map is the navigation-stack root and a restored workspace starts with the terminal pushed on top, so UIKit never laid the map out before the first terminal-to-map pop; the zoom's matched source tile did not exist yet and the first transition after a cold open rendered as a one-frame cut. Reconciling items now forces cell layout while the container is detached, sizing it to the window-scene estimate when SwiftUI has not sized it yet. The real layout pass at pop time corrects the geometry; later transitions are unchanged. Co-Authored-By: Claude Fable 5 --- .../PaneMapCollectionView.swift | 27 +++++++++++++++++++ .../PaneMapCollectionLayoutEngineTests.swift | 17 ++++++++++++ 2 files changed, 44 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index 92a4527d5e0e..60f465883c02 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -194,6 +194,15 @@ struct PaneMapCollectionView: UIViewRepresentable { 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 } @@ -548,6 +557,24 @@ final class PaneMapCollectionContainerView: UIView { 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) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index 275d7450d975..e7ad062af61b 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -296,6 +296,23 @@ import UIKit #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 From 719ec2c963a0b2230040800d4951a53abed083fb Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 5 Aug 2026 16:19:32 -0700 Subject: [PATCH 64/78] fix(panes): deduplicate PaneMapReorderStateTests suite that broke test compilation Two @Suite declarations named PaneMapReorderStateTests existed in the same test target: the original in PaneMapCollectionLayoutEngineTests.swift and the revision-monotonicity suite added later as a dedicated file. Every hosted ios-simulator job failed with "invalid redeclaration of 'PaneMapReorderStateTests'" before reaching a single test. Merge the four reorder tests from the embedded copy into the dedicated file, move the misfiled PaneMapSelectionArbitration test into its own PaneMapSelectionArbitrationTests suite, and drop the embedded copy. No test is removed; the target compiles again. Co-Authored-By: Claude Fable 5 --- .../PaneMapCollectionLayoutEngineTests.swift | 106 ------------------ .../PaneMapReorderStateTests.swift | 86 ++++++++++++++ .../PaneMapSelectionArbitrationTests.swift | 23 ++++ 3 files changed, 109 insertions(+), 106 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapSelectionArbitrationTests.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index e7ad062af61b..afe81cec53ad 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -348,109 +348,3 @@ import UIKit } } #endif - -@Suite struct PaneMapReorderStateTests { - @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) - } - - @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/PaneMapReorderStateTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift index 4aaa121f9e43..845151abcb7e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapReorderStateTests.swift @@ -78,4 +78,90 @@ import Testing #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) + } +} From 4cdd8eb4e4c51a193f2f697c6437a47ad1d26015 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 5 Aug 2026 16:41:56 -0700 Subject: [PATCH 65/78] test(panes): drop stale MobileInjectedAttachStartupTests referencing removed API The main merge replaced MobileStartupConnectionCoordinator's connectInjectedAttach with the claim/finish lifecycle, and DogfoodAttachPreparationTests already covers that lifecycle end to end. The stale file kept the whole CmuxMobileShellUITests target from compiling, so no package UI suite could run in CI. Co-Authored-By: Claude Fable 5 --- .../MobileInjectedAttachStartupTests.swift | 41 ------------------- 1 file changed, 41 deletions(-) delete mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileInjectedAttachStartupTests.swift 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 - } -} From 1a3ffcea780236c78bd06b925ae557805c1a4972 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Wed, 5 Aug 2026 16:55:52 -0700 Subject: [PATCH 66/78] test(panes): import SwiftUI for the cold-open prewarm namespace Co-Authored-By: Claude Fable 5 --- .../PaneMapCollectionLayoutEngineTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index afe81cec53ad..e55641db3bb5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -2,6 +2,7 @@ import CoreGraphics import CmuxMobileShellModel import Testing #if os(iOS) +import SwiftUI import UIKit #endif @testable import CmuxMobileShellUI From b38947c07c12f9d66b4f95d67f280133cb1353f5 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 6 Aug 2026 21:24:01 -0700 Subject: [PATCH 67/78] test(panes): real-shell pane-layout workspace must survive pane-map navigation The panes fixture (CMUX_UITEST_PANES_PREVIEW) hosts the pane-zoom pair standalone, so it never caught the P0 crash that killed the production shell: opening a workspace whose sync carries a pane layout mounts the zoom navigation inside the compact stack's pushed destination, and the window's shared NavigationAuthority dies reconciling the two typed paths (SwiftUI.AnyNavigationPath.Error.comparisonTypeMismatch in NavigationColumnState.boundPathChange). Every crash also wipes onboarding and Stack auth state. Teach the mock sync host to serve a two-pane split layout for workspace-main and drive the real shell through every on-device trigger: the initial workspace push, repeated 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). Red until the un-nesting fix lands in the next commit. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 119 +++++++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 3 deletions(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 3e93e8096945..d3b48b7c0ca4 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -3167,6 +3167,70 @@ final class cmuxUITests: XCTestCase { ) } + /// 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"] + for cycle in 1...2 { + tap(app.buttons["MobileSurfaceDeckPaneMap"], 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) + XCTAssertTrue( + waitForPaneMap(overlay, in: app, toBeActive: false), + "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: 8)) + docsRow.tap() + XCTAssertTrue(app.otherElements["MobileTerminalSurface"].waitForExistence(timeout: 8)) + 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: [ @@ -7498,6 +7562,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" @@ -7561,13 +7628,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 @@ -8080,7 +8149,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, @@ -8093,11 +8162,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) From afb4b6c5d1bd8e7e705eccde434a46bf0109cd21 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 6 Aug 2026 21:24:26 -0700 Subject: [PATCH 68/78] fix(panes): host the zoomed terminal as a presentation under pushed shells Opening a pane-layout workspace in the real compact shell fataled within seconds: PaneZoomNavigationStack nested a second typed NavigationStack ([PaneZoomPresentationState.Endpoint]) inside the shell stack's pushed destination ([MobileWorkspacePreview.ID]). Both stacks join the window's shared NavigationAuthority, whose flush queue reconciles one stack's bound path against the other stack's column and force-try!s AnyNavigationPath.Error.comparisonTypeMismatch in NavigationColumnState.boundPathChange. Type-erasing the nested path to NavigationPath was verified NOT to fix it: the misrouted comparison still traps, just deferred to the next push (even of a layout-free workspace, against the popped pane stack's stale column). The standalone fixture never crashed because it has no ancestor stack, which is why the hosted UI tests missed this. Replace the component with PaneZoomHost, which picks the mechanism by an explicit hosting mode passed from each shell call site: - navigationPush (workspaces tab, notifications, notification search): the pane map renders directly in the ancestor stack's destination and the terminal is a zoom fullScreenCover carrying its own root-only NavigationStack. Presentations own a separate navigation context, so nothing joins the ancestor's authority. - column (split detail, regular width): the documented stack-in-a-column pattern is kept unchanged, terminal pushed over the pane-map root. PaneZoomPresentationState's routing API is untouched. The zoom transition moves into the component so both hostings anchor it to the same matchedTransitionSource tiles. WorkspaceDetailView's sheets, dialogs, and the connection-recovery banner now attach to both the base layer and the terminal cover behind opposite visibility gates (binding gates, not structural branches, so layer flips never change subtree identity); a covered base cannot present, and exactly one attachment is live at a time. The panes fixture mirrors the shell's size-class policy so each device family exercises the hosting the production shell uses. Verified on the real-shell repro (sim, live Mac): unpatched build crashed within 15s of opening the workspace; this build survives the open, repeated pane-map zoom round-trips, popping to the list, and switching workspaces with zero new crash reports. Co-Authored-By: Claude Fable 5 --- .../Debug/PanesTabsPreviewHost.swift | 114 ++++++++----- .../MobileConnectionRecoveryOverlay.swift | 18 +- .../PaneZoomPresentationState.swift | 103 +++++++++++- .../WorkspaceDetailContainer.swift | 5 + .../WorkspaceDetailView.swift | 158 ++++++++++++------ .../WorkspaceShellView.swift | 10 +- 6 files changed, 300 insertions(+), 108 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index f7662cfbc8ff..5ba230d92121 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -2,6 +2,7 @@ import CMUXMobileCore import CmuxMobileShellModel import CmuxMobileSupport +import CmuxMobileWorkspace import os import SwiftUI import UIKit @@ -152,51 +153,32 @@ struct PanesTabsPreviewHost: View { 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 let layout = fixtureLayout { - PaneZoomNavigationStack( - presentation: $paneZoomPresentation, - terminalTheme: terminalTheme - ) { - 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) - .navigationTransition( - .zoom( - sourceID: paneZoomSourceSurfaceID, - in: paneZoomNamespace - ) - ) + 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 @@ -214,6 +196,52 @@ struct PanesTabsPreviewHost: View { } } + @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 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/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index 5149418605fc..6e9c7ac6767d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -50,21 +50,105 @@ struct PaneZoomPresentationState: Equatable { } } -/// Keeps the pane-map route local to a workspace destination. The parent stack -/// still owns workspace-list navigation and its shared back button, while this -/// path starts with the restored terminal already installed on the first frame. -struct PaneZoomNavigationStack: View { +/// 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. + private var presentationHost: some View { + root() + .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)) } } } @@ -79,10 +163,13 @@ struct PaneZoomNavigationStack: View { ) } #endif - // 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. + } + + private var isTerminalPresentedBinding: Binding { + Binding( + get: { presentation.isTerminalPresented }, + set: { presentation.presentationDidChange(isTerminalPresented: $0) } + ) } private var navigationPath: Binding<[PaneZoomPresentationState.Endpoint]> { 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/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 35a7dc819f59..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 @@ -125,11 +130,35 @@ struct WorkspaceDetailView: View { #endif var body: some View { #if os(iOS) + // 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 + ) + .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) + #endif + } + + #if os(iOS) + private var detailRootContent: some View { Group { if let layout = workspace.layout { - PaneZoomNavigationStack( + PaneZoomHost( presentation: $paneZoomPresentation, - terminalTheme: store.activeTerminalTheme + hosting: paneZoomHosting, + terminalTheme: store.activeTerminalTheme, + zoomSourceID: paneZoomSourceSurfaceID, + zoomNamespace: paneZoomNamespace ) { paneMapRoot(layout: layout) .accessibilityHidden(paneZoomPresentation.isTerminalPresented) @@ -139,20 +168,17 @@ struct WorkspaceDetailView: View { .toolbar { workspaceDetailToolbar(mode: .paneMap) } .navigationBarBackButtonHidden(true) } terminal: { - terminalWorkspaceEndpoint - .mobileSurfaceDeckInset( - isVisible: shouldShowSurfaceDeck, - value: surfaceDeckValue, - actions: surfaceDeckActions, - terminalTheme: store.activeTerminalTheme - ) - .navigationBarBackButtonHidden(true) - .navigationTransition( - .zoom( - sourceID: paneZoomSourceSurfaceID, - in: paneZoomNamespace + detailPresentations( + terminalWorkspaceEndpoint + .mobileSurfaceDeckInset( + isVisible: shouldShowSurfaceDeck, + value: surfaceDeckValue, + actions: surfaceDeckActions, + terminalTheme: store.activeTerminalTheme ) - ) + .navigationBarBackButtonHidden(true), + active: terminalCoverIsPresented + ) } } else { terminalWorkspaceEndpoint @@ -171,48 +197,76 @@ struct WorkspaceDetailView: View { .onChange(of: workspace.layout != nil) { _, hasLayout in paneZoomPresentation.layoutAvailabilityDidChange(hasLayout: hasLayout) } - .closeWorkspaceConfirmation( - isPresented: $isConfirmingClose, - confirm: confirmCloseWorkspaceFromMenu - ) - .sheet(isPresented: $isFeedbackComposerPresented) { - feedbackComposer - } - .sheet(isPresented: $isTextSheetPresented) { - TerminalTextSheetView(surfaceID: textSheetSurfaceID) - } - .sheet(isPresented: $isWorkspaceChangesSheetPresented) { - WorkspaceChangesSheet( - store: store, - workspaceID: workspace.rpcWorkspaceID.rawValue, - workspaceTitle: workspace.name - ) - .presentationDetents([.large]) - .presentationDragIndicator(.visible) - } - .workspaceRenameDialog( - isPresented: $isRenamePresented, - text: $renameText, - onSave: commitRenameFromDialog - ) - .sheet(isPresented: $isCustomizationPresented) { - WorkspaceCustomizationSheet(workspace: workspace) { initialDraft, submittedDraft in - await customizeWorkspace?(workspace.id, initialDraft, submittedDraft) - ?? .failure() - } - } - .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) - #else - Group { detailSurfaceContent } + } + + /// 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: $isConfirmingClose, + isPresented: presentationGate($isConfirmingClose, active: active), confirm: confirmCloseWorkspaceFromMenu ) - .mobileConnectionRecoveryOverlay(store: store, signOut: signOut) - #endif + .sheet(isPresented: presentationGate($isFeedbackComposerPresented, active: active)) { + feedbackComposer + } + .sheet(isPresented: presentationGate($isTextSheetPresented, active: active)) { + TerminalTextSheetView(surfaceID: textSheetSurfaceID) + } + .sheet(isPresented: presentationGate($isWorkspaceChangesSheetPresented, active: active)) { + WorkspaceChangesSheet( + store: store, + workspaceID: workspace.rpcWorkspaceID.rawValue, + workspaceTitle: workspace.name + ) + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + } + .workspaceRenameDialog( + isPresented: presentationGate($isRenamePresented, active: active), + text: $renameText, + onSave: commitRenameFromDialog + ) + .sheet(isPresented: presentationGate($isCustomizationPresented, active: active)) { + WorkspaceCustomizationSheet(workspace: workspace) { initialDraft, submittedDraft in + await customizeWorkspace?(workspace.id, initialDraft, submittedDraft) + ?? .failure() + } + } + .mobileConnectionRecoveryOverlay( + store: store, + signOut: signOut, + isActive: active + ) + } + + /// 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 } + ) } - #if os(iOS) 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 diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index 1159202c8603..c1ace45757b2 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -254,7 +254,8 @@ struct WorkspaceShellView: View { workspaceDestination( for: workspaceID, createWorkspace: createWorkspaceInCompactStack, - canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection + canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection, + paneZoomHosting: .navigationPush ) .toolbarVisibility(.hidden, for: .tabBar) } @@ -411,7 +412,8 @@ struct WorkspaceShellView: View { workspaceDestination( for: workspaceID, createWorkspace: createWorkspaceInCompactStack, - canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection + canCreateWorkspaceForSelection: presentation.canCreateWorkspaceForSelection, + paneZoomHosting: .navigationPush ) .toolbarVisibility(.hidden, for: .tabBar) } @@ -474,6 +476,7 @@ struct WorkspaceShellView: View { for: workspaceID, createWorkspace: createWorkspaceInCompactStack, canCreateWorkspaceForSelection: canCreateWorkspaceForSelection, + paneZoomHosting: .navigationPush, backButtonConfiguration: WorkspaceBackButtonConfiguration( unreadCount: unreadWorkspaceCount(excluding: workspaceID), badgeContrast: .darkBackground, @@ -567,6 +570,7 @@ struct WorkspaceShellView: View { for: store.selectedWorkspaceID, createWorkspace: createWorkspaceIfConnected, canCreateWorkspaceForSelection: canCreateWorkspaceForSelection, + paneZoomHosting: .column, safeAreaContext: splitColumnVisibility == .detailOnly ? .fullWidth : .splitSidebarVisible ) #if os(iOS) @@ -1048,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 { @@ -1061,6 +1066,7 @@ struct WorkspaceShellView: View { setWorkspaceUnread: setWorkspaceUnreadClosure, closeWorkspace: closeWorkspaceClosure, safeAreaContext: safeAreaContext, + paneZoomHosting: paneZoomHosting, backButtonConfiguration: backButtonConfiguration, signOut: signOut ) From 61c2901725bf8a2f93f0beee74094ca8b1d2c1d5 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 6 Aug 2026 22:39:02 -0700 Subject: [PATCH 69/78] test(panes): give the cover re-presentation liveness waits CI headroom The regression drive-through asserted the tile-tap return within waitForPaneMap's default 4 seconds. With the terminal hosted as a full-screen cover, returning from the pane map re-presents the cover and rebuilds the terminal subtree, which takes 6-10 seconds on a saturated CI runner; the first green run recorded only these two timing misses while the app survived the entire drive. The test guards liveness, not latency, so widen the return waits to 15 seconds and the map-open waits to 8. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index d3b48b7c0ca4..a5758d7afbec 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -3202,13 +3202,16 @@ final class cmuxUITests: XCTestCase { for cycle in 1...2 { tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) XCTAssertTrue( - waitForPaneMap(overlay, in: app, toBeActive: true), + waitForPaneMap(overlay, in: app, toBeActive: true, timeout: 8), "Pane map must open from the surface deck (cycle \(cycle))" ) XCTAssertEqual(app.state, .runningForeground) tap(app.buttons["MobilePaneMapTile-terminal-build"], in: app) + // Returning to the terminal re-presents its full-screen cover and + // rebuilds the terminal subtree, which takes several seconds on a + // saturated CI runner; this is a liveness check, not a latency one. XCTAssertTrue( - waitForPaneMap(overlay, in: app, toBeActive: false), + waitForPaneMap(overlay, in: app, toBeActive: false, timeout: 15), "Tapping a tile must return to the terminal (cycle \(cycle))" ) XCTAssertEqual(app.state, .runningForeground) From bb81ab3a3e0876afac7f1d2f310f4d4bffe9adc5 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 6 Aug 2026 23:12:20 -0700 Subject: [PATCH 70/78] fix(panes): hide covered pane-map chrome from accessibility in push hosting With the terminal hosted as a full-screen cover, the pane-map bar stays mounted underneath and iOS keeps its items in the accessibility tree, so the shared back button, title menu, and changes chip existed twice (once per bar). VoiceOver could reach covered controls and identifier-based automation failed with "multiple matching elements", which is how the fixture UI test caught it. Gate every pane-map toolbar item with accessibilityHidden while the cover is presented, in the workspace detail and the panes fixture; column hosting is untouched because its endpoints swap by navigation instead of covering. Co-Authored-By: Claude Fable 5 --- .../Debug/PanesTabsPreviewHost.swift | 11 +++++++++++ .../CmuxMobileShellUI/WorkspaceDetailView.swift | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 5ba230d92121..1a8ef87b4030 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -456,14 +456,23 @@ struct PanesTabsPreviewHost: View { @ToolbarContentBuilder private func previewToolbar(mode: PreviewToolbarMode) -> some ToolbarContent { + // Mirrors WorkspaceDetailView: in push hosting the pane-map bar stays + // mounted (covered) under the terminal cover's own bar, so its items + // must leave the accessibility tree while covered or shared + // identifiers match twice. + let coveredByTerminal = mode == .paneMap + && paneZoomHosting == .navigationPush + && paneZoomPresentation.isTerminalPresented ToolbarItem(id: "workspace-back", placement: .topBarLeading) { WorkspaceBackButton(unreadCount: 2, action: {}) + .accessibilityHidden(coveredByTerminal) } if #available(iOS 26.0, *) { ToolbarSpacer(.fixed, placement: .topBarLeading) } ToolbarItem(id: "workspace-title", placement: .topBarLeading) { previewWorkspaceTitleMenu(mode: mode) + .accessibilityHidden(coveredByTerminal) } switch mode { case .paneMap: @@ -472,9 +481,11 @@ struct PanesTabsPreviewHost: View { isRefreshing: isPaneMapRefreshing, refresh: { paneMapRefreshTrigger &+= 1 } ) + .accessibilityHidden(coveredByTerminal) } ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { PaneMapDoneToolbarButton(done: returnToTerminalFromPaneMap) + .accessibilityHidden(coveredByTerminal) } case .terminal: ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index c0efa41cb616..59c627b86e06 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -349,9 +349,16 @@ struct WorkspaceDetailView: View { private func workspaceDetailToolbar( mode: WorkspaceDetailToolbarMode ) -> some ToolbarContent { + // In push hosting the pane-map bar stays mounted (covered) while the + // terminal's full-screen cover shows its own bar with the same shared + // items. Without this gate both back buttons and title menus exist in + // the accessibility tree at once, breaking assistive tech and any + // identifier-based automation with "multiple matching elements". + let coveredByTerminal = mode == .paneMap && terminalCoverIsPresented if backButtonConfiguration != nil { ToolbarItem(id: "workspace-back", placement: .topBarLeading) { workspaceBackToolbarButton + .accessibilityHidden(coveredByTerminal) } if #available(iOS 26.0, *) { ToolbarSpacer(.fixed, placement: .topBarLeading) @@ -359,6 +366,7 @@ struct WorkspaceDetailView: View { } ToolbarItem(id: "workspace-title", placement: .topBarLeading) { workspaceTitleToolbarMenu(mode: mode) + .accessibilityHidden(coveredByTerminal) } if workspaceChangesAreAvailable { ToolbarItem(id: "workspace-changes", placement: .topBarTrailing) { @@ -370,6 +378,7 @@ struct WorkspaceDetailView: View { // The chrome sits on the terminal theme's background, not the // system scheme; resolve the counts' green/red for that. .environment(\.colorScheme, store.activeTerminalTheme.terminalColorScheme) + .accessibilityHidden(coveredByTerminal) } } switch mode { @@ -383,9 +392,11 @@ struct WorkspaceDetailView: View { isRefreshing: isPaneMapRefreshing, refresh: refreshPaneMapFromToolbar ) + .accessibilityHidden(coveredByTerminal) } ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { PaneMapDoneToolbarButton(done: returnToTerminalFromPaneMap) + .accessibilityHidden(coveredByTerminal) } } } From 2d0fc11090433ab54ddf9a2ea5b42c2480e8bf01 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 6 Aug 2026 23:44:30 -0700 Subject: [PATCH 71/78] test(panes): size pane-map return waits for the cover rebuild on CI The cover re-presentation rebuilds the terminal subtree, and the CI simulator VM takes 15-18 seconds for it where the old stack pop restored a retained view instantly; the green run showed the deck reappearing about 18 seconds after the tile tap while the 15-second wait had already expired. Raise waitForPaneMap's default to 20 seconds (wait-until, so fast runs are unchanged; negative checks keep their explicit short timeouts), and anchor the regression test's return check on the surface deck's reappearance, which lives inside the terminal presentation and avoids entangling the liveness check with cover toolbar hit-testing. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index a5758d7afbec..f64627bd834e 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -3199,19 +3199,22 @@ final class cmuxUITests: XCTestCase { ) let overlay = app.otherElements["MobilePaneMapOverlay"] + let deckPaneMapButton = app.buttons["MobileSurfaceDeckPaneMap"] for cycle in 1...2 { - tap(app.buttons["MobileSurfaceDeckPaneMap"], in: app) + tap(deckPaneMapButton, in: app) XCTAssertTrue( - waitForPaneMap(overlay, in: app, toBeActive: true, timeout: 8), + 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) - // Returning to the terminal re-presents its full-screen cover and - // rebuilds the terminal subtree, which takes several seconds on a - // saturated CI runner; this is a liveness check, not a latency one. + // 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( - waitForPaneMap(overlay, in: app, toBeActive: false, timeout: 15), + deckPaneMapButton.waitForExistence(timeout: 30), "Tapping a tile must return to the terminal (cycle \(cycle))" ) XCTAssertEqual(app.state, .runningForeground) @@ -3222,9 +3225,9 @@ final class cmuxUITests: XCTestCase { // 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: 8)) + XCTAssertTrue(docsRow.waitForExistence(timeout: 20)) docsRow.tap() - XCTAssertTrue(app.otherElements["MobileTerminalSurface"].waitForExistence(timeout: 8)) + XCTAssertTrue(app.otherElements["MobileTerminalSurface"].waitForExistence(timeout: 20)) try await Task.sleep(for: .seconds(3)) XCTAssertEqual( app.state, @@ -5460,7 +5463,12 @@ final class cmuxUITests: XCTestCase { _ overlay: XCUIElement, in app: XCUIApplication, toBeActive isActive: Bool, - timeout: TimeInterval = 4 + // 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 From 00bf15260f367dd357d7a22262bdb019e5ec44b4 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 7 Aug 2026 00:43:11 -0700 Subject: [PATCH 72/78] fix(panes): hide the covered pane-map bar instead of gating items Per-item accessibilityHidden inside ToolbarItem content does not remove the covered bar's items from the accessibility tree on the iOS 26.4 simulator runtime, so the shared back button still matched twice under the terminal cover ("multiple matching elements" in the fixture and regression runs). Hide the base's whole navigation bar while the cover is presented, centralized in PaneZoomHost's push hosting; the bar is invisible under the cover anyway and returns the moment the terminal starts unzooming. This supersedes the per-item gates, which are reverted. Co-Authored-By: Claude Fable 5 --- .../Debug/PanesTabsPreviewHost.swift | 11 ----------- .../PaneZoomPresentationState.swift | 12 ++++++++++++ .../CmuxMobileShellUI/WorkspaceDetailView.swift | 11 ----------- 3 files changed, 12 insertions(+), 22 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift index 1a8ef87b4030..5ba230d92121 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Debug/PanesTabsPreviewHost.swift @@ -456,23 +456,14 @@ struct PanesTabsPreviewHost: View { @ToolbarContentBuilder private func previewToolbar(mode: PreviewToolbarMode) -> some ToolbarContent { - // Mirrors WorkspaceDetailView: in push hosting the pane-map bar stays - // mounted (covered) under the terminal cover's own bar, so its items - // must leave the accessibility tree while covered or shared - // identifiers match twice. - let coveredByTerminal = mode == .paneMap - && paneZoomHosting == .navigationPush - && paneZoomPresentation.isTerminalPresented ToolbarItem(id: "workspace-back", placement: .topBarLeading) { WorkspaceBackButton(unreadCount: 2, action: {}) - .accessibilityHidden(coveredByTerminal) } if #available(iOS 26.0, *) { ToolbarSpacer(.fixed, placement: .topBarLeading) } ToolbarItem(id: "workspace-title", placement: .topBarLeading) { previewWorkspaceTitleMenu(mode: mode) - .accessibilityHidden(coveredByTerminal) } switch mode { case .paneMap: @@ -481,11 +472,9 @@ struct PanesTabsPreviewHost: View { isRefreshing: isPaneMapRefreshing, refresh: { paneMapRefreshTrigger &+= 1 } ) - .accessibilityHidden(coveredByTerminal) } ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { PaneMapDoneToolbarButton(done: returnToTerminalFromPaneMap) - .accessibilityHidden(coveredByTerminal) } case .terminal: ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift index 6e9c7ac6767d..8f88ba7a3fb3 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneZoomPresentationState.swift @@ -104,8 +104,20 @@ struct PaneZoomHost: View { /// 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 } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 59c627b86e06..c0efa41cb616 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -349,16 +349,9 @@ struct WorkspaceDetailView: View { private func workspaceDetailToolbar( mode: WorkspaceDetailToolbarMode ) -> some ToolbarContent { - // In push hosting the pane-map bar stays mounted (covered) while the - // terminal's full-screen cover shows its own bar with the same shared - // items. Without this gate both back buttons and title menus exist in - // the accessibility tree at once, breaking assistive tech and any - // identifier-based automation with "multiple matching elements". - let coveredByTerminal = mode == .paneMap && terminalCoverIsPresented if backButtonConfiguration != nil { ToolbarItem(id: "workspace-back", placement: .topBarLeading) { workspaceBackToolbarButton - .accessibilityHidden(coveredByTerminal) } if #available(iOS 26.0, *) { ToolbarSpacer(.fixed, placement: .topBarLeading) @@ -366,7 +359,6 @@ struct WorkspaceDetailView: View { } ToolbarItem(id: "workspace-title", placement: .topBarLeading) { workspaceTitleToolbarMenu(mode: mode) - .accessibilityHidden(coveredByTerminal) } if workspaceChangesAreAvailable { ToolbarItem(id: "workspace-changes", placement: .topBarTrailing) { @@ -378,7 +370,6 @@ struct WorkspaceDetailView: View { // The chrome sits on the terminal theme's background, not the // system scheme; resolve the counts' green/red for that. .environment(\.colorScheme, store.activeTerminalTheme.terminalColorScheme) - .accessibilityHidden(coveredByTerminal) } } switch mode { @@ -392,11 +383,9 @@ struct WorkspaceDetailView: View { isRefreshing: isPaneMapRefreshing, refresh: refreshPaneMapFromToolbar ) - .accessibilityHidden(coveredByTerminal) } ToolbarItem(id: "workspace-trailing", placement: .topBarTrailing) { PaneMapDoneToolbarButton(done: returnToTerminalFromPaneMap) - .accessibilityHidden(coveredByTerminal) } } } From 7386aa181ad923b4f80bd4d648133dc343d7b1ca Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 7 Aug 2026 02:19:11 -0700 Subject: [PATCH 73/78] test(panes): only require pane-map-side hittability in waitForPaneMap Toolbar items inside a presented full-screen cover never report hittable to XCUI on the CI simulator runtime even though real taps land (the shared tap helper already falls back to frame coordinates for that). The inactive side of waitForPaneMap gated on the terminal utilities button's hittability, so every return-to-terminal wait expired on CI while the app was demonstrably healthy. Keep the hittability requirement for the pane-map side, whose bar is a regular navigation bar, and accept existence plus pane-map-chrome absence as the terminal endpoint signal. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index f64627bd834e..76bf83391a7e 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -5475,6 +5475,11 @@ final class cmuxUITests: XCTestCase { // 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" ] @@ -5482,7 +5487,7 @@ final class cmuxUITests: XCTestCase { predicate: NSPredicate( block: { _, _ in modeControl.exists - && modeControl.isHittable + && (!isActive || modeControl.isHittable) && (isActive ? overlay.exists : !overlay.exists) && (isActive || !app.buttons["MobilePaneMapRefresh"].exists) } From 51bf1abd3876601a55abbbfc98255c98a6bebc85 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 7 Aug 2026 03:44:48 -0700 Subject: [PATCH 74/78] test(panes): retry the docs-row push if the list swallowed the first tap Green run 31167770677 passed both zoom round-trips and the pop to the list, then the workspace-docs row tap left the runner on the list: the row was tapped while the popped pane workspace's cover was still tearing down, so the push never started. Retry the row tap once when the row is demonstrably still on screen after the terminal wait expires; the terminal-surface assertion stays strict. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 76bf83391a7e..098451c91559 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -3227,7 +3227,14 @@ final class cmuxUITests: XCTestCase { let docsRow = app.descendants(matching: .any)["MobileWorkspaceRow-workspace-docs"] XCTAssertTrue(docsRow.waitForExistence(timeout: 20)) docsRow.tap() - XCTAssertTrue(app.otherElements["MobileTerminalSurface"].waitForExistence(timeout: 20)) + 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() + } + XCTAssertTrue(docsTerminal.waitForExistence(timeout: 20)) try await Task.sleep(for: .seconds(3)) XCTAssertEqual( app.state, From 5536a50eab6efe6f2e8962c7fd92d0904ecc417d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 13 Aug 2026 00:01:39 -0700 Subject: [PATCH 75/78] fix(ios): preserve gated connect failure copy --- .../Sources/CmuxMobileShell/MobilePairingFailure.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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, From b27745f6cb5992d3a1f0f24ad1b0be976ad88c72 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 13 Aug 2026 04:35:54 -0700 Subject: [PATCH 76/78] test(panes): dump the AX tree when a pane-map presentation wait times out The waitForPaneMap timeout is the only failure signal CI keeps (the xcresult is not uploaded), so a red run never says which of the three conditions blocked. Print the condition values and the accessibility tree on timeout. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 098451c91559..dcca9eaf044d 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -5501,7 +5501,21 @@ final class cmuxUITests: XCTestCase { ), object: modeControl ) - return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed + 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 From 38a06df046ce43ec03ca93da98b71b54e9d35e4d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 13 Aug 2026 05:11:36 -0700 Subject: [PATCH 77/78] fix(panes): hide the covered pane map from accessibility at the UIKit level With the terminal hosted as a full-screen cover, the pane map stays mounted underneath and SwiftUI's subtree accessibilityHidden is not honored for it: the AX dump at the failing waits showed the overlay marker, collection, tiles, and tab strips all still queryable while the cover was up, so assistive tech saw the covered map and every identifier-based wait for the terminal return timed out. The collection container now sets accessibilityElementsHidden from the map's visibility (the reliable UIKit flag), and the overlay marker swaps to a Covered identifier so presentation queries cannot match it. Co-Authored-By: Claude Fable 5 --- .../CmuxMobileShellUI/PaneMapCollectionView.swift | 7 +++++++ .../Sources/CmuxMobileShellUI/PaneMapOverlay.swift | 11 ++++++++++- .../PaneMapCollectionLayoutEngineTests.swift | 1 + 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift index 60f465883c02..b6230a025a70 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapCollectionView.swift @@ -55,6 +55,11 @@ struct PaneMapCollectionView: UIViewRepresentable { 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 @@ -87,6 +92,7 @@ struct PaneMapCollectionView: UIViewRepresentable { labels: overflowLabels, scrollStep: context.coordinator.scrollOneViewport ) + container.accessibilityElementsHidden = !isVisible context.coordinator.attach(collectionView: collectionView, container: container) context.coordinator.reconcile(items: items) return container @@ -104,6 +110,7 @@ struct PaneMapCollectionView: UIViewRepresentable { labels: overflowLabels, scrollStep: context.coordinator.scrollOneViewport ) + container.accessibilityElementsHidden = !isVisible context.coordinator.reconcile(items: items) } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift index f379f1b51828..bf62d1e4e308 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PaneMapOverlay.swift @@ -55,16 +55,25 @@ struct PaneMapOverlay: View { 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("MobilePaneMapOverlay") + .accessibilityIdentifier( + isVisible ? "MobilePaneMapOverlay" : "MobilePaneMapOverlayCovered" + ) } .onAppear { if isVisible { diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift index e55641db3bb5..49cb7dad83af 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PaneMapCollectionLayoutEngineTests.swift @@ -272,6 +272,7 @@ import UIKit bottom: "bottom" ), allowsReordering: true, + isVisible: false, selectPreviewSurface: { _, _ in }, jumpToTerminal: { _ in }, reorderPanes: { _, _ in true } From 059ed21d08af40a1b6d999d5b66ac5549fe8b93d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 13 Aug 2026 05:42:26 -0700 Subject: [PATCH 78/78] test(panes): dump the AX tree when the post-pane docs push produces no terminal Both docs-row taps land with the app alive, yet MobileTerminalSurface never appears, so the push after pane-workspace teardown fails without a crash. CI keeps no xcresult; print the tree so the swallowed push is attributable to the list, an interposed layer, or an empty detail. Co-Authored-By: Claude Fable 5 --- ios/cmuxUITests/cmuxUITests.swift | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index dcca9eaf044d..ecad2ab67feb 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -3234,7 +3234,19 @@ final class cmuxUITests: XCTestCase { // retry once if we are demonstrably still on the list. docsRow.tap() } - XCTAssertTrue(docsTerminal.waitForExistence(timeout: 20)) + 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,