Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
@@ -0,0 +1,126 @@
import CMUXMobileCore
import CmuxMobilePairedMac
import Foundation

/// Presentation mode for explicit, user-triggered account computer recovery.
public enum MobileAccountComputerRecoveryMode: Equatable, Sendable {
/// Account recovery is unavailable in the current shell composition.
case unavailable
/// Search the signed-in account without relying on local pairing history.
case findAccountComputer
/// A local deletion marker exists, so explain this as restoring a deletion.
case recoverDeletedComputer
}

/// Result of an explicit, user-triggered account computer recovery attempt.
public enum MobileAccountComputerRecoveryResult: Equatable, Sendable {
/// A Mac was found through same-account Iroh discovery and persisted.
case recovered
/// No eligible Mac was live for the current account/team scope.
case notFound
/// A previous recovery attempt is still running, so this tap did not start another scan.
case alreadyInProgress
/// The account or team changed while recovery was running.
case staleScope
}

@MainActor
extension MobileShellComposite {
/// How the UI should present explicit same-account computer recovery.
public var accountComputerRecoveryMode: MobileAccountComputerRecoveryMode {
guard isSignedIn,
pairedMacStore != nil,
personalIrohDiscovery != nil else { return .unavailable }
return hasRecoverableDeletedComputers
? .recoverDeletedComputer
: .findAccountComputer
}

/// Find and connect a Mac through live same-account Iroh discovery.
///
/// Passive zero-touch discovery continues to exclude forgotten Macs. Explicit
/// recovery is authorized by the current account's live broker snapshot instead
/// of local pairing history. Forgotten candidates are tried first, and the
/// normal Iroh connection path must still authenticate the Mac's device ID and
/// app-instance tag before persistence clears any forgotten marker.
@discardableResult
public func recoverIrohMacFromAccount() async -> MobileAccountComputerRecoveryResult {
guard !isRecoveringAccountComputer else { return .alreadyInProgress }
isRecoveringAccountComputer = true
defer { isRecoveringAccountComputer = false }

guard isSignedIn,
let scope = await currentScopeSnapshot(),
let personalIrohDiscovery else { return .notFound }
let forgottenIDs = await forgottenMacDeviceIDs(scope: scope)
let knownIDs = Set(pairedMacsForIdentityMatching.flatMap { mac in
[mac.id, cmxCanonicalDeviceID(mac.macDeviceID)]
})

connectionRecoveryOwner.cancel()
applyConnectionRecoveryOwnerState()
invalidateStoredMacReconnectAttempt()

let discovered = await personalIrohDiscovery.discoverLiveMacs()
guard await isScopeCurrent(scope) else { return .staleScope }
let candidates = accountIrohRecoveryCandidates(
from: discovered,
forgottenIDs: forgottenIDs,
excludingKnownIDs: knownIDs
)

for mac in candidates {
guard await isScopeCurrent(scope) else { return .staleScope }
let recovered = await connectAccountDiscoveredIrohMac(
mac,
accountID: scope.userID,
ifStillCurrent: { [weak self] in
guard let self else { return false }
return self.isSignedIn
&& self.secondaryAggregationScopeGeneration == scope.generation
&& self.identityProvider?.currentUserID == scope.userID
}
)
guard await isScopeCurrent(scope) else { return .staleScope }
guard recovered else { continue }
await loadPairedMacs()
await loadRegistryDevices()
return .recovered
}
return .notFound
}

private func accountIrohRecoveryCandidates(
from discovered: [MobileDiscoveredIrohMac],
forgottenIDs: Set<String>,
excludingKnownIDs knownIDs: Set<String>
) -> [MobileDiscoveredIrohMac] {
var seen: Set<String> = []
var forgottenCandidates: [MobileDiscoveredIrohMac] = []
var unpairedCandidates: [MobileDiscoveredIrohMac] = []
for mac in discovered {
let canonicalDeviceID = cmxCanonicalDeviceID(mac.deviceID)
let pairingID = MobilePairedMac.pairingID(
macDeviceID: canonicalDeviceID,
instanceTag: mac.instanceTag
)
let isForgotten = forgottenIDs.contains(canonicalDeviceID)
|| forgottenIDs.contains(pairingID)
let isKnown = knownIDs.contains(canonicalDeviceID)
|| knownIDs.contains(pairingID)
guard isForgotten || !isKnown,
!mac.routes.isEmpty,
mac.routes.contains(where: { $0.kind == .iroh }),
seen.insert(pairingID).inserted else { continue }
if isForgotten {
forgottenCandidates.append(mac)
} else {
unpairedCandidates.append(mac)
}
}
return Array(
(forgottenCandidates + unpairedCandidates)
.prefix(Self.maximumAutomaticIrohCandidateCount)
)
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2147,12 +2147,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
/// completes. Filtering the current scope keeps that late write hidden until
/// the user explicitly pairs/connects that Mac again.
@ObservationIgnored var forgottenMacDeviceIDsByScope: [String: Set<String>] = [:]
/// True when the current account/team scope has a deleted-computer marker
/// that can be recovered through explicit same-account Iroh discovery.
/// True when the current account/team scope has a deleted-computer marker.
///
/// This controls recovery copy and passive-discovery suppression. Explicit
/// same-account recovery remains available without a marker.
public internal(set) var hasRecoverableDeletedComputers = false
/// True while the explicit deleted-computer recovery path is scanning and
/// reconnecting through account-scoped Iroh discovery.
public internal(set) var isRecoveringDeletedComputer = false
/// True while explicit account recovery is scanning and reconnecting through
/// account-scoped Iroh discovery.
public internal(set) var isRecoveringAccountComputer = false

var pairedMacsForIdentityMatching: [MobilePairedMac] {
storedPairedMacs.isEmpty ? pairedMacs : storedPairedMacs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ struct IrohZeroTouchDiscoveryTests {

await fixture.shell.loadPairedMacs()
#expect(fixture.shell.hasRecoverableDeletedComputers)
#expect(await fixture.shell.recoverForgottenIrohMacFromAccount() == .recovered)
#expect(await fixture.shell.recoverIrohMacFromAccount() == .recovered)

#expect(fixture.shell.connectionState == .connected)
#expect(fixture.factory.attemptedRouteIDs() == ["iroh-mac-a"])
Expand All @@ -115,6 +115,27 @@ struct IrohZeroTouchDiscoveryTests {
)))
}

@Test
func explicitAccountRecoveryDialsLiveMacWithoutForgottenMarker() async throws {
let fixture = try await makeFixture(
candidates: [try candidate(deviceID: "mac-a", endpointByte: "a")],
reportedDeviceID: "mac-a"
)
defer { fixture.cleanup() }

await fixture.shell.loadPairedMacs()
#expect(!fixture.shell.hasRecoverableDeletedComputers)
#expect(await fixture.shell.recoverIrohMacFromAccount() == .recovered)

#expect(fixture.shell.connectionState == .connected)
#expect(fixture.factory.attemptedRouteIDs() == ["iroh-mac-a"])
let rows = try await fixture.store.loadAll(stackUserID: "user-1", teamID: nil)
let saved = try #require(rows.first)
#expect(rows.count == 1)
#expect(saved.macDeviceID == "mac-a")
#expect(saved.instanceTag == "stable")
}

@Test
func explicitAccountRecoveryAcceptsMixedRouteCandidateWhenIrohRouteExists() async throws {
let mixedRouteCandidate = try candidate(
Expand All @@ -141,7 +162,7 @@ struct IrohZeroTouchDiscoveryTests {

await fixture.shell.loadPairedMacs()
#expect(fixture.shell.hasRecoverableDeletedComputers)
#expect(await fixture.shell.recoverForgottenIrohMacFromAccount() == .recovered)
#expect(await fixture.shell.recoverIrohMacFromAccount() == .recovered)

#expect(fixture.factory.attemptedRouteIDs() == ["iroh-mac-a"])
let rows = try await fixture.store.loadAll(stackUserID: "user-1", teamID: nil)
Expand All @@ -163,7 +184,7 @@ struct IrohZeroTouchDiscoveryTests {
scope: scope
)

#expect(await fixture.shell.recoverForgottenIrohMacFromAccount() == .notFound)
#expect(await fixture.shell.recoverIrohMacFromAccount() == .notFound)

#expect(fixture.shell.connectionState == .disconnected)
#expect(fixture.factory.attemptedRouteIDs() == ["iroh-mac-a"])
Expand All @@ -190,11 +211,11 @@ struct IrohZeroTouchDiscoveryTests {
scope: scope
)
let firstRecovery = Task { @MainActor in
await fixture.shell.recoverForgottenIrohMacFromAccount()
await fixture.shell.recoverIrohMacFromAccount()
}
await discovery.waitUntilRequested()

#expect(await fixture.shell.recoverForgottenIrohMacFromAccount() == .alreadyInProgress)
#expect(await fixture.shell.recoverIrohMacFromAccount() == .alreadyInProgress)

discovery.resume()
#expect(await firstRecovery.value == .recovered)
Expand All @@ -216,7 +237,7 @@ struct IrohZeroTouchDiscoveryTests {
scope: scope
)
let recovery = Task { @MainActor in
await fixture.shell.recoverForgottenIrohMacFromAccount()
await fixture.shell.recoverIrohMacFromAccount()
}
await discovery.waitUntilRequested()

Expand All @@ -243,7 +264,7 @@ struct IrohZeroTouchDiscoveryTests {
scope: scope
)
let recovery = Task { @MainActor in
await fixture.shell.recoverForgottenIrohMacFromAccount()
await fixture.shell.recoverIrohMacFromAccount()
}
await discovery.waitUntilRequested()

Expand Down
Loading