From c619c10b5511a8cab621d83cdb41c239c9f4d47e Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 01:43:22 -0700 Subject: [PATCH 1/8] iOS: re-implement still-needed fixes from #5259 #5259 was 569 commits behind and edited files the iOS refactor deleted, so it was closed and the still-relevant fixes re-done fresh against current main: - Auth: run the sign-out teardown hook (push-token DELETE) BEFORE revoking the Stack session, so the server-side device-token delete can still authenticate; otherwise the device keeps receiving pushes for a signed-out account. (+test) - iOS push notification toggle strings localized (en + ja). - Notifications toggle: mirror MobilePushCoordinator.isEnabled into @State so the label/icon refresh after the async enable/disable (isEnabled is a non-observable UserDefaults read). - createTerminal(in:): target an explicit workspace so an in-flight create can't land in a drifted selection. (+test) - Terminal focus-suppression + detached-surface guards: suppress autofocus after chrome actions, dismiss the hidden input before chrome so the grid recomputes full-height, and stop a SwiftUI-dismantled surface from doing render/output/a11y work. Ported across GhosttySurfaceView / GhosttySurfaceRepresentable / WorkspaceShellView / WorkspaceDetailContainer / WorkspaceDetailView. Skipped (already on main): nonisolated isolation fixes; .id(terminalID) remount + delegate isolation. Dropped CMUX_PUSH_REDACTED_* (server-side, obsolete). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Coordinator/AuthCoordinator.swift | 12 ++- .../AuthCoordinatorTests.swift | 19 +++++ .../Tests/CmuxAuthRuntimeTests/Fakes.swift | 6 ++ .../MobileShellComposite.swift | 19 +++-- .../MobileShellCompositePreviewTests.swift | 16 ++++ .../GhosttySurfaceRepresentable.swift | 9 ++- .../MobileSettingsView.swift | 15 +++- .../WorkspaceDetailContainer.swift | 8 +- .../WorkspaceDetailView.swift | 50 +++++++++++- .../WorkspaceShellView.swift | 17 +++- .../GhosttySurfaceView.swift | 78 +++++++++++++++++-- ios/cmux/Resources/Localizable.xcstrings | 34 ++++++++ 12 files changed, 259 insertions(+), 24 deletions(-) diff --git a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift index 554323d8b38a..9c2e8f25ad41 100644 --- a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +++ b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift @@ -433,9 +433,16 @@ public final class AuthCoordinator { /// Sign out and clear local + persisted session state. /// /// - Parameter onSignedOut: An async hook the composition root uses to run - /// post-sign-out side effects (e.g. push unregistration) that live above - /// this package. Defaults to a no-op. + /// token-authenticated teardown (e.g. deleting the APNs device token from + /// the server) that lives above this package. It runs **before** the Stack + /// session is revoked and local state is cleared, so the hook still has a + /// valid access/refresh token to authenticate its request. After + /// `client.signOut()` the token is gone and a server-side DELETE would be + /// silently skipped, leaving the device receiving pushes for a signed-out + /// account. Defaults to a no-op. public func signOut(onSignedOut: @Sendable () async -> Void = {}) async { + // Run the teardown hook first, while tokens are still valid (see note). + await onSignedOut() do { try await client.signOut() } catch { @@ -443,7 +450,6 @@ public final class AuthCoordinator { } if launch.includesDevAuth { debugCredentials = nil } clearAuthState() - await onSignedOut() } // MARK: - Tokens diff --git a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift index e12395430dc0..ad9bc9bf61c9 100644 --- a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift +++ b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift @@ -98,6 +98,25 @@ import Testing #expect(await ranHook.fired) } + @Test func signOutRunsHookWhileTokensStillValid() async throws { + // The push-token DELETE runs as the onSignedOut hook and needs a valid + // access token. Regression: the hook used to run after client.signOut() + // revoked the session, so the DELETE was silently skipped. + let user = CMUXAuthUser(id: "u1", primaryEmail: "a@b.com", displayName: "A") + let client = FakeAuthClient(user: user) + let (coordinator, _) = makeCoordinator(client: client) + try await coordinator.signInWithPassword(email: "a@b.com", password: "pw") + + let probe = TokenProbe() + await coordinator.signOut(onSignedOut: { + let token = try? await coordinator.accessToken() + await probe.set(token) + }) + + #expect(await probe.value != nil) // hook saw a valid token (ran before revoke) + #expect(coordinator.isAuthenticated == false) // session revoked afterward + } + @Test func devAuthFortyTwoShortcutSignsIn() async throws { let user = CMUXAuthUser(id: "debug", primaryEmail: "l@l.com", displayName: "L") let client = FakeAuthClient(user: user) diff --git a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift index 90cdb58f878b..1c8d5a6a075a 100644 --- a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift +++ b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift @@ -110,6 +110,12 @@ actor HookFlag { func fire() { fired = true } } +/// Captures a value observed inside an async hook, for ordering assertions. +actor TokenProbe { + private(set) var value: String? + func set(_ token: String?) { value = token } +} + extension AuthLaunchOptions { static func plain(includesDevAuth: Bool = false) -> AuthLaunchOptions { AuthLaunchOptions( diff --git a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index a50456942d38..e16889ee50c2 100644 --- a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -762,7 +762,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { selectedTerminalID = workspace.terminals.first?.id } - public func createTerminal() { + /// Creates a terminal in `workspaceID`, or the selected workspace when nil. + /// + /// Callers that act on a specific workspace (e.g. the "+" button on a + /// workspace row) should pass its id so an in-flight create can't land in a + /// different workspace if the selection drifts before the async work runs. + public func createTerminal(in workspaceID: MobileWorkspacePreview.ID? = nil) { + let targetWorkspaceID = workspaceID ?? selectedWorkspace?.id + // Pin selection to the target so async creation + the resulting + // terminal selection stay on the workspace the caller intended. + if let targetWorkspaceID { selectedWorkspaceID = targetWorkspaceID } guard remoteClient == nil else { guard createTerminalTask == nil else { return } let taskID = UUID() @@ -770,11 +779,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { createTerminalTask = Task { @MainActor [weak self] in defer { self?.clearCreateTerminalTask(id: taskID) } guard let self else { return } - await self.createRemoteTerminal() + await self.createRemoteTerminal(in: targetWorkspaceID) } return } - guard let workspaceIndex = workspaces.firstIndex(where: { $0.id == selectedWorkspace?.id }) else { + guard let workspaceIndex = workspaces.firstIndex(where: { $0.id == targetWorkspaceID }) else { return } let terminalIndex = workspaces[workspaceIndex].terminals.count + 1 @@ -1308,9 +1317,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } - private func createRemoteTerminal() async { + private func createRemoteTerminal(in explicitWorkspaceID: MobileWorkspacePreview.ID? = nil) async { guard let client = remoteClient, - let workspaceID = selectedWorkspace?.id.rawValue else { return } + let workspaceID = (explicitWorkspaceID ?? selectedWorkspace?.id)?.rawValue else { return } let requestedWorkspaceID = MobileWorkspacePreview.ID(rawValue: workspaceID) let generation = connectionGeneration do { diff --git a/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index 83e4400fe24c..5c8b0f3d9ab1 100644 --- a/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -78,6 +78,22 @@ import Testing #expect(store.selectedTerminalID?.rawValue == "workspace-main-terminal-4") } + @Test func createTerminalUsesExplicitWorkspaceContextOverStaleSelection() { + let store = MobileShellComposite.preview() + store.signIn() + store.pairingCode = "debug" + store.connectPreviewHost() + // Selection drifts to a different workspace than the one the "+" was tapped on. + store.selectedWorkspaceID = "workspace-docs" + + store.createTerminal(in: "workspace-main") + + // The new terminal lands in the explicitly-targeted workspace, not the selected one. + #expect(store.selectedWorkspace?.id.rawValue == "workspace-main") + #expect(store.selectedWorkspace?.terminals.count == 4) + #expect(store.selectedTerminalID?.rawValue == "workspace-main-terminal-4") + } + @Test func selectingWorkspaceReconcilesTerminalSelection() { let store = MobileShellComposite.preview() store.signIn() diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift index de3ef044e7ed..cf9c1c4edde0 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift @@ -16,6 +16,11 @@ struct GhosttySurfaceRepresentable: UIViewRepresentable { let surfaceID: String let store: CMUXMobileShellStore let fontSize: Float32 + /// Whether the mounted surface should grab the keyboard when it attaches to + /// a window. Driven by the host's autofocus-suppression state so chrome + /// actions (create workspace/terminal, switch terminal) do not pop the + /// software keyboard. + var autoFocusOnWindowAttach: Bool = true func makeCoordinator() -> Coordinator { Coordinator(surfaceID: surfaceID, store: store) @@ -38,15 +43,17 @@ struct GhosttySurfaceRepresentable: UIViewRepresentable { delegate: context.coordinator, fontSize: fontSize ) + view.autoFocusOnWindowAttach = autoFocusOnWindowAttach context.coordinator.attach(surfaceView: view) return view } func updateUIView(_ uiView: UIView, context: Context) { - // No prop-driven mutations yet; bytes flow via the byte sink. + (uiView as? GhosttySurfaceView)?.autoFocusOnWindowAttach = autoFocusOnWindowAttach } static func dismantleUIView(_ uiView: UIView, coordinator: Coordinator) { + (uiView as? GhosttySurfaceView)?.prepareForDismantle() coordinator.detach() } diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift index a9d1ca6b451b..d71032097b3e 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift @@ -16,6 +16,11 @@ struct MobileSettingsView: View { @Environment(\.dismiss) private var dismiss @State private var showingShortcuts = false + /// Mirrors ``MobilePushCoordinator/isEnabled`` so the toggle's label/icon + /// update after the async enable/disable. The coordinator exposes + /// `isEnabled` as a non-observable `UserDefaults` read, so reading it + /// directly in `body` would not re-render when it flips. + @State private var notificationsEnabled = false var body: some View { NavigationStack { @@ -87,23 +92,25 @@ struct MobileSettingsView: View { Section(L10n.string("mobile.settings.notifications", defaultValue: "Notifications")) { Button { Task { - if pushCoordinator.isEnabled { + if notificationsEnabled { await pushCoordinator.disable() + notificationsEnabled = false } else { - _ = await pushCoordinator.enable() + notificationsEnabled = await pushCoordinator.enable() } } } label: { Label( - pushCoordinator.isEnabled + notificationsEnabled ? L10n.string("mobile.notifications.disable", defaultValue: "Turn Off Agent Notifications") : L10n.string("mobile.notifications.enable", defaultValue: "Notify Me About Agents"), - systemImage: pushCoordinator.isEnabled ? "bell.slash" : "bell" + systemImage: notificationsEnabled ? "bell.slash" : "bell" ) } .accessibilityIdentifier("MobileSettingsNotifications") } } + .onAppear { notificationsEnabled = pushCoordinator.isEnabled } .navigationTitle(L10n.string("mobile.workspaces.settings", defaultValue: "Settings")) .navigationBarTitleDisplayMode(.inline) .toolbar { diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift index 50d699284f92..f72dc790155c 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift @@ -14,6 +14,8 @@ struct WorkspaceDetailContainer: View { let workspaceID: MobileWorkspacePreview.ID? let createWorkspace: () -> Void let safeAreaContext: MobileTerminalSafeAreaContext + @Binding var suppressNextTerminalAutoFocus: Bool + @Binding var terminalAutoFocusSuppressedSurfaceIDs: Set private var workspace: MobileWorkspacePreview? { if let workspaceID { @@ -34,10 +36,12 @@ struct WorkspaceDetailContainer: View { set: { store.selectTerminal($0) } ), createWorkspace: createWorkspace, - createTerminal: store.createTerminal, + createTerminal: { store.createTerminal(in: workspace.id) }, reportTerminalViewport: store.reportTerminalViewport, sendTerminalInput: store.sendTerminalRawInput, - safeAreaContext: safeAreaContext + safeAreaContext: safeAreaContext, + suppressNextTerminalAutoFocus: $suppressNextTerminalAutoFocus, + terminalAutoFocusSuppressedSurfaceIDs: $terminalAutoFocusSuppressedSurfaceIDs ) .onAppear { if store.selectedWorkspaceID != workspace.id { diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 98b14010e404..037c4ae165eb 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -22,6 +22,8 @@ struct WorkspaceDetailView: View { let reportTerminalViewport: (MobileWorkspacePreview.ID, MobileTerminalPreview.ID, MobileTerminalViewportSize) -> Void let sendTerminalInput: (String) -> Void let safeAreaContext: MobileTerminalSafeAreaContext + @Binding var suppressNextTerminalAutoFocus: Bool + @Binding var terminalAutoFocusSuppressedSurfaceIDs: Set @State private var isTerminalPickerPresented = false private var selectedTerminal: MobileTerminalPreview? { @@ -45,7 +47,8 @@ struct WorkspaceDetailView: View { GhosttySurfaceRepresentable( surfaceID: terminalID, store: store, - fontSize: MobileTerminalFontPreference.defaultSize + fontSize: MobileTerminalFontPreference.defaultSize, + autoFocusOnWindowAttach: shouldAutoFocusTerminalSurface(terminalID) ) // Identity must track the selected terminal. The representable's // coordinator binds its byte sink to the surfaceID at make time and @@ -54,6 +57,9 @@ struct WorkspaceDetailView: View { // Keying on terminalID tears down the old surface (unregistering its // sink via dismantleUIView) and builds the newly-selected one. .id(terminalID) + .onAppear { + clearConsumedTerminalAutoFocusSuppression(for: terminalID) + } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .background(TerminalPalette.background) // The surface positions its grid + docked toolbar from @@ -89,6 +95,12 @@ struct WorkspaceDetailView: View { .background(TerminalPalette.background) #endif .navigationTitle(workspace.name) + .onAppear { + suppressPendingTerminalAutoFocusIfNeeded(for: selectedTerminal?.id) + } + .onChange(of: selectedTerminal?.id) { _, terminalID in + suppressPendingTerminalAutoFocusIfNeeded(for: terminalID) + } .mobileTerminalNavigationChrome() .toolbar { #if os(iOS) @@ -219,28 +231,64 @@ struct WorkspaceDetailView: View { private func createWorkspaceFromToolbar() { dismissTerminalKeyboardForChrome() + suppressNextTerminalAutoFocus = true createWorkspace() } private func createWorkspaceFromTerminalPicker() { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = false + suppressNextTerminalAutoFocus = true createWorkspace() } private func createTerminalFromToolbar() { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = false + suppressNextTerminalAutoFocus = true createTerminal() } private func selectTerminalFromPicker(_ terminalID: MobileTerminalPreview.ID) { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = false + // Switching to a different terminal is chrome, not a typing intent, so + // the newly-selected surface must not grab the keyboard on attach. + if selectedTerminal?.id != terminalID { + terminalAutoFocusSuppressedSurfaceIDs.insert(terminalID.rawValue) + } + suppressNextTerminalAutoFocus = false selectedTerminalID = terminalID } private func dismissTerminalKeyboardForChrome() { + // Resign the terminal's hidden text input first so the surface clears + // its keyboard geometry and recomputes full-height before chrome covers + // it; then sweep any other responder across the scene. + GhosttySurfaceView.resignActiveInput() UIApplication.shared.dismissMobileKeyboard() } + + /// Whether the surface for `terminalID` may autofocus on its next window + /// attach. False while a one-shot suppression is pending or this surface is + /// in the per-surface suppression set. + private func shouldAutoFocusTerminalSurface(_ terminalID: String) -> Bool { + !suppressNextTerminalAutoFocus + && !terminalAutoFocusSuppressedSurfaceIDs.contains(terminalID) + } + + /// Clears the per-surface suppression once the surface has appeared (and so + /// has already mounted with autofocus disabled). + private func clearConsumedTerminalAutoFocusSuppression(for terminalID: String) { + terminalAutoFocusSuppressedSurfaceIDs.remove(terminalID) + } + + /// Converts a pending one-shot suppression into a per-surface entry for the + /// terminal that is about to become visible, then resets the one-shot flag. + private func suppressPendingTerminalAutoFocusIfNeeded(for terminalID: MobileTerminalPreview.ID?) { + guard suppressNextTerminalAutoFocus, + let terminalID else { return } + terminalAutoFocusSuppressedSurfaceIDs.insert(terminalID.rawValue) + suppressNextTerminalAutoFocus = false + } } diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index b919cad03ae1..7076c0a24a41 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -16,6 +16,16 @@ struct WorkspaceShellView: View { @State private var pendingCompactCreateNavigationWorkspaceIDs: Set? @State private var hasPresentedSplitDetail = false @State private var splitColumnVisibility: NavigationSplitViewVisibility = .automatic + /// One-shot suppression of the next terminal autofocus. Set after a chrome + /// action that creates a workspace or terminal so the freshly-attached + /// surface does not steal the keyboard. Consumed (and translated into a + /// per-surface entry in ``terminalAutoFocusSuppressedSurfaceIDs``) when the + /// detail view next appears or its selected terminal changes. + @State private var suppressNextTerminalAutoFocus = false + /// Surface IDs whose next window attach must NOT autofocus. A surface in + /// this set mounts with `autoFocusOnWindowAttach: false`; the entry clears + /// once that surface has appeared and consumed the suppression. + @State private var terminalAutoFocusSuppressedSurfaceIDs: Set = [] #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.verticalSizeClass) private var verticalSizeClass @@ -131,6 +141,9 @@ struct WorkspaceShellView: View { private func selectWorkspace(_ id: MobileWorkspacePreview.ID) { pendingCompactCreateNavigationWorkspaceIDs = nil + // Selecting an existing workspace is a user-driven focus intent, so the + // terminal that comes up should be allowed to take the keyboard. + suppressNextTerminalAutoFocus = false store.selectedWorkspaceID = id if usesCompactStack, compactNavigationPath.last != id { compactNavigationPath = [id] @@ -173,7 +186,9 @@ struct WorkspaceShellView: View { store: store, workspaceID: workspaceID, createWorkspace: createWorkspace, - safeAreaContext: safeAreaContext + safeAreaContext: safeAreaContext, + suppressNextTerminalAutoFocus: $suppressNextTerminalAutoFocus, + terminalAutoFocusSuppressedSurfaceIDs: $terminalAutoFocusSuppressedSurfaceIDs ) } } diff --git a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift index ad958419940e..cb53017b76cb 100644 --- a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift +++ b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift @@ -496,6 +496,12 @@ public enum TerminalInputAccessoryAction: Int, CaseIterable { } public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { + /// The surface whose hidden text input is currently first responder, if any. + /// + /// Tracked statically so chrome (SwiftUI overlays presented over the + /// terminal) can dismiss the live keyboard via ``resignActiveInput()`` + /// without holding a reference to the specific surface. + private static weak var activeInputSurface: GhosttySurfaceView? private weak var runtime: GhosttyRuntime? private weak var delegate: GhosttySurfaceViewDelegate? private let fontSize: Float32 @@ -771,7 +777,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { guard let self else { return } // Toggle: dismiss when the keyboard is up, bring it back when down. if self.inputProxy.isFirstResponder { - self.inputProxy.resignFirstResponder() + self.resignInput() } else { self.focusInput() } @@ -944,6 +950,15 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { /// flush with the grid bottom (no gap) and its bottom rests on the keyboard /// edge (up) or above the home indicator (down). private weak var dockedToolbar: UIView? + /// True once SwiftUI has dismantled the hosting representable for this + /// surface. A dismantled surface performs no render, output, or + /// accessibility work so a view SwiftUI has removed cannot keep driving the + /// renderer or the accessibility tree. + private var isDismantled = false + /// Whether the hidden terminal input should become first responder when the + /// surface attaches to a window. Set to `false` to suppress autofocus after + /// chrome actions (create workspace/terminal, switch terminal) so the + /// software keyboard does not pop up unprompted. public var autoFocusOnWindowAttach = true @objc private func handleKeyboardWillShow(_ notification: Notification) { @@ -1332,6 +1347,10 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { MobileDebugLog.anchormux("surface.didMoveToWindow window=\(window != nil)") syncSurfaceVisibility() if window != nil { + isDismantled = false + #if DEBUG + debugAccessibilityProxy.isAccessibilityElement = true + #endif setNeedsGeometrySync() setFocus(true) if autoFocusOnWindowAttach { @@ -1339,15 +1358,14 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { } startDisplayLink() } else { - stopDisplayLink() - setFocus(false) + prepareForReuseAfterDetach() } } private var lastProcessOutputLogTime: CFTimeInterval = 0 public func processOutput(_ data: Data) { - guard let surface else { return } + guard let surface, !isDismantled else { return } #if DEBUG if lastInputTimestamp > 0 { let elapsed = (CACurrentMediaTime() - lastInputTimestamp) * 1000.0 @@ -1399,7 +1417,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { } #endif DispatchQueue.main.async { - guard let self else { return } + guard let self, !self.isDismantled else { return } self.needsDraw = true if let cursorVisibilityDelta, cursorVisibilityDelta != self.hostCursorVisible { self.hostCursorVisible = cursorVisibilityDelta @@ -1469,11 +1487,53 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { @objc func focusInput() { onFocusInputRequestedForTesting?() + Self.activeInputSurface = self setNeedsGeometrySync() inputProxy.updateAccessoryLayoutInsets() inputProxy.becomeFirstResponder() } + /// Resigns the currently focused terminal input proxy, if any. + /// + /// Use before presenting SwiftUI chrome over the terminal so UIKit releases + /// the hidden text input and the terminal can recalculate full-height + /// geometry after the keyboard leaves. + public static func resignActiveInput() { + activeInputSurface?.resignInput() + } + + /// Resigns this surface's hidden text input and clears keyboard geometry. + public func resignInput() { + let wasFirstResponder = inputProxy.isFirstResponder + inputProxy.resignFirstResponder() + if Self.activeInputSurface === self { + Self.activeInputSurface = nil + } + guard wasFirstResponder, keyboardHeight != 0 else { return } + keyboardHeight = 0 + setNeedsGeometrySync() + } + + /// Stops user-visible and accessibility output from a surface SwiftUI has removed. + public func prepareForDismantle() { + isDismantled = true + prepareForReuseAfterDetach() + } + + /// Quiesces the surface on window detach: resigns input, stops the display + /// link, drops focus, and removes the debug accessibility carrier from the + /// tree. Does not set ``isDismantled`` so a transient detach can re-attach + /// and resume; only ``prepareForDismantle()`` marks the surface dead. + private func prepareForReuseAfterDetach() { + resignInput() + stopDisplayLink() + setFocus(false) + #if DEBUG + debugAccessibilityProxy.accessibilityLabel = nil + debugAccessibilityProxy.isAccessibilityElement = false + #endif + } + func simulateTextInputForTesting(_ text: String) { setFocus(true) sendText(text) @@ -1805,7 +1865,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { // now bounded in libghostty (so a foreground stall self-heals as a // skipped frame the display link re-drives), but we still gate on // suspension; `resumeRendering` clears it on the next active transition. - guard !renderingSuspended, let surface else { return } + guard !renderingSuspended, let surface, !isDismantled else { return } // Coalesce: never let more than one render_now sit on the serial queue. // (Called on main from the display link.) if renderInFlight { @@ -1823,6 +1883,10 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { DispatchQueue.main.async { guard let self else { return } self.renderInFlight = false + guard !self.isDismantled else { + self.needsAnotherRender = false + return + } if self.needsAnotherRender { self.needsAnotherRender = false self.requestRender() @@ -2327,7 +2391,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { } func drawForWakeup() { - guard surface != nil, window != nil else { return } + guard surface != nil, window != nil, !isDismantled else { return } // Don't call `ghostty_surface_refresh` here: that wakes the renderer // thread to present asynchronously (`setSurface` → `dispatch_async` to // main → size-guard discard), which both blanks frames and competes diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 95fc6fd17106..690f97cba086 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -2907,6 +2907,40 @@ } } } + }, + "mobile.notifications.enable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Notify Me About Agents" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント通知を受け取る" + } + } + } + }, + "mobile.notifications.disable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Turn Off Agent Notifications" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "エージェント通知をオフにする" + } + } + } } }, "version": "1.0" From c389a84121c64421e1d467fa60b2b523a9d22076 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 01:57:32 -0700 Subject: [PATCH 2/8] iOS: suppress terminal autofocus on workspace-list create Autoreview: the workspace-list '+' (split + compact) created a workspace and mounted its terminal with autoFocusOnWindowAttach still true, popping the keyboard. Route both list-create paths through the same suppression the detail toolbar uses. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../CmuxMobileShellUI/WorkspaceShellView.swift | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index 7076c0a24a41..8838c87f4a78 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -121,7 +121,7 @@ struct WorkspaceShellView: View { connectionStatus: store.macConnectionStatus, navigationStyle: .sidebar, selectWorkspace: selectWorkspace, - createWorkspace: store.createWorkspace, + createWorkspace: createWorkspaceFromSplitList, rescanQR: { store.disconnectAndForgetActiveMac() }, signOut: signOut ) @@ -129,7 +129,7 @@ struct WorkspaceShellView: View { } detail: { workspaceDestination( for: store.selectedWorkspaceID, - createWorkspace: store.createWorkspace, + createWorkspace: createWorkspaceFromSplitList, safeAreaContext: splitColumnVisibility == .detailOnly ? .fullWidth : .splitSidebarVisible ) } @@ -150,7 +150,17 @@ struct WorkspaceShellView: View { } } + /// Split-layout list/detail "+" create. Suppresses autofocus like the + /// compact path so the new terminal doesn't pop the keyboard on mount. + private func createWorkspaceFromSplitList() { + suppressNextTerminalAutoFocus = true + store.createWorkspace() + } + private func createWorkspaceInCompactStack() { + // Creating a workspace is a chrome action: the new terminal should not + // grab the keyboard the instant it mounts. + suppressNextTerminalAutoFocus = true let existingWorkspaceIDs = Set(store.workspaces.map(\.id)) pendingCompactCreateNavigationWorkspaceIDs = existingWorkspaceIDs store.createWorkspace() From 17d9b571c9171e1bc056cc2b8d9256429a604e52 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 02:29:35 -0700 Subject: [PATCH 3/8] iOS: don't block sign-out on push teardown; let keyboardWillHide own cleanup Autoreview round 2: - AuthCoordinator.signOut: bound the onSignedOut teardown (push-token DELETE) in a task group with a 5s deadline so local sign-out is never gated on a slow/ stuck network call, while still giving the DELETE a chance with valid tokens. - GhosttySurfaceView.resignInput(): stop pre-zeroing keyboardHeight; let resignFirstResponder's keyboardWillHide run the full hide cleanup (toolbar animation, proxy state) instead of short-circuiting it. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Coordinator/AuthCoordinator.swift | 17 ++++++++++++++--- .../CmuxMobileTerminal/GhosttySurfaceView.swift | 9 +++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift index 9c2e8f25ad41..32324e225153 100644 --- a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +++ b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift @@ -440,9 +440,20 @@ public final class AuthCoordinator { /// `client.signOut()` the token is gone and a server-side DELETE would be /// silently skipped, leaving the device receiving pushes for a signed-out /// account. Defaults to a no-op. - public func signOut(onSignedOut: @Sendable () async -> Void = {}) async { - // Run the teardown hook first, while tokens are still valid (see note). - await onSignedOut() + public func signOut(onSignedOut: @escaping @Sendable () async -> Void = {}) async { + // Give token-authenticated teardown (the push-token DELETE) a bounded + // chance to run while tokens are still valid, but never block local + // sign-out on a slow/stuck network call: proceed as soon as the hook + // finishes or the deadline elapses, whichever comes first. + await withTaskGroup(of: Void.self) { group in + group.addTask { await onSignedOut() } + group.addTask { + // Bounded teardown deadline (cancelled below once one task wins). + try? await Task.sleep(for: .seconds(5)) + } + await group.next() + group.cancelAll() + } do { try await client.signOut() } catch { diff --git a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift index cb53017b76cb..a41c5e59e0f1 100644 --- a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift +++ b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift @@ -1504,14 +1504,15 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { /// Resigns this surface's hidden text input and clears keyboard geometry. public func resignInput() { - let wasFirstResponder = inputProxy.isFirstResponder inputProxy.resignFirstResponder() if Self.activeInputSurface === self { Self.activeInputSurface = nil } - guard wasFirstResponder, keyboardHeight != 0 else { return } - keyboardHeight = 0 - setNeedsGeometrySync() + // Don't zero `keyboardHeight` here. `resignFirstResponder()` triggers + // `keyboardWillHide`, which owns the full hide cleanup (proxy state, + // docked-toolbar animation, geometry). Pre-zeroing would make that + // handler's `keyboardHeight != 0` guard short-circuit, leaving the + // toolbar at the old keyboard edge with a stale glyph. } /// Stops user-visible and accessibility output from a surface SwiftUI has removed. From 076eaa0d028a55ce787a5900dbe63239f484150c Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 03:06:37 -0700 Subject: [PATCH 4/8] AuthCoordinator: don't let a stuck push teardown block local sign-out Autoreview round 3: the round-2 withTaskGroup bound still structurally awaited the teardown child, so a teardown that ignores cancellation (a wedged network DELETE) would keep withTaskGroup from returning and block local sign-out past the deadline. Run the teardown unstructured and only await a deadline it cancels on completion: sign-out proceeds at min(teardown, 5s), and a stuck teardown keeps running detached without holding up the local clear. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Coordinator/AuthCoordinator.swift | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift index 32324e225153..4441a6734958 100644 --- a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +++ b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift @@ -443,17 +443,20 @@ public final class AuthCoordinator { public func signOut(onSignedOut: @escaping @Sendable () async -> Void = {}) async { // Give token-authenticated teardown (the push-token DELETE) a bounded // chance to run while tokens are still valid, but never block local - // sign-out on a slow/stuck network call: proceed as soon as the hook - // finishes or the deadline elapses, whichever comes first. - await withTaskGroup(of: Void.self) { group in - group.addTask { await onSignedOut() } - group.addTask { - // Bounded teardown deadline (cancelled below once one task wins). - try? await Task.sleep(for: .seconds(5)) - } - await group.next() - group.cancelAll() - } + // sign-out on a stuck call. The teardown runs unstructured and cancels + // the deadline when it finishes; we only await the deadline, so a hook + // that ignores cancellation keeps running detached without holding up + // sign-out past the deadline. + let deadline = Task { + // Bounded, cancellable sign-out teardown deadline (carve-out): + // cancelled early when the hook completes. + try? await Task.sleep(for: .seconds(5)) + } + _ = Task { + await onSignedOut() + deadline.cancel() + } + await deadline.value do { try await client.signOut() } catch { From bfdf259e7f08d8d8c44e1fd36c7a9872a1804bc8 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 03:45:11 -0700 Subject: [PATCH 5/8] iOS terminal: free libghostty surface on the output queue, not a separate one Autoreview round 4: disposeSurface() freed the surface on GhosttySurfaceDisposer's own serial queue while process_output / render_now / binding_action run on the shared Self.outputQueue with a captured surface pointer. Two different queues let the free race a queued ghostty_* call on the same pointer (use-after-free during fast terminal switches / removals). Free on Self.outputQueue instead. It's serial and FIFO, so the free is ordered after every already-enqueued block that captured the pointer, and never runs concurrently with one. processOutput's main-actor guard stops new work once surface is nil, so only the bounded backlog drains before the free. Removes the separate-queue disposer (a namespace-enum carve-out) entirely. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../GhosttySurfaceView.swift | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift index a41c5e59e0f1..46c98417d444 100644 --- a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift +++ b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift @@ -144,19 +144,6 @@ final class GhosttySurfaceBridge: @unchecked Sendable { } } -// lint:allow namespace-enum — surface-teardown helper on the off-limits render path; its serial DispatchQueue is the sanctioned libghostty free-after-detach carve-out. Reshape deferred to the GhosttySurfaceView split wave. -private enum GhosttySurfaceDisposer { - static let queue = DispatchQueue(label: "GhosttySurfaceDisposer.queue") - - static func dispose(surface: ghostty_surface_t, bridge: GhosttySurfaceBridge) { - let retainedBridge = Unmanaged.passRetained(bridge) - queue.async { - ghostty_surface_free(surface) - retainedBridge.release() - } - } -} - struct TerminalHardwareKeyCommand: Sendable { let input: String let modifierFlags: UIKeyModifierFlags @@ -1659,7 +1646,21 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { GhosttySurfaceView.unregister(surface: surface) self.surface = nil bridge.detach() - GhosttySurfaceDisposer.dispose(surface: surface, bridge: bridge) + // Free on the SAME serial `outputQueue` that runs `process_output`, + // `render_now`, and `binding_action` (all of which capture this C + // surface pointer), not a separate queue. FIFO ordering guarantees the + // free runs after every already-enqueued block that captured the + // pointer, so a dismantled/removed surface's queued libghostty work can + // never use-after-free against the free, and no two of them ever touch + // the surface concurrently. `processOutput`'s main-actor guard stops new + // work from being enqueued once `surface` is nil, so only the bounded + // backlog drains before the free. (Retain the bridge across the hop; it + // owns the userdata libghostty still references until the free.) + let retainedBridge = Unmanaged.passRetained(bridge) + Self.outputQueue.async { + ghostty_surface_free(surface) + retainedBridge.release() + } } private var preferredScreenScale: CGFloat { From e79b7973f3a492d50ed699d97d9b1f74152cd643 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 04:09:11 -0700 Subject: [PATCH 6/8] AuthCoordinator: structured (joined) sign-out teardown, not detached Autoreview round 5: the round-4 unstructured teardown could outlive signOut(). unregisterFromServer() builds its DELETE from the LIVE AuthCoordinator's tokens (PushRegistrationService.makeRequest reads tokenProvider at request-build time), so a delayed stale task that ran after a subsequent sign-in would authenticate the device-token DELETE with the NEW account's credentials and break push for that session. Make the teardown structured: a task group runs the hook + a bounded deadline, then cancelAll() once either finishes; the group joins the (cancelled) hook before returning, so no teardown ever outlives signOut. The push DELETE runs on URLSession (cancellation-aware), so cancelAll() unblocks the join promptly, and awaiting inline guarantees the hook reads this account's tokens since no new sign-in can interleave before signOut returns. (Reverses the round-3 detached approach, which traded round-5's severe cross-account corruption for a hypothetical block by a hook that ignores cancellation; the real hook cancels.) The deadline is an injected Duration (teardownTimeout, default 5s) per the bounded-delay carve-out, so the new signOutJoinsAndCancelsSlowTeardownAtDeadline test exercises the cancel-and-join path in 50ms with no real waiting. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Coordinator/AuthCoordinator.swift | 44 ++++++++++++------- .../AuthCoordinatorTests.swift | 34 ++++++++++++++ .../Tests/CmuxAuthRuntimeTests/Fakes.swift | 12 +++++ 3 files changed, 73 insertions(+), 17 deletions(-) diff --git a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift index 4441a6734958..ce188cb098ce 100644 --- a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +++ b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift @@ -440,23 +440,33 @@ public final class AuthCoordinator { /// `client.signOut()` the token is gone and a server-side DELETE would be /// silently skipped, leaving the device receiving pushes for a signed-out /// account. Defaults to a no-op. - public func signOut(onSignedOut: @escaping @Sendable () async -> Void = {}) async { - // Give token-authenticated teardown (the push-token DELETE) a bounded - // chance to run while tokens are still valid, but never block local - // sign-out on a stuck call. The teardown runs unstructured and cancels - // the deadline when it finishes; we only await the deadline, so a hook - // that ignores cancellation keeps running detached without holding up - // sign-out past the deadline. - let deadline = Task { - // Bounded, cancellable sign-out teardown deadline (carve-out): - // cancelled early when the hook completes. - try? await Task.sleep(for: .seconds(5)) - } - _ = Task { - await onSignedOut() - deadline.cancel() - } - await deadline.value + /// - Parameter teardownTimeout: How long the structured teardown may run + /// before it is cancelled so a slow call can't hold sign-out open. Injected + /// as a duration (rather than a wall clock) so tests exercise the deadline + /// path without real waiting. Defaults to 5 seconds. + public func signOut( + onSignedOut: @escaping @Sendable () async -> Void = {}, + teardownTimeout: Duration = .seconds(5) + ) async { + // Run the token-authenticated teardown (the push-token DELETE) while the + // signing-out account's tokens are still valid, bounded so a slow call + // can't hold sign-out open indefinitely. The teardown is STRUCTURED: on + // deadline we cancel it and the task group still joins it before + // returning, so it can never outlive sign-out and rebuild its request + // from a later sign-in's credentials. The push DELETE runs on URLSession + // (cancellation-aware), so `cancelAll()` unblocks the join promptly; + // awaiting it inline also guarantees it reads this account's tokens, + // since no new sign-in can interleave before `signOut` returns. + await withTaskGroup(of: Void.self) { group in + group.addTask { await onSignedOut() } + group.addTask { + // Bounded, cancellable teardown deadline (carve-out); the loser + // is cancelled by `cancelAll()` once the first task finishes. + try? await Task.sleep(for: teardownTimeout) + } + await group.next() + group.cancelAll() + } do { try await client.signOut() } catch { diff --git a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift index ad9bc9bf61c9..f2d8f9be8ed7 100644 --- a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift +++ b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift @@ -117,6 +117,40 @@ import Testing #expect(coordinator.isAuthenticated == false) // session revoked afterward } + @Test func signOutJoinsAndCancelsSlowTeardownAtDeadline() async throws { + // Regression: the teardown must be STRUCTURED (joined), not detached. A + // detached hook could outlive signOut() and, after a later sign-in, + // rebuild its push-token DELETE from the new account's tokens. With a + // short deadline the task group cancels the slow hook and joins it before + // signOut returns, so by the time signOut returns the hook has already + // been cancelled (never left running) and sign-out wasn't blocked for the + // hook's full duration. + let user = CMUXAuthUser(id: "u1", primaryEmail: "a@b.com", displayName: "A") + let client = FakeAuthClient(user: user) + let (coordinator, _) = makeCoordinator(client: client) + try await coordinator.signInWithPassword(email: "a@b.com", password: "pw") + + let outcome = TeardownOutcomeProbe() + await coordinator.signOut( + onSignedOut: { + await outcome.markStarted() + do { + // Cancellation-aware slow work, like the URLSession DELETE. + try await Task.sleep(for: .seconds(60)) + await outcome.markFinished() + } catch { + await outcome.markCancelled() + } + }, + teardownTimeout: .milliseconds(50) + ) + + #expect(await outcome.started) + #expect(await outcome.cancelled) // joined + cancelled before return + #expect(await outcome.finished == false) // the 60s path never completed + #expect(coordinator.isAuthenticated == false) + } + @Test func devAuthFortyTwoShortcutSignsIn() async throws { let user = CMUXAuthUser(id: "debug", primaryEmail: "l@l.com", displayName: "L") let client = FakeAuthClient(user: user) diff --git a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift index 1c8d5a6a075a..6bd715423758 100644 --- a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift +++ b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift @@ -116,6 +116,18 @@ actor TokenProbe { func set(_ token: String?) { value = token } } +/// Records the lifecycle of a sign-out teardown hook so a test can prove the +/// teardown is structured (joined + cancelled before sign-out returns) rather +/// than detached. +actor TeardownOutcomeProbe { + private(set) var started = false + private(set) var finished = false + private(set) var cancelled = false + func markStarted() { started = true } + func markFinished() { finished = true } + func markCancelled() { cancelled = true } +} + extension AuthLaunchOptions { static func plain(includesDevAuth: Bool = false) -> AuthLaunchOptions { AuthLaunchOptions( From b5eb8aa8447a49ab68a96e245e34b752b8360a0b Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 05:02:12 -0700 Subject: [PATCH 7/8] iOS terminal: store-owned autofocus suppression + failing tests Moves the "don't autofocus a freshly-created terminal" suppression out of WorkspaceShellView's @State (a free-floating `suppressNextTerminalAutoFocus` boolean plus a convert-on-next-selection dance) and into MobileShellComposite, keyed by terminal id. The boolean could not tell a chrome create from a push-notification deep link (both arrive as the same selection change), so any "suppress whatever comes next" scheme sometimes suppressed the wrong surface; it also leaked when a create failed and the selection never changed. This commit lands the store API (`shouldAutoFocusTerminalSurface`, `consumeTerminalAutoFocusSuppression`, `selectTerminalFromChrome`), migrates the three views to read it, and adds behavior tests, but does NOT yet wire the create paths to suppress the new terminal id. The "created terminal is suppressed" tests therefore fail here (red); the next commit adds the wiring. Also reorders createTerminal(in:) so a remote create that is going to abort (another create already in flight) bails before pinning selectedWorkspaceID, so a second "+" can't strand the UI on a workspace with no new terminal. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../MobileShellComposite.swift | 50 ++++++++++++++- .../MobileShellCompositePreviewTests.swift | 64 +++++++++++++++++++ .../WorkspaceDetailContainer.swift | 10 +-- .../WorkspaceDetailView.swift | 54 +++------------- .../WorkspaceShellView.swift | 28 ++------ 5 files changed, 127 insertions(+), 79 deletions(-) diff --git a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index e16889ee50c2..f99e1f89dbc4 100644 --- a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -87,6 +87,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } public var selectedTerminalID: MobileTerminalPreview.ID? + /// Surface IDs whose next window attach must NOT grab the keyboard. + /// + /// A surface in this set mounts with autofocus disabled; the entry is + /// cleared once that surface has appeared and consumed the suppression + /// (``consumeTerminalAutoFocusSuppression(for:)``). Ownership lives here, + /// next to selection and terminal creation, rather than in the view, so the + /// create path can mark the *exact* new terminal id the instant it becomes + /// the selection. A freshly created terminal therefore never steals the + /// keyboard, while push-notification navigation (``selectTerminal(_:)``) is + /// intentionally left out of the set and allowed to autofocus. + private var terminalAutoFocusSuppressedSurfaceIDs: Set = [] + private let runtime: (any MobileSyncRuntime)? private let pairedMacStore: (any MobilePairedMacStoring)? private let identityProvider: (any MobileIdentityProviding)? @@ -769,11 +781,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// different workspace if the selection drifts before the async work runs. public func createTerminal(in workspaceID: MobileWorkspacePreview.ID? = nil) { let targetWorkspaceID = workspaceID ?? selectedWorkspace?.id - // Pin selection to the target so async creation + the resulting - // terminal selection stay on the workspace the caller intended. - if let targetWorkspaceID { selectedWorkspaceID = targetWorkspaceID } guard remoteClient == nil else { + // Bail BEFORE pinning selection when a create is already in flight, + // so a second "+" on another workspace can't strand the UI on that + // workspace with no new terminal while the earlier RPC still runs. guard createTerminalTask == nil else { return } + // Pin selection to the target so the async create + the resulting + // terminal selection stay on the workspace the caller intended. + if let targetWorkspaceID { selectedWorkspaceID = targetWorkspaceID } let taskID = UUID() createTerminalTaskID = taskID createTerminalTask = Task { @MainActor [weak self] in @@ -786,6 +801,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard let workspaceIndex = workspaces.firstIndex(where: { $0.id == targetWorkspaceID }) else { return } + selectedWorkspaceID = targetWorkspaceID let terminalIndex = workspaces[workspaceIndex].terminals.count + 1 let terminal = MobileTerminalPreview( id: .init(rawValue: "\(workspaces[workspaceIndex].id.rawValue)-terminal-\(terminalIndex)"), @@ -799,6 +815,34 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { selectedTerminalID = id } + /// Selects `id` as a chrome action (the terminal picker), so the surface + /// that comes up does not grab the keyboard. + /// + /// Switching terminals from the picker is a navigation intent, not a typing + /// intent, so unlike ``selectTerminal(_:)`` (which a push-notification deep + /// link uses and which is allowed to autofocus) this suppresses the target + /// surface's next autofocus. Re-confirming the already-selected terminal is + /// a no-op suppression, since no surface re-attach happens. + public func selectTerminalFromChrome(_ id: MobileTerminalPreview.ID) { + if id != selectedTerminalID { + terminalAutoFocusSuppressedSurfaceIDs.insert(id.rawValue) + } + selectedTerminalID = id + } + + /// Whether the surface for `terminalID` may grab the keyboard on its next + /// window attach. False while a one-shot suppression is pending for it. + public func shouldAutoFocusTerminalSurface(_ terminalID: String) -> Bool { + !terminalAutoFocusSuppressedSurfaceIDs.contains(terminalID) + } + + /// Clears the one-shot autofocus suppression for `terminalID` once its + /// surface has mounted (and so has already attached with autofocus + /// disabled). Called from the surface's `onAppear`. + public func consumeTerminalAutoFocusSuppression(for terminalID: String) { + terminalAutoFocusSuppressedSurfaceIDs.remove(terminalID) + } + public func reportTerminalViewport( workspaceID: MobileWorkspacePreview.ID, terminalID: MobileTerminalPreview.ID, diff --git a/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index 5c8b0f3d9ab1..47a4fe2e341b 100644 --- a/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -94,6 +94,70 @@ import Testing #expect(store.selectedTerminalID?.rawValue == "workspace-main-terminal-4") } + @Test func createdTerminalIsAutoFocusSuppressedUntilConsumed() throws { + let store = MobileShellComposite.preview() + store.signIn() + store.pairingCode = "debug" + store.connectPreviewHost() + + store.createTerminal() + + // A freshly created terminal must not grab the keyboard on mount. + let created = try #require(store.selectedTerminalID).rawValue + #expect(store.shouldAutoFocusTerminalSurface(created) == false) + // Its surface appearing consumes the one-shot suppression. + store.consumeTerminalAutoFocusSuppression(for: created) + #expect(store.shouldAutoFocusTerminalSurface(created) == true) + } + + @Test func createdWorkspaceTerminalIsAutoFocusSuppressed() { + let store = MobileShellComposite.preview() + store.signIn() + store.pairingCode = "debug" + store.connectPreviewHost() + + store.createWorkspace() + + #expect(store.selectedTerminalID?.rawValue == "workspace-3-terminal-1") + #expect(store.shouldAutoFocusTerminalSurface("workspace-3-terminal-1") == false) + } + + @Test func pushNavigationSelectionStaysAutoFocusable() throws { + let store = MobileShellComposite.preview() + store.signIn() + store.pairingCode = "debug" + store.connectPreviewHost() + + // A chrome create suppresses the new terminal... + store.createTerminal() + let created = try #require(store.selectedTerminalID).rawValue + #expect(store.shouldAutoFocusTerminalSurface(created) == false) + + // ...but a push-notification deep link to an existing terminal is a + // focus intent and must still autofocus: suppression attaches to the + // created id, not to "whatever selection comes next". + store.selectTerminal("terminal-agent") + #expect(store.shouldAutoFocusTerminalSurface("terminal-agent") == true) + } + + @Test func chromeTerminalSwitchSuppressesTargetButNotReconfirm() throws { + let store = MobileShellComposite.preview() + store.signIn() + store.pairingCode = "debug" + store.connectPreviewHost() + + // Re-confirming the already-selected terminal from the picker re-attaches + // nothing, so it must not leave a dangling suppression. + let current = try #require(store.selectedTerminalID) + store.selectTerminalFromChrome(current) + #expect(store.shouldAutoFocusTerminalSurface(current.rawValue) == true) + + // Switching to a different terminal IS chrome: suppress its autofocus. + store.selectTerminalFromChrome("terminal-agent") + #expect(store.selectedTerminalID?.rawValue == "terminal-agent") + #expect(store.shouldAutoFocusTerminalSurface("terminal-agent") == false) + } + @Test func selectingWorkspaceReconcilesTerminalSelection() { let store = MobileShellComposite.preview() store.signIn() diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift index f72dc790155c..c1d09843221d 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift @@ -14,8 +14,6 @@ struct WorkspaceDetailContainer: View { let workspaceID: MobileWorkspacePreview.ID? let createWorkspace: () -> Void let safeAreaContext: MobileTerminalSafeAreaContext - @Binding var suppressNextTerminalAutoFocus: Bool - @Binding var terminalAutoFocusSuppressedSurfaceIDs: Set private var workspace: MobileWorkspacePreview? { if let workspaceID { @@ -31,17 +29,11 @@ struct WorkspaceDetailContainer: View { connectionStatus: store.macConnectionStatus, workspace: workspace, store: store, - selectedTerminalID: Binding( - get: { store.selectedTerminalID }, - set: { store.selectTerminal($0) } - ), createWorkspace: createWorkspace, createTerminal: { store.createTerminal(in: workspace.id) }, reportTerminalViewport: store.reportTerminalViewport, sendTerminalInput: store.sendTerminalRawInput, - safeAreaContext: safeAreaContext, - suppressNextTerminalAutoFocus: $suppressNextTerminalAutoFocus, - terminalAutoFocusSuppressedSurfaceIDs: $terminalAutoFocusSuppressedSurfaceIDs + safeAreaContext: safeAreaContext ) .onAppear { if store.selectedWorkspaceID != workspace.id { diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 037c4ae165eb..43bf6a0a8a21 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -16,18 +16,15 @@ struct WorkspaceDetailView: View { let connectionStatus: MobileMacConnectionStatus let workspace: MobileWorkspacePreview @Bindable var store: CMUXMobileShellStore - @Binding var selectedTerminalID: MobileTerminalPreview.ID? let createWorkspace: () -> Void let createTerminal: () -> Void let reportTerminalViewport: (MobileWorkspacePreview.ID, MobileTerminalPreview.ID, MobileTerminalViewportSize) -> Void let sendTerminalInput: (String) -> Void let safeAreaContext: MobileTerminalSafeAreaContext - @Binding var suppressNextTerminalAutoFocus: Bool - @Binding var terminalAutoFocusSuppressedSurfaceIDs: Set @State private var isTerminalPickerPresented = false private var selectedTerminal: MobileTerminalPreview? { - workspace.terminals.first { $0.id == selectedTerminalID } ?? workspace.terminals.first + workspace.terminals.first { $0.id == store.selectedTerminalID } ?? workspace.terminals.first } var body: some View { @@ -48,7 +45,7 @@ struct WorkspaceDetailView: View { surfaceID: terminalID, store: store, fontSize: MobileTerminalFontPreference.defaultSize, - autoFocusOnWindowAttach: shouldAutoFocusTerminalSurface(terminalID) + autoFocusOnWindowAttach: store.shouldAutoFocusTerminalSurface(terminalID) ) // Identity must track the selected terminal. The representable's // coordinator binds its byte sink to the surfaceID at make time and @@ -58,7 +55,7 @@ struct WorkspaceDetailView: View { // sink via dismantleUIView) and builds the newly-selected one. .id(terminalID) .onAppear { - clearConsumedTerminalAutoFocusSuppression(for: terminalID) + store.consumeTerminalAutoFocusSuppression(for: terminalID) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .background(TerminalPalette.background) @@ -95,12 +92,6 @@ struct WorkspaceDetailView: View { .background(TerminalPalette.background) #endif .navigationTitle(workspace.name) - .onAppear { - suppressPendingTerminalAutoFocusIfNeeded(for: selectedTerminal?.id) - } - .onChange(of: selectedTerminal?.id) { _, terminalID in - suppressPendingTerminalAutoFocusIfNeeded(for: terminalID) - } .mobileTerminalNavigationChrome() .toolbar { #if os(iOS) @@ -231,34 +222,30 @@ struct WorkspaceDetailView: View { private func createWorkspaceFromToolbar() { dismissTerminalKeyboardForChrome() - suppressNextTerminalAutoFocus = true createWorkspace() } private func createWorkspaceFromTerminalPicker() { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = false - suppressNextTerminalAutoFocus = true createWorkspace() } private func createTerminalFromToolbar() { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = false - suppressNextTerminalAutoFocus = true createTerminal() } private func selectTerminalFromPicker(_ terminalID: MobileTerminalPreview.ID) { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = false - // Switching to a different terminal is chrome, not a typing intent, so - // the newly-selected surface must not grab the keyboard on attach. - if selectedTerminal?.id != terminalID { - terminalAutoFocusSuppressedSurfaceIDs.insert(terminalID.rawValue) - } - suppressNextTerminalAutoFocus = false - selectedTerminalID = terminalID + // Switching from the picker 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 + // `selectTerminal` path instead and is allowed to autofocus. + store.selectTerminalFromChrome(terminalID) } private func dismissTerminalKeyboardForChrome() { @@ -268,27 +255,4 @@ struct WorkspaceDetailView: View { GhosttySurfaceView.resignActiveInput() UIApplication.shared.dismissMobileKeyboard() } - - /// Whether the surface for `terminalID` may autofocus on its next window - /// attach. False while a one-shot suppression is pending or this surface is - /// in the per-surface suppression set. - private func shouldAutoFocusTerminalSurface(_ terminalID: String) -> Bool { - !suppressNextTerminalAutoFocus - && !terminalAutoFocusSuppressedSurfaceIDs.contains(terminalID) - } - - /// Clears the per-surface suppression once the surface has appeared (and so - /// has already mounted with autofocus disabled). - private func clearConsumedTerminalAutoFocusSuppression(for terminalID: String) { - terminalAutoFocusSuppressedSurfaceIDs.remove(terminalID) - } - - /// Converts a pending one-shot suppression into a per-surface entry for the - /// terminal that is about to become visible, then resets the one-shot flag. - private func suppressPendingTerminalAutoFocusIfNeeded(for terminalID: MobileTerminalPreview.ID?) { - guard suppressNextTerminalAutoFocus, - let terminalID else { return } - terminalAutoFocusSuppressedSurfaceIDs.insert(terminalID.rawValue) - suppressNextTerminalAutoFocus = false - } } diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift index 8838c87f4a78..728cbd82d35e 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceShellView.swift @@ -16,16 +16,6 @@ struct WorkspaceShellView: View { @State private var pendingCompactCreateNavigationWorkspaceIDs: Set? @State private var hasPresentedSplitDetail = false @State private var splitColumnVisibility: NavigationSplitViewVisibility = .automatic - /// One-shot suppression of the next terminal autofocus. Set after a chrome - /// action that creates a workspace or terminal so the freshly-attached - /// surface does not steal the keyboard. Consumed (and translated into a - /// per-surface entry in ``terminalAutoFocusSuppressedSurfaceIDs``) when the - /// detail view next appears or its selected terminal changes. - @State private var suppressNextTerminalAutoFocus = false - /// Surface IDs whose next window attach must NOT autofocus. A surface in - /// this set mounts with `autoFocusOnWindowAttach: false`; the entry clears - /// once that surface has appeared and consumed the suppression. - @State private var terminalAutoFocusSuppressedSurfaceIDs: Set = [] #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.verticalSizeClass) private var verticalSizeClass @@ -141,26 +131,22 @@ struct WorkspaceShellView: View { private func selectWorkspace(_ id: MobileWorkspacePreview.ID) { pendingCompactCreateNavigationWorkspaceIDs = nil - // Selecting an existing workspace is a user-driven focus intent, so the - // terminal that comes up should be allowed to take the keyboard. - suppressNextTerminalAutoFocus = false + // Selecting an existing workspace is a user-driven focus intent: its + // preferred terminal is not in the store's suppression set, so it is + // free to take the keyboard. store.selectedWorkspaceID = id if usesCompactStack, compactNavigationPath.last != id { compactNavigationPath = [id] } } - /// Split-layout list/detail "+" create. Suppresses autofocus like the - /// compact path so the new terminal doesn't pop the keyboard on mount. + /// Split-layout list/detail "+" create. The store marks the freshly-created + /// terminal so it doesn't pop the keyboard on mount. private func createWorkspaceFromSplitList() { - suppressNextTerminalAutoFocus = true store.createWorkspace() } private func createWorkspaceInCompactStack() { - // Creating a workspace is a chrome action: the new terminal should not - // grab the keyboard the instant it mounts. - suppressNextTerminalAutoFocus = true let existingWorkspaceIDs = Set(store.workspaces.map(\.id)) pendingCompactCreateNavigationWorkspaceIDs = existingWorkspaceIDs store.createWorkspace() @@ -196,9 +182,7 @@ struct WorkspaceShellView: View { store: store, workspaceID: workspaceID, createWorkspace: createWorkspace, - safeAreaContext: safeAreaContext, - suppressNextTerminalAutoFocus: $suppressNextTerminalAutoFocus, - terminalAutoFocusSuppressedSurfaceIDs: $terminalAutoFocusSuppressedSurfaceIDs + safeAreaContext: safeAreaContext ) } } From ceb5f4537b8fc5e72388c065ad44fa2da2be7fd5 Mon Sep 17 00:00:00 2001 From: lawrencecchen <54008264+lawrencecchen@users.noreply.github.com> Date: Sat, 6 Jun 2026 05:02:55 -0700 Subject: [PATCH 8/8] iOS terminal: wire create paths to suppress new-terminal autofocus Every create path (local + remote createWorkspace/createTerminal) now marks the freshly-created terminal id in the store the instant it becomes the selection, so its surface mounts with autofocus disabled. This makes the previous commit's tests pass (green) and dissolves the bot-flagged edge cases of the old boolean: - A create that fails (remote RPC error) never produces a terminal id, so there is nothing to leak and the current terminal stays autofocusable. - A push-notification deep link goes through selectTerminal, which is left out of the suppression set, so it autofocuses even mid-create. - Re-confirming the already-selected terminal in the picker is a no-op suppression (selectTerminalFromChrome only suppresses an actual switch). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../MobileShellComposite.swift | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index f99e1f89dbc4..7790c465998b 100644 --- a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -772,6 +772,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { workspaces.append(workspace) selectedWorkspaceID = workspace.id selectedTerminalID = workspace.terminals.first?.id + suppressTerminalAutoFocusOnNextAttach(for: selectedTerminalID) } /// Creates a terminal in `workspaceID`, or the selected workspace when nil. @@ -809,6 +810,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) workspaces[workspaceIndex].terminals.append(terminal) selectedTerminalID = terminal.id + suppressTerminalAutoFocusOnNextAttach(for: terminal.id) } public func selectTerminal(_ id: MobileTerminalPreview.ID?) { @@ -843,6 +845,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { terminalAutoFocusSuppressedSurfaceIDs.remove(terminalID) } + /// Marks `terminalID` so its surface does not autofocus on its next window + /// attach. Called by every create path the instant the new terminal becomes + /// the selection, so a freshly created terminal never steals the keyboard. + private func suppressTerminalAutoFocusOnNextAttach(for terminalID: MobileTerminalPreview.ID?) { + guard let terminalID else { return } + terminalAutoFocusSuppressedSurfaceIDs.insert(terminalID.rawValue) + } + public func reportTerminalViewport( workspaceID: MobileWorkspacePreview.ID, terminalID: MobileTerminalPreview.ID, @@ -1348,11 +1358,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard isCurrentRemoteOperation(client: client, generation: generation), !Task.isCancelled else { return } applyRemoteWorkspaceList(response, mergeExistingWorkspaces: true) - if let createdID = response.createdWorkspaceID { - let createdWorkspaceID = MobileWorkspacePreview.ID(rawValue: createdID) - setSelectedWorkspaceID(createdWorkspaceID) + let createdWorkspace = response.createdWorkspaceID.map(MobileWorkspacePreview.ID.init(rawValue:)) + if let createdWorkspace { + setSelectedWorkspaceID(createdWorkspace) } syncSelectedTerminalForWorkspace() + if createdWorkspace != nil { + // A "+" actually created and selected a new workspace, so its + // terminal is freshly created: don't pop the keyboard on mount. + // When no workspace was created the selection never moved, so we + // must not suppress the user's current terminal. + suppressTerminalAutoFocusOnNextAttach(for: selectedTerminalID) + } } catch { guard generation == connectionGeneration, !Task.isCancelled else { return } guard !disconnectForAuthorizationFailureIfNeeded(error) else { return } @@ -1379,7 +1396,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { applyRemoteWorkspaceList(response, mergeExistingWorkspaces: true) if selectedWorkspaceID == requestedWorkspaceID, let createdID = response.createdTerminalID { - selectedTerminalID = MobileTerminalPreview.ID(rawValue: createdID) + let createdTerminalID = MobileTerminalPreview.ID(rawValue: createdID) + selectedTerminalID = createdTerminalID + suppressTerminalAutoFocusOnNextAttach(for: createdTerminalID) } } catch { guard generation == connectionGeneration, !Task.isCancelled else { return }