fix(swift-ios): harden native client architecture
This commit is contained in:
29 files changed
+1507
-128
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import ClerkKit
|
||||
import Foundation
|
||||
import Observation
|
||||
import OSLog
|
||||
|
||||
public extension Notification.Name {
|
||||
static let t3ConnectSessionChanged = Notification.Name("T3ConnectSessionChanged")
|
||||
@@ -16,6 +17,10 @@ public protocol T3ConnectCapable: AnyObject {
|
||||
func connectT3Environment(
|
||||
_ credential: T3ConnectManagedEnvironmentCredential
|
||||
) async throws
|
||||
|
||||
/// Ends the account session and removes only relay-managed runtime state.
|
||||
/// Directly paired environments belong to the device and must survive.
|
||||
func signOutT3Connect() async
|
||||
}
|
||||
|
||||
public struct T3ConnectCloudEnvironment: Identifiable, Equatable, Sendable {
|
||||
@@ -39,6 +44,10 @@ public struct T3ConnectCloudEnvironment: Identifiable, Equatable, Sendable {
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class T3ConnectController {
|
||||
private static let logger = Logger(
|
||||
subsystem: "codes.t3.swift-ios",
|
||||
category: "T3Connect"
|
||||
)
|
||||
public let resolution: T3ConnectConfigurationResolution
|
||||
public let managedAuthorizer: T3ConnectManagedEnvironmentAuthorizer
|
||||
|
||||
@@ -57,13 +66,31 @@ public final class T3ConnectController {
|
||||
private let relay: T3ConnectRelayClient?
|
||||
private var registeredDeviceID: String?
|
||||
private var refreshGeneration: UInt64 = 0
|
||||
private var signOutOperation: (@MainActor @Sendable () async throws -> Void)?
|
||||
|
||||
public init(
|
||||
public convenience init(
|
||||
resolution: T3ConnectConfigurationResolution = T3ConnectConfiguration.resolve(),
|
||||
transport: any HTTPTransport = URLSessionHTTPTransport(),
|
||||
signer: T3ConnectDPoPSigner = T3ConnectDPoPSigner()
|
||||
) {
|
||||
self.init(
|
||||
resolution: resolution,
|
||||
transport: transport,
|
||||
signer: signer,
|
||||
configureAuth: true,
|
||||
signOutOperation: nil
|
||||
)
|
||||
}
|
||||
|
||||
private init(
|
||||
resolution: T3ConnectConfigurationResolution,
|
||||
transport: any HTTPTransport,
|
||||
signer: T3ConnectDPoPSigner,
|
||||
configureAuth: Bool,
|
||||
signOutOperation: (@MainActor @Sendable () async throws -> Void)?
|
||||
) {
|
||||
self.resolution = resolution
|
||||
self.signOutOperation = signOutOperation
|
||||
managedAuthorizer = T3ConnectManagedEnvironmentAuthorizer(
|
||||
transport: transport,
|
||||
signer: signer
|
||||
@@ -73,7 +100,7 @@ public final class T3ConnectController {
|
||||
relay = nil
|
||||
return
|
||||
}
|
||||
auth = T3ConnectClerkSession(configuration: configuration)
|
||||
auth = configureAuth ? T3ConnectClerkSession(configuration: configuration) : nil
|
||||
relay = T3ConnectRelayClient(
|
||||
configuration: configuration,
|
||||
transport: transport,
|
||||
@@ -81,6 +108,21 @@ public final class T3ConnectController {
|
||||
)
|
||||
}
|
||||
|
||||
convenience init(
|
||||
resolution: T3ConnectConfigurationResolution,
|
||||
transport: any HTTPTransport,
|
||||
signer: T3ConnectDPoPSigner,
|
||||
signOutOperation: @escaping @MainActor @Sendable () async throws -> Void
|
||||
) {
|
||||
self.init(
|
||||
resolution: resolution,
|
||||
transport: transport,
|
||||
signer: signer,
|
||||
configureAuth: false,
|
||||
signOutOperation: signOutOperation
|
||||
)
|
||||
}
|
||||
|
||||
public var unavailableReason: String? {
|
||||
guard case let .unavailable(reason) = resolution else { return nil }
|
||||
return reason
|
||||
@@ -145,34 +187,46 @@ public final class T3ConnectController {
|
||||
}
|
||||
|
||||
public func signOut() async {
|
||||
guard let auth, let relay else { return }
|
||||
guard let relay else { return }
|
||||
refreshGeneration &+= 1
|
||||
let generation = refreshGeneration
|
||||
isRefreshing = true
|
||||
defer {
|
||||
if refreshGeneration == generation { isRefreshing = false }
|
||||
}
|
||||
if let auth,
|
||||
let registeredDeviceID,
|
||||
let token = try? await loadedRelayToken(auth) {
|
||||
// Remote delivery must not outlive the signed-in session on this
|
||||
// install. A failed best-effort unregister must not trap the user
|
||||
// in an account they are trying to leave.
|
||||
try? await relay.unregisterDevice(
|
||||
deviceID: registeredDeviceID,
|
||||
clerkToken: token
|
||||
)
|
||||
}
|
||||
|
||||
// Local authorization state is security-sensitive and must be cleared
|
||||
// before Clerk performs network work. A failed remote sign-out can be
|
||||
// reported, but it cannot leave relay tokens or managed state usable.
|
||||
await relay.clearTokenCache()
|
||||
registeredDeviceID = nil
|
||||
account = nil
|
||||
environments = []
|
||||
|
||||
do {
|
||||
if let registeredDeviceID,
|
||||
let token = try? await loadedRelayToken(auth) {
|
||||
// Remote delivery must not outlive the signed-in session on this
|
||||
// install. A failed best-effort unregister must not trap the user
|
||||
// in an account they are trying to leave.
|
||||
try? await relay.unregisterDevice(
|
||||
deviceID: registeredDeviceID,
|
||||
clerkToken: token
|
||||
)
|
||||
if let signOutOperation {
|
||||
try await signOutOperation()
|
||||
} else if let auth {
|
||||
try await auth.signOut()
|
||||
}
|
||||
try await auth.signOut()
|
||||
guard refreshGeneration == generation else { return }
|
||||
await relay.clearTokenCache()
|
||||
registeredDeviceID = nil
|
||||
account = nil
|
||||
environments = []
|
||||
Self.logger.info("T3 Connect account session signed out")
|
||||
} catch {
|
||||
if refreshGeneration == generation {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
guard refreshGeneration == generation else { return }
|
||||
Self.logger.error(
|
||||
"T3 Connect remote sign-out failed: \(error.localizedDescription, privacy: .private)"
|
||||
)
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
extension FeatureInputAnswer {
|
||||
var jsonValue: JSONValue {
|
||||
@@ -11,11 +12,25 @@ extension FeatureInputAnswer {
|
||||
}
|
||||
}
|
||||
|
||||
private struct T3ConnectManagedCleanupError: LocalizedError {
|
||||
let failureCount: Int
|
||||
|
||||
var errorDescription: String? {
|
||||
"Couldn’t remove \(failureCount) managed T3 Connect "
|
||||
+ (failureCount == 1 ? "environment." : "environments.")
|
||||
}
|
||||
}
|
||||
|
||||
/// Composes the transport-focused Core layer with the UI-focused Features layer.
|
||||
@MainActor
|
||||
final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
FeatureProjectCreationClient, FeatureWorkspaceAssetResolving, T3ConnectCapable
|
||||
{
|
||||
private static let maximumRetainedThreadDetails = 6
|
||||
private static let t3ConnectLogger = Logger(
|
||||
subsystem: "codes.t3.swift-ios",
|
||||
category: "T3Connect"
|
||||
)
|
||||
private static let initialThreadUserTurnLimit = 10
|
||||
private static let olderThreadPageUserTurnLimit = 20
|
||||
|
||||
@@ -54,6 +69,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
private var activeThreadEnvironmentID: String?
|
||||
private var latestDetails: [String: FeatureThreadDetail] = [:]
|
||||
private var detailRenderCaches: [String: NativeDetailRenderCache] = [:]
|
||||
private var detailCacheRecency: [String] = []
|
||||
private var attachmentURLs: [AttachmentCacheKey: CachedAttachmentURL] = [:]
|
||||
private var pendingBootstrapSubmissions: [PendingBootstrapSubmission] = []
|
||||
private var pendingTurnSubmissions: [String: PendingTurnSubmission] = [:]
|
||||
@@ -186,6 +202,32 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func backgroundSnapshot() async throws -> FeatureSnapshot {
|
||||
let environments = try await runtime.environments()
|
||||
guard let activeClient = try await runtime.activeClient() else {
|
||||
return disconnectedSnapshot(environments: environments)
|
||||
}
|
||||
let environment = activeClient.environment
|
||||
let loads = await loadEnvironmentShells(environments)
|
||||
guard let currentClient = try await runtime.activeClient(),
|
||||
currentClient.environment.id == environment.id else {
|
||||
throw CancellationError()
|
||||
}
|
||||
|
||||
reconcileEnvironmentLoads(loads, savedEnvironments: environments)
|
||||
let activeIsReachable = loads.contains {
|
||||
$0.environment.id == environment.id && $0.shell != nil
|
||||
}
|
||||
let snapshot = makeSnapshot(
|
||||
environments: environments,
|
||||
activeEnvironment: environment,
|
||||
connectionState: activeIsReachable ? .connected : .disconnected,
|
||||
connectionDetail: activeIsReachable ? nil : "That server is currently unreachable."
|
||||
)
|
||||
latestSnapshot = snapshot
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func events() -> AsyncStream<FeatureEvent> {
|
||||
stream
|
||||
}
|
||||
@@ -279,6 +321,38 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
startPolling(managedClient)
|
||||
}
|
||||
|
||||
func signOutT3Connect() async {
|
||||
// Clear the account and relay-token cache even when Clerk's remote
|
||||
// sign-out fails, then revoke every locally minted managed credential.
|
||||
// Manual pairings are device-owned and deliberately survive sign-out.
|
||||
await t3ConnectController.signOut()
|
||||
do {
|
||||
let managedIDs = try await runtime.environments()
|
||||
.filter { $0.kind == .managedDPoP }
|
||||
.map(\.id)
|
||||
var failureCount = 0
|
||||
for id in managedIDs {
|
||||
do {
|
||||
try await removeEnvironment(id: id)
|
||||
} catch {
|
||||
failureCount += 1
|
||||
Self.t3ConnectLogger.error(
|
||||
"Managed environment removal failed: \(error.localizedDescription, privacy: .private)"
|
||||
)
|
||||
}
|
||||
}
|
||||
guard failureCount == 0 else {
|
||||
throw T3ConnectManagedCleanupError(failureCount: failureCount)
|
||||
}
|
||||
Self.t3ConnectLogger.info("Cleared managed T3 Connect runtime state")
|
||||
} catch {
|
||||
Self.t3ConnectLogger.error(
|
||||
"Managed T3 Connect cleanup failed: \(error.localizedDescription, privacy: .private)"
|
||||
)
|
||||
t3ConnectController.errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func activateEnvironment(id: String) async throws {
|
||||
let activated = try await runtime.activate(id: id)
|
||||
await adoptEnvironment(activated.environment, client: activated)
|
||||
@@ -395,6 +469,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
pendingOlderThreadPage = nil
|
||||
latestDetails.removeAll()
|
||||
detailRenderCaches.removeAll()
|
||||
detailCacheRecency.removeAll()
|
||||
attachmentURLs.removeAll()
|
||||
pendingBootstrapSubmissions.removeAll()
|
||||
pendingTurnSubmissions.removeAll()
|
||||
@@ -1080,6 +1155,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
}
|
||||
latestDetails[route.uiID] = nil
|
||||
detailRenderCaches[route.uiID] = nil
|
||||
detailCacheRecency.removeAll { $0 == route.uiID }
|
||||
await emitCachedSnapshot(for: route.environmentID)
|
||||
try? await refresh(client: route.client, includeArchived: true)
|
||||
}
|
||||
@@ -1207,6 +1283,8 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
activeThreadPage = nil
|
||||
threadHistoryEpoch &+= 1
|
||||
pendingOlderThreadPage = nil
|
||||
markThreadCacheRecentlyUsed(id)
|
||||
evictOldThreadCachesIfNeeded()
|
||||
}
|
||||
|
||||
func sendMessage(
|
||||
@@ -2134,6 +2212,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
)
|
||||
case .projectUpserted, .projectRemoved, .threadUpserted, .threadRemoved:
|
||||
await self.consume(delta: item, client: activeClient)
|
||||
case .refreshRequired:
|
||||
if let shell = try? await activeClient.shellSnapshot() {
|
||||
await self.consume(
|
||||
shell: shell,
|
||||
client: activeClient,
|
||||
refreshActiveThread: true
|
||||
)
|
||||
}
|
||||
case .synchronized:
|
||||
break
|
||||
}
|
||||
@@ -2406,7 +2492,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
sequence = nextSequence
|
||||
case let .threadRemoved(nextSequence, _):
|
||||
sequence = nextSequence
|
||||
case .snapshot, .synchronized:
|
||||
case .snapshot, .synchronized, .refreshRequired:
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2452,6 +2538,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
if let uiThreadID {
|
||||
latestDetails[uiThreadID] = nil
|
||||
detailRenderCaches[uiThreadID] = nil
|
||||
detailCacheRecency.removeAll { $0 == uiThreadID }
|
||||
}
|
||||
if activeThreadID == uiThreadID {
|
||||
resetDetailRefresh()
|
||||
@@ -2464,7 +2551,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
threadHistoryEpoch &+= 1
|
||||
pendingOlderThreadPage = nil
|
||||
}
|
||||
case .snapshot, .synchronized:
|
||||
case .snapshot, .synchronized, .refreshRequired:
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3313,10 +3400,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
snapshot.environments[index].connectionDetail = detail
|
||||
}
|
||||
latestSnapshot = snapshot
|
||||
continuation.yield(.snapshot(snapshot))
|
||||
return
|
||||
}
|
||||
continuation.yield(
|
||||
.connection(connection)
|
||||
)
|
||||
continuation.yield(.connection(connection))
|
||||
}
|
||||
|
||||
private func makeSnapshot(
|
||||
@@ -3453,7 +3540,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
snoozedUntil: thread.snoozedUntil.map(parseDate),
|
||||
snoozedAt: thread.snoozedAt.map(parseDate),
|
||||
pinnedAt: thread.pinnedAt.map(parseDate),
|
||||
supportsSettlement: environment.descriptor?.capabilities.threadSettlement,
|
||||
supportsSnooze: environment.descriptor?.capabilities.threadSnooze,
|
||||
supportsPinning: environment.descriptor?.capabilities.threadPinning,
|
||||
supportsTitleRegeneration: environment.descriptor?.capabilities.threadTitleRegeneration,
|
||||
attentionAt: failureDate(
|
||||
latestTurn: thread.latestTurn,
|
||||
session: thread.session
|
||||
@@ -3511,7 +3601,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
snoozedUntil: thread.snoozedUntil.map(parseDate),
|
||||
snoozedAt: thread.snoozedAt.map(parseDate),
|
||||
pinnedAt: thread.pinnedAt.map(parseDate),
|
||||
supportsSettlement: environment.descriptor?.capabilities.threadSettlement,
|
||||
supportsSnooze: environment.descriptor?.capabilities.threadSnooze,
|
||||
supportsPinning: environment.descriptor?.capabilities.threadPinning,
|
||||
supportsTitleRegeneration: environment.descriptor?.capabilities.threadTitleRegeneration,
|
||||
attentionAt: failureDate(
|
||||
latestTurn: thread.latestTurn,
|
||||
session: thread.session
|
||||
@@ -3538,6 +3631,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
)
|
||||
let cache = detailRenderCaches[threadID] ?? NativeDetailRenderCache()
|
||||
detailRenderCaches[threadID] = cache
|
||||
markThreadCacheRecentlyUsed(threadID)
|
||||
|
||||
if !cache.isInitialized || mutations == nil || mutations?.requiresFullRebuild == true {
|
||||
cache.messagesByID = thread.messages.reduce(into: [:]) { result, raw in
|
||||
@@ -3588,6 +3682,27 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
)
|
||||
}
|
||||
|
||||
private func markThreadCacheRecentlyUsed(_ threadID: String) {
|
||||
detailCacheRecency.removeAll { $0 == threadID }
|
||||
detailCacheRecency.append(threadID)
|
||||
}
|
||||
|
||||
private func evictOldThreadCachesIfNeeded() {
|
||||
while detailCacheRecency.count > Self.maximumRetainedThreadDetails {
|
||||
let threadID = detailCacheRecency.removeFirst()
|
||||
guard threadID != activeThreadID else {
|
||||
detailCacheRecency.append(threadID)
|
||||
break
|
||||
}
|
||||
latestDetails[threadID] = nil
|
||||
detailRenderCaches[threadID] = nil
|
||||
terminalSnapshots = terminalSnapshots.filter { $0.key.threadID != threadID }
|
||||
if let hydration = attachmentHydrationTasks.removeValue(forKey: threadID) {
|
||||
hydration.task.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func featurePage(
|
||||
_ page: OrchestrationThreadDetailPage?,
|
||||
isLoading: Bool = false
|
||||
@@ -3809,12 +3924,15 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
|
||||
private func sortedByCreation(
|
||||
_ activities: [OrchestrationActivity]
|
||||
) -> [OrchestrationActivity] {
|
||||
activities.enumerated()
|
||||
.map { (index: $0.offset, date: parseDate($0.element.createdAt), activity: $0.element) }
|
||||
.sorted { lhs, rhs in
|
||||
lhs.date != rhs.date ? lhs.date < rhs.date : lhs.index < rhs.index
|
||||
}
|
||||
.map(\.activity)
|
||||
var decorated: [(index: Int, date: Date, activity: OrchestrationActivity)] = []
|
||||
decorated.reserveCapacity(activities.count)
|
||||
for (index, activity) in activities.enumerated() {
|
||||
decorated.append((index, parseDate(activity.createdAt), activity))
|
||||
}
|
||||
decorated.sort { lhs, rhs in
|
||||
lhs.date != rhs.date ? lhs.date < rhs.date : lhs.index < rhs.index
|
||||
}
|
||||
return decorated.map(\.activity)
|
||||
}
|
||||
|
||||
private func seedWorkLogs(
|
||||
|
||||
@@ -11,6 +11,7 @@ extension Notification.Name {
|
||||
enum PlatformAgentAwarenessProjection {
|
||||
static let terminalVisibilityWindow: TimeInterval = 15 * 60
|
||||
static let maximumRows = 5
|
||||
static let minimumPersistenceInterval: TimeInterval = 30
|
||||
|
||||
static func aggregate(
|
||||
snapshot: FeatureSnapshot,
|
||||
@@ -182,9 +183,11 @@ final class PlatformAgentAwarenessCoordinator {
|
||||
}
|
||||
|
||||
private var activityUpdateTask: Task<Void, Never>?
|
||||
private var widgetUpdateTask: Task<Void, Never>?
|
||||
private var lastSignature: Signature?
|
||||
private var inFlightSignature: Signature?
|
||||
private var synchronizationGeneration = 0
|
||||
private var widgetGeneration = 0
|
||||
|
||||
init(
|
||||
updateLiveActivity: @escaping @MainActor (
|
||||
@@ -215,7 +218,17 @@ final class PlatformAgentAwarenessCoordinator {
|
||||
let signature = Signature(
|
||||
activeCount: aggregate.activeCount,
|
||||
subtitle: aggregate.subtitle,
|
||||
rows: aggregate.activities,
|
||||
// `updatedAt` advances throughout a turn without changing visible
|
||||
// state. Bucket it so long work still refreshes ActivityKit's stale
|
||||
// date without writing widget state for every shell delta.
|
||||
rows: aggregate.activities.map { row in
|
||||
var row = row
|
||||
let bucket = floor(
|
||||
now.timeIntervalSince1970 / PlatformAgentAwarenessProjection.minimumPersistenceInterval
|
||||
) * PlatformAgentAwarenessProjection.minimumPersistenceInterval
|
||||
row.updatedAt = Date(timeIntervalSince1970: bucket).ISO8601Format()
|
||||
return row
|
||||
},
|
||||
enabled: liveActivitiesEnabled
|
||||
)
|
||||
let synchronization = Synchronization(
|
||||
@@ -239,8 +252,7 @@ final class PlatformAgentAwarenessCoordinator {
|
||||
updatedAt: aggregate.updatedAt,
|
||||
tasks: aggregate.activities
|
||||
)
|
||||
try? T3TaskWidgetSnapshotStore.save(widgetSnapshot)
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget")
|
||||
scheduleWidgetUpdate(widgetSnapshot)
|
||||
|
||||
schedule(synchronization)
|
||||
}
|
||||
@@ -253,8 +265,7 @@ final class PlatformAgentAwarenessCoordinator {
|
||||
let generation = synchronizationGeneration
|
||||
lastSignature = nil
|
||||
inFlightSignature = nil
|
||||
try? T3TaskWidgetSnapshotStore.save(.empty)
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget")
|
||||
scheduleWidgetUpdate(.empty)
|
||||
activityUpdateTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await endLiveActivities()
|
||||
@@ -293,6 +304,21 @@ final class PlatformAgentAwarenessCoordinator {
|
||||
}
|
||||
}
|
||||
|
||||
private func scheduleWidgetUpdate(_ snapshot: T3TaskWidgetSnapshot) {
|
||||
widgetUpdateTask?.cancel()
|
||||
widgetGeneration &+= 1
|
||||
let generation = widgetGeneration
|
||||
widgetUpdateTask = Task { @MainActor [weak self] in
|
||||
let saved = await PlatformWidgetSnapshotWriter.shared.save(
|
||||
snapshot,
|
||||
generation: generation
|
||||
)
|
||||
guard let self, saved, widgetGeneration == generation else { return }
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget")
|
||||
widgetUpdateTask = nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func synchronizeLiveActivity(
|
||||
aggregate: T3RelayAgentActivityAggregateState,
|
||||
enabled: Bool,
|
||||
@@ -355,3 +381,20 @@ final class PlatformAgentAwarenessCoordinator {
|
||||
NotificationCenter.default.post(name: .platformLiveActivityChanged, object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private actor PlatformWidgetSnapshotWriter {
|
||||
static let shared = PlatformWidgetSnapshotWriter()
|
||||
|
||||
private var latestGeneration = 0
|
||||
|
||||
func save(_ snapshot: T3TaskWidgetSnapshot, generation: Int) -> Bool {
|
||||
guard generation >= latestGeneration else { return false }
|
||||
latestGeneration = generation
|
||||
do {
|
||||
try T3TaskWidgetSnapshotStore.save(snapshot)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,17 +49,43 @@ final class PlatformBackgroundRefreshCoordinator {
|
||||
return
|
||||
}
|
||||
|
||||
// Install cancellation before creating the operation. If expiration
|
||||
// wins the race, `install` immediately cancels the new task.
|
||||
let cancellation = PlatformBackgroundRefreshCancellation()
|
||||
task.expirationHandler = {
|
||||
cancellation.cancel()
|
||||
}
|
||||
let operation = Task { @MainActor in
|
||||
await refreshAction()
|
||||
}
|
||||
task.expirationHandler = {
|
||||
operation.cancel()
|
||||
}
|
||||
cancellation.install(operation)
|
||||
let succeeded = await operation.value
|
||||
task.setTaskCompleted(success: succeeded && !operation.isCancelled)
|
||||
}
|
||||
}
|
||||
|
||||
private final class PlatformBackgroundRefreshCancellation: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var operation: Task<Bool, Never>?
|
||||
private var didExpire = false
|
||||
|
||||
func install(_ operation: Task<Bool, Never>) {
|
||||
let shouldCancel = lock.withLock {
|
||||
self.operation = operation
|
||||
return didExpire
|
||||
}
|
||||
if shouldCancel { operation.cancel() }
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
let operation = lock.withLock {
|
||||
didExpire = true
|
||||
return self.operation
|
||||
}
|
||||
operation?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
enum PlatformBackgroundRefreshPolicy {
|
||||
/// iOS chooses the actual cadence. Fifteen minutes is merely the earliest
|
||||
/// useful retry and avoids repeatedly asking the scheduler for immediate work.
|
||||
|
||||
@@ -11,6 +11,7 @@ struct PlatformRootView: View {
|
||||
@State private var incomingShareCoordinator = PlatformIncomingShareCoordinator()
|
||||
@State private var incomingShareNeedsProject = false
|
||||
@State private var importedShareProjectID: String?
|
||||
@State private var recentThreadsPersistenceTask: Task<Void, Never>?
|
||||
|
||||
init(model: FeatureRootModel) {
|
||||
self.model = model
|
||||
@@ -318,7 +319,12 @@ struct PlatformRootView: View {
|
||||
current: model.snapshot.threads
|
||||
)
|
||||
previousThreadStates = current
|
||||
PlatformRecentThreadStore.shared.update(from: model.snapshot.threads)
|
||||
recentThreadsPersistenceTask?.cancel()
|
||||
let threads = model.snapshot.threads
|
||||
recentThreadsPersistenceTask = Task.detached(priority: .utility) {
|
||||
guard !Task.isCancelled else { return }
|
||||
PlatformRecentThreadStore.shared.update(from: threads)
|
||||
}
|
||||
synchronizeAgentAwareness()
|
||||
|
||||
for signal in signals {
|
||||
|
||||
@@ -15,8 +15,7 @@ struct T3CodeApp: App {
|
||||
)
|
||||
PlatformBackgroundRefreshCoordinator.shared.install { [weak model] in
|
||||
guard let model else { return false }
|
||||
await model.reload()
|
||||
return !Task.isCancelled
|
||||
return await model.refreshInBackground()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,40 @@
|
||||
import Foundation
|
||||
|
||||
/// Arrays sent by the server are allowed to grow new element variants before a
|
||||
/// mobile release catches up. Decode each element independently so one future
|
||||
/// project, thread, message, or activity cannot discard the rest of a snapshot.
|
||||
@propertyWrapper
|
||||
public struct ForwardCompatibleArray<Element>: Codable, Equatable, Sendable
|
||||
where Element: Codable & Equatable & Sendable {
|
||||
public var wrappedValue: [Element]
|
||||
|
||||
public init(wrappedValue: [Element]) {
|
||||
self.wrappedValue = wrappedValue
|
||||
}
|
||||
|
||||
public init(from decoder: any Decoder) throws {
|
||||
var container = try decoder.unkeyedContainer()
|
||||
var values: [Element] = []
|
||||
values.reserveCapacity(container.count ?? 0)
|
||||
while !container.isAtEnd {
|
||||
// `superDecoder` advances the unkeyed container even when the
|
||||
// element itself is not understood by this client.
|
||||
let elementDecoder = try container.superDecoder()
|
||||
if let value = try? Element(from: elementDecoder) {
|
||||
values.append(value)
|
||||
}
|
||||
}
|
||||
wrappedValue = values
|
||||
}
|
||||
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.unkeyedContainer()
|
||||
for value in wrappedValue {
|
||||
try container.encode(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum EnvironmentKind: String, Codable, Sendable {
|
||||
case bearer
|
||||
case local
|
||||
@@ -410,23 +445,23 @@ public struct OrchestrationThread: Codable, Identifiable, Equatable, Sendable {
|
||||
public let snoozedAt: String?
|
||||
public let pinnedAt: String?
|
||||
public let deletedAt: String?
|
||||
public let messages: [OrchestrationMessage]
|
||||
public let activities: [OrchestrationActivity]
|
||||
public let checkpoints: [CheckpointSummary]
|
||||
@ForwardCompatibleArray public var messages: [OrchestrationMessage]
|
||||
@ForwardCompatibleArray public var activities: [OrchestrationActivity]
|
||||
@ForwardCompatibleArray public var checkpoints: [CheckpointSummary]
|
||||
public let session: OrchestrationSession?
|
||||
}
|
||||
|
||||
public struct OrchestrationShellSnapshot: Codable, Equatable, Sendable {
|
||||
public let snapshotSequence: Int
|
||||
public let projects: [OrchestrationProject]
|
||||
public let threads: [OrchestrationThreadShell]
|
||||
@ForwardCompatibleArray public var projects: [OrchestrationProject]
|
||||
@ForwardCompatibleArray public var threads: [OrchestrationThreadShell]
|
||||
public let updatedAt: String
|
||||
}
|
||||
|
||||
public struct OrchestrationReadModel: Codable, Equatable, Sendable {
|
||||
public let snapshotSequence: Int
|
||||
public let projects: [OrchestrationProject]
|
||||
public let threads: [OrchestrationThread]
|
||||
@ForwardCompatibleArray public var projects: [OrchestrationProject]
|
||||
@ForwardCompatibleArray public var threads: [OrchestrationThread]
|
||||
public let updatedAt: String
|
||||
}
|
||||
|
||||
@@ -472,6 +507,9 @@ public enum ShellStreamItem: Decodable, Sendable {
|
||||
case projectRemoved(sequence: Int, projectID: String)
|
||||
case threadUpserted(sequence: Int, thread: OrchestrationThreadShell)
|
||||
case threadRemoved(sequence: Int, threadID: String)
|
||||
/// A newer server emitted a delta this build cannot reduce. The live client
|
||||
/// should fetch an authoritative shell snapshot and keep the stream alive.
|
||||
case refreshRequired
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case kind, sequence, snapshot, project, projectId, thread, threadId
|
||||
@@ -484,33 +522,62 @@ public enum ShellStreamItem: Decodable, Sendable {
|
||||
case "synchronized":
|
||||
self = .synchronized
|
||||
case "snapshot":
|
||||
self = .snapshot(try container.decode(OrchestrationShellSnapshot.self, forKey: .snapshot))
|
||||
guard let snapshot = try? container.decode(
|
||||
OrchestrationShellSnapshot.self,
|
||||
forKey: .snapshot
|
||||
) else {
|
||||
self = .refreshRequired
|
||||
return
|
||||
}
|
||||
self = .snapshot(snapshot)
|
||||
case "project-upserted":
|
||||
guard let sequence = try? container.decode(Int.self, forKey: .sequence),
|
||||
let project = try? container.decode(
|
||||
OrchestrationProject.self,
|
||||
forKey: .project
|
||||
) else {
|
||||
self = .refreshRequired
|
||||
return
|
||||
}
|
||||
self = .projectUpserted(
|
||||
sequence: try container.decode(Int.self, forKey: .sequence),
|
||||
project: try container.decode(OrchestrationProject.self, forKey: .project)
|
||||
sequence: sequence,
|
||||
project: project
|
||||
)
|
||||
case "project-removed":
|
||||
guard let sequence = try? container.decode(Int.self, forKey: .sequence),
|
||||
let projectID = try? container.decode(String.self, forKey: .projectId) else {
|
||||
self = .refreshRequired
|
||||
return
|
||||
}
|
||||
self = .projectRemoved(
|
||||
sequence: try container.decode(Int.self, forKey: .sequence),
|
||||
projectID: try container.decode(String.self, forKey: .projectId)
|
||||
sequence: sequence,
|
||||
projectID: projectID
|
||||
)
|
||||
case "thread-upserted":
|
||||
guard let sequence = try? container.decode(Int.self, forKey: .sequence),
|
||||
let thread = try? container.decode(
|
||||
OrchestrationThreadShell.self,
|
||||
forKey: .thread
|
||||
) else {
|
||||
self = .refreshRequired
|
||||
return
|
||||
}
|
||||
self = .threadUpserted(
|
||||
sequence: try container.decode(Int.self, forKey: .sequence),
|
||||
thread: try container.decode(OrchestrationThreadShell.self, forKey: .thread)
|
||||
sequence: sequence,
|
||||
thread: thread
|
||||
)
|
||||
case "thread-removed":
|
||||
guard let sequence = try? container.decode(Int.self, forKey: .sequence),
|
||||
let threadID = try? container.decode(String.self, forKey: .threadId) else {
|
||||
self = .refreshRequired
|
||||
return
|
||||
}
|
||||
self = .threadRemoved(
|
||||
sequence: try container.decode(Int.self, forKey: .sequence),
|
||||
threadID: try container.decode(String.self, forKey: .threadId)
|
||||
sequence: sequence,
|
||||
threadID: threadID
|
||||
)
|
||||
default:
|
||||
throw DecodingError.dataCorruptedError(
|
||||
forKey: .kind,
|
||||
in: container,
|
||||
debugDescription: "Unknown shell stream item \(kind)"
|
||||
)
|
||||
self = .refreshRequired
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -529,17 +596,21 @@ public enum ThreadStreamItem: Decodable, Sendable {
|
||||
case "synchronized":
|
||||
self = .synchronized
|
||||
case "snapshot":
|
||||
self = .snapshot(
|
||||
try container.decode(OrchestrationThreadDetailSnapshot.self, forKey: .snapshot)
|
||||
)
|
||||
guard let snapshot = try? container.decode(
|
||||
OrchestrationThreadDetailSnapshot.self,
|
||||
forKey: .snapshot
|
||||
) else {
|
||||
self = .event(.null)
|
||||
return
|
||||
}
|
||||
self = .snapshot(snapshot)
|
||||
case "event":
|
||||
self = .event(try container.decode(JSONValue.self, forKey: .event))
|
||||
self = .event((try? container.decode(JSONValue.self, forKey: .event)) ?? .null)
|
||||
default:
|
||||
throw DecodingError.dataCorruptedError(
|
||||
forKey: .kind,
|
||||
in: container,
|
||||
debugDescription: "Unknown thread stream item \(kind)"
|
||||
)
|
||||
// The detail reducer already treats an unrecognized event as an
|
||||
// authoritative-refresh request. Reuse that path without adding a
|
||||
// second stream state or terminating the subscription.
|
||||
self = .event(.null)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
public protocol WebSocketConnection: Sendable {
|
||||
func send(_ data: Data) async throws
|
||||
@@ -152,6 +153,11 @@ private struct RPCResponseEnvelope: Decodable, Sendable {
|
||||
public actor WebSocketRPCClient {
|
||||
public typealias EndpointProvider = @Sendable () async throws -> URL
|
||||
|
||||
private static let logger = Logger(
|
||||
subsystem: "com.t3tools.t3code",
|
||||
category: "WebSocketRPC"
|
||||
)
|
||||
|
||||
private struct UnaryRequest {
|
||||
let envelope: RPCRequestEnvelope
|
||||
var sent: Bool
|
||||
@@ -230,12 +236,18 @@ public actor WebSocketRPCClient {
|
||||
guard let value else { return false }
|
||||
return await value.sendKeepalive(expectedConnectionID: connectionID)
|
||||
}
|
||||
|
||||
func reconnectDelay(failureCount: Int, loopID: UUID) async -> Duration? {
|
||||
guard let value else { return nil }
|
||||
return await value.reconnectDelay(failureCount: failureCount, loopID: loopID)
|
||||
}
|
||||
}
|
||||
|
||||
private let connector: any WebSocketConnecting
|
||||
private let endpointProvider: EndpointProvider
|
||||
private let connectionWaitTimeout: Duration
|
||||
private let responseTimeout: Duration
|
||||
private let reconnectBackoff: @Sendable (Int) -> Duration
|
||||
private var connection: (any WebSocketConnection)?
|
||||
private var connectionID: UUID?
|
||||
private var loopTask: Task<Void, Never>?
|
||||
@@ -251,11 +263,18 @@ public actor WebSocketRPCClient {
|
||||
connector: any WebSocketConnecting = URLSessionWebSocketConnector(),
|
||||
connectionWaitTimeout: Duration = .seconds(4),
|
||||
responseTimeout: Duration = .seconds(30),
|
||||
reconnectBackoff: @escaping @Sendable (Int) -> Duration = { failureCount in
|
||||
// Jitter desynchronizes reconnects across environments so a
|
||||
// server restart doesn't trigger simultaneous ticket mints.
|
||||
let backoff = min(5.0, 0.35 * pow(1.7, Double(failureCount - 1)))
|
||||
return .seconds(backoff * Double.random(in: 0.5...1.0))
|
||||
},
|
||||
endpointProvider: @escaping EndpointProvider
|
||||
) {
|
||||
self.connector = connector
|
||||
self.connectionWaitTimeout = connectionWaitTimeout
|
||||
self.responseTimeout = responseTimeout
|
||||
self.reconnectBackoff = reconnectBackoff
|
||||
self.endpointProvider = endpointProvider
|
||||
}
|
||||
|
||||
@@ -411,7 +430,7 @@ public actor WebSocketRPCClient {
|
||||
throw RPCError.disconnected
|
||||
}
|
||||
openedID = id
|
||||
retry = 0
|
||||
logger.info("WebSocket connection installed")
|
||||
try await withTaskCancellationHandler {
|
||||
while await owner.ownsConnection(loopID: loopID, connectionID: id),
|
||||
!Task.isCancelled {
|
||||
@@ -419,6 +438,10 @@ public actor WebSocketRPCClient {
|
||||
guard try await owner.handle(data, connectionID: id) else {
|
||||
throw RPCError.disconnected
|
||||
}
|
||||
// URLSession's `resume()` does not expose a completed
|
||||
// WebSocket handshake. A valid inbound frame is the
|
||||
// first proof that the connection is actually usable.
|
||||
retry = 0
|
||||
}
|
||||
} onCancel: {
|
||||
Task { await opened.close() }
|
||||
@@ -428,6 +451,9 @@ public actor WebSocketRPCClient {
|
||||
}
|
||||
guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
|
||||
} catch {
|
||||
logger.warning(
|
||||
"WebSocket connection failed: \(String(describing: error), privacy: .private)"
|
||||
)
|
||||
if let openedID {
|
||||
if !(await owner.disconnected(connectionID: openedID)) {
|
||||
await openedConnection?.close()
|
||||
@@ -437,11 +463,11 @@ public actor WebSocketRPCClient {
|
||||
}
|
||||
guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
|
||||
retry += 1
|
||||
// Jitter desynchronizes reconnects across environments so a
|
||||
// server restart doesn't trigger simultaneous ticket mints.
|
||||
let backoff = min(5.0, 0.35 * pow(1.7, Double(retry - 1)))
|
||||
let delay = backoff * Double.random(in: 0.5...1.0)
|
||||
try? await Task.sleep(for: .seconds(delay))
|
||||
guard let delay = await owner.reconnectDelay(
|
||||
failureCount: retry,
|
||||
loopID: loopID
|
||||
) else { break }
|
||||
try? await Task.sleep(for: delay)
|
||||
}
|
||||
}
|
||||
await owner.finishConnectionLoop(loopID)
|
||||
@@ -452,6 +478,11 @@ public actor WebSocketRPCClient {
|
||||
return ConnectionAttempt(connector: connector, endpointProvider: endpointProvider)
|
||||
}
|
||||
|
||||
private func reconnectDelay(failureCount: Int, loopID: UUID) -> Duration? {
|
||||
guard isCurrentConnectionLoop(loopID) else { return nil }
|
||||
return reconnectBackoff(failureCount)
|
||||
}
|
||||
|
||||
private func installConnection(
|
||||
_ opened: any WebSocketConnection,
|
||||
loopID: UUID
|
||||
@@ -510,6 +541,7 @@ public actor WebSocketRPCClient {
|
||||
keepaliveTask = nil
|
||||
connection = nil
|
||||
connectionID = nil
|
||||
Self.logger.info("WebSocket connection closed")
|
||||
failUnary(RPCError.disconnected, includingUnsent: false)
|
||||
subscriptionByRequestID.removeAll()
|
||||
let oneShotSubscriptions = subscriptions.filter { !$0.value.reconnect }
|
||||
@@ -591,7 +623,8 @@ public actor WebSocketRPCClient {
|
||||
private func sendSubscription(_ subscriptionID: UUID) async {
|
||||
guard let connection,
|
||||
let connectionID,
|
||||
var subscription = subscriptions[subscriptionID] else { return }
|
||||
var subscription = subscriptions[subscriptionID],
|
||||
subscription.requestID == nil else { return }
|
||||
let requestID = allocateRequestID()
|
||||
let envelope = RPCRequestEnvelope(
|
||||
id: requestID,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import ImageIO
|
||||
import PhotosUI
|
||||
import OSLog
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import UIKit
|
||||
@@ -96,6 +97,10 @@ struct FeatureImageAttachmentPicker: View {
|
||||
isPhotoLibraryPresented = false
|
||||
loadPhotoSelections(images)
|
||||
},
|
||||
onFailure: { message in
|
||||
isPhotoLibraryPresented = false
|
||||
errorMessage = message
|
||||
},
|
||||
onCancel: { isPhotoLibraryPresented = false }
|
||||
)
|
||||
.ignoresSafeArea()
|
||||
@@ -273,10 +278,11 @@ struct FeaturePhotoLibraryItem: @unchecked Sendable {
|
||||
private struct FeaturePhotoLibraryPicker: UIViewControllerRepresentable {
|
||||
let maximumCount: Int
|
||||
let onSelect: ([Data]) -> Void
|
||||
let onFailure: (String) -> Void
|
||||
let onCancel: () -> Void
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator(onSelect: onSelect, onCancel: onCancel)
|
||||
Coordinator(onSelect: onSelect, onFailure: onFailure, onCancel: onCancel)
|
||||
}
|
||||
|
||||
func makeUIViewController(context: Context) -> PHPickerViewController {
|
||||
@@ -295,14 +301,17 @@ private struct FeaturePhotoLibraryPicker: UIViewControllerRepresentable {
|
||||
|
||||
final class Coordinator: NSObject, PHPickerViewControllerDelegate {
|
||||
private let onSelect: ([Data]) -> Void
|
||||
private let onFailure: (String) -> Void
|
||||
private let onCancel: () -> Void
|
||||
private var didFinish = false
|
||||
|
||||
init(
|
||||
onSelect: @escaping ([Data]) -> Void,
|
||||
onFailure: @escaping (String) -> Void,
|
||||
onCancel: @escaping () -> Void
|
||||
) {
|
||||
self.onSelect = onSelect
|
||||
self.onFailure = onFailure
|
||||
self.onCancel = onCancel
|
||||
}
|
||||
|
||||
@@ -334,14 +343,30 @@ private struct FeaturePhotoLibraryPicker: UIViewControllerRepresentable {
|
||||
let items = results.map { FeaturePhotoLibraryItem(provider: $0.itemProvider) }
|
||||
Task { @MainActor in
|
||||
var images: [Data] = []
|
||||
var firstError: Error?
|
||||
for item in items {
|
||||
if let data = try? await item.loadData() {
|
||||
do {
|
||||
let data = try await item.loadData()
|
||||
images.append(data)
|
||||
} catch {
|
||||
firstError = firstError ?? error
|
||||
Self.logger.error(
|
||||
"Photo selection materialization failed: \(error.localizedDescription, privacy: .private)"
|
||||
)
|
||||
}
|
||||
}
|
||||
onSelect(images)
|
||||
if images.isEmpty, let firstError {
|
||||
onFailure(firstError.localizedDescription)
|
||||
} else {
|
||||
onSelect(images)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static let logger = Logger(
|
||||
subsystem: Bundle.main.bundleIdentifier ?? "codes.t3.swift-ios",
|
||||
category: "Attachments"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ public struct T3ConnectView: View {
|
||||
@State private var didFinishInitialRefresh = false
|
||||
private let connectEnvironment:
|
||||
@MainActor (T3ConnectManagedEnvironmentCredential) async throws -> Void
|
||||
private let signOut: @MainActor () async -> Void
|
||||
private let onConnected: @MainActor () async -> Void
|
||||
|
||||
public init(
|
||||
@@ -17,6 +18,7 @@ public struct T3ConnectView: View {
|
||||
) {
|
||||
controller = capability.t3ConnectController
|
||||
connectEnvironment = capability.connectT3Environment
|
||||
signOut = capability.signOutT3Connect
|
||||
self.onConnected = onConnected
|
||||
}
|
||||
|
||||
@@ -28,7 +30,7 @@ public struct T3ConnectView: View {
|
||||
if controller.account != nil {
|
||||
ToolbarItem(placement: .topBarTrailing) {
|
||||
Button("Sign out", role: .destructive) {
|
||||
Task { await controller.signOut() }
|
||||
Task { await signOut() }
|
||||
}
|
||||
.disabled(controller.isRefreshing)
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ struct FeatureDetailRenderUpdate: Equatable {
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class FeatureRootModel {
|
||||
private static let maximumRetainedThreadDetails = 6
|
||||
|
||||
public private(set) var snapshot = FeatureSnapshot()
|
||||
public private(set) var details: [String: FeatureThreadDetail] = [:]
|
||||
/// Advances whenever a Home presentation input changes.
|
||||
@@ -37,6 +39,7 @@ public final class FeatureRootModel {
|
||||
private var pendingThreadsByID: [String: FeatureThread] = [:]
|
||||
private var pendingCompletionSubmissionIDs: Set<String> = []
|
||||
private var pendingDiscardSubmissionIDs: Set<String> = []
|
||||
private var detailRecency: [String] = []
|
||||
private var outboxDrainTask: Task<Void, Never>?
|
||||
private var outboxRetryAttempt = 0
|
||||
private var outboxGeneration: UInt64 = 0
|
||||
@@ -76,6 +79,20 @@ public final class FeatureRootModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Background refresh is deliberately separate from `reload()`: native
|
||||
/// clients must not mount WebSocket streams or timers for a bounded BG task.
|
||||
public func refreshInBackground() async -> Bool {
|
||||
do {
|
||||
install(try await client.backgroundSnapshot())
|
||||
return !Task.isCancelled
|
||||
} catch {
|
||||
if !Self.isBenignCancellation(error) {
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func reloadAfterConnection() async {
|
||||
clearDetails()
|
||||
await reload()
|
||||
@@ -383,6 +400,8 @@ public final class FeatureRootModel {
|
||||
/// Ends any selected-thread transport work when its detail view closes.
|
||||
public func releaseThread(_ id: String) {
|
||||
client.releaseThread(id: id)
|
||||
markDetailRecentlyUsed(id)
|
||||
evictOldThreadDetailsIfNeeded()
|
||||
}
|
||||
|
||||
public func sendMessage(threadID: String, text: String, selection: FeatureSelection?) async -> Bool {
|
||||
@@ -703,6 +722,7 @@ public final class FeatureRootModel {
|
||||
} ?? prepared
|
||||
guard details[id] != next else { return }
|
||||
details[id] = next
|
||||
markDetailRecentlyUsed(id)
|
||||
bumpDetailRevision(id: id, change: .full)
|
||||
}
|
||||
|
||||
@@ -712,6 +732,7 @@ public final class FeatureRootModel {
|
||||
acknowledgeDeliveredMessages(incoming.messages)
|
||||
let next = addingPendingMessages(to: incoming)
|
||||
details[id] = next
|
||||
markDetailRecentlyUsed(id)
|
||||
let appended = next.messages.dropFirst(incoming.messages.count).map(\.id)
|
||||
let pendingDelta = FeatureDetailDelta(
|
||||
changedMessages: delta.changedMessages + next.messages.dropFirst(incoming.messages.count),
|
||||
@@ -730,22 +751,39 @@ public final class FeatureRootModel {
|
||||
mutation(&detail)
|
||||
guard detail != previous else { return }
|
||||
details[id] = detail
|
||||
markDetailRecentlyUsed(id)
|
||||
bumpDetailRevision(id: id, change: change)
|
||||
}
|
||||
|
||||
private func removeDetail(id: String) {
|
||||
guard details.removeValue(forKey: id) != nil else { return }
|
||||
detailRecency.removeAll { $0 == id }
|
||||
bumpDetailRevision(id: id, change: .full)
|
||||
}
|
||||
|
||||
private func clearDetails() {
|
||||
guard !details.isEmpty else { return }
|
||||
details.removeAll()
|
||||
detailRecency.removeAll()
|
||||
detailRevision &+= 1
|
||||
detailRevisions.removeAll()
|
||||
detailRenderUpdates.removeAll()
|
||||
}
|
||||
|
||||
private func markDetailRecentlyUsed(_ id: String) {
|
||||
detailRecency.removeAll { $0 == id }
|
||||
detailRecency.append(id)
|
||||
}
|
||||
|
||||
private func evictOldThreadDetailsIfNeeded() {
|
||||
let protected = Set(pendingSubmissionsByID.values.map(\.threadID))
|
||||
while details.count > Self.maximumRetainedThreadDetails,
|
||||
let candidate = detailRecency.first(where: { !protected.contains($0) }) {
|
||||
detailRecency.removeAll { $0 == candidate }
|
||||
removeDetail(id: candidate)
|
||||
}
|
||||
}
|
||||
|
||||
private func bumpDetailRevision(id: String, change: FeatureDetailRenderChange) {
|
||||
let baseRevision = detailRevisions[id] ?? 0
|
||||
detailRevision &+= 1
|
||||
|
||||
@@ -5,6 +5,9 @@ import Foundation
|
||||
@MainActor
|
||||
public protocol FeatureClient: AnyObject {
|
||||
func initialSnapshot() async throws -> FeatureSnapshot
|
||||
/// Performs one bounded refresh without starting long-lived subscriptions.
|
||||
/// Background tasks use this instead of the foreground bootstrap path.
|
||||
func backgroundSnapshot() async throws -> FeatureSnapshot
|
||||
func events() -> AsyncStream<FeatureEvent>
|
||||
|
||||
func pair(endpoint: String, token: String?) async throws
|
||||
@@ -124,6 +127,10 @@ public protocol FeatureClient: AnyObject {
|
||||
}
|
||||
|
||||
public extension FeatureClient {
|
||||
func backgroundSnapshot() async throws -> FeatureSnapshot {
|
||||
try await initialSnapshot()
|
||||
}
|
||||
|
||||
func loadEarlierThreadTurns(id _: String) async throws -> FeatureThreadDetail? {
|
||||
nil
|
||||
}
|
||||
|
||||
@@ -145,7 +145,10 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
public var snoozedUntil: Date?
|
||||
public var snoozedAt: Date?
|
||||
public var pinnedAt: Date?
|
||||
public var supportsSettlement: Bool?
|
||||
public var supportsSnooze: Bool?
|
||||
public var supportsPinning: Bool?
|
||||
public var supportsTitleRegeneration: Bool?
|
||||
public var attentionAt: Date?
|
||||
public var workingStartedAt: Date?
|
||||
public var latestTurnCompletedAt: Date?
|
||||
@@ -177,7 +180,10 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
snoozedUntil: Date? = nil,
|
||||
snoozedAt: Date? = nil,
|
||||
pinnedAt: Date? = nil,
|
||||
supportsSettlement: Bool? = nil,
|
||||
supportsSnooze: Bool? = nil,
|
||||
supportsPinning: Bool? = nil,
|
||||
supportsTitleRegeneration: Bool? = nil,
|
||||
attentionAt: Date? = nil,
|
||||
workingStartedAt: Date? = nil,
|
||||
latestTurnCompletedAt: Date? = nil,
|
||||
@@ -208,7 +214,10 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
self.snoozedUntil = snoozedUntil
|
||||
self.snoozedAt = snoozedAt
|
||||
self.pinnedAt = pinnedAt
|
||||
self.supportsSettlement = supportsSettlement
|
||||
self.supportsSnooze = supportsSnooze
|
||||
self.supportsPinning = supportsPinning
|
||||
self.supportsTitleRegeneration = supportsTitleRegeneration
|
||||
self.attentionAt = attentionAt
|
||||
self.workingStartedAt = workingStartedAt
|
||||
self.latestTurnCompletedAt = latestTurnCompletedAt
|
||||
@@ -221,6 +230,14 @@ public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codabl
|
||||
public var canTogglePin: Bool {
|
||||
pinnedAt != nil || supportsPinning != false
|
||||
}
|
||||
|
||||
public var canToggleSettlement: Bool {
|
||||
isSettled || supportsSettlement != false
|
||||
}
|
||||
|
||||
public var canToggleSnooze: Bool {
|
||||
snoozedUntil != nil || supportsSnooze != false
|
||||
}
|
||||
}
|
||||
|
||||
public enum FeatureMessageRole: String, Sendable, Codable {
|
||||
|
||||
@@ -215,7 +215,7 @@ struct HomeThreadCollectionView: UIViewRepresentable {
|
||||
}
|
||||
primaryAction.image = UIImage(systemName: "pin.slash")
|
||||
primaryAction.backgroundColor = .systemBlue
|
||||
} else {
|
||||
} else if thread.canToggleSettlement {
|
||||
let isSettled = thread.isEffectivelySettled(at: .now)
|
||||
primaryAction = UIContextualAction(
|
||||
style: .normal,
|
||||
@@ -228,6 +228,14 @@ struct HomeThreadCollectionView: UIViewRepresentable {
|
||||
systemName: isSettled ? "arrow.counterclockwise" : "checkmark"
|
||||
)
|
||||
primaryAction.backgroundColor = isSettled ? .systemBlue : .systemGreen
|
||||
} else {
|
||||
primaryAction = UIContextualAction(style: .normal, title: "Archive") {
|
||||
[weak self] _, _, finish in
|
||||
self?.parent.onArchive(thread, true)
|
||||
finish(true)
|
||||
}
|
||||
primaryAction.image = UIImage(systemName: "archivebox")
|
||||
primaryAction.backgroundColor = .systemGray
|
||||
}
|
||||
|
||||
let configuration = UISwipeActionsConfiguration(actions: [delete, primaryAction])
|
||||
@@ -393,32 +401,38 @@ struct HomeThreadCollectionView: UIViewRepresentable {
|
||||
}
|
||||
)
|
||||
}
|
||||
let isSettled = thread.isEffectivelySettled(at: .now)
|
||||
actions.append(
|
||||
UIAction(
|
||||
title: isSettled ? "Reopen" : "Settle",
|
||||
image: UIImage(systemName: isSettled ? "arrow.counterclockwise" : "checkmark")
|
||||
) { [weak self] _ in
|
||||
self?.parent.onSettle(thread, !isSettled)
|
||||
}
|
||||
)
|
||||
|
||||
let isSnoozed = thread.isEffectivelySnoozed(at: .now)
|
||||
let snooze = UIAction(
|
||||
title: isSnoozed ? "Unsnooze" : "Snooze 1 hour",
|
||||
image: UIImage(systemName: isSnoozed ? "bell" : "clock")
|
||||
) { [weak self] _ in
|
||||
self?.parent.onSnooze(
|
||||
thread,
|
||||
isSnoozed ? nil : Date.now.addingTimeInterval(60 * 60)
|
||||
if thread.canToggleSettlement {
|
||||
let isSettled = thread.isEffectivelySettled(at: .now)
|
||||
actions.append(
|
||||
UIAction(
|
||||
title: isSettled ? "Reopen" : "Settle",
|
||||
image: UIImage(
|
||||
systemName: isSettled ? "arrow.counterclockwise" : "checkmark"
|
||||
)
|
||||
) { [weak self] _ in
|
||||
self?.parent.onSettle(thread, !isSettled)
|
||||
}
|
||||
)
|
||||
}
|
||||
if thread.state == .queued
|
||||
|| thread.state == .waitingForApproval
|
||||
|| thread.state == .waitingForInput {
|
||||
snooze.attributes = .disabled
|
||||
|
||||
if thread.canToggleSnooze {
|
||||
let isSnoozed = thread.isEffectivelySnoozed(at: .now)
|
||||
let snooze = UIAction(
|
||||
title: isSnoozed ? "Unsnooze" : "Snooze 1 hour",
|
||||
image: UIImage(systemName: isSnoozed ? "bell" : "clock")
|
||||
) { [weak self] _ in
|
||||
self?.parent.onSnooze(
|
||||
thread,
|
||||
isSnoozed ? nil : Date.now.addingTimeInterval(60 * 60)
|
||||
)
|
||||
}
|
||||
if thread.state == .queued
|
||||
|| thread.state == .waitingForApproval
|
||||
|| thread.state == .waitingForInput {
|
||||
snooze.attributes = .disabled
|
||||
}
|
||||
actions.append(snooze)
|
||||
}
|
||||
actions.append(snooze)
|
||||
}
|
||||
|
||||
actions.append(
|
||||
|
||||
@@ -7,6 +7,7 @@ public struct ProviderModelPicker: View {
|
||||
}
|
||||
|
||||
let providers: [FeatureProvider]
|
||||
private let normalizedProviders: [FeatureProvider]
|
||||
@Binding var selection: FeatureSelection?
|
||||
let style: Style
|
||||
let isLoading: Bool
|
||||
@@ -24,6 +25,7 @@ public struct ProviderModelPicker: View {
|
||||
materializesDefaultSelection: Bool = true
|
||||
) {
|
||||
self.providers = providers
|
||||
normalizedProviders = ProviderModelCatalogNormalizer.normalized(providers)
|
||||
_selection = selection
|
||||
self.style = style
|
||||
self.isLoading = isLoading
|
||||
@@ -122,10 +124,6 @@ public struct ProviderModelPicker: View {
|
||||
selection = resolved
|
||||
}
|
||||
|
||||
private var normalizedProviders: [FeatureProvider] {
|
||||
ProviderModelCatalogNormalizer.normalized(providers)
|
||||
}
|
||||
|
||||
private var selectionLabel: String {
|
||||
guard let selectedOption else {
|
||||
return "Choose model"
|
||||
@@ -179,6 +177,7 @@ private struct ModelPickerSheet: View {
|
||||
@State private var query = ""
|
||||
@State private var configuring: DailyUXModelOption?
|
||||
@State private var legacyModelsExpanded = false
|
||||
@State private var catalogCache = ModelPickerCatalogCache()
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
@@ -230,7 +229,9 @@ private struct ModelPickerSheet: View {
|
||||
}
|
||||
|
||||
private var modelList: some View {
|
||||
List {
|
||||
let catalog = cachedCatalog
|
||||
let sections = ProviderModelDisplaySections(catalog: catalog)
|
||||
return List {
|
||||
if modelChangesAreLocked {
|
||||
Section {
|
||||
Label(
|
||||
@@ -242,23 +243,23 @@ private struct ModelPickerSheet: View {
|
||||
}
|
||||
}
|
||||
|
||||
if !displaySections.favorites.isEmpty {
|
||||
if !sections.favorites.isEmpty {
|
||||
Section("Favorites") {
|
||||
ForEach(displaySections.favorites) { option in
|
||||
ForEach(sections.favorites) { option in
|
||||
modelRow(option)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !displaySections.recents.isEmpty {
|
||||
if !sections.recents.isEmpty {
|
||||
Section("Recent") {
|
||||
ForEach(displaySections.recents) { option in
|
||||
ForEach(sections.recents) { option in
|
||||
modelRow(option)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ForEach(displaySections.currentProviderGroups, id: \.provider.id) { group in
|
||||
ForEach(sections.currentProviderGroups, id: \.provider.id) { group in
|
||||
Section(group.provider.name) {
|
||||
ForEach(group.models) { option in
|
||||
modelRow(option)
|
||||
@@ -266,10 +267,10 @@ private struct ModelPickerSheet: View {
|
||||
}
|
||||
}
|
||||
|
||||
if !displaySections.legacy.isEmpty {
|
||||
if !sections.legacy.isEmpty {
|
||||
Section {
|
||||
DisclosureGroup(isExpanded: $legacyModelsExpanded) {
|
||||
ForEach(displaySections.legacy) { option in
|
||||
ForEach(sections.legacy) { option in
|
||||
modelRow(option)
|
||||
}
|
||||
} label: {
|
||||
@@ -277,7 +278,7 @@ private struct ModelPickerSheet: View {
|
||||
Text("Legacy models")
|
||||
.font(T3Typography.control.weight(.semibold))
|
||||
Spacer()
|
||||
Text("\(displaySections.legacy.count)")
|
||||
Text("\(sections.legacy.count)")
|
||||
.font(T3Typography.supporting.monospacedDigit())
|
||||
.foregroundStyle(T3Colors.textTertiary)
|
||||
}
|
||||
@@ -352,17 +353,17 @@ private struct ModelPickerSheet: View {
|
||||
recentStorage.split(separator: "\n").map(String.init)
|
||||
}
|
||||
|
||||
private var catalog: DailyUXModelCatalog {
|
||||
DailyUXModelCatalog(
|
||||
private var cachedCatalog: DailyUXModelCatalog {
|
||||
catalogCache.catalog(
|
||||
providers: providers,
|
||||
query: query,
|
||||
favoriteIDs: favoriteIDs,
|
||||
recentIDs: recentIDs
|
||||
favoriteStorage: favoriteStorage,
|
||||
recentStorage: recentStorage
|
||||
)
|
||||
}
|
||||
|
||||
private var displaySections: ProviderModelDisplaySections {
|
||||
ProviderModelDisplaySections(catalog: catalog)
|
||||
ProviderModelDisplaySections(catalog: cachedCatalog)
|
||||
}
|
||||
|
||||
private var resolvedSelection: FeatureSelection? {
|
||||
@@ -428,6 +429,47 @@ private struct ModelPickerSheet: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// SwiftUI computed properties are ordinary function calls. The picker reads
|
||||
/// its catalog throughout one body evaluation and invalidates on every search
|
||||
/// keystroke, so retain the last derivation by its real inputs.
|
||||
@MainActor
|
||||
private final class ModelPickerCatalogCache {
|
||||
private struct Key: Equatable {
|
||||
let providers: [FeatureProvider]
|
||||
let query: String
|
||||
let favoriteStorage: String
|
||||
let recentStorage: String
|
||||
}
|
||||
|
||||
private var key: Key?
|
||||
private var value: DailyUXModelCatalog?
|
||||
|
||||
func catalog(
|
||||
providers: [FeatureProvider],
|
||||
query: String,
|
||||
favoriteStorage: String,
|
||||
recentStorage: String
|
||||
) -> DailyUXModelCatalog {
|
||||
let key = Key(
|
||||
providers: providers,
|
||||
query: query,
|
||||
favoriteStorage: favoriteStorage,
|
||||
recentStorage: recentStorage
|
||||
)
|
||||
if self.key == key, let value { return value }
|
||||
|
||||
let value = DailyUXModelCatalog(
|
||||
providers: providers,
|
||||
query: query,
|
||||
favoriteIDs: Set(favoriteStorage.split(separator: "\n").map(String.init)),
|
||||
recentIDs: recentStorage.split(separator: "\n").map(String.init)
|
||||
)
|
||||
self.key = key
|
||||
self.value = value
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker never represents an implicit "automatic" model. A missing or stale
|
||||
/// selection becomes the environment's concrete preferred model as soon as the
|
||||
/// catalog is available.
|
||||
|
||||
@@ -103,6 +103,17 @@ chooses an available iPhone from the newest installed Simulator runtime:
|
||||
Set `T3_SWIFT_SIMULATOR_ID` to pin a specific simulator. CI can invoke this same
|
||||
entry point without duplicating the simulator-selection or signing policy.
|
||||
|
||||
Contract fixtures are encoded from the TypeScript schemas and decoded by the
|
||||
Swift test target. Regenerate and verify them after a relevant wire change:
|
||||
|
||||
```sh
|
||||
node scripts/generate-swift-wire-fixtures.ts
|
||||
node scripts/generate-swift-wire-fixtures.ts --check
|
||||
```
|
||||
|
||||
Pull requests that change `apps/swift-ios`, `packages/contracts`, or the fixture
|
||||
generator run both checks in the path-gated SwiftUI workflow.
|
||||
|
||||
## Install on a physical device
|
||||
|
||||
Enable Developer Mode on the device, connect and trust the Mac, then find its
|
||||
|
||||
@@ -19,6 +19,21 @@
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
<key>NSExceptionDomains</key>
|
||||
<dict>
|
||||
<key>ts.net</key>
|
||||
<dict>
|
||||
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
||||
<true/>
|
||||
<key>NSIncludesSubdomains</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>T3ConnectClerkJWTTemplate</key>
|
||||
<string>$(T3CODE_CLERK_JWT_TEMPLATE)</string>
|
||||
<key>T3ConnectClerkPublishableKey</key>
|
||||
|
||||
@@ -551,6 +551,7 @@
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_STRICT_CONCURRENCY = complete;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -604,6 +605,7 @@
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_STRICT_CONCURRENCY = complete;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -622,7 +624,6 @@
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Swift Dev";
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||
INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES;
|
||||
INFOPLIST_KEY_NSCameraUsageDescription = "Scan pairing QR codes and attach photos to T3 Code tasks.";
|
||||
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Allow T3 Code to connect to T3 Code servers on your local network or tailnet.";
|
||||
INFOPLIST_KEY_NSSupportsLiveActivities = YES;
|
||||
@@ -679,7 +680,6 @@
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "T3 Code SwiftUI";
|
||||
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||
INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES;
|
||||
INFOPLIST_KEY_NSCameraUsageDescription = "Scan pairing QR codes and attach photos to T3 Code tasks.";
|
||||
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Allow T3 Code to connect to T3 Code servers on your local network or tailnet.";
|
||||
INFOPLIST_KEY_NSSupportsLiveActivities = YES;
|
||||
|
||||
@@ -338,6 +338,222 @@ final class WebSocketRPCRaceTests: XCTestCase {
|
||||
await connection.releaseRequest()
|
||||
await client.stop()
|
||||
}
|
||||
|
||||
func testConnectionSetupAndSubscribeRaceSendsOneWireRequest() async throws {
|
||||
let connection = SetupSubscriptionRaceConnection()
|
||||
let client = WebSocketRPCClient(
|
||||
connector: SequencedConnector(connections: [connection]),
|
||||
endpointProvider: { URL(string: "wss://studio.example/ws")! }
|
||||
)
|
||||
|
||||
let request = Task {
|
||||
try await client.request("server.setupBarrier", as: JSONValue.self)
|
||||
}
|
||||
await connection.waitUntilUnarySendSuspends()
|
||||
|
||||
let stream = await client.subscribe("thread.events", as: JSONValue.self)
|
||||
await connection.waitUntilSubscriptionSendSuspends()
|
||||
await connection.releaseUnarySend()
|
||||
_ = try await request.value
|
||||
|
||||
let subscriptionRequestCount = await connection.subscriptionRequestCount()
|
||||
XCTAssertEqual(
|
||||
subscriptionRequestCount,
|
||||
1,
|
||||
"Connection setup and subscribe() must not both own the same subscription send."
|
||||
)
|
||||
_ = stream
|
||||
await connection.releaseSubscriptionSend()
|
||||
await client.stop()
|
||||
}
|
||||
|
||||
func testReconnectBackoffResetsOnlyAfterValidInboundTraffic() async {
|
||||
let connector = BackoffSequenceConnector()
|
||||
let recorder = BackoffRecorder()
|
||||
let client = WebSocketRPCClient(
|
||||
connector: connector,
|
||||
reconnectBackoff: { failureCount in
|
||||
recorder.record(failureCount)
|
||||
return .zero
|
||||
},
|
||||
endpointProvider: { URL(string: "wss://studio.example/ws")! }
|
||||
)
|
||||
|
||||
await client.start()
|
||||
await connector.waitUntilAttemptCount(4)
|
||||
|
||||
XCTAssertEqual(
|
||||
recorder.values,
|
||||
[1, 2, 1],
|
||||
"Merely opening a socket must not reset backoff; a decoded server frame should."
|
||||
)
|
||||
await client.stop()
|
||||
}
|
||||
}
|
||||
|
||||
private final class BackoffRecorder: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var recorded: [Int] = []
|
||||
|
||||
var values: [Int] {
|
||||
lock.withLock { recorded }
|
||||
}
|
||||
|
||||
func record(_ value: Int) {
|
||||
lock.withLock { recorded.append(value) }
|
||||
}
|
||||
}
|
||||
|
||||
private actor BackoffSequenceConnector: WebSocketConnecting {
|
||||
private let provenConnection = PongThenFailConnection()
|
||||
private let finalConnection = BlockingReceiveConnection()
|
||||
private var attemptCount = 0
|
||||
private var waiters: [(Int, CheckedContinuation<Void, Never>)] = []
|
||||
|
||||
func connect(to _: URL) throws -> any WebSocketConnection {
|
||||
attemptCount += 1
|
||||
let ready = waiters.filter { attemptCount >= $0.0 }
|
||||
waiters.removeAll { attemptCount >= $0.0 }
|
||||
ready.forEach { $0.1.resume() }
|
||||
switch attemptCount {
|
||||
case 1, 2:
|
||||
throw URLError(.cannotConnectToHost)
|
||||
case 3:
|
||||
return provenConnection
|
||||
default:
|
||||
return finalConnection
|
||||
}
|
||||
}
|
||||
|
||||
func waitUntilAttemptCount(_ count: Int) async {
|
||||
guard attemptCount < count else { return }
|
||||
await withCheckedContinuation { continuation in
|
||||
waiters.append((count, continuation))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private actor PongThenFailConnection: WebSocketConnection {
|
||||
private var sentPong = false
|
||||
|
||||
func send(_: Data) {}
|
||||
|
||||
func receive() throws -> Data {
|
||||
guard !sentPong else { throw URLError(.networkConnectionLost) }
|
||||
sentPong = true
|
||||
return try JSONEncoder.t3.encode(JSONValue.object(["_tag": .string("Pong")]))
|
||||
}
|
||||
|
||||
func close() {}
|
||||
}
|
||||
|
||||
private actor BlockingReceiveConnection: WebSocketConnection {
|
||||
private var continuation: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_: Data) {}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
self.continuation = continuation
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
continuation?.resume(throwing: CancellationError())
|
||||
continuation = nil
|
||||
}
|
||||
}
|
||||
|
||||
private actor SetupSubscriptionRaceConnection: WebSocketConnection {
|
||||
private var unaryRequestID: Int?
|
||||
private var unarySendContinuation: CheckedContinuation<Void, Never>?
|
||||
private var unaryWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var subscriptionSends = 0
|
||||
private var subscriptionSendContinuation: CheckedContinuation<Void, Never>?
|
||||
private var subscriptionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var queuedResponses: [Data] = []
|
||||
private var receiver: CheckedContinuation<Data, Error>?
|
||||
|
||||
func send(_ data: Data) async throws {
|
||||
let envelope = try JSONDecoder.t3.decode(JSONValue.self, from: data)
|
||||
guard envelope["_tag"]?.stringValue == "Request",
|
||||
case let .number(rawID)? = envelope["id"],
|
||||
let requestID = Int(exactly: rawID)
|
||||
else { return }
|
||||
|
||||
if envelope["tag"]?.stringValue == "server.setupBarrier" {
|
||||
unaryRequestID = requestID
|
||||
let waiters = unaryWaiters
|
||||
unaryWaiters.removeAll()
|
||||
waiters.forEach { $0.resume() }
|
||||
await withCheckedContinuation { unarySendContinuation = $0 }
|
||||
enqueue(try success(requestID: requestID))
|
||||
} else {
|
||||
subscriptionSends += 1
|
||||
let waiters = subscriptionWaiters
|
||||
subscriptionWaiters.removeAll()
|
||||
waiters.forEach { $0.resume() }
|
||||
await withCheckedContinuation { subscriptionSendContinuation = $0 }
|
||||
}
|
||||
}
|
||||
|
||||
func receive() async throws -> Data {
|
||||
if !queuedResponses.isEmpty { return queuedResponses.removeFirst() }
|
||||
return try await withCheckedThrowingContinuation { receiver = $0 }
|
||||
}
|
||||
|
||||
func close() {
|
||||
unarySendContinuation?.resume()
|
||||
unarySendContinuation = nil
|
||||
subscriptionSendContinuation?.resume()
|
||||
subscriptionSendContinuation = nil
|
||||
receiver?.resume(throwing: CancellationError())
|
||||
receiver = nil
|
||||
}
|
||||
|
||||
func waitUntilUnarySendSuspends() async {
|
||||
guard unaryRequestID == nil else { return }
|
||||
await withCheckedContinuation { unaryWaiters.append($0) }
|
||||
}
|
||||
|
||||
func waitUntilSubscriptionSendSuspends() async {
|
||||
guard subscriptionSends == 0 else { return }
|
||||
await withCheckedContinuation { subscriptionWaiters.append($0) }
|
||||
}
|
||||
|
||||
func releaseUnarySend() {
|
||||
unarySendContinuation?.resume()
|
||||
unarySendContinuation = nil
|
||||
}
|
||||
|
||||
func releaseSubscriptionSend() {
|
||||
subscriptionSendContinuation?.resume()
|
||||
subscriptionSendContinuation = nil
|
||||
}
|
||||
|
||||
func subscriptionRequestCount() -> Int { subscriptionSends }
|
||||
|
||||
private func enqueue(_ data: Data) {
|
||||
if let receiver {
|
||||
self.receiver = nil
|
||||
receiver.resume(returning: data)
|
||||
} else {
|
||||
queuedResponses.append(data)
|
||||
}
|
||||
}
|
||||
|
||||
private func success(requestID: Int) throws -> Data {
|
||||
try JSONEncoder.t3.encode(
|
||||
JSONValue.object([
|
||||
"_tag": .string("Exit"),
|
||||
"requestId": .number(Double(requestID)),
|
||||
"exit": .object([
|
||||
"_tag": .string("Success"),
|
||||
"value": .object([:]),
|
||||
]),
|
||||
])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private actor RequestCancellationGate {
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import T3Code
|
||||
|
||||
final class WireFixtureContractTests: XCTestCase {
|
||||
func testGeneratedContractFixturesDecodeInSwift() throws {
|
||||
let shell = try decodeFixture(
|
||||
"shell-snapshot",
|
||||
as: OrchestrationShellSnapshot.self
|
||||
)
|
||||
XCTAssertEqual(shell.snapshotSequence, 42)
|
||||
XCTAssertEqual(shell.projects.map(\.id), ["project-fixture"])
|
||||
XCTAssertEqual(shell.threads.map(\.id), ["thread-fixture"])
|
||||
XCTAssertEqual(shell.threads.first?.modelSelection.instanceId, "codex")
|
||||
|
||||
let detail = try decodeFixture(
|
||||
"thread-detail-snapshot",
|
||||
as: OrchestrationThreadDetailSnapshot.self
|
||||
)
|
||||
XCTAssertEqual(detail.thread.messages.map(\.id), ["message-fixture"])
|
||||
XCTAssertEqual(detail.page?.beforeCursor, "fixture-cursor")
|
||||
XCTAssertEqual(detail.page?.threadSequence, 40)
|
||||
|
||||
let shellItem = try decodeFixture(
|
||||
"shell-stream-snapshot",
|
||||
as: ShellStreamItem.self
|
||||
)
|
||||
guard case let .snapshot(streamShell) = shellItem else {
|
||||
return XCTFail("Expected a shell snapshot stream item")
|
||||
}
|
||||
XCTAssertEqual(streamShell.snapshotSequence, shell.snapshotSequence)
|
||||
|
||||
let threadItem = try decodeFixture(
|
||||
"thread-stream-snapshot",
|
||||
as: ThreadStreamItem.self
|
||||
)
|
||||
guard case let .snapshot(streamDetail) = threadItem else {
|
||||
return XCTFail("Expected a thread snapshot stream item")
|
||||
}
|
||||
XCTAssertEqual(streamDetail.thread.id, detail.thread.id)
|
||||
}
|
||||
|
||||
func testSnapshotsDropOnlyUnknownArrayElements() throws {
|
||||
let known = try fixtureObject("shell-snapshot")
|
||||
var payload = try XCTUnwrap(known as? [String: Any])
|
||||
payload["projects"] = [
|
||||
["id": "future-project", "kind": "not-yet-supported"],
|
||||
try XCTUnwrap((payload["projects"] as? [Any])?.first),
|
||||
]
|
||||
payload["threads"] = [
|
||||
["id": "future-thread", "runtimeMode": "future-mode"],
|
||||
try XCTUnwrap((payload["threads"] as? [Any])?.first),
|
||||
]
|
||||
|
||||
let snapshot = try JSONDecoder.t3.decode(
|
||||
OrchestrationShellSnapshot.self,
|
||||
from: JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys])
|
||||
)
|
||||
|
||||
XCTAssertEqual(snapshot.projects.map(\.id), ["project-fixture"])
|
||||
XCTAssertEqual(snapshot.threads.map(\.id), ["thread-fixture"])
|
||||
}
|
||||
|
||||
func testUnknownStreamItemsRequestRefreshWithoutEndingDecoding() throws {
|
||||
let shell = try JSONDecoder.t3.decode(
|
||||
ShellStreamItem.self,
|
||||
from: Data(#"{"kind":"future-shell-delta","sequence":43}"#.utf8)
|
||||
)
|
||||
guard case .refreshRequired = shell else {
|
||||
return XCTFail("Expected an authoritative shell refresh")
|
||||
}
|
||||
|
||||
let malformedKnownShell = try JSONDecoder.t3.decode(
|
||||
ShellStreamItem.self,
|
||||
from: Data(#"{"kind":"thread-upserted","sequence":43,"thread":{"id":"future"}}"#.utf8)
|
||||
)
|
||||
guard case .refreshRequired = malformedKnownShell else {
|
||||
return XCTFail("Expected malformed known deltas to refresh")
|
||||
}
|
||||
|
||||
let thread = try JSONDecoder.t3.decode(
|
||||
ThreadStreamItem.self,
|
||||
from: Data(#"{"kind":"future-thread-delta","sequence":43}"#.utf8)
|
||||
)
|
||||
guard case let .event(event) = thread else {
|
||||
return XCTFail("Expected the detail reducer compatibility path")
|
||||
}
|
||||
XCTAssertEqual(event, .null)
|
||||
}
|
||||
|
||||
private func decodeFixture<Value: Decodable>(
|
||||
_ name: String,
|
||||
as type: Value.Type
|
||||
) throws -> Value {
|
||||
try JSONDecoder.t3.decode(type, from: fixtureData(name))
|
||||
}
|
||||
|
||||
private func fixtureObject(_ name: String) throws -> Any {
|
||||
try JSONSerialization.jsonObject(with: fixtureData(name))
|
||||
}
|
||||
|
||||
private func fixtureData(_ name: String) throws -> Data {
|
||||
let testsDirectory = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent()
|
||||
.deletingLastPathComponent()
|
||||
return try Data(
|
||||
contentsOf: testsDirectory
|
||||
.appendingPathComponent("Fixtures/Wire/\(name).json")
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,26 @@ struct DailyUXSidebarTests {
|
||||
#expect(explicitlyUnsupported.canTogglePin)
|
||||
}
|
||||
|
||||
@Test
|
||||
func lifecycleActionsHonorCapabilitiesAndKeepReverseActionsReachable() {
|
||||
var capabilityThread = thread(id: "capabilities", created: -20, updated: -10)
|
||||
capabilityThread.supportsSettlement = false
|
||||
capabilityThread.supportsSnooze = false
|
||||
#expect(!capabilityThread.canToggleSettlement)
|
||||
#expect(!capabilityThread.canToggleSnooze)
|
||||
|
||||
capabilityThread.isSettled = true
|
||||
capabilityThread.snoozedUntil = now.addingTimeInterval(3_600)
|
||||
#expect(capabilityThread.canToggleSettlement)
|
||||
#expect(capabilityThread.canToggleSnooze)
|
||||
|
||||
var legacy = thread(id: "legacy-capabilities", created: -20, updated: -10)
|
||||
legacy.supportsSettlement = nil
|
||||
legacy.supportsSnooze = nil
|
||||
#expect(legacy.canToggleSettlement)
|
||||
#expect(legacy.canToggleSnooze)
|
||||
}
|
||||
|
||||
@Test
|
||||
func snoozedThreadsHaveAReachableReverseState() {
|
||||
var snoozed = thread(id: "snoozed", created: -20, updated: -10)
|
||||
|
||||
@@ -5,6 +5,22 @@ import Testing
|
||||
@MainActor
|
||||
@Suite("Feature root model")
|
||||
struct FeatureRootModelTests {
|
||||
@Test
|
||||
func backgroundRefreshUsesTheBoundedClientPath() async {
|
||||
let client = FeatureClientStub()
|
||||
client.backgroundSnapshotValue = FeatureSnapshot(
|
||||
connection: .init(state: .connected, environmentName: "Remote")
|
||||
)
|
||||
let model = testRootModel(client: client)
|
||||
|
||||
let succeeded = await model.refreshInBackground()
|
||||
|
||||
#expect(succeeded)
|
||||
#expect(client.backgroundSnapshotCallCount == 1)
|
||||
#expect(client.initialSnapshotCallCount == 0)
|
||||
#expect(model.snapshot.connection.environmentName == "Remote")
|
||||
}
|
||||
|
||||
@Test
|
||||
func savedServersKeepWorkspaceNavigationAvailableWhileDisconnected() {
|
||||
let savedEnvironment = FeatureEnvironment(
|
||||
@@ -1158,6 +1174,9 @@ private final class FeatureClientStub: FeatureClient {
|
||||
private let eventStream: AsyncStream<FeatureEvent>
|
||||
private let eventContinuation: AsyncStream<FeatureEvent>.Continuation
|
||||
var snapshot = FeatureSnapshot()
|
||||
var backgroundSnapshotValue: FeatureSnapshot?
|
||||
var initialSnapshotCallCount = 0
|
||||
var backgroundSnapshotCallCount = 0
|
||||
var snapshotAfterPair: FeatureSnapshot?
|
||||
var snapshotAfterEnvironmentRemoval: FeatureSnapshot?
|
||||
var createdThread = FeatureThread(id: "created", projectID: "project", title: "Created")
|
||||
@@ -1204,6 +1223,7 @@ private final class FeatureClientStub: FeatureClient {
|
||||
}
|
||||
|
||||
func initialSnapshot() async throws -> FeatureSnapshot {
|
||||
initialSnapshotCallCount += 1
|
||||
if removedEnvironmentID != nil, let snapshotAfterEnvironmentRemoval {
|
||||
return snapshotAfterEnvironmentRemoval
|
||||
}
|
||||
@@ -1213,6 +1233,11 @@ private final class FeatureClientStub: FeatureClient {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func backgroundSnapshot() async throws -> FeatureSnapshot {
|
||||
backgroundSnapshotCallCount += 1
|
||||
return backgroundSnapshotValue ?? snapshot
|
||||
}
|
||||
|
||||
func pair(endpoint: String, token: String?) async throws {
|
||||
pairEndpoint = endpoint
|
||||
pairToken = token
|
||||
|
||||
@@ -147,6 +147,24 @@ final class NativeMultiEnvironmentTests: XCTestCase {
|
||||
await fixture.client.disconnect()
|
||||
}
|
||||
|
||||
func testBackgroundSnapshotDoesNotStartAggregateRefreshLoops() async throws {
|
||||
let loader = CountingAggregateEnvironmentLoader()
|
||||
let fixture = try await makeFixture(
|
||||
aggregateEnvironmentLoader: { runtime in
|
||||
await loader.recordLoad()
|
||||
return try await runtime.environments()
|
||||
}
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: fixture.directory) }
|
||||
|
||||
let snapshot = try await fixture.client.backgroundSnapshot()
|
||||
|
||||
XCTAssertEqual(snapshot.connection.state, .connected)
|
||||
let aggregateLoadCount = await loader.callCount
|
||||
XCTAssertEqual(aggregateLoadCount, 0)
|
||||
await fixture.client.disconnect()
|
||||
}
|
||||
|
||||
func testAggregateRefreshRetriesTransientEnvironmentLoadFailures() async throws {
|
||||
let retryObserved = expectation(description: "aggregate refresh retried")
|
||||
let loader = FailOnceAggregateEnvironmentLoader(retryObserved: retryObserved)
|
||||
@@ -424,6 +442,14 @@ private actor FailOnceAggregateEnvironmentLoader {
|
||||
}
|
||||
}
|
||||
|
||||
private actor CountingAggregateEnvironmentLoader {
|
||||
private(set) var callCount = 0
|
||||
|
||||
func recordLoad() {
|
||||
callCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
private actor BlockingFirstAggregateEnvironmentLoader {
|
||||
private let firstLoadStarted: XCTestExpectation
|
||||
private let restartedLoadObserved: XCTestExpectation
|
||||
|
||||
@@ -154,6 +154,83 @@ final class T3ConnectNativeCapabilityTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testSignOutRemovesManagedStateWhenClerkFailsAndPreservesManualPairing() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-connect-sign-out-\(UUID().uuidString)")
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let manual = Environment(
|
||||
id: "manual-1",
|
||||
label: "Big O",
|
||||
httpBaseURL: URL(string: "http://100.64.0.1:3773")!,
|
||||
webSocketBaseURL: URL(string: "ws://100.64.0.1:3773/ws")!
|
||||
)
|
||||
let managed = Environment(
|
||||
id: "managed-1",
|
||||
label: "Managed Studio",
|
||||
httpBaseURL: URL(string: "https://managed.example")!,
|
||||
webSocketBaseURL: URL(string: "wss://managed.example")!,
|
||||
kind: .managedDPoP
|
||||
)
|
||||
let store = EnvironmentStore(
|
||||
fileURL: directory.appendingPathComponent("environments.json")
|
||||
)
|
||||
try await store.save([managed, manual])
|
||||
try await store.setActiveEnvironment(id: managed.id)
|
||||
let manualCredential = EnvironmentCredential(accessToken: "manual-secret")
|
||||
let managedCredential = EnvironmentCredential.managedDPoP(
|
||||
accessToken: "managed-secret",
|
||||
expiresAt: Date().addingTimeInterval(300),
|
||||
scopes: T3ConnectManagedEnvironmentAuthorizer.standardScopes,
|
||||
environmentID: managed.id,
|
||||
proofKeyThumbprint: "proof-key"
|
||||
)
|
||||
let credentials = InMemoryCredentialStore(
|
||||
credentials: [
|
||||
manual.id: manualCredential,
|
||||
managed.id: managedCredential,
|
||||
]
|
||||
)
|
||||
let signer = try testSigner()
|
||||
let transport = T3ConnectNativeHTTPTransport(descriptorEnvironmentID: managed.id)
|
||||
let controller = T3ConnectController(
|
||||
resolution: .available(
|
||||
T3ConnectConfiguration(
|
||||
clerkPublishableKey: "pk_test",
|
||||
relayHTTPURL: URL(string: "https://relay.example")!
|
||||
)
|
||||
),
|
||||
transport: transport,
|
||||
signer: signer,
|
||||
signOutOperation: { throw T3ConnectNativeTestError.clerkSignOutFailed }
|
||||
)
|
||||
let runtime = EnvironmentRuntime(
|
||||
environmentStore: store,
|
||||
credentialStore: credentials,
|
||||
httpTransport: transport,
|
||||
webSocketConnector: T3ConnectBlockingConnector(),
|
||||
managedAuthorization: T3ConnectRuntimeAuthorization(controller: controller)
|
||||
)
|
||||
let client = NativeFeatureClient(
|
||||
runtime: runtime,
|
||||
t3ConnectController: controller
|
||||
)
|
||||
|
||||
await client.signOutT3Connect()
|
||||
|
||||
let remainingEnvironments = try await runtime.environments()
|
||||
let activeEnvironmentID = try await store.activeEnvironmentID()
|
||||
let remainingManualCredential = await credentials.credential(for: manual.id)
|
||||
let remainingManagedCredential = await credentials.credential(for: managed.id)
|
||||
XCTAssertEqual(remainingEnvironments, [manual])
|
||||
XCTAssertEqual(activeEnvironmentID, manual.id)
|
||||
XCTAssertEqual(remainingManualCredential, manualCredential)
|
||||
XCTAssertNil(remainingManagedCredential)
|
||||
XCTAssertEqual(
|
||||
controller.errorMessage,
|
||||
T3ConnectNativeTestError.clerkSignOutFailed.localizedDescription
|
||||
)
|
||||
}
|
||||
|
||||
func testInjectedManagedRuntimeRequiresItsMatchingController() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("t3-connect-controller-mismatch-\(UUID().uuidString)")
|
||||
@@ -279,6 +356,7 @@ private actor T3ConnectNativeHTTPTransport: HTTPTransport {
|
||||
|
||||
private enum T3ConnectNativeTestError: Error {
|
||||
case unexpectedPath(String?)
|
||||
case clerkSignOutFailed
|
||||
}
|
||||
|
||||
private actor T3ConnectBlockingConnector: WebSocketConnecting {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"snapshotSequence": 42,
|
||||
"projects": [
|
||||
{
|
||||
"id": "project-fixture",
|
||||
"title": "Fixture project",
|
||||
"workspaceRoot": "/workspace/fixture",
|
||||
"repositoryIdentity": null,
|
||||
"defaultModelSelection": {
|
||||
"instanceId": "codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"options": [
|
||||
{
|
||||
"id": "effort",
|
||||
"value": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scripts": [],
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"threads": [
|
||||
{
|
||||
"id": "thread-fixture",
|
||||
"projectId": "project-fixture",
|
||||
"title": "Fixture thread",
|
||||
"modelSelection": {
|
||||
"instanceId": "codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"options": [
|
||||
{
|
||||
"id": "effort",
|
||||
"value": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"runtimeMode": "full-access",
|
||||
"interactionMode": "default",
|
||||
"branch": "main",
|
||||
"worktreePath": null,
|
||||
"latestTurn": null,
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z",
|
||||
"archivedAt": null,
|
||||
"settledOverride": null,
|
||||
"settledAt": null,
|
||||
"snoozedUntil": null,
|
||||
"snoozedAt": null,
|
||||
"pinnedAt": null,
|
||||
"titleRegeneration": null,
|
||||
"session": null,
|
||||
"latestUserMessageAt": "2026-08-07T12:00:00.000Z",
|
||||
"hasPendingApprovals": false,
|
||||
"hasPendingUserInput": false,
|
||||
"hasActionableProposedPlan": false,
|
||||
"backgroundLiveness": null,
|
||||
"planProgress": null
|
||||
}
|
||||
],
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z"
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"kind": "snapshot",
|
||||
"snapshot": {
|
||||
"snapshotSequence": 42,
|
||||
"projects": [
|
||||
{
|
||||
"id": "project-fixture",
|
||||
"title": "Fixture project",
|
||||
"workspaceRoot": "/workspace/fixture",
|
||||
"repositoryIdentity": null,
|
||||
"defaultModelSelection": {
|
||||
"instanceId": "codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"options": [
|
||||
{
|
||||
"id": "effort",
|
||||
"value": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scripts": [],
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"threads": [
|
||||
{
|
||||
"id": "thread-fixture",
|
||||
"projectId": "project-fixture",
|
||||
"title": "Fixture thread",
|
||||
"modelSelection": {
|
||||
"instanceId": "codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"options": [
|
||||
{
|
||||
"id": "effort",
|
||||
"value": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"runtimeMode": "full-access",
|
||||
"interactionMode": "default",
|
||||
"branch": "main",
|
||||
"worktreePath": null,
|
||||
"latestTurn": null,
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z",
|
||||
"archivedAt": null,
|
||||
"settledOverride": null,
|
||||
"settledAt": null,
|
||||
"snoozedUntil": null,
|
||||
"snoozedAt": null,
|
||||
"pinnedAt": null,
|
||||
"titleRegeneration": null,
|
||||
"session": null,
|
||||
"latestUserMessageAt": "2026-08-07T12:00:00.000Z",
|
||||
"hasPendingApprovals": false,
|
||||
"hasPendingUserInput": false,
|
||||
"hasActionableProposedPlan": false,
|
||||
"backgroundLiveness": null,
|
||||
"planProgress": null
|
||||
}
|
||||
],
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"snapshotSequence": 42,
|
||||
"thread": {
|
||||
"id": "thread-fixture",
|
||||
"projectId": "project-fixture",
|
||||
"title": "Fixture thread",
|
||||
"modelSelection": {
|
||||
"instanceId": "codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"options": [
|
||||
{
|
||||
"id": "effort",
|
||||
"value": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"runtimeMode": "full-access",
|
||||
"interactionMode": "default",
|
||||
"branch": "main",
|
||||
"worktreePath": null,
|
||||
"latestTurn": null,
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z",
|
||||
"archivedAt": null,
|
||||
"settledOverride": null,
|
||||
"settledAt": null,
|
||||
"snoozedUntil": null,
|
||||
"snoozedAt": null,
|
||||
"pinnedAt": null,
|
||||
"titleRegeneration": null,
|
||||
"deletedAt": null,
|
||||
"messages": [
|
||||
{
|
||||
"id": "message-fixture",
|
||||
"role": "user",
|
||||
"text": "Verify the native wire contract",
|
||||
"attachments": [],
|
||||
"turnId": "turn-fixture",
|
||||
"streaming": false,
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"proposedPlans": [],
|
||||
"activities": [],
|
||||
"checkpoints": [],
|
||||
"session": null
|
||||
},
|
||||
"page": {
|
||||
"beforeCursor": "fixture-cursor",
|
||||
"hasMore": true,
|
||||
"snapshotSequence": 42,
|
||||
"threadSequence": 40
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"kind": "snapshot",
|
||||
"snapshot": {
|
||||
"snapshotSequence": 42,
|
||||
"thread": {
|
||||
"id": "thread-fixture",
|
||||
"projectId": "project-fixture",
|
||||
"title": "Fixture thread",
|
||||
"modelSelection": {
|
||||
"instanceId": "codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"options": [
|
||||
{
|
||||
"id": "effort",
|
||||
"value": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"runtimeMode": "full-access",
|
||||
"interactionMode": "default",
|
||||
"branch": "main",
|
||||
"worktreePath": null,
|
||||
"latestTurn": null,
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z",
|
||||
"archivedAt": null,
|
||||
"settledOverride": null,
|
||||
"settledAt": null,
|
||||
"snoozedUntil": null,
|
||||
"snoozedAt": null,
|
||||
"pinnedAt": null,
|
||||
"titleRegeneration": null,
|
||||
"deletedAt": null,
|
||||
"messages": [
|
||||
{
|
||||
"id": "message-fixture",
|
||||
"role": "user",
|
||||
"text": "Verify the native wire contract",
|
||||
"attachments": [],
|
||||
"turnId": "turn-fixture",
|
||||
"streaming": false,
|
||||
"createdAt": "2026-08-07T12:00:00.000Z",
|
||||
"updatedAt": "2026-08-07T12:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"proposedPlans": [],
|
||||
"activities": [],
|
||||
"checkpoints": [],
|
||||
"session": null
|
||||
},
|
||||
"page": {
|
||||
"beforeCursor": "fixture-cursor",
|
||||
"hasMore": true,
|
||||
"snapshotSequence": 42,
|
||||
"threadSequence": 40
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationShellStreamItem,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
OrchestrationThreadStreamItem,
|
||||
} from "../packages/contracts/src/orchestration.ts";
|
||||
|
||||
const root = resolve(import.meta.dirname, "..");
|
||||
const outputDirectory = resolve(root, "apps/swift-ios/Tests/Fixtures/Wire");
|
||||
const check = process.argv.includes("--check");
|
||||
const timestamp = "2026-08-07T12:00:00.000Z";
|
||||
|
||||
const project = {
|
||||
id: "project-fixture",
|
||||
title: "Fixture project",
|
||||
workspaceRoot: "/workspace/fixture",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.6-sol",
|
||||
options: [{ id: "effort", value: "high" }],
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
deletedAt: null,
|
||||
};
|
||||
|
||||
const threadShell = {
|
||||
id: "thread-fixture",
|
||||
projectId: project.id,
|
||||
title: "Fixture thread",
|
||||
modelSelection: project.defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
pinnedAt: null,
|
||||
titleRegeneration: null,
|
||||
session: null,
|
||||
latestUserMessageAt: timestamp,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
backgroundLiveness: null,
|
||||
planProgress: null,
|
||||
};
|
||||
|
||||
const shellSnapshotInput = {
|
||||
snapshotSequence: 42,
|
||||
projects: [project],
|
||||
threads: [threadShell],
|
||||
updatedAt: timestamp,
|
||||
};
|
||||
|
||||
const threadDetailInput = {
|
||||
snapshotSequence: 42,
|
||||
thread: {
|
||||
...threadShell,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
id: "message-fixture",
|
||||
role: "user",
|
||||
text: "Verify the native wire contract",
|
||||
attachments: [],
|
||||
turnId: "turn-fixture",
|
||||
streaming: false,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
},
|
||||
page: {
|
||||
beforeCursor: "fixture-cursor",
|
||||
hasMore: true,
|
||||
snapshotSequence: 42,
|
||||
threadSequence: 40,
|
||||
},
|
||||
};
|
||||
|
||||
const decodeShellSnapshot = Schema.decodeUnknownSync(OrchestrationShellSnapshot);
|
||||
const encodeShellSnapshot = Schema.encodeSync(OrchestrationShellSnapshot);
|
||||
const decodeThreadDetail = Schema.decodeUnknownSync(OrchestrationThreadDetailSnapshot);
|
||||
const encodeThreadDetail = Schema.encodeSync(OrchestrationThreadDetailSnapshot);
|
||||
const decodeShellStreamItem = Schema.decodeUnknownSync(OrchestrationShellStreamItem);
|
||||
const encodeShellStreamItem = Schema.encodeSync(OrchestrationShellStreamItem);
|
||||
const decodeThreadStreamItem = Schema.decodeUnknownSync(OrchestrationThreadStreamItem);
|
||||
const encodeThreadStreamItem = Schema.encodeSync(OrchestrationThreadStreamItem);
|
||||
|
||||
const shellSnapshot = encodeShellSnapshot(decodeShellSnapshot(shellSnapshotInput));
|
||||
const threadDetail = encodeThreadDetail(decodeThreadDetail(threadDetailInput));
|
||||
const fixtures = new Map<string, unknown>([
|
||||
["shell-snapshot.json", shellSnapshot],
|
||||
["thread-detail-snapshot.json", threadDetail],
|
||||
[
|
||||
"shell-stream-snapshot.json",
|
||||
encodeShellStreamItem(decodeShellStreamItem({ kind: "snapshot", snapshot: shellSnapshot })),
|
||||
],
|
||||
[
|
||||
"thread-stream-snapshot.json",
|
||||
encodeThreadStreamItem(decodeThreadStreamItem({ kind: "snapshot", snapshot: threadDetail })),
|
||||
],
|
||||
]);
|
||||
|
||||
let stale = false;
|
||||
for (const [name, value] of fixtures) {
|
||||
const path = resolve(outputDirectory, name);
|
||||
const contents = `${JSON.stringify(value, null, 2)}\n`;
|
||||
if (check) {
|
||||
const current = await readFile(path, "utf8").catch(() => undefined);
|
||||
if (current !== contents) {
|
||||
console.error(`[swift-wire-fixtures] stale: ${name}`);
|
||||
stale = true;
|
||||
}
|
||||
} else {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, contents);
|
||||
console.log(`[swift-wire-fixtures] wrote ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (stale) {
|
||||
console.error("Run `node scripts/generate-swift-wire-fixtures.ts` and commit the result.");
|
||||
process.exitCode = 1;
|
||||
}
|
||||
Reference in new issue
Block a user