diff --git a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift new file mode 100644 index 0000000000..4b30839759 --- /dev/null +++ b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift @@ -0,0 +1,256 @@ +import ActivityKit +import Foundation +import WidgetKit + +extension Notification.Name { + static let platformLiveActivityChanged = Notification.Name( + "T3PlatformLiveActivityChanged" + ) +} + +enum PlatformAgentAwarenessProjection { + static let terminalVisibilityWindow: TimeInterval = 15 * 60 + static let maximumRows = 5 + + static func aggregate( + snapshot: FeatureSnapshot, + now: Date = .now + ) -> T3RelayAgentActivityAggregateState { + let projects = Dictionary(uniqueKeysWithValues: snapshot.projects.map { ($0.id, $0) }) + let eligible = snapshot.threads.filter { thread in + guard !thread.isArchived else { return false } + if isActive(thread.state) { return true } + guard thread.state == .completed || thread.state == .failed else { return false } + return now.timeIntervalSince(thread.updatedAt) <= terminalVisibilityWindow + } + let rows = eligible.compactMap { thread -> T3RelayAgentActivityAggregateRow? in + guard let project = projects[thread.projectID] else { return nil } + let environmentID = thread.environmentID ?? project.environmentID + let threadID = thread.wireID ?? thread.id + let phase = phase(for: thread.state) + return T3RelayAgentActivityAggregateRow( + environmentId: environmentID, + threadId: threadID, + projectTitle: project.name, + threadTitle: thread.title, + modelTitle: modelTitle( + for: thread, + environmentID: environmentID, + snapshot: snapshot + ), + phase: phase, + status: status(for: thread.state), + updatedAt: thread.updatedAt.ISO8601Format(), + deepLink: PlatformRoute.thread( + environmentID: environmentID, + threadID: threadID + ).url?.absoluteString ?? "/" + ) + } + .sorted { left, right in + let leftPriority = priority(left.phase) + let rightPriority = priority(right.phase) + if leftPriority != rightPriority { return leftPriority < rightPriority } + return left.updatedAt > right.updatedAt + } + let visibleRows = Array(rows.prefix(maximumRows)) + let activeCount = eligible.count { isActive($0.state) } + let attentionCount = eligible.count { + $0.state == .waitingForApproval || $0.state == .waitingForInput + } + let subtitle: String + if attentionCount > 0 { + subtitle = attentionCount == 1 + ? "1 task needs attention" + : "\(attentionCount) tasks need attention" + } else if activeCount > 0 { + subtitle = activeCount == 1 ? "1 active task" : "\(activeCount) active tasks" + } else if visibleRows.contains(where: { $0.phase == .failed }) { + subtitle = "Agent work failed" + } else if !visibleRows.isEmpty { + subtitle = "Agent work completed" + } else { + subtitle = "Ready for a task" + } + return T3RelayAgentActivityAggregateState( + title: "T3 Code", + subtitle: subtitle, + activeCount: activeCount, + updatedAt: now.ISO8601Format(), + activities: visibleRows + ) + } + + static func widgetSnapshot( + snapshot: FeatureSnapshot, + now: Date = .now + ) -> T3TaskWidgetSnapshot { + let aggregate = aggregate(snapshot: snapshot, now: now) + return T3TaskWidgetSnapshot( + updatedAt: aggregate.updatedAt, + tasks: aggregate.activities + ) + } + + private static func isActive(_ state: FeatureThreadState) -> Bool { + switch state { + case .queued, .working, .waitingForApproval, .waitingForInput: + true + case .idle, .failed, .completed: + false + } + } + + private static func phase(for state: FeatureThreadState) -> T3AgentActivityPhase { + switch state { + case .queued: .starting + case .working: .running + case .waitingForApproval: .waitingForApproval + case .waitingForInput: .waitingForInput + case .failed: .failed + case .completed: .completed + case .idle: .stale + } + } + + private static func status(for state: FeatureThreadState) -> String { + switch state { + case .queued: "Starting" + case .working: "Working" + case .waitingForApproval: "Approval" + case .waitingForInput: "Input" + case .failed: "Failed" + case .completed: "Done" + case .idle: "Idle" + } + } + + private static func priority(_ phase: T3AgentActivityPhase) -> Int { + switch phase { + case .waitingForApproval, .waitingForInput: 0 + case .failed: 1 + case .starting, .running: 2 + case .completed, .stale: 3 + } + } + + private static func modelTitle( + for thread: FeatureThread, + environmentID: String, + snapshot: FeatureSnapshot + ) -> String { + let providers = snapshot.providersByEnvironment?[environmentID] ?? snapshot.providers + let provider = thread.providerID.flatMap { providerID in + providers.first { $0.id == providerID } + } + if let modelID = thread.modelID, + let model = provider?.models.first(where: { $0.id == modelID }) + { + return model.name + } + return thread.modelID ?? provider?.name ?? thread.providerName ?? "" + } +} + +@MainActor +final class PlatformAgentAwarenessCoordinator { + static let shared = PlatformAgentAwarenessCoordinator() + + private struct Signature: Equatable { + let activeCount: Int + let subtitle: String + let rows: [T3RelayAgentActivityAggregateRow] + let enabled: Bool + } + + private var activityUpdateTask: Task? + private var lastSignature: Signature? + + func synchronize(snapshot: FeatureSnapshot, liveActivitiesEnabled: Bool) { + let now = Date.now + let aggregate = PlatformAgentAwarenessProjection.aggregate( + snapshot: snapshot, + now: now + ) + let signature = Signature( + activeCount: aggregate.activeCount, + subtitle: aggregate.subtitle, + rows: aggregate.activities, + enabled: liveActivitiesEnabled + ) + guard signature != lastSignature else { return } + lastSignature = signature + + let widgetSnapshot = T3TaskWidgetSnapshot( + updatedAt: aggregate.updatedAt, + tasks: aggregate.activities + ) + Task.detached(priority: .utility) { + try? T3TaskWidgetSnapshotStore.save(widgetSnapshot) + WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget") + } + + activityUpdateTask?.cancel() + activityUpdateTask = Task { @MainActor in + await synchronizeLiveActivity( + aggregate: aggregate, + enabled: liveActivitiesEnabled, + now: now + ) + } + } + + private func synchronizeLiveActivity( + aggregate: T3RelayAgentActivityAggregateState, + enabled: Bool, + now: Date + ) async { + guard !Task.isCancelled else { return } + let activities = Activity.activities + + guard enabled, ActivityAuthorizationInfo().areActivitiesEnabled else { + for activity in activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + notifyActivityChanged() + return + } + + guard let state = try? LiveActivityAttributes.ContentState(aggregate: aggregate) else { + return + } + let content = ActivityContent( + state: state, + staleDate: now.addingTimeInterval(10 * 60) + ) + + if aggregate.activeCount == 0 { + for activity in activities { + await activity.end( + content, + dismissalPolicy: .after(now.addingTimeInterval(5 * 60)) + ) + } + notifyActivityChanged() + return + } + + if let primary = activities.first { + await primary.update(content) + for duplicate in activities.dropFirst() { + await duplicate.end(nil, dismissalPolicy: .immediate) + } + } else { + _ = try? Activity.request( + attributes: LiveActivityAttributes(), + content: content, + pushType: .token + ) + } + notifyActivityChanged() + } + + private func notifyActivityChanged() { + NotificationCenter.default.post(name: .platformLiveActivityChanged, object: nil) + } +} diff --git a/apps/swift-ios/App/Platform/PlatformBackgroundRefresh.swift b/apps/swift-ios/App/Platform/PlatformBackgroundRefresh.swift new file mode 100644 index 0000000000..441d77fd15 --- /dev/null +++ b/apps/swift-ios/App/Platform/PlatformBackgroundRefresh.swift @@ -0,0 +1,67 @@ +import BackgroundTasks +import Foundation + +@MainActor +final class PlatformBackgroundRefreshCoordinator { + typealias RefreshAction = @MainActor @Sendable () async -> Bool + + static let shared = PlatformBackgroundRefreshCoordinator() + static var identifier: String { + "\(Bundle.main.bundleIdentifier ?? "com.t3tools.t3code.swiftui").refresh" + } + + private var refreshAction: RefreshAction? + private var isRegistered = false + + func install(refreshAction: @escaping RefreshAction) { + self.refreshAction = refreshAction + } + + func register() { + guard !isRegistered else { return } + isRegistered = BGTaskScheduler.shared.register( + forTaskWithIdentifier: Self.identifier, + using: nil + ) { task in + guard let refreshTask = task as? BGAppRefreshTask else { + task.setTaskCompleted(success: false) + return + } + Task { @MainActor in + await Self.shared.handle(refreshTask) + } + } + } + + func schedule() { + guard isRegistered else { return } + let request = BGAppRefreshTaskRequest(identifier: Self.identifier) + request.earliestBeginDate = Date().addingTimeInterval( + PlatformBackgroundRefreshPolicy.minimumDelay + ) + try? BGTaskScheduler.shared.submit(request) + } + + private func handle(_ task: BGAppRefreshTask) async { + schedule() + guard let refreshAction else { + task.setTaskCompleted(success: false) + return + } + + let operation = Task { @MainActor in + await refreshAction() + } + task.expirationHandler = { + operation.cancel() + } + let succeeded = await operation.value + task.setTaskCompleted(success: succeeded && !operation.isCancelled) + } +} + +enum PlatformBackgroundRefreshPolicy { + /// iOS chooses the actual cadence. Fifteen minutes is merely the earliest + /// useful retry and avoids repeatedly asking the scheduler for immediate work. + static let minimumDelay: TimeInterval = 15 * 60 +} diff --git a/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift b/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift new file mode 100644 index 0000000000..a56e8051ef --- /dev/null +++ b/apps/swift-ios/App/Platform/PlatformCloudDelivery.swift @@ -0,0 +1,392 @@ +import ActivityKit +import CryptoKit +import Foundation +import Security +import UIKit + +enum PlatformInstallationIdentity { + private static let service = "com.t3tools.t3code.swiftui.installation" + private static let account = "device-id" + private static let fallbackKey = "swift-ios.installation-id.v1" + + static func value() -> String { + if let stored = readKeychainValue() { return stored } + let created = UUID().uuidString.lowercased() + let insertion: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecValueData as String: Data(created.utf8), + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + ] + let status = SecItemAdd(insertion as CFDictionary, nil) + if status == errSecSuccess { return created } + if status == errSecDuplicateItem, let winner = readKeychainValue() { return winner } + return value(defaults: .standard) + } + + /// Injectable fallback used only when Keychain is unavailable and by tests. + static func value(defaults: UserDefaults) -> String { + if let existing = defaults.string(forKey: fallbackKey), !existing.isEmpty { + return existing + } + let created = UUID().uuidString.lowercased() + defaults.set(created, forKey: fallbackKey) + return created + } + + private static func readKeychainValue() -> String? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne, + ] + var item: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, + let data = item as? Data, + let value = String(data: data, encoding: .utf8), + UUID(uuidString: value) != nil else { + return nil + } + return value.lowercased() + } +} + +enum PlatformCloudDeliveryRegistrationFactory { + static func registration( + deviceID: String, + deviceName: String, + systemVersion: OperatingSystemVersion, + appVersion: String?, + bundleID: String?, + pushToken: String?, + pushToStartToken: String?, + settings: FeatureSettings, + apsEnvironment: T3ConnectDeviceRegistration.APNSEnvironment + ) -> T3ConnectDeviceRegistration { + T3ConnectDeviceRegistration( + deviceID: deviceID, + label: deviceName, + iosMajorVersion: systemVersion.majorVersion, + appVersion: appVersion, + bundleID: bundleID, + apsEnvironment: apsEnvironment, + pushToken: pushToken, + pushToStartToken: pushToStartToken, + preferences: T3ConnectDevicePreferences( + liveActivitiesEnabled: settings.liveActivitiesEnabled, + notificationsEnabled: settings.notificationsEnabled + ) + ) + } +} + +/// Keeps the relay's device record aligned with this installation. Token values +/// only travel over DPoP-authenticated relay requests; local success caches store +/// SHA-256 fingerprints rather than reusable push credentials. +@MainActor +final class PlatformCloudDeliveryCoordinator { + static let shared = PlatformCloudDeliveryCoordinator() + + private let defaults: UserDefaults + private let tokenSink: PlatformPersistedDeviceTokenSink + private let deviceID: String + + private weak var controller: T3ConnectController? + private var settings: FeatureSettings? + private var needsRegistration = false + private var registrationTask: Task? + private var observerTasks: [Task] = [] + private var pushToStartTask: Task? + private var activityUpdatesTask: Task? + private var activityTokenTasks: [String: Task] = [:] + private var pendingActivityTokens: Set = [] + private var retryTask: Task? + + private let deviceFingerprintKey = "swift-ios.cloud-delivery-device.v1" + private let deviceRegisteredAtKey = "swift-ios.cloud-delivery-device-date.v1" + private let activityFingerprintKey = "swift-ios.cloud-delivery-activities.v1" + private let healingInterval: TimeInterval = 60 + + init( + defaults: UserDefaults = .standard, + tokenSink: PlatformPersistedDeviceTokenSink? = nil, + deviceID: String? = nil + ) { + self.defaults = defaults + self.tokenSink = tokenSink ?? .shared + self.deviceID = deviceID ?? PlatformInstallationIdentity.value() + } + + deinit { + registrationTask?.cancel() + pushToStartTask?.cancel() + activityUpdatesTask?.cancel() + retryTask?.cancel() + observerTasks.forEach { $0.cancel() } + activityTokenTasks.values.forEach { $0.cancel() } + } + + func install(controller: T3ConnectController) { + self.controller = controller + guard observerTasks.isEmpty else { + requestRegistration() + return + } + + for name in [Notification.Name.platformDeviceTokenChanged, .platformLiveActivityChanged] { + observerTasks.append(Task { @MainActor [weak self] in + for await _ in NotificationCenter.default.notifications(named: name) { + guard !Task.isCancelled else { return } + self?.refreshActivityTokenObservers() + self?.requestRegistration() + } + }) + } + observerTasks.append(Task { @MainActor [weak self] in + for await _ in NotificationCenter.default.notifications(named: .t3ConnectSessionChanged) { + guard !Task.isCancelled, let self else { return } + if controller.account == nil { + clearSuccessfulRegistrationCache() + endPrivateActivities() + } + refreshActivityTokenObservers() + requestRegistration() + } + }) + + if #available(iOS 17.2, *) { + pushToStartTask = Task { @MainActor [weak self] in + for await _ in Activity.pushToStartTokenUpdates { + guard !Task.isCancelled else { return } + self?.requestRegistration() + } + } + } + activityUpdatesTask = Task { @MainActor [weak self] in + for await activity in Activity.activityUpdates { + guard !Task.isCancelled, let self else { return } + if let token = activity.pushToken?.hexadecimalString { + pendingActivityTokens.insert(token) + } + refreshActivityTokenObservers() + requestRegistration() + } + } + refreshActivityTokenObservers() + requestRegistration() + } + + func synchronize(settings: FeatureSettings) { + self.settings = settings + refreshActivityTokenObservers() + requestRegistration() + } + + private func refreshActivityTokenObservers() { + let activities = Activity.activities + let currentIDs = Set(activities.map(\.id)) + for id in Array(activityTokenTasks.keys) where !currentIDs.contains(id) { + activityTokenTasks.removeValue(forKey: id)?.cancel() + } + + for activity in activities { + if let token = activity.pushToken?.hexadecimalString { + pendingActivityTokens.insert(token) + } + guard activityTokenTasks[activity.id] == nil else { continue } + activityTokenTasks[activity.id] = Task { @MainActor [weak self] in + for await token in activity.pushTokenUpdates { + guard !Task.isCancelled else { return } + self?.pendingActivityTokens.insert(token.hexadecimalString) + self?.requestRegistration() + } + } + } + } + + private func requestRegistration() { + retryTask?.cancel() + retryTask = nil + needsRegistration = true + guard registrationTask == nil else { return } + registrationTask = Task { @MainActor [weak self] in + guard let self else { return } + while needsRegistration, !Task.isCancelled { + needsRegistration = false + await registerCurrentState() + await Task.yield() + } + registrationTask = nil + if needsRegistration { requestRegistration() } + } + } + + private func registerCurrentState() async { + guard let controller, let settings else { return } + let registration = currentRegistration(settings: settings) + guard registration.iosMajorVersion >= 18 else { return } + controller.rememberRegisteredDevice(id: deviceID) + + let accountBeforeRequest = controller.account?.id + let fingerprint = Self.fingerprint( + registration, + accountID: accountBeforeRequest + ) + let canReuseRegistration = accountBeforeRequest != nil + && defaults.string(forKey: deviceFingerprintKey) == fingerprint + && Date.now.timeIntervalSince( + defaults.object(forKey: deviceRegisteredAtKey) as? Date ?? .distantPast + ) < healingInterval + + do { + if !canReuseRegistration { + try await controller.registerDevice(registration) + guard accountBeforeRequest == nil + || controller.account?.id == accountBeforeRequest else { + needsRegistration = true + return + } + defaults.set( + Self.fingerprint(registration, accountID: controller.account?.id), + forKey: deviceFingerprintKey + ) + defaults.set(Date.now, forKey: deviceRegisteredAtKey) + } + + guard let accountID = controller.account?.id else { return } + let now = Date.now.timeIntervalSince1970 + var completed = (defaults.dictionary(forKey: activityFingerprintKey) ?? [:]) + .compactMapValues { ($0 as? NSNumber)?.doubleValue } + .filter { now - $0.value < healingInterval } + for token in Array(pendingActivityTokens) { + let tokenFingerprint = Self.fingerprint( + "\(deviceID)|\(token)", + accountID: accountID + ) + guard completed[tokenFingerprint] == nil else { + pendingActivityTokens.remove(token) + continue + } + try await controller.registerLiveActivity( + T3ConnectLiveActivityRegistration( + deviceID: deviceID, + activityPushToken: token + ) + ) + guard controller.account?.id == accountID else { + needsRegistration = true + return + } + completed[tokenFingerprint] = now + pendingActivityTokens.remove(token) + } + let bounded = completed.sorted { $0.value > $1.value }.prefix(8) + defaults.set( + Dictionary(uniqueKeysWithValues: bounded.map { ($0.key, $0.value) }), + forKey: activityFingerprintKey + ) + scheduleRetry(after: healingInterval) + } catch is CancellationError { + return + } catch is T3ConnectAuthError { + return + } catch let error as T3ConnectRelayError { + guard case .invalidConfiguration = error else { + scheduleRetry(after: 15) + return + } + } catch { + // Signed-out and offline states are expected. The next account, + // network, foreground, or token event retries without noisy UI. + scheduleRetry(after: 15) + return + } + } + + private func scheduleRetry(after delay: TimeInterval) { + retryTask?.cancel() + retryTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(delay)) + guard !Task.isCancelled, let self else { return } + retryTask = nil + refreshActivityTokenObservers() + requestRegistration() + } + } + + private func clearSuccessfulRegistrationCache() { + defaults.removeObject(forKey: deviceFingerprintKey) + defaults.removeObject(forKey: deviceRegisteredAtKey) + defaults.removeObject(forKey: activityFingerprintKey) + } + + private func endPrivateActivities() { + pendingActivityTokens.removeAll() + Task { @MainActor in + for activity in Activity.activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + } + } + + private func currentRegistration(settings: FeatureSettings) -> T3ConnectDeviceRegistration { + let version = Bundle.main.object( + forInfoDictionaryKey: "CFBundleShortVersionString" + ) as? String + let pushToStartToken: String? = if #available(iOS 17.2, *) { + Activity.pushToStartToken?.hexadecimalString + } else { + nil + } + var effectiveSettings = settings + effectiveSettings.notificationsEnabled = settings.notificationsEnabled + && PlatformNotificationService.shared.enabled + && tokenSink.currentToken != nil + effectiveSettings.liveActivitiesEnabled = settings.liveActivitiesEnabled + && ActivityAuthorizationInfo().areActivitiesEnabled + return PlatformCloudDeliveryRegistrationFactory.registration( + deviceID: deviceID, + deviceName: UIDevice.current.name, + systemVersion: ProcessInfo.processInfo.operatingSystemVersion, + appVersion: version, + bundleID: Bundle.main.bundleIdentifier, + pushToken: tokenSink.currentToken, + pushToStartToken: pushToStartToken, + settings: effectiveSettings, + apsEnvironment: Self.apsEnvironment + ) + } + + private static var apsEnvironment: T3ConnectDeviceRegistration.APNSEnvironment { + #if DEBUG + .sandbox + #else + .production + #endif + } + + private static func fingerprint( + _ value: Value, + accountID: String? + ) -> String { + let data = (try? JSONEncoder.t3.encode(value)) ?? Data() + return fingerprint(Data((accountID ?? "unloaded").utf8) + data) + } + + private static func fingerprint(_ value: String, accountID: String?) -> String { + fingerprint(Data("\(accountID ?? "unloaded")|\(value)".utf8)) + } + + private static func fingerprint(_ data: Data) -> String { + Data(SHA256.hash(data: data)).hexadecimalString + } +} + +private extension Data { + var hexadecimalString: String { + map { String(format: "%02x", $0) }.joined() + } +} diff --git a/apps/swift-ios/App/Platform/PlatformDeepLinks.swift b/apps/swift-ios/App/Platform/PlatformDeepLinks.swift index bde0893ad6..69cb85a633 100644 --- a/apps/swift-ios/App/Platform/PlatformDeepLinks.swift +++ b/apps/swift-ios/App/Platform/PlatformDeepLinks.swift @@ -1,6 +1,8 @@ import Foundation enum PlatformRoute: Codable, Hashable, Identifiable, Sendable { + static let nativeScheme = "t3code-swiftui" + case connection(endpoint: String, token: String?) case environment(id: String) case project(environmentID: String?, projectID: String) @@ -24,7 +26,7 @@ enum PlatformRoute: Codable, Hashable, Identifiable, Sendable { var url: URL? { var components = URLComponents() - components.scheme = "t3code" + components.scheme = Self.nativeScheme switch self { case let .connection(endpoint, token): @@ -91,7 +93,7 @@ enum PlatformDeepLinkParser { } let query = queryValues(components.queryItems ?? []) - if ["t3", "t3code"].contains(scheme) { + if ["t3", "t3code", PlatformRoute.nativeScheme].contains(scheme) { let segments = customSchemeSegments(components) if isConnectionRoute(segments: segments, query: query) { return try connectionRoute(url) diff --git a/apps/swift-ios/App/Platform/PlatformIncomingShare.swift b/apps/swift-ios/App/Platform/PlatformIncomingShare.swift new file mode 100644 index 0000000000..3493c1d8cb --- /dev/null +++ b/apps/swift-ios/App/Platform/PlatformIncomingShare.swift @@ -0,0 +1,321 @@ +import Foundation +import Observation +import SwiftUI + +enum PlatformIncomingShareError: LocalizedError, Equatable { + case missingImage(String) + case invalidImage(String) + case invalidEnvelope + + var errorDescription: String? { + switch self { + case let .missingImage(name): + "The shared image \(name) is no longer available. Share it again to retry." + case let .invalidImage(name): + "The shared image \(name) is incomplete or too large. Share it again to retry." + case .invalidEnvelope: + "This shared item is invalid. Share it again to retry." + } + } +} + +struct PlatformIncomingShareSource: Sendable { + var loadAll: @Sendable () async -> [T3IncomingShareEnvelope] + var data: @Sendable (T3IncomingShareImage) async throws -> Data + var remove: @Sendable (String) async throws -> Void + + static let live = PlatformIncomingShareSource( + loadAll: { + await Task.detached(priority: .utility) { + T3IncomingShareStore.loadAll() + }.value + }, + data: { image in + guard let root = T3SharedContainer.rootURL?.standardizedFileURL, + let url = T3IncomingShareStore.fileURL(for: image)?.standardizedFileURL, + url.path.hasPrefix(root.path + "/") else { + throw PlatformIncomingShareError.missingImage(image.fileName) + } + let data = try await Task.detached(priority: .userInitiated) { + guard FileManager.default.fileExists(atPath: url.path) else { + throw PlatformIncomingShareError.missingImage(image.fileName) + } + return try Data(contentsOf: url, options: .mappedIfSafe) + }.value + guard !data.isEmpty, + data.count <= T3IncomingShareStore.maximumImageBytes, + data.count == image.byteCount else { + throw PlatformIncomingShareError.invalidImage(image.fileName) + } + return data + }, + remove: { id in + guard UUID(uuidString: id) != nil else { + throw PlatformIncomingShareError.invalidEnvelope + } + try await Task.detached(priority: .utility) { + try T3IncomingShareStore.remove(id: id) + }.value + } + ) +} + +struct PlatformIncomingShareDraftRepository: Sendable { + var importContent: @Sendable ( + _ shareID: String, + _ text: String, + _ attachments: [FeatureDraftAttachment], + _ key: String, + _ maximumAttachmentCount: Int + ) async throws -> FeatureComposerDraft + + static let live = PlatformIncomingShareDraftRepository( + importContent: { shareID, text, attachments, key, maximumAttachmentCount in + try await FeatureComposerDraftStore.shared.importSharedContent( + shareID: shareID, + text: text, + attachments: attachments, + for: key, + maximumAttachmentCount: maximumAttachmentCount + ) + } + ) +} + +/// Moves one extension envelope into the durable new-task draft. The saved +/// attachment identifiers make the operation idempotent if inbox cleanup fails +/// after the atomic draft write. +struct PlatformIncomingSharePipeline: Sendable { + static let maximumAttachmentCount = 8 + + private let source: PlatformIncomingShareSource + private let drafts: PlatformIncomingShareDraftRepository + private let prepareImage: @Sendable (Data, Int) async throws -> FeatureDraftAttachment + + init( + source: PlatformIncomingShareSource = .live, + drafts: PlatformIncomingShareDraftRepository = .live, + prepareImage: @escaping @Sendable (Data, Int) async throws -> FeatureDraftAttachment = { + data, + ordinal in + try await Task.detached(priority: .userInitiated) { + try FeatureImageProcessor.attachment(from: data, ordinal: ordinal) + }.value + } + ) { + self.source = source + self.drafts = drafts + self.prepareImage = prepareImage + } + + func pendingEnvelopes() async -> [T3IncomingShareEnvelope] { + await source.loadAll() + } + + func importEnvelope( + _ envelope: T3IncomingShareEnvelope, + into project: FeatureProject + ) async throws -> FeatureComposerDraft { + guard UUID(uuidString: envelope.id) != nil else { + throw PlatformIncomingShareError.invalidEnvelope + } + let key = FeatureComposerDraftStore.newTaskKey(project: project) + var prepared: [FeatureDraftAttachment] = [] + prepared.reserveCapacity(envelope.images.count) + for (offset, image) in envelope.images.enumerated() { + let data = try await source.data(image) + let attachment = try await prepareImage( + data, + offset + 1 + ) + prepared.append(Self.stableAttachment(attachment, for: image)) + } + + let merged = try await drafts.importContent( + envelope.id, + envelope.text, + prepared, + key, + Self.maximumAttachmentCount + ) + + // The repository's actor operation atomically merges the latest draft + // and records the share ID. Never acknowledge the inbox before it ends. + try await source.remove(envelope.id) + return merged + } + + private static func stableAttachment( + _ attachment: FeatureDraftAttachment, + for image: T3IncomingShareImage + ) -> FeatureDraftAttachment { + FeatureDraftAttachment( + id: UUID(uuidString: image.id) ?? attachment.id, + data: attachment.data, + thumbnailData: attachment.thumbnailData, + filename: attachment.filename, + mimeType: attachment.mimeType + ) + } +} + +@MainActor +@Observable +final class PlatformIncomingShareCoordinator { + private(set) var pendingEnvelope: T3IncomingShareEnvelope? + private(set) var isImporting = false + + private let pipeline: PlatformIncomingSharePipeline + private var isRefreshing = false + private var lastNoProjectNoticeID: String? + + init(pipeline: PlatformIncomingSharePipeline = PlatformIncomingSharePipeline()) { + self.pipeline = pipeline + } + + /// Returns true once per pending envelope when the app cannot offer a + /// destination. The envelope remains in the shared container. + func refresh(hasProjects: Bool) async -> Bool { + guard pendingEnvelope == nil, !isRefreshing, !isImporting else { + return pendingEnvelope != nil + && !hasProjects + && markNoProjectNoticeIfNeeded() + } + isRefreshing = true + let envelopes = await pipeline.pendingEnvelopes() + isRefreshing = false + pendingEnvelope = envelopes.first + guard pendingEnvelope != nil, !hasProjects else { return false } + return markNoProjectNoticeIfNeeded() + } + + func dismissDestination() { + guard !isImporting else { return } + pendingEnvelope = nil + } + + func importPending(into project: FeatureProject) async throws { + guard let pendingEnvelope, !isImporting else { return } + isImporting = true + do { + _ = try await pipeline.importEnvelope(pendingEnvelope, into: project) + self.pendingEnvelope = nil + lastNoProjectNoticeID = nil + isImporting = false + } catch { + isImporting = false + throw error + } + } + + private func markNoProjectNoticeIfNeeded() -> Bool { + guard let id = pendingEnvelope?.id, + lastNoProjectNoticeID != id else { + return false + } + lastNoProjectNoticeID = id + return true + } +} + +struct PlatformIncomingShareDestinationSheet: View { + let envelope: T3IncomingShareEnvelope + let projects: [FeatureProject] + let environments: [FeatureEnvironment] + let isImporting: Bool + let onCancel: () -> Void + let onSelect: (FeatureProject) -> Void + + var body: some View { + NavigationStack { + List { + if !summary.isEmpty { + Section { + Text(summary) + .font(.body) + .foregroundStyle(.secondary) + .lineLimit(3) + } + .listRowBackground(Color.black) + } + + Section("Choose a project") { + ForEach(projects) { project in + Button { + onSelect(project) + } label: { + HStack(spacing: 12) { + Image(systemName: "folder") + .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 3) { + Text(project.name) + .font(.body.weight(.semibold)) + .foregroundStyle(.primary) + if let environmentName = environmentName(for: project) { + Text(environmentName) + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + Spacer() + if isImporting { + ProgressView() + .controlSize(.small) + } else { + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) + } + } + .frame(minHeight: 48) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(isImporting) + .listRowBackground(Color.black) + } + } + + if !envelope.warnings.isEmpty { + Section { + ForEach(envelope.warnings, id: \.self) { warning in + Label(warning, systemImage: "exclamationmark.triangle") + .font(.footnote) + .foregroundStyle(.secondary) + } + } + .listRowBackground(Color.black) + } + } + .scrollContentBackground(.hidden) + .background(Color.black) + .navigationTitle("Start a task") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel", action: onCancel) + .disabled(isImporting) + } + } + } + .background(Color.black.ignoresSafeArea()) + .preferredColorScheme(.dark) + .presentationDetents([.medium, .large]) + .presentationDragIndicator(.visible) + .interactiveDismissDisabled(isImporting) + } + + private var summary: String { + if !envelope.text.isEmpty, !envelope.images.isEmpty { + return "\(envelope.text)\n\(envelope.images.count) image\(envelope.images.count == 1 ? "" : "s")" + } + if !envelope.text.isEmpty { return envelope.text } + guard !envelope.images.isEmpty else { return "" } + return "\(envelope.images.count) shared image\(envelope.images.count == 1 ? "" : "s")" + } + + private func environmentName(for project: FeatureProject) -> String? { + guard environments.count > 1 else { return nil } + return environments.first { $0.id == project.environmentID }?.name + } +} diff --git a/apps/swift-ios/App/Platform/PlatformNotifications.swift b/apps/swift-ios/App/Platform/PlatformNotifications.swift index ed6047c17a..6cf6fe5954 100644 --- a/apps/swift-ios/App/Platform/PlatformNotifications.swift +++ b/apps/swift-ios/App/Platform/PlatformNotifications.swift @@ -60,6 +60,10 @@ final class PlatformPersistedDeviceTokenSink: PlatformDeviceTokenSink { self.defaults = defaults } + var currentToken: String? { + defaults.string(forKey: key) + } + func registered(token: String) { defaults.set(token, forKey: key) NotificationCenter.default.post( @@ -239,6 +243,7 @@ final class T3PlatformAppDelegate: NSObject, UIApplicationDelegate { _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { + PlatformBackgroundRefreshCoordinator.shared.register() PlatformNotificationService.shared.installDelegate() if let payload = launchOptions?[.remoteNotification] as? [AnyHashable: Any], let route = PlatformNotificationPayload.route(from: payload) { diff --git a/apps/swift-ios/App/Platform/PlatformRootView.swift b/apps/swift-ios/App/Platform/PlatformRootView.swift index 1e310367e5..98150c3577 100644 --- a/apps/swift-ios/App/Platform/PlatformRootView.swift +++ b/apps/swift-ios/App/Platform/PlatformRootView.swift @@ -8,6 +8,9 @@ struct PlatformRootView: View { @State private var pendingRoute: PlatformRoute? @State private var previousThreads: [String: FeatureThread]? @State private var lastNotificationPreference: Bool? + @State private var incomingShareCoordinator = PlatformIncomingShareCoordinator() + @State private var incomingShareNeedsProject = false + @State private var importedShareProjectID: String? init(model: FeatureRootModel) { self.model = model @@ -38,8 +41,10 @@ struct PlatformRootView: View { guard !isLoading else { return } processThreadChanges() synchronizeNotificationPreference() + synchronizeCloudDelivery() consumePendingRouteIfPossible() consumeMailboxRouteIfAvailable() + refreshIncomingShares() } .onChange(of: model.homePresentationRevision) { _, _ in processThreadChanges() @@ -48,11 +53,65 @@ struct PlatformRootView: View { if phase == .active { consumeMailboxRouteIfAvailable() synchronizeNotificationPreference() + synchronizeCloudDelivery() + refreshIncomingShares() + } else if phase == .background { + PlatformBackgroundRefreshCoordinator.shared.schedule() } } .onChange(of: model.snapshot.settings.notificationsEnabled) { _, _ in synchronizeNotificationPreference() + synchronizeCloudDelivery() } + .onChange(of: model.snapshot.settings.liveActivitiesEnabled) { _, _ in + synchronizeAgentAwareness() + synchronizeCloudDelivery() + } + .onChange(of: model.snapshot.projects.map(\.id)) { _, _ in + refreshIncomingShares() + } + .sheet(item: presentedIncomingShare, onDismiss: openImportedShareDraft) { envelope in + PlatformIncomingShareDestinationSheet( + envelope: envelope, + projects: incomingShareProjects, + environments: model.snapshot.environments, + isImporting: incomingShareCoordinator.isImporting, + onCancel: incomingShareCoordinator.dismissDestination, + onSelect: importIncomingShare(into:) + ) + } + .alert("Create a project to continue", isPresented: $incomingShareNeedsProject) { + Button("Not now", role: .cancel) {} + Button("Create project") { + navigationRequest = FeatureWorkspaceNavigationRequest( + destination: .newTask(projectID: nil) + ) + } + } message: { + Text("Your share is saved. Connect an environment and create a project to finish importing it.") + } + } + + private var incomingShareProjects: [FeatureProject] { + DailyUXCreationContext.projects(in: model.snapshot).sorted { + if $0.name.localizedStandardCompare($1.name) == .orderedSame { + return $0.environmentID < $1.environmentID + } + return $0.name.localizedStandardCompare($1.name) == .orderedAscending + } + } + + private var presentedIncomingShare: Binding { + Binding( + get: { + guard !incomingShareProjects.isEmpty else { return nil } + return incomingShareCoordinator.pendingEnvelope + }, + set: { value in + guard value == nil, importedShareProjectID == nil else { return } + incomingShareCoordinator.dismissDestination() + } + ) } private var shouldShowWorkspace: Bool { @@ -123,6 +182,48 @@ struct PlatformRootView: View { } } + private func synchronizeCloudDelivery() { + guard !model.isLoading else { return } + PlatformCloudDeliveryCoordinator.shared.synchronize( + settings: model.snapshot.settings + ) + } + + private func refreshIncomingShares() { + guard !model.isLoading else { return } + let hasProjects = !incomingShareProjects.isEmpty + Task { @MainActor in + if await incomingShareCoordinator.refresh(hasProjects: hasProjects) { + incomingShareNeedsProject = true + } + } + } + + private func importIncomingShare(into project: FeatureProject) { + guard !incomingShareCoordinator.isImporting else { return } + importedShareProjectID = project.id + Task { @MainActor in + do { + try await incomingShareCoordinator.importPending(into: project) + } catch { + importedShareProjectID = nil + model.errorMessage = error.localizedDescription + } + } + } + + private func openImportedShareDraft() { + guard let projectID = importedShareProjectID else { return } + importedShareProjectID = nil + navigationRequest = FeatureWorkspaceNavigationRequest( + destination: .newTask(projectID: projectID) + ) + PlatformHapticEngine.shared.emit( + .success, + enabled: model.snapshot.settings.hapticsEnabled + ) + } + @MainActor private func consume(_ route: PlatformRoute) async { switch route { @@ -216,6 +317,7 @@ struct PlatformRootView: View { ) previousThreads = current PlatformRecentThreadStore.shared.update(from: model.snapshot.threads) + synchronizeAgentAwareness() for signal in signals { if scenePhase == .active { @@ -228,4 +330,11 @@ struct PlatformRootView: View { } } } + + private func synchronizeAgentAwareness() { + PlatformAgentAwarenessCoordinator.shared.synchronize( + snapshot: model.snapshot, + liveActivitiesEnabled: model.snapshot.settings.liveActivitiesEnabled + ) + } } diff --git a/apps/swift-ios/App/T3CodeApp.swift b/apps/swift-ios/App/T3CodeApp.swift index 0820bd6dba..cb0e53c74f 100644 --- a/apps/swift-ios/App/T3CodeApp.swift +++ b/apps/swift-ios/App/T3CodeApp.swift @@ -8,7 +8,16 @@ struct T3CodeApp: App { init() { let client = NativeFeatureClient() - _model = State(initialValue: FeatureRootModel(client: client)) + let model = FeatureRootModel(client: client) + _model = State(initialValue: model) + PlatformCloudDeliveryCoordinator.shared.install( + controller: client.t3ConnectController + ) + PlatformBackgroundRefreshCoordinator.shared.install { [weak model] in + guard let model else { return false } + await model.reload() + return !Task.isCancelled + } } var body: some Scene { diff --git a/apps/swift-ios/Extensions/Share/Info.plist b/apps/swift-ios/Extensions/Share/Info.plist new file mode 100644 index 0000000000..48b76a5d52 --- /dev/null +++ b/apps/swift-ios/Extensions/Share/Info.plist @@ -0,0 +1,27 @@ + + + + + CFBundleDisplayName + T3 Code (SwiftUI) + NSExtension + + NSExtensionAttributes + + NSExtensionActivationRule + + NSExtensionActivationSupportsImageWithMaxCount + 8 + NSExtensionActivationSupportsText + + NSExtensionActivationSupportsWebURLWithMaxCount + 1 + + + NSExtensionPointIdentifier + com.apple.share-services + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).T3ShareViewController + + + diff --git a/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift b/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift new file mode 100644 index 0000000000..28ccb0c7e2 --- /dev/null +++ b/apps/swift-ios/Extensions/Share/SharePayloadLoader.swift @@ -0,0 +1,111 @@ +import Foundation +import UniformTypeIdentifiers + +struct T3LoadedSharePayload: Sendable { + var textFragments: [String] + var images: [T3PendingShareImage] +} + +enum T3SharePayloadLoader { + static func load(from inputItems: [Any]) async -> T3LoadedSharePayload { + var textFragments: [String] = [] + var images: [T3PendingShareImage] = [] + + for case let item as NSExtensionItem in inputItems { + if let attributedText = item.attributedContentText?.string { + textFragments.append(attributedText) + } + + for provider in item.attachments ?? [] { + if images.count < T3IncomingShareStore.maximumImageCount, + let imageType = provider.registeredTypeIdentifiers.first(where: { + UTType($0)?.conforms(to: .image) == true + }), + let data = try? await loadData(from: provider, typeIdentifier: imageType) + { + images.append( + T3PendingShareImage( + data: data, + suggestedName: provider.suggestedName, + typeIdentifier: imageType + ) + ) + continue + } + + if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier), + let value = try? await loadItem( + from: provider, + typeIdentifier: UTType.url.identifier + ), + let urlText = urlString(from: value) + { + textFragments.append(urlText) + continue + } + + if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier), + let value = try? await loadItem( + from: provider, + typeIdentifier: UTType.plainText.identifier + ), + let text = textString(from: value) + { + textFragments.append(text) + } + } + } + + return T3LoadedSharePayload(textFragments: textFragments, images: images) + } + + private static func loadData( + from provider: NSItemProvider, + typeIdentifier: String + ) async throws -> Data { + try await withCheckedThrowingContinuation { continuation in + provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in + if let data { + continuation.resume(returning: data) + } else { + continuation.resume(throwing: error ?? CocoaError(.fileReadUnknown)) + } + } + } + } + + private static func loadItem( + from provider: NSItemProvider, + typeIdentifier: String + ) async throws -> NSSecureCoding { + try await withCheckedThrowingContinuation { continuation in + provider.loadItem(forTypeIdentifier: typeIdentifier) { value, error in + if let value { + continuation.resume(returning: value) + } else { + continuation.resume(throwing: error ?? CocoaError(.fileReadUnknown)) + } + } + } + } + + private static func urlString(from value: NSSecureCoding) -> String? { + if let url = value as? URL { + return url.absoluteString + } + if let text = value as? String, URL(string: text) != nil { + return text + } + return nil + } + + private static func textString(from value: NSSecureCoding) -> String? { + if let text = value as? String { + return text + } + if let attributedText = value as? NSAttributedString { + return attributedText.string + } + return nil + } +} diff --git a/apps/swift-ios/Extensions/Share/ShareViewController.swift b/apps/swift-ios/Extensions/Share/ShareViewController.swift new file mode 100644 index 0000000000..149dfbb374 --- /dev/null +++ b/apps/swift-ios/Extensions/Share/ShareViewController.swift @@ -0,0 +1,189 @@ +import SwiftUI +import UIKit + +final class T3ShareViewController: UIViewController { + private var hostingController: UIHostingController? + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .black + + let content = T3ShareExtensionView( + save: { [weak self] in + let inputItems = self?.extensionContext?.inputItems ?? [] + let payload = await T3SharePayloadLoader.load(from: inputItems) + return try await Task.detached { + try T3IncomingShareStore.write( + textFragments: payload.textFragments, + images: payload.images + ) + }.value + }, + cancel: { [weak self] in + self?.extensionContext?.cancelRequest(withError: CocoaError(.userCancelled)) + }, + complete: { [weak self] in + self?.extensionContext?.completeRequest(returningItems: nil) + } + ) + let hostingController = UIHostingController(rootView: content) + hostingController.view.backgroundColor = .black + addChild(hostingController) + hostingController.view.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(hostingController.view) + NSLayoutConstraint.activate([ + hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + hostingController.view.topAnchor.constraint(equalTo: view.topAnchor), + hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + hostingController.didMove(toParent: self) + self.hostingController = hostingController + } +} + +struct T3ShareExtensionView: View { + enum Phase: Equatable { + case ready + case saving + case saved(imageCount: Int) + case failed(message: String) + } + + let save: () async throws -> T3IncomingShareEnvelope + let cancel: () -> Void + let complete: () -> Void + + @State private var phase = Phase.ready + + var body: some View { + VStack(spacing: 0) { + HStack { + Button("Cancel", action: cancel) + .foregroundStyle(.secondary) + .disabled(isSaving) + Spacer() + Text("T3 Code") + .font(.system(size: 17, weight: .semibold)) + .foregroundStyle(.white) + Spacer() + Color.clear.frame(width: 52, height: 1) + } + .padding(.horizontal, 18) + .padding(.vertical, 15) + + Divider().overlay(.white.opacity(0.1)) + + VStack(spacing: 14) { + Image(systemName: phaseSymbol) + .font(.system(size: 32, weight: .medium)) + .foregroundStyle(phaseTint) + .accessibilityHidden(true) + Text(title) + .font(.system(size: 22, weight: .bold)) + .foregroundStyle(.white) + .multilineTextAlignment(.center) + Text(message) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .lineSpacing(3) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(.horizontal, 28) + .padding(.vertical, 24) + + Button(action: primaryAction) { + Text(primaryTitle) + .font(.system(size: 16, weight: .semibold)) + .foregroundStyle(.black) + .frame(maxWidth: .infinity) + .frame(height: 50) + .background(.white, in: RoundedRectangle(cornerRadius: 13)) + } + .buttonStyle(.plain) + .disabled(isSaving) + .opacity(isSaving ? 0.55 : 1) + .padding(.horizontal, 18) + .padding(.bottom, 18) + } + .background(Color.black.ignoresSafeArea()) + .preferredColorScheme(.dark) + } + + private var isSaving: Bool { + phase == .saving + } + + private var title: String { + switch phase { + case .ready: "Add to a new task" + case .saving: "Saving shared content" + case .saved: "Ready in T3 Code" + case .failed: "Could not add this" + } + } + + private var message: String { + switch phase { + case .ready: + "Text, links, and up to eight images will be waiting in the native composer." + case .saving: + "Keeping a durable copy so nothing gets lost." + case let .saved(imageCount): + imageCount == 0 + ? "Open T3 Code to choose a project and send it." + : "Saved \(imageCount) image\(imageCount == 1 ? "" : "s"). Open T3 Code to choose a project." + case let .failed(message): + message + } + } + + private var phaseSymbol: String { + switch phase { + case .ready: "square.and.arrow.up" + case .saving: "arrow.down.doc" + case .saved: "checkmark.circle.fill" + case .failed: "exclamationmark.triangle.fill" + } + } + + private var phaseTint: Color { + switch phase { + case .saved: Color(red: 0.43, green: 0.91, blue: 0.72) + case .failed: Color(red: 0.99, green: 0.46, blue: 0.46) + default: .white + } + } + + private var primaryTitle: String { + switch phase { + case .ready: "Add to T3 Code" + case .saving: "Saving…" + case .saved: "Done" + case .failed: "Try again" + } + } + + private func primaryAction() { + switch phase { + case .ready, .failed: + phase = .saving + Task { + do { + let envelope = try await save() + phase = .saved(imageCount: envelope.images.count) + } catch { + phase = .failed( + message: (error as? LocalizedError)?.errorDescription + ?? "The shared content could not be saved." + ) + } + } + case .saved: + complete() + case .saving: + break + } + } +} diff --git a/apps/swift-ios/Extensions/Share/T3CodeShare.entitlements b/apps/swift-ios/Extensions/Share/T3CodeShare.entitlements new file mode 100644 index 0000000000..471530405f --- /dev/null +++ b/apps/swift-ios/Extensions/Share/T3CodeShare.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.com.t3tools.t3code.swiftui + + + diff --git a/apps/swift-ios/Extensions/Shared/AgentActivityAttributes.swift b/apps/swift-ios/Extensions/Shared/AgentActivityAttributes.swift new file mode 100644 index 0000000000..c79d515534 --- /dev/null +++ b/apps/swift-ios/Extensions/Shared/AgentActivityAttributes.swift @@ -0,0 +1,119 @@ +import ActivityKit +import Foundation + +enum T3AgentActivityPhase: String, Codable, Hashable, Sendable { + case starting + case running + case waitingForApproval = "waiting_for_approval" + case waitingForInput = "waiting_for_input" + case completed + case failed + case stale + + var systemImage: String { + switch self { + case .starting: + "circle.dotted" + case .running: + "arrow.trianglehead.2.clockwise.rotate.90" + case .waitingForApproval: + "exclamationmark.circle.fill" + case .waitingForInput: + "questionmark.circle.fill" + case .completed: + "checkmark.circle.fill" + case .failed: + "xmark.octagon.fill" + case .stale: + "clock.arrow.circlepath" + } + } +} + +/// Mirrors `RelayAgentActivityAggregateRow` in packages/contracts/src/relay.ts. +struct T3RelayAgentActivityAggregateRow: Codable, Hashable, Identifiable, Sendable { + var environmentId: String + var threadId: String + var projectTitle: String + var threadTitle: String + var modelTitle: String + var phase: T3AgentActivityPhase + var status: String + var updatedAt: String + var deepLink: String + + var id: String { "\(environmentId):\(threadId)" } + + /// Generate the native query route rather than trusting a web-shaped path. + var nativeDeepLinkURL: URL? { + var components = URLComponents() + components.scheme = T3SharedContainer.urlScheme + components.host = "threads" + components.queryItems = [ + URLQueryItem(name: "environment", value: environmentId), + URLQueryItem(name: "thread", value: threadId), + ] + return components.url + } +} + +/// Mirrors `RelayAgentActivityAggregateState` in packages/contracts/src/relay.ts. +struct T3RelayAgentActivityAggregateState: Codable, Hashable, Sendable { + var title: String + var subtitle: String + var activeCount: Int + var updatedAt: String + var activities: [T3RelayAgentActivityAggregateRow] + + var attentionFirstActivities: [T3RelayAgentActivityAggregateRow] { + activities.sorted { left, right in + let leftPriority = left.phase.presentationPriority + let rightPriority = right.phase.presentationPriority + return leftPriority == rightPriority + ? left.updatedAt > right.updatedAt + : leftPriority < rightPriority + } + } +} + +/// This exact type and state envelope are part of the relay/APNs protocol. +/// The relay sends `attributes-type: LiveActivityAttributes`, empty attributes, +/// and `{ name: "AgentActivity", props: "" }` as content state. +struct LiveActivityAttributes: ActivityAttributes, Hashable { + struct ContentState: Codable, Hashable, Sendable { + var name: String + var props: String + + var aggregate: T3RelayAgentActivityAggregateState? { + guard name == LiveActivityAttributes.activityName, + let data = props.data(using: .utf8) + else { + return nil + } + return try? JSONDecoder().decode(T3RelayAgentActivityAggregateState.self, from: data) + } + + init(name: String, props: String) { + self.name = name + self.props = props + } + + init(aggregate: T3RelayAgentActivityAggregateState) throws { + name = LiveActivityAttributes.activityName + props = String(decoding: try JSONEncoder().encode(aggregate), as: UTF8.self) + } + } + + static let activityName = "AgentActivity" +} + +extension T3AgentActivityPhase { + fileprivate var presentationPriority: Int { + switch self { + case .waitingForApproval, .waitingForInput: 0 + case .failed: 1 + case .starting, .running: 2 + case .completed, .stale: 3 + } + } +} diff --git a/apps/swift-ios/Extensions/Shared/ShareInbox.swift b/apps/swift-ios/Extensions/Shared/ShareInbox.swift new file mode 100644 index 0000000000..af6b51dc85 --- /dev/null +++ b/apps/swift-ios/Extensions/Shared/ShareInbox.swift @@ -0,0 +1,215 @@ +import Foundation + +struct T3IncomingShareImage: Codable, Hashable, Identifiable, Sendable { + var id: String + var fileName: String + var typeIdentifier: String + var relativePath: String + var byteCount: Int +} + +struct T3IncomingShareEnvelope: Codable, Hashable, Identifiable, Sendable { + static let schemaVersion = 1 + + var schemaVersion: Int + var id: String + var createdAt: Date + var text: String + var images: [T3IncomingShareImage] + var warnings: [String] +} + +struct T3PendingShareImage: Sendable { + var data: Data + var suggestedName: String? + var typeIdentifier: String +} + +enum T3IncomingShareStoreError: LocalizedError { + case appGroupUnavailable + case noSupportedContent + + var errorDescription: String? { + switch self { + case .appGroupUnavailable: + "T3 Code could not access its shared inbox." + case .noSupportedContent: + "This app did not provide text, a URL, or a supported image." + } + } +} + +/// A crash-safe handoff from the short-lived share extension to the host app. +/// Each share gets its own UUID directory and an atomically-written manifest. +enum T3IncomingShareStore { + static let inboxRelativePath = "Library/Application Support/T3Code/IncomingShares" + static let manifestFileName = "manifest.json" + static let maximumImageCount = 8 + static let maximumImageBytes = 10 * 1_024 * 1_024 + + static func write( + textFragments: [String], + images: [T3PendingShareImage], + now: Date = Date(), + id: String = UUID().uuidString.lowercased() + ) throws -> T3IncomingShareEnvelope { + guard let containerURL = T3SharedContainer.rootURL else { + throw T3IncomingShareStoreError.appGroupUnavailable + } + + let normalizedText = deduplicatedText(textFragments) + let itemDirectory = containerURL + .appending(path: inboxRelativePath, directoryHint: .isDirectory) + .appending(path: id, directoryHint: .isDirectory) + var warnings: [String] = [] + var savedImages: [T3IncomingShareImage] = [] + + do { + try FileManager.default.createDirectory( + at: itemDirectory, + withIntermediateDirectories: true + ) + + for (index, image) in images.prefix(maximumImageCount).enumerated() { + guard !image.data.isEmpty, image.data.count <= maximumImageBytes else { + warnings.append("One shared image exceeded the 10 MB attachment limit.") + continue + } + + let attachmentID = UUID().uuidString.lowercased() + let fileName = safeFileName( + image.suggestedName, + fallback: "shared-image-\(index + 1).\(fileExtension(for: image.typeIdentifier))" + ) + let storedName = "\(attachmentID)-\(fileName)" + let fileURL = itemDirectory.appending(path: storedName, directoryHint: .notDirectory) + try image.data.write(to: fileURL, options: .atomic) + savedImages.append( + T3IncomingShareImage( + id: attachmentID, + fileName: fileName, + typeIdentifier: image.typeIdentifier, + relativePath: "\(inboxRelativePath)/\(id)/\(storedName)", + byteCount: image.data.count + ) + ) + } + + if images.count > maximumImageCount { + warnings.append("Only the first \(maximumImageCount) shared images were attached.") + } + + guard !normalizedText.isEmpty || !savedImages.isEmpty else { + throw T3IncomingShareStoreError.noSupportedContent + } + + let envelope = T3IncomingShareEnvelope( + schemaVersion: T3IncomingShareEnvelope.schemaVersion, + id: id, + createdAt: now, + text: normalizedText, + images: savedImages, + warnings: warnings + ) + let manifestURL = itemDirectory.appending( + path: manifestFileName, + directoryHint: .notDirectory + ) + try encoder.encode(envelope).write(to: manifestURL, options: .atomic) + return envelope + } catch { + try? FileManager.default.removeItem(at: itemDirectory) + throw error + } + } + + static func loadAll() -> [T3IncomingShareEnvelope] { + guard let containerURL = T3SharedContainer.rootURL else { return [] } + let inboxURL = containerURL.appending(path: inboxRelativePath, directoryHint: .isDirectory) + guard let directories = try? FileManager.default.contentsOfDirectory( + at: inboxURL, + includingPropertiesForKeys: [.isDirectoryKey], + options: [.skipsHiddenFiles] + ) else { + return [] + } + + return directories.compactMap { directory in + let manifestURL = directory.appending(path: manifestFileName, directoryHint: .notDirectory) + guard let data = try? Data(contentsOf: manifestURL) else { return nil } + return try? decoder.decode(T3IncomingShareEnvelope.self, from: data) + } + .filter { $0.schemaVersion == T3IncomingShareEnvelope.schemaVersion } + .sorted { $0.createdAt < $1.createdAt } + } + + static func remove(id: String) throws { + guard let containerURL = T3SharedContainer.rootURL else { + throw T3IncomingShareStoreError.appGroupUnavailable + } + guard UUID(uuidString: id) != nil else { + throw T3IncomingShareStoreError.noSupportedContent + } + let inboxURL = containerURL + .appending(path: inboxRelativePath, directoryHint: .isDirectory) + .standardizedFileURL + let itemURL = inboxURL + .appending(path: id, directoryHint: .isDirectory) + .standardizedFileURL + guard itemURL.deletingLastPathComponent() == inboxURL else { + throw T3IncomingShareStoreError.noSupportedContent + } + guard FileManager.default.fileExists(atPath: itemURL.path) else { return } + try FileManager.default.removeItem(at: itemURL) + } + + static func fileURL(for image: T3IncomingShareImage) -> URL? { + guard let root = T3SharedContainer.rootURL?.standardizedFileURL else { return nil } + let inbox = root.appending(path: inboxRelativePath, directoryHint: .isDirectory) + .standardizedFileURL + let url = root.appending(path: image.relativePath, directoryHint: .notDirectory) + .standardizedFileURL + guard url.path.hasPrefix(inbox.path + "/") else { return nil } + return url + } + + private static func deduplicatedText(_ fragments: [String]) -> String { + var seen: Set = [] + return fragments.compactMap { fragment in + let value = fragment.trimmingCharacters(in: .whitespacesAndNewlines) + guard !value.isEmpty, seen.insert(value).inserted else { return nil } + return value + }.joined(separator: "\n\n") + } + + private static func safeFileName(_ proposed: String?, fallback: String) -> String { + let candidate = proposed?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let lastPathComponent = URL(fileURLWithPath: candidate).lastPathComponent + let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: ".-_ ")) + let sanitized = String(lastPathComponent.unicodeScalars.filter(allowed.contains)).prefix(96) + return sanitized.isEmpty ? fallback : String(sanitized) + } + + private static func fileExtension(for typeIdentifier: String) -> String { + switch typeIdentifier.lowercased() { + case "public.jpeg", "public.jpg", "image/jpeg": "jpg" + case "public.heic", "image/heic": "heic" + case "public.webp", "image/webp": "webp" + case "com.compuserve.gif", "image/gif": "gif" + default: "png" + } + } + + private static let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.sortedKeys] + return encoder + }() + + private static let decoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return decoder + }() +} diff --git a/apps/swift-ios/Extensions/Shared/SharedContainer.swift b/apps/swift-ios/Extensions/Shared/SharedContainer.swift new file mode 100644 index 0000000000..276a505671 --- /dev/null +++ b/apps/swift-ios/Extensions/Shared/SharedContainer.swift @@ -0,0 +1,12 @@ +import Foundation + +enum T3SharedContainer { + static let appGroupID = "group.com.t3tools.t3code.swiftui" + static let urlScheme = "t3code-swiftui" + + static var rootURL: URL? { + FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: appGroupID + ) + } +} diff --git a/apps/swift-ios/Extensions/Shared/T3Code.entitlements b/apps/swift-ios/Extensions/Shared/T3Code.entitlements new file mode 100644 index 0000000000..223fe3b909 --- /dev/null +++ b/apps/swift-ios/Extensions/Shared/T3Code.entitlements @@ -0,0 +1,12 @@ + + + + + aps-environment + $(APS_ENVIRONMENT) + com.apple.security.application-groups + + group.com.t3tools.t3code.swiftui + + + diff --git a/apps/swift-ios/Extensions/Shared/TaskWidgetSnapshot.swift b/apps/swift-ios/Extensions/Shared/TaskWidgetSnapshot.swift new file mode 100644 index 0000000000..22f9dd3044 --- /dev/null +++ b/apps/swift-ios/Extensions/Shared/TaskWidgetSnapshot.swift @@ -0,0 +1,47 @@ +import Foundation + +struct T3TaskWidgetSnapshot: Codable, Hashable, Sendable { + static let empty = T3TaskWidgetSnapshot(updatedAt: "", tasks: []) + + var updatedAt: String + var tasks: [T3RelayAgentActivityAggregateRow] +} + +/// The host writes one small snapshot after task-state changes; the widget only +/// performs a bounded file read when WidgetKit requests a timeline. +enum T3TaskWidgetSnapshotStore { + static let fileName = "task-widget-snapshot.json" + + static func load() -> T3TaskWidgetSnapshot { + guard let url = fileURL(), + let data = try? Data(contentsOf: url), + let snapshot = try? JSONDecoder().decode(T3TaskWidgetSnapshot.self, from: data) + else { + return .empty + } + return snapshot + } + + static func save(_ snapshot: T3TaskWidgetSnapshot) throws { + guard let url = fileURL() else { + throw CocoaError(.fileNoSuchFile) + } + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try encoder.encode(snapshot).write(to: url, options: .atomic) + } + + private static func fileURL() -> URL? { + T3SharedContainer.rootURL? + .appending(path: "Library/Application Support/T3Code", directoryHint: .isDirectory) + .appending(path: fileName, directoryHint: .notDirectory) + } + + private static let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return encoder + }() +} diff --git a/apps/swift-ios/Extensions/Tests/ExtensionContractTests.swift b/apps/swift-ios/Extensions/Tests/ExtensionContractTests.swift new file mode 100644 index 0000000000..519dde1f40 --- /dev/null +++ b/apps/swift-ios/Extensions/Tests/ExtensionContractTests.swift @@ -0,0 +1,45 @@ +import Foundation +import XCTest +@testable import T3Code + +final class ExtensionContractTests: XCTestCase { + func testLiveActivityDecodesTheRelayAPNSEnvelope() throws { + let props = #"{"title":"T3 Code","subtitle":"2 active agents, 1 needs attention","activeCount":2,"updatedAt":"2026-08-01T12:00:00.000Z","activities":[{"environmentId":"env-1","threadId":"thread-working","projectTitle":"t3code","threadTitle":"Build the native app","modelTitle":"GPT-5.6 Sol","phase":"running","status":"Working","updatedAt":"2026-08-01T12:00:00.000Z","deepLink":"/env-1/thread-working"},{"environmentId":"env-2","threadId":"thread-approval","projectTitle":"uploadthing","threadTitle":"Ship upload recovery","modelTitle":"Claude Opus 5","phase":"waiting_for_approval","status":"Approval","updatedAt":"2026-08-01T11:59:00.000Z","deepLink":"/env-2/thread-approval"}]}"# + let state = LiveActivityAttributes.ContentState( + name: "AgentActivity", + props: props + ) + + let aggregate = try XCTUnwrap(state.aggregate) + XCTAssertEqual(aggregate.activeCount, 2) + XCTAssertEqual(aggregate.activities.count, 2) + XCTAssertEqual(aggregate.attentionFirstActivities.first?.threadId, "thread-approval") + XCTAssertEqual( + aggregate.attentionFirstActivities.first?.nativeDeepLinkURL?.absoluteString, + "t3code-swiftui://threads?environment=env-2&thread=thread-approval" + ) + } + + func testLocalLiveActivityStatePreservesTheExactNameAndPropsKeys() throws { + let aggregate = T3RelayAgentActivityAggregateState( + title: "T3 Code", + subtitle: "1 active agent", + activeCount: 1, + updatedAt: "2026-08-01T12:00:00.000Z", + activities: [] + ) + let state = try LiveActivityAttributes.ContentState(aggregate: aggregate) + let encoded = try XCTUnwrap( + JSONSerialization.jsonObject(with: JSONEncoder().encode(state)) as? [String: Any] + ) + + XCTAssertEqual(Set(encoded.keys), Set(["name", "props"])) + XCTAssertEqual(encoded["name"] as? String, "AgentActivity") + XCTAssertEqual(state.aggregate, aggregate) + } + + func testUnexpectedActivityNamesNeverDecodeAsAgentState() { + let state = LiveActivityAttributes.ContentState(name: "Other", props: "{}") + XCTAssertNil(state.aggregate) + } +} diff --git a/apps/swift-ios/Extensions/Widgets/AgentActivityWidget.swift b/apps/swift-ios/Extensions/Widgets/AgentActivityWidget.swift new file mode 100644 index 0000000000..e1e5293af5 --- /dev/null +++ b/apps/swift-ios/Extensions/Widgets/AgentActivityWidget.swift @@ -0,0 +1,180 @@ +import ActivityKit +import SwiftUI +import WidgetKit + +struct T3TaskLiveActivity: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: LiveActivityAttributes.self) { context in + T3LiveActivityLockScreenView(context: context) + .activityBackgroundTint(.black) + .activitySystemActionForegroundColor(.white) + .widgetURL(T3ActivityPresentation(state: context.state).deepLinkURL) + } dynamicIsland: { context in + let presentation = T3ActivityPresentation(state: context.state) + return DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + Text("T3") + .font(.system(size: 14, weight: .black, design: .rounded)) + .foregroundStyle(presentation.tint) + .padding(.leading, 4) + } + + DynamicIslandExpandedRegion(.trailing) { + Label(presentation.shortStatus, systemImage: presentation.phase.systemImage) + .font(.caption.weight(.semibold)) + .foregroundStyle(presentation.tint) + .lineLimit(1) + .padding(.trailing, 4) + } + + DynamicIslandExpandedRegion(.bottom) { + VStack(alignment: .leading, spacing: 5) { + ForEach(presentation.rows.prefix(3)) { row in + T3LiveActivityRow(row: row) + } + if presentation.rows.isEmpty { + Text(presentation.subtitle) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(2) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 8) + .padding(.bottom, 2) + } + } compactLeading: { + Text("T3") + .font(.system(size: 11, weight: .black, design: .rounded)) + .foregroundStyle(presentation.tint) + } compactTrailing: { + Image(systemName: presentation.phase.systemImage) + .foregroundStyle(presentation.tint) + } minimal: { + Image(systemName: presentation.phase.systemImage) + .foregroundStyle(presentation.tint) + } + .widgetURL(presentation.deepLinkURL) + .keylineTint(presentation.tint) + } + } +} + +private struct T3LiveActivityLockScreenView: View { + let context: ActivityViewContext + + private var presentation: T3ActivityPresentation { + T3ActivityPresentation(state: context.state) + } + + var body: some View { + VStack(alignment: .leading, spacing: 9) { + HStack(spacing: 8) { + Text("T3 Code") + .font(.system(size: 14, weight: .bold)) + .foregroundStyle(.white) + Spacer(minLength: 8) + Label(presentation.shortStatus, systemImage: presentation.phase.systemImage) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(presentation.tint) + .lineLimit(1) + } + + if presentation.rows.isEmpty { + Text(presentation.subtitle) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(2) + } else { + ForEach(presentation.rows.prefix(4)) { row in + T3LiveActivityRow(row: row) + } + } + } + .padding(15) + } +} + +private struct T3LiveActivityRow: View { + let row: T3RelayAgentActivityAggregateRow + + var body: some View { + HStack(spacing: 7) { + Image(systemName: row.phase.systemImage) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(row.phase.tint) + .frame(width: 14) + Text(row.threadTitle) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white) + .lineLimit(1) + Text(row.projectTitle) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + Spacer(minLength: 6) + Text(row.status) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(row.phase.tint) + .lineLimit(1) + } + } +} + +private struct T3ActivityPresentation { + let aggregate: T3RelayAgentActivityAggregateState? + + init(state: LiveActivityAttributes.ContentState) { + aggregate = state.aggregate + } + + var rows: [T3RelayAgentActivityAggregateRow] { + aggregate?.attentionFirstActivities ?? [] + } + + var phase: T3AgentActivityPhase { + rows.first?.phase ?? .stale + } + + var tint: Color { phase.tint } + + var shortStatus: String { + if let row = rows.first(where: { + $0.phase == .waitingForApproval || $0.phase == .waitingForInput + }) { + return row.phase == .waitingForApproval ? "Approval" : "Input" + } + guard let aggregate else { return "Updating" } + if aggregate.activeCount > 0 { + return "\(aggregate.activeCount) active" + } + return rows.contains(where: { $0.phase == .failed }) ? "Failed" : "Done" + } + + var subtitle: String { + aggregate?.subtitle ?? "Waiting for the latest task status." + } + + var deepLinkURL: URL? { + rows.first?.nativeDeepLinkURL + } +} + +extension T3AgentActivityPhase { + var tint: Color { + switch self { + case .starting, .running: + Color(red: 0.22, green: 0.75, blue: 0.98) + case .waitingForApproval: + Color(red: 0.99, green: 0.78, blue: 0.22) + case .waitingForInput: + Color(red: 0.65, green: 0.69, blue: 0.99) + case .completed: + Color(red: 0.43, green: 0.91, blue: 0.72) + case .failed: + Color(red: 0.99, green: 0.46, blue: 0.46) + case .stale: + Color.secondary + } + } +} diff --git a/apps/swift-ios/Extensions/Widgets/Info.plist b/apps/swift-ios/Extensions/Widgets/Info.plist new file mode 100644 index 0000000000..9a6f063b27 --- /dev/null +++ b/apps/swift-ios/Extensions/Widgets/Info.plist @@ -0,0 +1,13 @@ + + + + + CFBundleDisplayName + T3 Code Widgets + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/apps/swift-ios/Extensions/Widgets/RecentTasksWidget.swift b/apps/swift-ios/Extensions/Widgets/RecentTasksWidget.swift new file mode 100644 index 0000000000..82e1795b22 --- /dev/null +++ b/apps/swift-ios/Extensions/Widgets/RecentTasksWidget.swift @@ -0,0 +1,224 @@ +import SwiftUI +import WidgetKit + +private struct T3TaskWidgetEntry: TimelineEntry { + var date: Date + var snapshot: T3TaskWidgetSnapshot +} + +private struct T3TaskWidgetProvider: TimelineProvider { + func placeholder(in _: Context) -> T3TaskWidgetEntry { + T3TaskWidgetEntry(date: Date(), snapshot: .preview) + } + + func getSnapshot(in context: Context, completion: @escaping (T3TaskWidgetEntry) -> Void) { + let snapshot = context.isPreview ? T3TaskWidgetSnapshot.preview : T3TaskWidgetSnapshotStore.load() + completion(T3TaskWidgetEntry(date: Date(), snapshot: snapshot)) + } + + func getTimeline(in _: Context, completion: @escaping (Timeline) -> Void) { + let now = Date() + let entry = T3TaskWidgetEntry(date: now, snapshot: T3TaskWidgetSnapshotStore.load()) + completion(Timeline(entries: [entry], policy: .after(now.addingTimeInterval(15 * 60)))) + } +} + +struct T3RecentTasksWidget: Widget { + private let kind = "T3RecentTasksWidget" + + var body: some WidgetConfiguration { + StaticConfiguration(kind: kind, provider: T3TaskWidgetProvider()) { entry in + T3TaskWidgetView(entry: entry) + .containerBackground(.black, for: .widget) + } + .configurationDisplayName("T3 Code Tasks") + .description("See active and recent T3 Code tasks at a glance.") + .supportedFamilies([.systemSmall, .systemMedium, .accessoryRectangular]) + } +} + +private struct T3TaskWidgetView: View { + @Environment(\.widgetFamily) private var family + let entry: T3TaskWidgetEntry + + var body: some View { + switch family { + case .systemMedium: + mediumView + case .accessoryRectangular: + accessoryView + default: + smallView + } + } + + private var orderedTasks: [T3RelayAgentActivityAggregateRow] { + entry.snapshot.tasks.sorted { left, right in + let leftPriority = left.phase.widgetPriority + let rightPriority = right.phase.widgetPriority + return leftPriority == rightPriority + ? left.updatedAt > right.updatedAt + : leftPriority < rightPriority + } + } + + private var smallView: some View { + VStack(alignment: .leading, spacing: 8) { + header + Spacer(minLength: 0) + if let task = orderedTasks.first { + Link(destination: task.nativeDeepLinkURL ?? T3WidgetURLs.newTask) { + VStack(alignment: .leading, spacing: 5) { + Label(task.status, systemImage: task.phase.systemImage) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(task.phase.tint) + .lineLimit(1) + Text(task.threadTitle) + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.white) + .lineLimit(2) + Text(task.projectTitle) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + } else { + emptyState + } + } + .widgetURL(orderedTasks.first?.nativeDeepLinkURL ?? T3WidgetURLs.newTask) + } + + private var mediumView: some View { + VStack(alignment: .leading, spacing: 8) { + header + if orderedTasks.isEmpty { + Spacer(minLength: 0) + emptyState + Spacer(minLength: 0) + } else { + ForEach(Array(orderedTasks.prefix(3).enumerated()), id: \.element.id) { index, task in + Link(destination: task.nativeDeepLinkURL ?? T3WidgetURLs.newTask) { + HStack(spacing: 8) { + Image(systemName: task.phase.systemImage) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(task.phase.tint) + .frame(width: 15) + VStack(alignment: .leading, spacing: 1) { + Text(task.threadTitle) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white) + .lineLimit(1) + Text(task.projectTitle) + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 6) + Text(task.status) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(task.phase.tint) + .lineLimit(1) + } + } + if index < min(orderedTasks.count, 3) - 1 { + Divider().overlay(.white.opacity(0.1)) + } + } + } + } + } + + private var accessoryView: some View { + Group { + if let task = orderedTasks.first { + VStack(alignment: .leading, spacing: 2) { + Label(task.status, systemImage: task.phase.systemImage) + .font(.caption.weight(.semibold)) + Text(task.threadTitle) + .font(.caption2.weight(.medium)) + .lineLimit(1) + } + } else { + Label("New task", systemImage: "square.and.pencil") + .font(.caption.weight(.semibold)) + } + } + .widgetURL(orderedTasks.first?.nativeDeepLinkURL ?? T3WidgetURLs.newTask) + } + + private var header: some View { + HStack(spacing: 6) { + Text("T3") + .font(.system(size: 14, weight: .black, design: .rounded)) + .foregroundStyle(.white) + Text("Code") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.secondary) + Spacer(minLength: 6) + Link(destination: T3WidgetURLs.newTask) { + Image(systemName: "square.and.pencil") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white) + } + .accessibilityLabel("New task") + } + } + + private var emptyState: some View { + VStack(alignment: .leading, spacing: 4) { + Text("Ready for a task") + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(.white) + Text("Tap to start in T3 Code") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + } + } +} + +private enum T3WidgetURLs { + static let newTask = URL(string: "t3code-swiftui://new-task")! +} + +private extension T3AgentActivityPhase { + var widgetPriority: Int { + switch self { + case .waitingForApproval, .waitingForInput: 0 + case .failed: 1 + case .starting, .running: 2 + case .completed, .stale: 3 + } + } +} + +private extension T3TaskWidgetSnapshot { + static let preview = T3TaskWidgetSnapshot( + updatedAt: "2026-08-01T12:00:00.000Z", + tasks: [ + T3RelayAgentActivityAggregateRow( + environmentId: "preview", + threadId: "one", + projectTitle: "t3code", + threadTitle: "Polish native task list", + modelTitle: "GPT-5.6 Sol", + phase: .running, + status: "Working", + updatedAt: "2026-08-01T12:00:00.000Z", + deepLink: "/preview/one" + ), + T3RelayAgentActivityAggregateRow( + environmentId: "preview", + threadId: "two", + projectTitle: "uploadthing", + threadTitle: "Review multipart recovery", + modelTitle: "Claude Opus 5", + phase: .waitingForApproval, + status: "Approval", + updatedAt: "2026-08-01T11:59:00.000Z", + deepLink: "/preview/two" + ), + ] + ) +} diff --git a/apps/swift-ios/Extensions/Widgets/T3CodeWidgets.entitlements b/apps/swift-ios/Extensions/Widgets/T3CodeWidgets.entitlements new file mode 100644 index 0000000000..471530405f --- /dev/null +++ b/apps/swift-ios/Extensions/Widgets/T3CodeWidgets.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.com.t3tools.t3code.swiftui + + + diff --git a/apps/swift-ios/Extensions/Widgets/T3CodeWidgets.swift b/apps/swift-ios/Extensions/Widgets/T3CodeWidgets.swift new file mode 100644 index 0000000000..4b4564bf93 --- /dev/null +++ b/apps/swift-ios/Extensions/Widgets/T3CodeWidgets.swift @@ -0,0 +1,10 @@ +import SwiftUI +import WidgetKit + +@main +struct T3CodeWidgetBundle: WidgetBundle { + var body: some Widget { + T3TaskLiveActivity() + T3RecentTasksWidget() + } +} diff --git a/apps/swift-ios/Features/Connection/ConnectionDetails.swift b/apps/swift-ios/Features/Connection/ConnectionDetails.swift index de2f3c1546..d4ecff1a22 100644 --- a/apps/swift-ios/Features/Connection/ConnectionDetails.swift +++ b/apps/swift-ios/Features/Connection/ConnectionDetails.swift @@ -118,7 +118,7 @@ enum ConnectionDetailsParser { let allItems = queryItems + fragmentItems let token = firstValue(named: tokenNames, in: allItems) - if ["t3", "t3code"].contains(scheme) { + if ["t3", "t3code", "t3code-swiftui"].contains(scheme) { if let wrappedPairingURL = firstValue(named: wrappedPairingURLNames, in: allItems) { var wrapped = try parse(wrappedPairingURL) if wrapped.pairingCode == nil { @@ -159,7 +159,7 @@ enum ConnectionDetailsParser { private static func firstURL(in input: String) -> String? { guard let expression = try? NSRegularExpression( - pattern: #"(?i)(?:(?:https?|wss?|t3)://|t3code:(?://)?)[^\s<>"']+"# + pattern: #"(?i)(?:(?:https?|wss?|t3)://|t3code(?:-swiftui)?:(?://)?)[^\s<>"']+"# ) else { return nil } diff --git a/apps/swift-ios/Features/Settings/SettingsView.swift b/apps/swift-ios/Features/Settings/SettingsView.swift index 9e1773d57c..2d356bd76d 100644 --- a/apps/swift-ios/Features/Settings/SettingsView.swift +++ b/apps/swift-ios/Features/Settings/SettingsView.swift @@ -219,6 +219,7 @@ public struct SettingsView: View { } Toggle("Haptics", isOn: $settings.hapticsEnabled) Toggle("Notifications", isOn: $settings.notificationsEnabled) + Toggle("Live Activities", isOn: $settings.liveActivitiesEnabled) } } diff --git a/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift b/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift index d5db31039f..00fe5387fa 100644 --- a/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift +++ b/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift @@ -42,6 +42,19 @@ public struct FeatureComposerWorkspaceDraft: Sendable, Equatable { } } +public enum FeatureComposerDraftImportError: LocalizedError, Equatable, Sendable { + case attachmentLimitExceeded(available: Int) + + public var errorDescription: String? { + switch self { + case let .attachmentLimitExceeded(available): + available == 0 + ? "This draft already has eight attachments. Remove one before importing the share." + : "This share needs more attachment slots. The current draft has room for \(available)." + } + } +} + /// Persists composer state independently of view navigation. Draft writes are /// atomic, and callers debounce high-frequency text changes before reaching /// this actor so image data is not repeatedly encoded for every keystroke. @@ -59,12 +72,14 @@ public actor FeatureComposerDraftStore { var attachments: [PersistedAttachment] var selection: FeatureSelection? var workspace: PersistedWorkspace? + var importedShareIDs: [String]? init(_ draft: FeatureComposerDraft) { text = draft.text attachments = draft.attachments.map(PersistedAttachment.init) selection = draft.selection workspace = draft.workspace.map(PersistedWorkspace.init) + importedShareIDs = nil } var featureValue: FeatureComposerDraft { @@ -152,12 +167,58 @@ public actor FeatureComposerDraftStore { if draft.isEmpty { drafts.removeValue(forKey: key) } else { - drafts[key] = PersistedDraft(draft) + var persisted = PersistedDraft(draft) + // Preserve the crash-replay ledger while the composer performs its + // ordinary debounced saves after opening an imported share. + persisted.importedShareIDs = drafts[key]?.importedShareIDs + drafts[key] = persisted } try persist(drafts) loadedDrafts = drafts } + /// Atomically imports one share-extension envelope into the latest stored + /// draft. The share ID is committed with the content, so a host crash after + /// this write but before inbox cleanup cannot duplicate the import. + @discardableResult + public func importSharedContent( + shareID: String, + text: String, + attachments: [FeatureDraftAttachment], + for key: String, + maximumAttachmentCount: Int = 8 + ) throws -> FeatureComposerDraft { + var drafts = try loadIfNeeded() + var persisted = drafts[key] ?? PersistedDraft(FeatureComposerDraft()) + var importedIDs = persisted.importedShareIDs ?? [] + guard !importedIDs.contains(shareID) else { return persisted.featureValue } + + let existingIDs = Set(persisted.attachments.map(\.id)) + let uniqueAttachments = attachments.filter { !existingIDs.contains($0.id) } + let availableCount = max(0, maximumAttachmentCount - persisted.attachments.count) + guard uniqueAttachments.count <= availableCount else { + throw FeatureComposerDraftImportError.attachmentLimitExceeded( + available: availableCount + ) + } + + let incomingText = text.trimmingCharacters(in: .whitespacesAndNewlines) + if !incomingText.isEmpty { + persisted.text = persisted.text.trimmingCharacters(in: .whitespacesAndNewlines) + persisted.text = persisted.text.isEmpty + ? incomingText + : "\(persisted.text)\n\n\(incomingText)" + } + + persisted.attachments.append(contentsOf: uniqueAttachments.map(PersistedAttachment.init)) + importedIDs.append(shareID) + persisted.importedShareIDs = Array(importedIDs.suffix(32)) + drafts[key] = persisted + try persist(drafts) + loadedDrafts = drafts + return persisted.featureValue + } + public func removeDraft(for key: String) throws { var drafts = try loadIfNeeded() guard drafts.removeValue(forKey: key) != nil else { return } diff --git a/apps/swift-ios/Features/Shared/FeatureModels.swift b/apps/swift-ios/Features/Shared/FeatureModels.swift index c3ef22cd08..dec73000e1 100644 --- a/apps/swift-ios/Features/Shared/FeatureModels.swift +++ b/apps/swift-ios/Features/Shared/FeatureModels.swift @@ -673,19 +673,63 @@ public struct FeatureSettings: Sendable, Equatable, Codable { public var appearance: FeatureAppearance public var hapticsEnabled: Bool public var notificationsEnabled: Bool + public var liveActivitiesEnabled: Bool public var defaultSelection: FeatureSelection? public init( appearance: FeatureAppearance = .dark, hapticsEnabled: Bool = true, notificationsEnabled: Bool = true, + liveActivitiesEnabled: Bool = true, defaultSelection: FeatureSelection? = nil ) { self.appearance = appearance self.hapticsEnabled = hapticsEnabled self.notificationsEnabled = notificationsEnabled + self.liveActivitiesEnabled = liveActivitiesEnabled self.defaultSelection = defaultSelection } + + private enum CodingKeys: String, CodingKey { + case appearance + case hapticsEnabled + case notificationsEnabled + case liveActivitiesEnabled + case defaultSelection + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + appearance = try container.decodeIfPresent( + FeatureAppearance.self, + forKey: .appearance + ) ?? .dark + hapticsEnabled = try container.decodeIfPresent( + Bool.self, + forKey: .hapticsEnabled + ) ?? true + notificationsEnabled = try container.decodeIfPresent( + Bool.self, + forKey: .notificationsEnabled + ) ?? true + liveActivitiesEnabled = try container.decodeIfPresent( + Bool.self, + forKey: .liveActivitiesEnabled + ) ?? true + defaultSelection = try container.decodeIfPresent( + FeatureSelection.self, + forKey: .defaultSelection + ) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(appearance, forKey: .appearance) + try container.encode(hapticsEnabled, forKey: .hapticsEnabled) + try container.encode(notificationsEnabled, forKey: .notificationsEnabled) + try container.encode(liveActivitiesEnabled, forKey: .liveActivitiesEnabled) + try container.encodeIfPresent(defaultSelection, forKey: .defaultSelection) + } } public struct FeatureEnvironmentPreferences: Sendable, Equatable, Codable { diff --git a/apps/swift-ios/README.md b/apps/swift-ios/README.md index 09ad203bb7..ef763e03b3 100644 --- a/apps/swift-ios/README.md +++ b/apps/swift-ios/README.md @@ -51,7 +51,11 @@ the active selection are stored separately in Application Support. - Workspace files and previews, working-tree review, Git status and common actions, plus an interactive terminal session scoped to each thread. - Native settings with persisted appearance and behavior preferences, platform - deep links, shortcuts, and local notification routing. + deep links, shortcuts, background refresh, and notification routing. +- A Share extension that imports text, URLs, and images into persistent project + drafts, plus Home Screen widgets and aggregate Live Activities for active work. +- DPoP-bound T3 Connect sessions with account-scoped relay credentials, APNs + device registration on iOS 18+, and automatic credential recovery. The app speaks the existing HTTP and Effect RPC WebSocket contracts directly. It does not embed a JavaScript runtime. @@ -117,9 +121,9 @@ Connect build settings above as environment variables. Optional overrides are 4. Smoke-test direct URL and QR pairing, T3 Connect, multi-environment navigation, task creation, follow-up messages, attachments, approvals, input requests, background/reconnect behavior, and deep links on an iPhone and iPad. -5. If remote push is shipping, add the APNs entitlement and matching provisioning - before archiving, then verify device-token registration end to end. Local - notifications do not require that entitlement. +5. Confirm the host, widget, and share-extension identifiers have App Group + provisioning, and the host has Push Notifications provisioning. Verify APNs + device registration and Share-extension handoff end to end. 6. Archive the `T3Code` scheme in Release, run Xcode's Validate App and privacy report, and confirm `PrivacyInfo.xcprivacy` is bundled. Re-audit the manifest whenever code adds a Required Reason API or data collection. diff --git a/apps/swift-ios/Resources/Info.plist b/apps/swift-ios/Resources/Info.plist index 626a017033..080b3d57d2 100644 --- a/apps/swift-ios/Resources/Info.plist +++ b/apps/swift-ios/Resources/Info.plist @@ -2,6 +2,10 @@ + BGTaskSchedulerPermittedIdentifiers + + $(PRODUCT_BUNDLE_IDENTIFIER).refresh + CFBundleURLTypes @@ -11,8 +15,7 @@ T3 Code SwiftUI Routes CFBundleURLSchemes - t3code - t3 + t3code-swiftui @@ -22,5 +25,10 @@ $(T3CODE_CLERK_PUBLISHABLE_KEY) T3ConnectRelayHTTPURL $(T3CODE_RELAY_URL) + UIBackgroundModes + + fetch + remote-notification + diff --git a/apps/swift-ios/T3Code.xcodeproj/project.pbxproj b/apps/swift-ios/T3Code.xcodeproj/project.pbxproj index ffff93ad16..8d7bf13f21 100644 --- a/apps/swift-ios/T3Code.xcodeproj/project.pbxproj +++ b/apps/swift-ios/T3Code.xcodeproj/project.pbxproj @@ -8,8 +8,40 @@ /* Begin PBXBuildFile section */ B10000000000000000000001 /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = B30000000000000000000001 /* ClerkKit */; }; + C10000000000000000000001 /* AgentActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000001 /* AgentActivityAttributes.swift */; }; + C10000000000000000000002 /* SharedContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000002 /* SharedContainer.swift */; }; + C10000000000000000000003 /* TaskWidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000003 /* TaskWidgetSnapshot.swift */; }; + C10000000000000000000004 /* ShareInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000004 /* ShareInbox.swift */; }; + C10000000000000000000005 /* AgentActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000001 /* AgentActivityAttributes.swift */; }; + C10000000000000000000006 /* SharedContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000002 /* SharedContainer.swift */; }; + C10000000000000000000007 /* TaskWidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000003 /* TaskWidgetSnapshot.swift */; }; + C10000000000000000000008 /* T3CodeWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000006 /* T3CodeWidgets.swift */; }; + C10000000000000000000009 /* AgentActivityWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000007 /* AgentActivityWidget.swift */; }; + C1000000000000000000000A /* RecentTasksWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000008 /* RecentTasksWidget.swift */; }; + C1000000000000000000000B /* SharedContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000002 /* SharedContainer.swift */; }; + C1000000000000000000000C /* ShareInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000004 /* ShareInbox.swift */; }; + C1000000000000000000000D /* SharePayloadLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4000000000000000000000B /* SharePayloadLoader.swift */; }; + C1000000000000000000000E /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4000000000000000000000C /* ShareViewController.swift */; }; + C1000000000000000000000F /* T3CodeWidgets.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = C4000000000000000000000F /* T3CodeWidgets.appex */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + C10000000000000000000010 /* T3CodeShare.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = C40000000000000000000010 /* T3CodeShare.appex */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + C10000000000000000000011 /* ExtensionContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40000000000000000000011 /* ExtensionContractTests.swift */; }; /* End PBXBuildFile section */ +/* Begin PBXCopyFilesBuildPhase section */ + CE0000000000000000000001 /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + C1000000000000000000000F /* T3CodeWidgets.appex in Embed App Extensions */, + C10000000000000000000010 /* T3CodeShare.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ BE0000000000000000000001 /* Exceptions for "Resources" folder in "T3Code" target */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; @@ -72,6 +104,20 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + C20000000000000000000003 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C20000000000000000000004 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXContainerItemProxy section */ @@ -82,6 +128,20 @@ remoteGlobalIDString = A50000000000000000000001; remoteInfo = T3Code; }; + CC0000000000000000000002 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A90000000000000000000001 /* Project object */; + proxyType = 1; + remoteGlobalIDString = C50000000000000000000003; + remoteInfo = T3CodeWidgets; + }; + CC0000000000000000000003 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A90000000000000000000001 /* Project object */; + proxyType = 1; + remoteGlobalIDString = C50000000000000000000004; + remoteInfo = T3CodeShare; + }; /* End PBXContainerItemProxy section */ /* Begin PBXGroup section */ @@ -94,6 +154,7 @@ A10000000000000000000004 /* DesignSystem */, A10000000000000000000005 /* Resources */, A10000000000000000000006 /* Tests */, + C30000000000000000000001 /* Extensions */, A30000000000000000000002 /* Products */, ); sourceTree = ""; @@ -103,10 +164,66 @@ children = ( A40000000000000000000001 /* T3 Code.app */, A40000000000000000000002 /* T3CodeTests.xctest */, + C4000000000000000000000F /* T3CodeWidgets.appex */, + C40000000000000000000010 /* T3CodeShare.appex */, ); name = Products; sourceTree = ""; }; + C30000000000000000000001 /* Extensions */ = { + isa = PBXGroup; + children = ( + C30000000000000000000002 /* Shared */, + C30000000000000000000003 /* Widgets */, + C30000000000000000000004 /* Share */, + C30000000000000000000005 /* Tests */, + ); + path = Extensions; + sourceTree = ""; + }; + C30000000000000000000002 /* Shared */ = { + isa = PBXGroup; + children = ( + C40000000000000000000001 /* AgentActivityAttributes.swift */, + C40000000000000000000002 /* SharedContainer.swift */, + C40000000000000000000003 /* TaskWidgetSnapshot.swift */, + C40000000000000000000004 /* ShareInbox.swift */, + C40000000000000000000005 /* T3Code.entitlements */, + ); + path = Shared; + sourceTree = ""; + }; + C30000000000000000000003 /* Widgets */ = { + isa = PBXGroup; + children = ( + C40000000000000000000006 /* T3CodeWidgets.swift */, + C40000000000000000000007 /* AgentActivityWidget.swift */, + C40000000000000000000008 /* RecentTasksWidget.swift */, + C40000000000000000000009 /* Info.plist */, + C4000000000000000000000A /* T3CodeWidgets.entitlements */, + ); + path = Widgets; + sourceTree = ""; + }; + C30000000000000000000004 /* Share */ = { + isa = PBXGroup; + children = ( + C4000000000000000000000B /* SharePayloadLoader.swift */, + C4000000000000000000000C /* ShareViewController.swift */, + C4000000000000000000000D /* Info.plist */, + C4000000000000000000000E /* T3CodeShare.entitlements */, + ); + path = Share; + sourceTree = ""; + }; + C30000000000000000000005 /* Tests */ = { + isa = PBXGroup; + children = ( + C40000000000000000000011 /* ExtensionContractTests.swift */, + ); + path = Tests; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -117,10 +234,13 @@ A70000000000000000000001 /* Sources */, A20000000000000000000001 /* Frameworks */, A80000000000000000000001 /* Resources */, + CE0000000000000000000001 /* Embed App Extensions */, ); buildRules = ( ); dependencies = ( + CD0000000000000000000002 /* PBXTargetDependency */, + CD0000000000000000000003 /* PBXTargetDependency */, ); fileSystemSynchronizedGroups = ( A10000000000000000000001 /* App */, @@ -160,6 +280,44 @@ productReference = A40000000000000000000002 /* T3CodeTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; + C50000000000000000000003 /* T3CodeWidgets */ = { + isa = PBXNativeTarget; + buildConfigurationList = C60000000000000000000004 /* Build configuration list for PBXNativeTarget "T3CodeWidgets" */; + buildPhases = ( + C70000000000000000000003 /* Sources */, + C20000000000000000000003 /* Frameworks */, + C80000000000000000000003 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = T3CodeWidgets; + packageProductDependencies = ( + ); + productName = T3CodeWidgets; + productReference = C4000000000000000000000F /* T3CodeWidgets.appex */; + productType = "com.apple.product-type.app-extension"; + }; + C50000000000000000000004 /* T3CodeShare */ = { + isa = PBXNativeTarget; + buildConfigurationList = C60000000000000000000005 /* Build configuration list for PBXNativeTarget "T3CodeShare" */; + buildPhases = ( + C70000000000000000000004 /* Sources */, + C20000000000000000000004 /* Frameworks */, + C80000000000000000000004 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = T3CodeShare; + packageProductDependencies = ( + ); + productName = T3CodeShare; + productReference = C40000000000000000000010 /* T3CodeShare.appex */; + productType = "com.apple.product-type.app-extension"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -172,11 +330,35 @@ TargetAttributes = { A50000000000000000000001 = { CreatedOnToolsVersion = 16.0; + SystemCapabilities = { + com.apple.ApplicationGroups.iOS = { + enabled = 1; + }; + com.apple.Push = { + enabled = 1; + }; + }; }; A50000000000000000000002 = { CreatedOnToolsVersion = 16.0; TestTargetID = A50000000000000000000001; }; + C50000000000000000000003 = { + CreatedOnToolsVersion = 16.0; + SystemCapabilities = { + com.apple.ApplicationGroups.iOS = { + enabled = 1; + }; + }; + }; + C50000000000000000000004 = { + CreatedOnToolsVersion = 16.0; + SystemCapabilities = { + com.apple.ApplicationGroups.iOS = { + enabled = 1; + }; + }; + }; }; }; buildConfigurationList = A60000000000000000000001 /* Build configuration list for PBXProject "T3Code" */; @@ -199,6 +381,8 @@ targets = ( A50000000000000000000001 /* T3Code */, A50000000000000000000002 /* T3CodeTests */, + C50000000000000000000003 /* T3CodeWidgets */, + C50000000000000000000004 /* T3CodeShare */, ); }; /* End PBXProject section */ @@ -218,6 +402,20 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + C80000000000000000000003 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C80000000000000000000004 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -225,6 +423,10 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + C10000000000000000000001 /* AgentActivityAttributes.swift in Sources */, + C10000000000000000000002 /* SharedContainer.swift in Sources */, + C10000000000000000000003 /* TaskWidgetSnapshot.swift in Sources */, + C10000000000000000000004 /* ShareInbox.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -232,6 +434,31 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + C10000000000000000000011 /* ExtensionContractTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C70000000000000000000003 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C10000000000000000000005 /* AgentActivityAttributes.swift in Sources */, + C10000000000000000000006 /* SharedContainer.swift in Sources */, + C10000000000000000000007 /* TaskWidgetSnapshot.swift in Sources */, + C10000000000000000000008 /* T3CodeWidgets.swift in Sources */, + C10000000000000000000009 /* AgentActivityWidget.swift in Sources */, + C1000000000000000000000A /* RecentTasksWidget.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C70000000000000000000004 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C1000000000000000000000B /* SharedContainer.swift in Sources */, + C1000000000000000000000C /* ShareInbox.swift in Sources */, + C1000000000000000000000D /* SharePayloadLoader.swift in Sources */, + C1000000000000000000000E /* ShareViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -243,6 +470,16 @@ target = A50000000000000000000001 /* T3Code */; targetProxy = AC0000000000000000000001 /* PBXContainerItemProxy */; }; + CD0000000000000000000002 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = C50000000000000000000003 /* T3CodeWidgets */; + targetProxy = CC0000000000000000000002 /* PBXContainerItemProxy */; + }; + CD0000000000000000000003 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = C50000000000000000000004 /* T3CodeShare */; + targetProxy = CC0000000000000000000003 /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ @@ -361,8 +598,10 @@ AB0000000000000000000003 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + APS_ENVIRONMENT = development; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = Extensions/Shared/T3Code.entitlements; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; ENABLE_PREVIEWS = YES; @@ -374,6 +613,8 @@ 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; + INFOPLIST_KEY_NSSupportsLiveActivitiesFrequentUpdates = YES; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; @@ -400,8 +641,10 @@ AB0000000000000000000004 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + APS_ENVIRONMENT = production; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = Extensions/Shared/T3Code.entitlements; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; @@ -412,6 +655,8 @@ 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; + INFOPLIST_KEY_NSSupportsLiveActivitiesFrequentUpdates = YES; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; @@ -471,6 +716,126 @@ }; name = Release; }; + CB0000000000000000000007 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_ENTITLEMENTS = Extensions/Widgets/T3CodeWidgets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Extensions/Widgets/Info.plist; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swiftui.widgets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + CB0000000000000000000008 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_ENTITLEMENTS = Extensions/Widgets/T3CodeWidgets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Extensions/Widgets/Info.plist; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swiftui.widgets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + CB0000000000000000000009 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_ENTITLEMENTS = Extensions/Share/T3CodeShare.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Extensions/Share/Info.plist; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swiftui.sharing; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + CB000000000000000000000A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_ENTITLEMENTS = Extensions/Share/T3CodeShare.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Extensions/Share/Info.plist; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.t3tools.t3code.swiftui.sharing; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -501,6 +866,24 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + C60000000000000000000004 /* Build configuration list for PBXNativeTarget "T3CodeWidgets" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CB0000000000000000000007 /* Debug */, + CB0000000000000000000008 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C60000000000000000000005 /* Build configuration list for PBXNativeTarget "T3CodeShare" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CB0000000000000000000009 /* Debug */, + CB000000000000000000000A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ @@ -537,6 +920,23 @@ path = T3CodeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + C40000000000000000000001 /* AgentActivityAttributes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActivityAttributes.swift; sourceTree = ""; }; + C40000000000000000000002 /* SharedContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedContainer.swift; sourceTree = ""; }; + C40000000000000000000003 /* TaskWidgetSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskWidgetSnapshot.swift; sourceTree = ""; }; + C40000000000000000000004 /* ShareInbox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareInbox.swift; sourceTree = ""; }; + C40000000000000000000005 /* T3Code.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = T3Code.entitlements; sourceTree = ""; }; + C40000000000000000000006 /* T3CodeWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = T3CodeWidgets.swift; sourceTree = ""; }; + C40000000000000000000007 /* AgentActivityWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActivityWidget.swift; sourceTree = ""; }; + C40000000000000000000008 /* RecentTasksWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecentTasksWidget.swift; sourceTree = ""; }; + C40000000000000000000009 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C4000000000000000000000A /* T3CodeWidgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = T3CodeWidgets.entitlements; sourceTree = ""; }; + C4000000000000000000000B /* SharePayloadLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharePayloadLoader.swift; sourceTree = ""; }; + C4000000000000000000000C /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = ""; }; + C4000000000000000000000D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C4000000000000000000000E /* T3CodeShare.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = T3CodeShare.entitlements; sourceTree = ""; }; + C4000000000000000000000F /* T3CodeWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = T3CodeWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + C40000000000000000000010 /* T3CodeShare.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = T3CodeShare.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + C40000000000000000000011 /* ExtensionContractTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExtensionContractTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ }; rootObject = A90000000000000000000001 /* Project object */; diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift new file mode 100644 index 0000000000..017c1ee807 --- /dev/null +++ b/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift @@ -0,0 +1,137 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Agent awareness projection") +struct PlatformAgentAwarenessTests { + @Test + func legacySettingsEnableLiveActivitiesWithoutResettingOtherPreferences() throws { + let legacy = Data( + #"{"appearance":"system","hapticsEnabled":false,"notificationsEnabled":false}"#.utf8 + ) + let decoded = try JSONDecoder.t3.decode(FeatureSettings.self, from: legacy) + + #expect(decoded.appearance == .system) + #expect(!decoded.hapticsEnabled) + #expect(!decoded.notificationsEnabled) + #expect(decoded.liveActivitiesEnabled) + + var disabled = decoded + disabled.liveActivitiesEnabled = false + let roundTrip = try JSONDecoder.t3.decode( + FeatureSettings.self, + from: JSONEncoder.t3.encode(disabled) + ) + #expect(!roundTrip.liveActivitiesEnabled) + } + + @Test + func ranksAttentionThenFailuresThenWorkAndDropsOldTerminalRows() throws { + let now = Date(timeIntervalSince1970: 2_000_000_000) + let project = FeatureProject( + id: "project", + wireID: "project-wire", + environmentID: "environment", + name: "t3code", + path: "/repo" + ) + let snapshot = FeatureSnapshot( + projects: [project], + threads: [ + Self.thread( + id: "working", + state: .working, + updatedAt: now.addingTimeInterval(-10) + ), + Self.thread( + id: "approval", + state: .waitingForApproval, + updatedAt: now.addingTimeInterval(-5) + ), + Self.thread( + id: "failure", + state: .failed, + updatedAt: now.addingTimeInterval(-20) + ), + Self.thread( + id: "old-complete", + state: .completed, + updatedAt: now.addingTimeInterval(-3_600) + ), + ], + providersByEnvironment: [ + "environment": [ + FeatureProvider( + id: "claude", + name: "Claude", + models: [FeatureModel(id: "claude-opus-5", name: "Opus 5")] + ), + ], + ] + ) + + let aggregate = PlatformAgentAwarenessProjection.aggregate( + snapshot: snapshot, + now: now + ) + + #expect(aggregate.activeCount == 2) + #expect(aggregate.subtitle == "1 task needs attention") + #expect(aggregate.activities.map(\.threadId) == ["approval", "failure", "working"]) + #expect(aggregate.activities.first?.modelTitle == "Opus 5") + #expect( + aggregate.activities.first?.nativeDeepLinkURL?.scheme + == PlatformRoute.nativeScheme + ) + } + + @Test + func widgetSnapshotUsesTheSameBoundedRowsAsTheLiveActivity() { + let now = Date(timeIntervalSince1970: 2_000_000_000) + let project = FeatureProject( + id: "project", + environmentID: "environment", + name: "t3code", + path: "/repo" + ) + let threads = (0..<8).map { index in + Self.thread( + id: "thread-\(index)", + state: .working, + updatedAt: now.addingTimeInterval(TimeInterval(-index)) + ) + } + let snapshot = FeatureSnapshot(projects: [project], threads: threads) + + let aggregate = PlatformAgentAwarenessProjection.aggregate( + snapshot: snapshot, + now: now + ) + let widget = PlatformAgentAwarenessProjection.widgetSnapshot( + snapshot: snapshot, + now: now + ) + + #expect(aggregate.activities.count == PlatformAgentAwarenessProjection.maximumRows) + #expect(widget.tasks == aggregate.activities) + #expect(widget.updatedAt == aggregate.updatedAt) + } + + private static func thread( + id: String, + state: FeatureThreadState, + updatedAt: Date + ) -> FeatureThread { + FeatureThread( + id: id, + wireID: id, + projectID: "project", + environmentID: "environment", + title: "Task \(id)", + updatedAt: updatedAt, + state: state, + providerID: "claude", + modelID: "claude-opus-5" + ) + } +} diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformBackgroundRefreshTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformBackgroundRefreshTests.swift new file mode 100644 index 0000000000..357a5904e9 --- /dev/null +++ b/apps/swift-ios/Tests/PlatformTests/PlatformBackgroundRefreshTests.swift @@ -0,0 +1,16 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Background refresh") +struct PlatformBackgroundRefreshTests { + @Test + @MainActor + func usesThePermittedIdentifierAndAConservativeRetryWindow() { + #expect( + PlatformBackgroundRefreshCoordinator.identifier + == "\(Bundle.main.bundleIdentifier ?? "com.t3tools.t3code.swiftui").refresh" + ) + #expect(PlatformBackgroundRefreshPolicy.minimumDelay == 15 * 60) + } +} diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformCloudDeliveryTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformCloudDeliveryTests.swift new file mode 100644 index 0000000000..7d2ea08d53 --- /dev/null +++ b/apps/swift-ios/Tests/PlatformTests/PlatformCloudDeliveryTests.swift @@ -0,0 +1,48 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Cloud delivery registration") +struct PlatformCloudDeliveryTests { + @Test + func installationIdentityIsStableWithinAnInstall() throws { + let suiteName = "cloud-delivery-\(UUID())" + let suite = try #require(UserDefaults(suiteName: suiteName)) + defer { suite.removePersistentDomain(forName: suiteName) } + + let first = PlatformInstallationIdentity.value(defaults: suite) + let second = PlatformInstallationIdentity.value(defaults: suite) + + #expect(!first.isEmpty) + #expect(first == second) + } + + @Test + func registrationCarriesRoutingAndUserPreferences() { + var settings = FeatureSettings() + settings.notificationsEnabled = false + settings.liveActivitiesEnabled = true + + let registration = PlatformCloudDeliveryRegistrationFactory.registration( + deviceID: "device-1", + deviceName: "Big O", + systemVersion: OperatingSystemVersion(majorVersion: 26, minorVersion: 0, patchVersion: 0), + appVersion: "1.2.3", + bundleID: "com.t3tools.t3code.swiftui", + pushToken: "apns-token", + pushToStartToken: "activity-token", + settings: settings, + apsEnvironment: .sandbox + ) + + #expect(registration.platform == "ios") + #expect(registration.iosMajorVersion == 26) + #expect(registration.bundleId == "com.t3tools.t3code.swiftui") + #expect(registration.apsEnvironment == .sandbox) + #expect(registration.pushToken == "apns-token") + #expect(registration.pushToStartToken == "activity-token") + #expect(!registration.preferences.notificationsEnabled) + #expect(registration.preferences.liveActivitiesEnabled) + } + +} diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift index 542a679c8a..300bc9607f 100644 --- a/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift +++ b/apps/swift-ios/Tests/PlatformTests/PlatformDeepLinkTests.swift @@ -66,10 +66,23 @@ struct PlatformDeepLinkTests { for route in routes { let url = try #require(route.url) + #expect(url.scheme == PlatformRoute.nativeScheme) #expect(try PlatformDeepLinkParser.parse(url) == route) } } + @Test + func acceptsLegacyRoutesWithoutClaimingTheirSharedSchemes() throws { + #expect( + try PlatformDeepLinkParser.parse("t3code://threads/environment/thread") + == .thread(environmentID: "environment", threadID: "thread") + ) + #expect( + try PlatformDeepLinkParser.parse("t3://threads/environment/thread") + == .thread(environmentID: "environment", threadID: "thread") + ) + } + @Test func mailboxConsumesExactlyOnce() throws { let suiteName = "PlatformDeepLinkTests.\(UUID().uuidString)" diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformIncomingShareTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformIncomingShareTests.swift new file mode 100644 index 0000000000..bdff310345 --- /dev/null +++ b/apps/swift-ios/Tests/PlatformTests/PlatformIncomingShareTests.swift @@ -0,0 +1,320 @@ +import Foundation +import Testing +@testable import T3Code + +@Suite("Incoming share import") +struct PlatformIncomingShareTests { + @Test + func persistsMergedDraftBeforeRemovingInboxEnvelope() async throws { + let recorder = IncomingShareTestRecorder() + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let store = FeatureComposerDraftStore( + fileURL: directory.appendingPathComponent("drafts.json") + ) + let selection = FeatureSelection(providerID: "codex", modelID: "gpt-5.6-sol") + let workspace = FeatureComposerWorkspaceDraft( + mode: .worktree, + branch: "main", + worktreePath: nil, + startFromOrigin: true + ) + let existingAttachment = Self.attachment(id: UUID(), value: 1) + let existing = FeatureComposerDraft( + text: "Existing prompt", + attachments: [existingAttachment], + selection: selection, + workspace: workspace + ) + let imageID = try #require(UUID(uuidString: "12345678-1234-1234-1234-123456789abc")) + let envelope = Self.envelope( + text: "Shared context", + images: [Self.image(id: imageID.uuidString)] + ) + let project = Self.project() + let expectedKey = FeatureComposerDraftStore.newTaskKey(project: project) + try await store.setDraft(existing, for: expectedKey) + let pipeline = PlatformIncomingSharePipeline( + source: PlatformIncomingShareSource( + loadAll: { [envelope] }, + data: { image in + await recorder.record("read:\(image.id)") + return Data([0xCA, 0xFE]) + }, + remove: { id in await recorder.record("remove:\(id)") } + ), + drafts: PlatformIncomingShareDraftRepository( + importContent: { shareID, text, attachments, key, maximumCount in + let draft = try await store.importSharedContent( + shareID: shareID, + text: text, + attachments: attachments, + for: key, + maximumAttachmentCount: maximumCount + ) + await recorder.capture(draft: draft, key: key) + await recorder.record("import:\(key)") + return draft + } + ), + prepareImage: { data, ordinal in + await recorder.record("prepare:\(ordinal)") + return FeatureDraftAttachment( + data: data, + filename: "Image \(ordinal).jpg", + mimeType: "image/jpeg" + ) + } + ) + + let merged = try await pipeline.importEnvelope(envelope, into: project) + let captured = await recorder.capturedDraft + let events = await recorder.events + + #expect(merged.text == "Existing prompt\n\nShared context") + #expect(merged.selection == selection) + #expect(merged.workspace == workspace) + #expect(merged.attachments.count == 2) + #expect(merged.attachments.last?.id == imageID) + #expect(captured?.key == expectedKey) + #expect(captured?.draft == merged) + #expect(events.suffix(2) == ["import:\(expectedKey)", "remove:\(envelope.id)"]) + #expect(try await store.draft(for: expectedKey) == merged) + } + + @Test + func failedDraftSaveLeavesTheInboxUntouched() async { + let recorder = IncomingShareTestRecorder() + let envelope = Self.envelope(text: "Keep me") + let pipeline = PlatformIncomingSharePipeline( + source: PlatformIncomingShareSource( + loadAll: { [envelope] }, + data: { _ in Data() }, + remove: { _ in await recorder.record("remove") } + ), + drafts: PlatformIncomingShareDraftRepository( + importContent: { _, _, _, _, _ in + await recorder.record("import") + throw IncomingShareTestError.saveFailed + } + ), + prepareImage: { _, _ in Self.attachment(id: UUID(), value: 1) } + ) + + do { + _ = try await pipeline.importEnvelope(envelope, into: Self.project()) + Issue.record("Expected the draft write to fail") + } catch { + #expect(error as? IncomingShareTestError == .saveFailed) + } + + #expect(await recorder.events == ["import"]) + } + + @Test + func imageFailureDoesNotPersistOrRemoveTheEnvelope() async { + let recorder = IncomingShareTestRecorder() + let envelope = Self.envelope( + images: [Self.image(id: UUID().uuidString)] + ) + let pipeline = PlatformIncomingSharePipeline( + source: PlatformIncomingShareSource( + loadAll: { [envelope] }, + data: { _ in throw IncomingShareTestError.imageFailed }, + remove: { _ in await recorder.record("remove") } + ), + drafts: PlatformIncomingShareDraftRepository( + importContent: { _, _, _, _, _ in + await recorder.record("import") + return FeatureComposerDraft() + } + ), + prepareImage: { _, _ in Self.attachment(id: UUID(), value: 1) } + ) + + do { + _ = try await pipeline.importEnvelope(envelope, into: Self.project()) + Issue.record("Expected image loading to fail") + } catch { + #expect(error as? IncomingShareTestError == .imageFailed) + } + + #expect(await recorder.events.isEmpty) + } + + @Test + func attachmentLimitPreservesTheWholeEnvelope() async throws { + let recorder = IncomingShareTestRecorder() + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let store = FeatureComposerDraftStore( + fileURL: directory.appendingPathComponent("drafts.json") + ) + let existing = FeatureComposerDraft( + attachments: (0..<7).map { Self.attachment(id: UUID(), value: UInt8($0)) } + ) + let envelope = Self.envelope( + images: [ + Self.image(id: UUID().uuidString), + Self.image(id: UUID().uuidString), + ] + ) + let pipeline = PlatformIncomingSharePipeline( + source: PlatformIncomingShareSource( + loadAll: { [envelope] }, + data: { _ in + await recorder.record("read") + return Data() + }, + remove: { _ in await recorder.record("remove") } + ), + drafts: PlatformIncomingShareDraftRepository( + importContent: { shareID, text, attachments, key, maximumCount in + await recorder.record("import") + return try await store.importSharedContent( + shareID: shareID, + text: text, + attachments: attachments, + for: key, + maximumAttachmentCount: maximumCount + ) + } + ), + prepareImage: { _, _ in Self.attachment(id: UUID(), value: 1) } + ) + let key = FeatureComposerDraftStore.newTaskKey(project: Self.project()) + try await store.setDraft(existing, for: key) + + do { + _ = try await pipeline.importEnvelope(envelope, into: Self.project()) + Issue.record("Expected the attachment limit to reject the import") + } catch let error as FeatureComposerDraftImportError { + if case let .attachmentLimitExceeded(available) = error { + #expect(available == 1) + } + } + + #expect(!(await recorder.events.contains("remove"))) + #expect(try await store.draft(for: key) == existing) + } + + @Test + func repeatedAtomicImportIsIdempotent() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let store = FeatureComposerDraftStore( + fileURL: directory.appendingPathComponent("drafts.json") + ) + let key = "environment:one:new-task:project" + let attachment = Self.attachment(id: UUID(), value: 1) + try await store.setDraft(FeatureComposerDraft(text: "Existing"), for: key) + + let once = try await store.importSharedContent( + shareID: "share-id", + text: "Shared", + attachments: [attachment], + for: key + ) + var edited = once + edited.text += "\nUser edit" + try await store.setDraft(edited, for: key) + let twice = try await store.importSharedContent( + shareID: "share-id", + text: "Shared", + attachments: [attachment], + for: key + ) + + #expect(once.text == "Existing\n\nShared") + #expect(once.attachments == [attachment]) + #expect(twice == edited) + } + + @Test + @MainActor + func noProjectNoticeKeepsEnvelopePendingAndOnlyReportsOnce() async { + let envelope = Self.envelope(text: "Pending") + let coordinator = PlatformIncomingShareCoordinator( + pipeline: PlatformIncomingSharePipeline( + source: PlatformIncomingShareSource( + loadAll: { [envelope] }, + data: { _ in Data() }, + remove: { _ in } + ), + drafts: PlatformIncomingShareDraftRepository( + importContent: { _, _, _, _, _ in FeatureComposerDraft() } + ), + prepareImage: { _, _ in Self.attachment(id: UUID(), value: 1) } + ) + ) + + #expect(await coordinator.refresh(hasProjects: false)) + #expect(coordinator.pendingEnvelope == envelope) + #expect(!(await coordinator.refresh(hasProjects: false))) + #expect(coordinator.pendingEnvelope == envelope) + } + + private static func envelope( + text: String = "", + images: [T3IncomingShareImage] = [] + ) -> T3IncomingShareEnvelope { + T3IncomingShareEnvelope( + schemaVersion: T3IncomingShareEnvelope.schemaVersion, + id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", + createdAt: Date(timeIntervalSince1970: 100), + text: text, + images: images, + warnings: [] + ) + } + + private static func image(id: String) -> T3IncomingShareImage { + T3IncomingShareImage( + id: id, + fileName: "reference.png", + typeIdentifier: "public.png", + relativePath: "image.png", + byteCount: 2 + ) + } + + private static func attachment(id: UUID, value: UInt8) -> FeatureDraftAttachment { + FeatureDraftAttachment( + id: id, + data: Data([value]), + filename: "Image.jpg", + mimeType: "image/jpeg" + ) + } + + private static func project() -> FeatureProject { + FeatureProject( + id: "project:environment:project", + wireID: "project", + environmentID: "environment", + name: "t3code", + path: "/repo" + ) + } +} + +private enum IncomingShareTestError: Error, Equatable { + case imageFailed + case saveFailed +} + +private actor IncomingShareTestRecorder { + private(set) var events: [String] = [] + private(set) var capturedDraft: (draft: FeatureComposerDraft, key: String)? + + func record(_ event: String) { + events.append(event) + } + + func capture(draft: FeatureComposerDraft, key: String) { + capturedDraft = (draft, key) + } +}