fix(swift-ios): load T3 Connect devices from relay
This commit is contained in:
4 files changed
+191
-2
No files matched your search
@@ -41,9 +41,17 @@ public struct T3ConnectCloudEnvironment: Identifiable, Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
protocol T3ConnectDeviceManaging: AnyObject {
|
||||
var hasActiveAccount: Bool { get }
|
||||
var currentRegisteredDeviceID: String? { get }
|
||||
func registeredDevices() async throws -> [T3ConnectRelayDevice]
|
||||
func unregisterDevice(id: String) async throws
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class T3ConnectController {
|
||||
public final class T3ConnectController: T3ConnectDeviceManaging {
|
||||
private static let logger = Logger(
|
||||
subsystem: "codes.t3.swift-ios",
|
||||
category: "T3Connect"
|
||||
@@ -133,6 +141,9 @@ public final class T3ConnectController {
|
||||
return reason
|
||||
}
|
||||
|
||||
public var currentRegisteredDeviceID: String? { registeredDeviceID }
|
||||
var hasActiveAccount: Bool { account != nil }
|
||||
|
||||
var clerk: Clerk? { auth?.client }
|
||||
|
||||
public func refresh() async {
|
||||
@@ -366,6 +377,38 @@ public final class T3ConnectController {
|
||||
registeredDeviceID = registration.deviceId
|
||||
}
|
||||
|
||||
public func registeredDevices() async throws -> [T3ConnectRelayDevice] {
|
||||
guard let auth, let relay else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
unavailableReason ?? "T3 Connect is unavailable in this build."
|
||||
)
|
||||
}
|
||||
let token = try await loadedRelayToken(auth)
|
||||
let generation = authorizationGeneration
|
||||
try beginAuthorizationOperation(generation)
|
||||
defer { endAuthorizationOperation() }
|
||||
let devices = try await relay.listDevices(clerkToken: token)
|
||||
try requireCurrentAuthorization(generation)
|
||||
return devices
|
||||
}
|
||||
|
||||
public func unregisterDevice(id: String) async throws {
|
||||
guard let auth, let relay else {
|
||||
throw T3ConnectRelayError.invalidConfiguration(
|
||||
unavailableReason ?? "T3 Connect is unavailable in this build."
|
||||
)
|
||||
}
|
||||
let token = try await loadedRelayToken(auth)
|
||||
let generation = authorizationGeneration
|
||||
try beginAuthorizationOperation(generation)
|
||||
defer { endAuthorizationOperation() }
|
||||
try await relay.unregisterDevice(deviceID: id, clerkToken: token)
|
||||
try requireCurrentAuthorization(generation)
|
||||
if registeredDeviceID == id {
|
||||
registeredDeviceID = nil
|
||||
}
|
||||
}
|
||||
|
||||
func rememberRegisteredDevice(id: String) {
|
||||
registeredDeviceID = id
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
|
||||
private let runtime: EnvironmentRuntime
|
||||
let t3ConnectController: T3ConnectController
|
||||
private let t3ConnectDeviceManager: any T3ConnectDeviceManaging
|
||||
private let hasMatchingT3ConnectController: Bool
|
||||
private let settingsStore: UserDefaults
|
||||
private let projectFaviconStore: FeatureProjectFaviconStore
|
||||
@@ -85,6 +86,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
] = [:]
|
||||
private var approvalRoutes: [String: PendingRequestRoute] = [:]
|
||||
private var inputRoutes: [String: PendingRequestRoute] = [:]
|
||||
private var relayDeviceSessionIDs: Set<String> = []
|
||||
private struct TerminalKey: Hashable {
|
||||
let threadID: String
|
||||
let terminalID: String
|
||||
@@ -117,6 +119,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
init(
|
||||
runtime: EnvironmentRuntime? = nil,
|
||||
t3ConnectController: T3ConnectController? = nil,
|
||||
t3ConnectDeviceManager: (any T3ConnectDeviceManaging)? = nil,
|
||||
settingsStore: UserDefaults = .standard,
|
||||
projectFaviconStore: FeatureProjectFaviconStore = FeatureProjectFaviconStore(),
|
||||
fallbackPollingInitialDelay: Duration = .seconds(3),
|
||||
@@ -142,6 +145,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
controller = T3ConnectController()
|
||||
}
|
||||
self.t3ConnectController = controller
|
||||
self.t3ConnectDeviceManager = t3ConnectDeviceManager ?? controller
|
||||
hasMatchingT3ConnectController = t3ConnectController != nil || runtime == nil
|
||||
self.runtime = runtime ?? EnvironmentRuntime(
|
||||
managedAuthorization: T3ConnectRuntimeAuthorization(controller: controller)
|
||||
@@ -1695,6 +1699,18 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
}
|
||||
|
||||
func loadDeviceSessions() async throws -> [FeatureDeviceSession] {
|
||||
if t3ConnectDeviceManager.hasActiveAccount {
|
||||
let devices = try await t3ConnectDeviceManager.registeredDevices()
|
||||
relayDeviceSessionIDs = Set(devices.map(\.deviceId))
|
||||
return devices.map {
|
||||
FeatureDeviceSession(
|
||||
relayDevice: $0,
|
||||
currentDeviceID: t3ConnectDeviceManager.currentRegisteredDeviceID
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
relayDeviceSessionIDs.removeAll()
|
||||
let client = try requireClient()
|
||||
try await requireScope("access:read", client: client)
|
||||
return try await client.clientSessions().map { session in
|
||||
@@ -1715,6 +1731,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
}
|
||||
|
||||
func revokeDeviceSession(id: String) async throws {
|
||||
if relayDeviceSessionIDs.contains(id) {
|
||||
try await t3ConnectDeviceManager.unregisterDevice(id: id)
|
||||
relayDeviceSessionIDs.remove(id)
|
||||
return
|
||||
}
|
||||
|
||||
let client = try requireClient()
|
||||
try await requireScope("access:write", client: client)
|
||||
guard try await client.revokeClientSession(id: id) else {
|
||||
@@ -1723,6 +1745,18 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
}
|
||||
|
||||
func revokeOtherDeviceSessions() async throws {
|
||||
if !relayDeviceSessionIDs.isEmpty {
|
||||
guard let currentID = t3ConnectDeviceManager.currentRegisteredDeviceID else {
|
||||
throw NativeFeatureClientError.currentDeviceUnknown
|
||||
}
|
||||
let otherIDs = relayDeviceSessionIDs.filter { $0 != currentID }
|
||||
for id in otherIDs {
|
||||
try await t3ConnectDeviceManager.unregisterDevice(id: id)
|
||||
}
|
||||
relayDeviceSessionIDs.subtract(otherIDs)
|
||||
return
|
||||
}
|
||||
|
||||
let client = try requireClient()
|
||||
try await requireScope("access:write", client: client)
|
||||
_ = try await client.revokeOtherClientSessions()
|
||||
@@ -5287,6 +5321,28 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
private static let dateFormatter = ISO8601DateFormatter()
|
||||
}
|
||||
|
||||
extension FeatureDeviceSession {
|
||||
init(relayDevice: T3ConnectRelayDevice, currentDeviceID: String?) {
|
||||
let updatedAt = Self.t3ConnectRelayDate(relayDevice.updatedAt)
|
||||
self.init(
|
||||
sessionID: relayDevice.deviceId,
|
||||
label: relayDevice.label,
|
||||
deviceType: relayDevice.platform.lowercased().contains("ipad") ? .tablet : .mobile,
|
||||
operatingSystem: "iOS \(relayDevice.iosMajorVersion)",
|
||||
browser: relayDevice.appVersion.map { "T3 Code \($0)" },
|
||||
issuedAt: updatedAt,
|
||||
expiresAt: .distantFuture,
|
||||
lastConnectedAt: updatedAt,
|
||||
isConnected: false,
|
||||
isCurrent: relayDevice.deviceId == currentDeviceID
|
||||
)
|
||||
}
|
||||
|
||||
private static func t3ConnectRelayDate(_ value: String) -> Date {
|
||||
(try? Date(value, strategy: .iso8601)) ?? .distantPast
|
||||
}
|
||||
}
|
||||
|
||||
enum NativeDetailRenderMutation: Equatable {
|
||||
case full
|
||||
case message(OrchestrationMessage)
|
||||
@@ -5862,6 +5918,7 @@ private enum NativeFeatureClientError: LocalizedError {
|
||||
case invalidProjectPath
|
||||
case branchRequired
|
||||
case deviceSessionNotFound
|
||||
case currentDeviceUnknown
|
||||
case missingScope(String)
|
||||
case tooManyAttachments
|
||||
|
||||
@@ -5877,6 +5934,7 @@ private enum NativeFeatureClientError: LocalizedError {
|
||||
case .invalidProjectPath: "Enter a workspace path on the connected environment."
|
||||
case .branchRequired: "Choose a base branch for the new worktree."
|
||||
case .deviceSessionNotFound: "That device session is no longer active."
|
||||
case .currentDeviceUnknown: "This installation has not registered for device access yet."
|
||||
case .missingScope: "This connection does not have permission to manage devices."
|
||||
case .tooManyAttachments: "You can attach up to 8 images per message."
|
||||
}
|
||||
|
||||
@@ -129,7 +129,8 @@ final class EmptyFeatureDeviceManager: FeatureDeviceManaging {
|
||||
enum DeviceManagementErrorCopy {
|
||||
static func message(for error: Error) -> String {
|
||||
let value = error.localizedDescription.lowercased()
|
||||
if value.contains("scope") || value.contains("403") || value.contains("forbidden") {
|
||||
if value.contains("scope") || value.contains("403") || value.contains("forbidden")
|
||||
|| value.contains("permission") {
|
||||
return "This connection does not have permission to manage devices."
|
||||
}
|
||||
if value.contains("offline") || value.contains("network")
|
||||
|
||||
@@ -34,6 +34,73 @@ struct DeviceManagementTests {
|
||||
#expect(desktop.displayName == "Desktop")
|
||||
}
|
||||
|
||||
@Test
|
||||
func mapsT3ConnectDeviceAsCurrentInstallation() {
|
||||
let relayDevice = T3ConnectRelayDevice(
|
||||
deviceId: "phone-1",
|
||||
label: "Theo’s iPhone",
|
||||
platform: "ios",
|
||||
iosMajorVersion: 27,
|
||||
appVersion: "1.0 (24)",
|
||||
notifications: .init(
|
||||
enabled: true,
|
||||
notifyOnApproval: true,
|
||||
notifyOnInput: true,
|
||||
notifyOnCompletion: true,
|
||||
notifyOnFailure: true
|
||||
),
|
||||
liveActivities: .init(enabled: true),
|
||||
updatedAt: "2026-08-10T18:30:00.000Z"
|
||||
)
|
||||
|
||||
let session = FeatureDeviceSession(
|
||||
relayDevice: relayDevice,
|
||||
currentDeviceID: "phone-1"
|
||||
)
|
||||
|
||||
#expect(session.id == "phone-1")
|
||||
#expect(session.displayName == "Theo’s iPhone")
|
||||
#expect(session.deviceType == .mobile)
|
||||
#expect(session.operatingSystem == "iOS 27")
|
||||
#expect(session.browser == "T3 Code 1.0 (24)")
|
||||
#expect(session.isCurrent)
|
||||
#expect(session.lastConnectedAt == session.issuedAt)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func loadsT3ConnectDevicesWithoutEnvironmentAdminScope() async throws {
|
||||
let manager = T3ConnectDeviceManagerStub(
|
||||
devices: [relayDevice(id: "phone-1")],
|
||||
currentDeviceID: "phone-1"
|
||||
)
|
||||
let client = NativeFeatureClient(t3ConnectDeviceManager: manager)
|
||||
|
||||
let sessions = try await client.loadDeviceSessions()
|
||||
|
||||
#expect(sessions.map(\.id) == ["phone-1"])
|
||||
#expect(sessions[0].isCurrent)
|
||||
#expect(manager.loadCount == 1)
|
||||
}
|
||||
|
||||
private func relayDevice(id: String) -> T3ConnectRelayDevice {
|
||||
T3ConnectRelayDevice(
|
||||
deviceId: id,
|
||||
label: "Theo’s iPhone",
|
||||
platform: "ios",
|
||||
iosMajorVersion: 27,
|
||||
appVersion: "1.0 (24)",
|
||||
notifications: .init(
|
||||
enabled: true,
|
||||
notifyOnApproval: true,
|
||||
notifyOnInput: true,
|
||||
notifyOnCompletion: true,
|
||||
notifyOnFailure: true
|
||||
),
|
||||
liveActivities: .init(enabled: true),
|
||||
updatedAt: "2026-08-10T18:30:00.000Z"
|
||||
)
|
||||
}
|
||||
|
||||
private func session(
|
||||
id: String,
|
||||
at date: Date,
|
||||
@@ -52,3 +119,23 @@ struct DeviceManagementTests {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class T3ConnectDeviceManagerStub: T3ConnectDeviceManaging {
|
||||
let hasActiveAccount = true
|
||||
let currentRegisteredDeviceID: String?
|
||||
private let devices: [T3ConnectRelayDevice]
|
||||
private(set) var loadCount = 0
|
||||
|
||||
init(devices: [T3ConnectRelayDevice], currentDeviceID: String?) {
|
||||
self.devices = devices
|
||||
self.currentRegisteredDeviceID = currentDeviceID
|
||||
}
|
||||
|
||||
func registeredDevices() async throws -> [T3ConnectRelayDevice] {
|
||||
loadCount += 1
|
||||
return devices
|
||||
}
|
||||
|
||||
func unregisterDevice(id: String) async throws {}
|
||||
}
|
||||
Reference in new issue
Block a user