Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -433,17 +433,47 @@ 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 {
authLog.error("Sign-out failed: \(error.localizedDescription, privacy: .private)")
}
if launch.includesDevAuth { debugCredentials = nil }
clearAuthState()
await onSignedOut()
}

// MARK: - Tokens
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions Packages/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/Fakes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -762,19 +762,28 @@ 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 }
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
guard remoteClient == nil else {
guard createTerminalTask == nil else { return }
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
}
let terminalIndex = workspaces[workspaceIndex].terminals.count + 1
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>

private var workspace: MobileWorkspacePreview? {
if let workspaceID {
Expand All @@ -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 {
Expand Down
Loading
Loading