diff --git a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift index 554323d8b38a..ce188cb098ce 100644 --- a/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +++ b/Packages/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift @@ -433,9 +433,40 @@ 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. - public func signOut(onSignedOut: @Sendable () async -> Void = {}) async { + /// 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. + /// - 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 { @@ -443,7 +474,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..f2d8f9be8ed7 100644 --- a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift +++ b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AuthCoordinatorTests.swift @@ -98,6 +98,59 @@ 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 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 90cdb58f878b..6bd715423758 100644 --- a/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift +++ b/Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift @@ -110,6 +110,24 @@ 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 } +} + +/// 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( diff --git a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 48967af4727d..6ea28bb61338 100644 --- a/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -93,6 +93,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)? @@ -936,23 +948,37 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { workspaces.append(workspace) selectedWorkspaceID = workspace.id selectedTerminalID = workspace.terminals.first?.id + suppressTerminalAutoFocusOnNextAttach(for: selectedTerminalID) } - 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 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 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 } + selectedWorkspaceID = targetWorkspaceID let terminalIndex = workspaces[workspaceIndex].terminals.count + 1 let terminal = MobileTerminalPreview( id: .init(rawValue: "\(workspaces[workspaceIndex].id.rawValue)-terminal-\(terminalIndex)"), @@ -960,12 +986,49 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) workspaces[workspaceIndex].terminals.append(terminal) selectedTerminalID = terminal.id + suppressTerminalAutoFocusOnNextAttach(for: terminal.id) } public func selectTerminal(_ id: MobileTerminalPreview.ID?) { 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) + } + + /// 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, @@ -1472,11 +1535,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 } @@ -1485,9 +1555,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 { @@ -1503,7 +1573,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 } diff --git a/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index 83e4400fe24c..47a4fe2e341b 100644 --- a/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -78,6 +78,86 @@ 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 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/GhosttySurfaceRepresentable.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift index ab32b524c525..0501ddc07ccd 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 64fb63ac1774..16a0cc10356a 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift @@ -20,6 +20,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 @State private var showingHostPicker = false var body: some View { @@ -103,23 +108,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..c1d09843221d 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailContainer.swift @@ -29,12 +29,8 @@ struct WorkspaceDetailContainer: View { connectionStatus: store.macConnectionStatus, workspace: workspace, store: store, - selectedTerminalID: Binding( - get: { store.selectedTerminalID }, - set: { store.selectTerminal($0) } - ), createWorkspace: createWorkspace, - createTerminal: store.createTerminal, + createTerminal: { store.createTerminal(in: workspace.id) }, reportTerminalViewport: store.reportTerminalViewport, sendTerminalInput: store.sendTerminalRawInput, safeAreaContext: safeAreaContext diff --git a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 98b14010e404..43bf6a0a8a21 100644 --- a/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -16,7 +16,6 @@ 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 @@ -25,7 +24,7 @@ struct WorkspaceDetailView: View { @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 { @@ -45,7 +44,8 @@ struct WorkspaceDetailView: View { GhosttySurfaceRepresentable( surfaceID: terminalID, store: store, - fontSize: MobileTerminalFontPreference.defaultSize + fontSize: MobileTerminalFontPreference.defaultSize, + 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 @@ -54,6 +54,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 { + store.consumeTerminalAutoFocusSuppression(for: terminalID) + } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .background(TerminalPalette.background) // The surface positions its grid + docked toolbar from @@ -237,10 +240,19 @@ struct WorkspaceDetailView: View { private func selectTerminalFromPicker(_ terminalID: MobileTerminalPreview.ID) { dismissTerminalKeyboardForChrome() isTerminalPickerPresented = 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() { + // 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() } } diff --git a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift index 862f36939cf7..89c2bddc4314 100644 --- a/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift +++ b/Packages/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift @@ -148,19 +148,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 @@ -525,6 +512,12 @@ public enum TerminalInputAccessoryAction: Int, CaseIterable, Sendable { } 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 @@ -800,7 +793,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() } @@ -977,6 +970,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) { @@ -1365,6 +1367,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 { @@ -1372,15 +1378,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 @@ -1432,7 +1437,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 @@ -1502,11 +1507,54 @@ 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() { + inputProxy.resignFirstResponder() + if Self.activeInputSurface === self { + Self.activeInputSurface = nil + } + // 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. + 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) @@ -1631,7 +1679,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 { @@ -1838,7 +1900,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 { @@ -1856,6 +1918,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() @@ -2360,7 +2426,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 9f30b78977b8..f63adbaf4e5a 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -3502,6 +3502,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"