fix(swift-ios): clear stale platform state

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:52 -07:00
1 parent 909cfec0ad
commit 3239bbf7c3
3 files changed
+129 -38

No files matched your search

@@ -156,6 +156,13 @@ enum PlatformAgentAwarenessProjection {
final class PlatformAgentAwarenessCoordinator {
static let shared = PlatformAgentAwarenessCoordinator()
private let updateLiveActivity: @MainActor (
T3RelayAgentActivityAggregateState,
Bool,
Date
) async throws -> Void
private let endLiveActivities: @MainActor () async -> Void
private struct Signature: Equatable {
let activeCount: Int
let subtitle: String
@@ -176,6 +183,26 @@ final class PlatformAgentAwarenessCoordinator {
private var latestSynchronization: Synchronization?
private var synchronizationGeneration = 0
init(
updateLiveActivity: @escaping @MainActor (
T3RelayAgentActivityAggregateState,
Bool,
Date
) async throws -> Void = { aggregate, enabled, now in
try await PlatformAgentAwarenessCoordinator.synchronizeLiveActivity(
aggregate: aggregate,
enabled: enabled,
now: now
)
},
endLiveActivities: @escaping @MainActor () async -> Void = {
await PlatformAgentAwarenessCoordinator.endAllLiveActivities()
}
) {
self.updateLiveActivity = updateLiveActivity
self.endLiveActivities = endLiveActivities
}
func synchronize(snapshot: FeatureSnapshot, liveActivitiesEnabled: Bool) {
let now = Date.now
let aggregate = PlatformAgentAwarenessProjection.aggregate(
@@ -209,30 +236,24 @@ final class PlatformAgentAwarenessCoordinator {
schedule(synchronization)
}
/// Account sign-out removes any activity that may contain account-scoped
/// content, then restores the latest local projection without waiting for
/// an unrelated thread update.
/// Account sign-out invalidates the cached account-scoped projection before
/// removing its activity. Only a later snapshot may publish new content.
func resetAndResynchronizeLiveActivity() {
activityUpdateTask?.cancel()
synchronizationGeneration &+= 1
let generation = synchronizationGeneration
lastSignature = nil
guard let latestSynchronization else {
activityUpdateTask?.cancel()
synchronizationGeneration &+= 1
inFlightSignature = nil
activityUpdateTask = Task { @MainActor in
for activity in Activity<LiveActivityAttributes>.activities {
await activity.end(nil, dismissalPolicy: .immediate)
}
notifyActivityChanged()
}
return
inFlightSignature = nil
latestSynchronization = nil
activityUpdateTask = Task { @MainActor [weak self] in
guard let self else { return }
await endLiveActivities()
guard synchronizationGeneration == generation else { return }
activityUpdateTask = nil
}
schedule(latestSynchronization, endingExistingActivitiesFirst: true)
}
private func schedule(
_ synchronization: Synchronization,
endingExistingActivitiesFirst: Bool = false
) {
private func schedule(_ synchronization: Synchronization) {
activityUpdateTask?.cancel()
synchronizationGeneration &+= 1
let generation = synchronizationGeneration
@@ -240,16 +261,10 @@ final class PlatformAgentAwarenessCoordinator {
activityUpdateTask = Task { @MainActor [weak self] in
guard let self else { return }
do {
if endingExistingActivitiesFirst {
for activity in Activity<LiveActivityAttributes>.activities {
await activity.end(nil, dismissalPolicy: .immediate)
}
try Task.checkCancellation()
}
try await synchronizeLiveActivity(
aggregate: synchronization.aggregate,
enabled: synchronization.enabled,
now: synchronization.now
try await updateLiveActivity(
synchronization.aggregate,
synchronization.enabled,
synchronization.now
)
try Task.checkCancellation()
guard synchronizationGeneration == generation,
@@ -268,7 +283,7 @@ final class PlatformAgentAwarenessCoordinator {
}
}
private func synchronizeLiveActivity(
private static func synchronizeLiveActivity(
aggregate: T3RelayAgentActivityAggregateState,
enabled: Bool,
now: Date
@@ -319,7 +334,14 @@ final class PlatformAgentAwarenessCoordinator {
notifyActivityChanged()
}
private func notifyActivityChanged() {
private static func endAllLiveActivities() async {
for activity in Activity<LiveActivityAttributes>.activities {
await activity.end(nil, dismissalPolicy: .immediate)
}
notifyActivityChanged()
}
private static func notifyActivityChanged() {
NotificationCenter.default.post(name: .platformLiveActivityChanged, object: nil)
}
}
@@ -4,11 +4,11 @@ private struct DeviceList: Decodable {
struct Result: Decodable {
struct Device: Decodable {
struct HardwareProperties: Decodable {
let udid: String
let udid: String?
}
let identifier: String
let hardwareProperties: HardwareProperties
let hardwareProperties: HardwareProperties?
}
let devices: [Device]
@@ -28,13 +28,17 @@ do {
from: Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1]))
)
let requested = CommandLine.arguments[2]
guard let device = payload.result.devices.first(where: {
$0.identifier.caseInsensitiveCompare(requested) == .orderedSame
|| $0.hardwareProperties.udid.caseInsensitiveCompare(requested) == .orderedSame
}) else {
guard let udid = payload.result.devices.lazy.compactMap({ device -> String? in
guard let udid = device.hardwareProperties?.udid, !udid.isEmpty else {
return nil
}
let matchesIdentifier = device.identifier.caseInsensitiveCompare(requested) == .orderedSame
let matchesUDID = udid.caseInsensitiveCompare(requested) == .orderedSame
return matchesIdentifier || matchesUDID ? udid : nil
}).first else {
throw CocoaError(.fileNoSuchFile)
}
print(device.hardwareProperties.udid)
print(udid)
} catch {
FileHandle.standardError.write(
Data("Could not resolve that device identifier: \(error.localizedDescription)\n".utf8)
@@ -117,6 +117,30 @@ struct PlatformAgentAwarenessTests {
#expect(widget.updatedAt == aggregate.updatedAt)
}
@Test
@MainActor
func signOutEndsActivitiesWithoutRepublishingTheCachedProjection() async {
let recorder = PlatformAgentAwarenessOperationRecorder()
let coordinator = PlatformAgentAwarenessCoordinator(
updateLiveActivity: { _, _, _ in
recorder.recordUpdate()
},
endLiveActivities: {
recorder.recordEnd()
}
)
coordinator.synchronize(snapshot: FeatureSnapshot(), liveActivitiesEnabled: true)
await recorder.waitForUpdateCount(1)
coordinator.resetAndResynchronizeLiveActivity()
await recorder.waitForEndCount(1)
await Task.yield()
#expect(recorder.updateCount == 1)
#expect(recorder.endCount == 1)
}
private static func thread(
id: String,
state: FeatureThreadState,
@@ -135,3 +159,44 @@ struct PlatformAgentAwarenessTests {
)
}
}
@MainActor
private final class PlatformAgentAwarenessOperationRecorder {
private(set) var updateCount = 0
private(set) var endCount = 0
private var updateWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
private var endWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
func recordUpdate() {
updateCount += 1
resumeReadyWaiters(&updateWaiters, count: updateCount)
}
func recordEnd() {
endCount += 1
resumeReadyWaiters(&endWaiters, count: endCount)
}
func waitForUpdateCount(_ count: Int) async {
guard updateCount < count else { return }
await withCheckedContinuation { continuation in
updateWaiters.append((count, continuation))
}
}
func waitForEndCount(_ count: Int) async {
guard endCount < count else { return }
await withCheckedContinuation { continuation in
endWaiters.append((count, continuation))
}
}
private func resumeReadyWaiters(
_ waiters: inout [(Int, CheckedContinuation<Void, Never>)],
count: Int
) {
let ready = waiters.filter { count >= $0.0 }
waiters.removeAll { count >= $0.0 }
ready.forEach { $0.1.resume() }
}
}