feat(swift-ios): add native platform integrations
This commit is contained in:
12 files changed
+1418
-4
No files matched your search
@@ -0,0 +1,302 @@
|
||||
import Foundation
|
||||
|
||||
enum PlatformRoute: Codable, Hashable, Identifiable, Sendable {
|
||||
case connection(endpoint: String, token: String?)
|
||||
case environment(id: String)
|
||||
case project(environmentID: String?, projectID: String)
|
||||
case thread(environmentID: String?, threadID: String)
|
||||
case newTask(environmentID: String?, projectID: String?)
|
||||
|
||||
var id: String {
|
||||
switch self {
|
||||
case let .connection(endpoint, token):
|
||||
"connection:\(endpoint):\(token ?? "")"
|
||||
case let .environment(id):
|
||||
"environment:\(id)"
|
||||
case let .project(environmentID, projectID):
|
||||
"project:\(environmentID ?? ""):\(projectID)"
|
||||
case let .thread(environmentID, threadID):
|
||||
"thread:\(environmentID ?? ""):\(threadID)"
|
||||
case let .newTask(environmentID, projectID):
|
||||
"new-task:\(environmentID ?? ""):\(projectID ?? "")"
|
||||
}
|
||||
}
|
||||
|
||||
var url: URL? {
|
||||
var components = URLComponents()
|
||||
components.scheme = "t3code"
|
||||
|
||||
switch self {
|
||||
case let .connection(endpoint, token):
|
||||
components.host = "connect"
|
||||
components.queryItems = [URLQueryItem(name: "endpoint", value: endpoint)]
|
||||
if let token {
|
||||
components.queryItems?.append(URLQueryItem(name: "token", value: token))
|
||||
}
|
||||
case let .environment(id):
|
||||
components.host = "environments"
|
||||
components.queryItems = [URLQueryItem(name: "environment", value: id)]
|
||||
case let .project(environmentID, projectID):
|
||||
components.host = "projects"
|
||||
components.queryItems = [
|
||||
environmentID.map { URLQueryItem(name: "environment", value: $0) },
|
||||
URLQueryItem(name: "project", value: projectID),
|
||||
].compactMap { $0 }
|
||||
case let .thread(environmentID, threadID):
|
||||
components.host = "threads"
|
||||
components.queryItems = [
|
||||
environmentID.map { URLQueryItem(name: "environment", value: $0) },
|
||||
URLQueryItem(name: "thread", value: threadID),
|
||||
].compactMap { $0 }
|
||||
case let .newTask(environmentID, projectID):
|
||||
components.host = "new-task"
|
||||
components.queryItems = [
|
||||
environmentID.map { URLQueryItem(name: "environment", value: $0) },
|
||||
projectID.map { URLQueryItem(name: "project", value: $0) },
|
||||
].compactMap { $0 }
|
||||
}
|
||||
return components.url
|
||||
}
|
||||
}
|
||||
|
||||
enum PlatformDeepLinkError: LocalizedError, Equatable {
|
||||
case unsupportedURL
|
||||
case missingIdentifier
|
||||
case invalidIdentifier
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .unsupportedURL:
|
||||
"That T3 Code link is not supported."
|
||||
case .missingIdentifier:
|
||||
"That T3 Code link is missing its destination."
|
||||
case .invalidIdentifier:
|
||||
"That T3 Code link contains an invalid destination."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum PlatformDeepLinkParser {
|
||||
private static let trustedWebHosts: Set<String> = [
|
||||
"app.t3.codes",
|
||||
"t3.codes",
|
||||
"www.t3.codes",
|
||||
]
|
||||
|
||||
static func parse(_ url: URL) throws -> PlatformRoute {
|
||||
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
|
||||
let scheme = components.scheme?.lowercased()
|
||||
else {
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
|
||||
let query = queryValues(components.queryItems ?? [])
|
||||
if ["t3", "t3code"].contains(scheme) {
|
||||
let segments = customSchemeSegments(components)
|
||||
if isConnectionRoute(segments: segments, query: query) {
|
||||
return try connectionRoute(url)
|
||||
}
|
||||
return try navigationRoute(segments: segments, query: query)
|
||||
}
|
||||
|
||||
guard ["http", "https"].contains(scheme) else {
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
|
||||
let segments = pathSegments(components.percentEncodedPath)
|
||||
if isConnectionRoute(segments: segments, query: query) {
|
||||
return try connectionRoute(url)
|
||||
}
|
||||
|
||||
guard let host = components.host?.lowercased(), trustedWebHosts.contains(host) else {
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
|
||||
if let explicit = try? navigationRoute(segments: segments, query: query) {
|
||||
return explicit
|
||||
}
|
||||
|
||||
// Web thread routes use /:environmentID/:threadID.
|
||||
if segments.count >= 2 {
|
||||
return .thread(
|
||||
environmentID: try validatedIdentifier(segments[0]),
|
||||
threadID: try validatedIdentifier(segments[1])
|
||||
)
|
||||
}
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
|
||||
static func parse(_ value: String) throws -> PlatformRoute {
|
||||
guard let url = URL(string: value.trimmingCharacters(in: .whitespacesAndNewlines)) else {
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
return try parse(url)
|
||||
}
|
||||
|
||||
private static func navigationRoute(
|
||||
segments: [String],
|
||||
query: [String: String]
|
||||
) throws -> PlatformRoute {
|
||||
let head = segments.first?.lowercased() ?? ""
|
||||
let tail = Array(segments.dropFirst())
|
||||
let queryEnvironment = query["environment"] ?? query["environmentid"] ?? query["env"]
|
||||
let queryProject = query["project"] ?? query["projectid"]
|
||||
let queryThread = query["thread"] ?? query["threadid"]
|
||||
|
||||
switch head {
|
||||
case "thread", "threads":
|
||||
let values = try routeIdentifiers(
|
||||
tail: tail,
|
||||
queryEnvironment: queryEnvironment,
|
||||
queryDestination: queryThread
|
||||
)
|
||||
return .thread(environmentID: values.environmentID, threadID: values.destinationID)
|
||||
case "project", "projects":
|
||||
let values = try routeIdentifiers(
|
||||
tail: tail,
|
||||
queryEnvironment: queryEnvironment,
|
||||
queryDestination: queryProject
|
||||
)
|
||||
return .project(environmentID: values.environmentID, projectID: values.destinationID)
|
||||
case "environment", "environments", "server", "servers":
|
||||
guard let rawID = tail.first ?? queryEnvironment else {
|
||||
throw PlatformDeepLinkError.missingIdentifier
|
||||
}
|
||||
return .environment(id: try validatedIdentifier(rawID))
|
||||
case "new", "new-task", "compose":
|
||||
return .newTask(
|
||||
environmentID: try queryEnvironment.map(validatedIdentifier),
|
||||
projectID: try queryProject.map(validatedIdentifier)
|
||||
)
|
||||
default:
|
||||
if let queryThread {
|
||||
return .thread(
|
||||
environmentID: try queryEnvironment.map(validatedIdentifier),
|
||||
threadID: try validatedIdentifier(queryThread)
|
||||
)
|
||||
}
|
||||
if let queryProject {
|
||||
return .project(
|
||||
environmentID: try queryEnvironment.map(validatedIdentifier),
|
||||
projectID: try validatedIdentifier(queryProject)
|
||||
)
|
||||
}
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
}
|
||||
|
||||
private static func routeIdentifiers(
|
||||
tail: [String],
|
||||
queryEnvironment: String?,
|
||||
queryDestination: String?
|
||||
) throws -> (environmentID: String?, destinationID: String) {
|
||||
if let queryDestination {
|
||||
return (
|
||||
try queryEnvironment.map(validatedIdentifier),
|
||||
try validatedIdentifier(queryDestination)
|
||||
)
|
||||
}
|
||||
if tail.count >= 2 {
|
||||
return (
|
||||
try validatedIdentifier(tail[0]),
|
||||
try validatedIdentifier(tail[1])
|
||||
)
|
||||
}
|
||||
guard let destination = tail.first else {
|
||||
throw PlatformDeepLinkError.missingIdentifier
|
||||
}
|
||||
return (try queryEnvironment.map(validatedIdentifier), try validatedIdentifier(destination))
|
||||
}
|
||||
|
||||
private static func connectionRoute(_ url: URL) throws -> PlatformRoute {
|
||||
do {
|
||||
let details = try ConnectionDetailsParser.parse(url.absoluteString)
|
||||
return .connection(endpoint: details.endpoint, token: details.pairingCode)
|
||||
} catch {
|
||||
throw PlatformDeepLinkError.unsupportedURL
|
||||
}
|
||||
}
|
||||
|
||||
private static func isConnectionRoute(
|
||||
segments: [String],
|
||||
query: [String: String]
|
||||
) -> Bool {
|
||||
let head = segments.first?.lowercased()
|
||||
return ["connect", "pair", "pairing"].contains(head)
|
||||
|| query["pairingurl"] != nil
|
||||
|| query["pairing_url"] != nil
|
||||
|| query["endpoint"] != nil
|
||||
|| query["server"] != nil
|
||||
|| query["host"] != nil
|
||||
}
|
||||
|
||||
private static func customSchemeSegments(_ components: URLComponents) -> [String] {
|
||||
var result: [String] = []
|
||||
if let host = components.host, !host.isEmpty {
|
||||
result.append(host)
|
||||
}
|
||||
result.append(contentsOf: pathSegments(components.percentEncodedPath))
|
||||
return result
|
||||
}
|
||||
|
||||
private static func pathSegments(_ percentEncodedPath: String) -> [String] {
|
||||
percentEncodedPath
|
||||
.split(separator: "/", omittingEmptySubsequences: true)
|
||||
.map { String($0).removingPercentEncoding ?? String($0) }
|
||||
}
|
||||
|
||||
private static func queryValues(_ items: [URLQueryItem]) -> [String: String] {
|
||||
items.reduce(into: [:]) { result, item in
|
||||
guard let value = item.value, !value.isEmpty else { return }
|
||||
result[item.name.lowercased()] = value
|
||||
}
|
||||
}
|
||||
|
||||
private static func validatedIdentifier(_ rawValue: String) throws -> String {
|
||||
let value = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !value.isEmpty else { throw PlatformDeepLinkError.missingIdentifier }
|
||||
guard value.utf8.count <= 1_024,
|
||||
value != ".",
|
||||
value != "..",
|
||||
value.unicodeScalars.allSatisfy({ !CharacterSet.controlCharacters.contains($0) })
|
||||
else {
|
||||
throw PlatformDeepLinkError.invalidIdentifier
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// One-shot storage bridges app intents and notification launches to the live scene.
|
||||
final class PlatformRouteMailbox: @unchecked Sendable {
|
||||
static let shared = PlatformRouteMailbox()
|
||||
|
||||
private let defaults: UserDefaults
|
||||
private let key: String
|
||||
private let lock = NSLock()
|
||||
|
||||
init(defaults: UserDefaults = .standard, key: String = "swift-ios.pending-platform-route.v1") {
|
||||
self.defaults = defaults
|
||||
self.key = key
|
||||
}
|
||||
|
||||
func put(_ route: PlatformRoute) {
|
||||
lock.withLock {
|
||||
defaults.set(try? JSONEncoder().encode(route), forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
func take() -> PlatformRoute? {
|
||||
lock.withLock {
|
||||
guard let data = defaults.data(forKey: key) else { return nil }
|
||||
defaults.removeObject(forKey: key)
|
||||
return try? JSONDecoder().decode(PlatformRoute.self, from: data)
|
||||
}
|
||||
}
|
||||
|
||||
func peek() -> PlatformRoute? {
|
||||
lock.withLock {
|
||||
guard let data = defaults.data(forKey: key) else { return nil }
|
||||
return try? JSONDecoder().decode(PlatformRoute.self, from: data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import UIKit
|
||||
|
||||
enum PlatformFeedbackKind: Equatable, Sendable {
|
||||
case success
|
||||
case warning
|
||||
case error
|
||||
}
|
||||
|
||||
struct PlatformThreadSignal: Equatable, Sendable {
|
||||
let kind: PlatformFeedbackKind
|
||||
let thread: FeatureThread
|
||||
}
|
||||
|
||||
enum PlatformThreadTransitionClassifier {
|
||||
static func signals(
|
||||
previous: [String: FeatureThread]?,
|
||||
current: [FeatureThread]
|
||||
) -> [PlatformThreadSignal] {
|
||||
guard let previous else { return [] }
|
||||
|
||||
return current.compactMap { thread in
|
||||
guard let old = previous[thread.id], old.state != thread.state else { return nil }
|
||||
let kind: PlatformFeedbackKind? = switch thread.state {
|
||||
case .waitingForApproval, .waitingForInput:
|
||||
.warning
|
||||
case .failed:
|
||||
.error
|
||||
case .completed where old.state == .working || old.state == .queued:
|
||||
.success
|
||||
default:
|
||||
nil
|
||||
}
|
||||
return kind.map { PlatformThreadSignal(kind: $0, thread: thread) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PlatformHapticEngine {
|
||||
static let shared = PlatformHapticEngine()
|
||||
|
||||
func emit(_ kind: PlatformFeedbackKind, enabled: Bool) {
|
||||
guard enabled else { return }
|
||||
let generator = UINotificationFeedbackGenerator()
|
||||
generator.prepare()
|
||||
switch kind {
|
||||
case .success:
|
||||
generator.notificationOccurred(.success)
|
||||
case .warning:
|
||||
generator.notificationOccurred(.warning)
|
||||
case .error:
|
||||
generator.notificationOccurred(.error)
|
||||
}
|
||||
}
|
||||
|
||||
func selection(enabled: Bool) {
|
||||
guard enabled else { return }
|
||||
let generator = UISelectionFeedbackGenerator()
|
||||
generator.prepare()
|
||||
generator.selectionChanged()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
@preconcurrency import UserNotifications
|
||||
import UIKit
|
||||
|
||||
extension Notification.Name {
|
||||
static let platformRouteReceived = Notification.Name("T3PlatformRouteReceived")
|
||||
static let platformDeviceTokenChanged = Notification.Name("T3PlatformDeviceTokenChanged")
|
||||
}
|
||||
|
||||
enum PlatformNotificationPayload {
|
||||
private static let routeKeys = ["t3_route", "route", "url", "deep_link", "deeplink"]
|
||||
|
||||
static func route(from userInfo: [AnyHashable: Any]) -> PlatformRoute? {
|
||||
for key in routeKeys {
|
||||
if let value = value(named: key, in: userInfo),
|
||||
let route = try? PlatformDeepLinkParser.parse(value) {
|
||||
return route
|
||||
}
|
||||
}
|
||||
|
||||
let environmentID = value(named: "environment_id", in: userInfo)
|
||||
?? value(named: "environmentId", in: userInfo)
|
||||
if let threadID = value(named: "thread_id", in: userInfo)
|
||||
?? value(named: "threadId", in: userInfo) {
|
||||
return .thread(environmentID: environmentID, threadID: threadID)
|
||||
}
|
||||
if let projectID = value(named: "project_id", in: userInfo)
|
||||
?? value(named: "projectId", in: userInfo) {
|
||||
return .project(environmentID: environmentID, projectID: projectID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func value(named name: String, in userInfo: [AnyHashable: Any]) -> String? {
|
||||
userInfo.first { key, _ in
|
||||
String(describing: key).caseInsensitiveCompare(name) == .orderedSame
|
||||
}.flatMap { _, value in
|
||||
let string = value as? String
|
||||
return string?.isEmpty == false ? string : nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
protocol PlatformDeviceTokenSink: AnyObject {
|
||||
func registered(token: String)
|
||||
func registrationFailed(_ error: Error)
|
||||
func invalidated()
|
||||
}
|
||||
|
||||
/// Persists the APNs identity and publishes a seam for server registration.
|
||||
/// The environment client can subscribe without coupling UIApplicationDelegate to transport code.
|
||||
@MainActor
|
||||
final class PlatformPersistedDeviceTokenSink: PlatformDeviceTokenSink {
|
||||
static let shared = PlatformPersistedDeviceTokenSink()
|
||||
|
||||
private let defaults: UserDefaults
|
||||
private let key = "swift-ios.apns-device-token.v1"
|
||||
|
||||
init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
func registered(token: String) {
|
||||
defaults.set(token, forKey: key)
|
||||
NotificationCenter.default.post(
|
||||
name: .platformDeviceTokenChanged,
|
||||
object: nil,
|
||||
userInfo: ["token": token]
|
||||
)
|
||||
}
|
||||
|
||||
func registrationFailed(_ error: Error) {
|
||||
NotificationCenter.default.post(
|
||||
name: .platformDeviceTokenChanged,
|
||||
object: nil,
|
||||
userInfo: ["error": error.localizedDescription]
|
||||
)
|
||||
}
|
||||
|
||||
func invalidated() {
|
||||
defaults.removeObject(forKey: key)
|
||||
NotificationCenter.default.post(name: .platformDeviceTokenChanged, object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PlatformNotificationService: NSObject, UNUserNotificationCenterDelegate {
|
||||
static let shared = PlatformNotificationService()
|
||||
|
||||
private let center: UNUserNotificationCenter
|
||||
private let tokenSink: any PlatformDeviceTokenSink
|
||||
private(set) var enabled = false
|
||||
|
||||
init(
|
||||
center: UNUserNotificationCenter = .current(),
|
||||
tokenSink: (any PlatformDeviceTokenSink)? = nil
|
||||
) {
|
||||
self.center = center
|
||||
self.tokenSink = tokenSink ?? PlatformPersistedDeviceTokenSink.shared
|
||||
super.init()
|
||||
}
|
||||
|
||||
func installDelegate() {
|
||||
center.delegate = self
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func synchronize(enabled: Bool) async -> Bool {
|
||||
installDelegate()
|
||||
|
||||
guard enabled else {
|
||||
self.enabled = false
|
||||
UIApplication.shared.unregisterForRemoteNotifications()
|
||||
center.removeAllPendingNotificationRequests()
|
||||
center.removeAllDeliveredNotifications()
|
||||
tokenSink.invalidated()
|
||||
return false
|
||||
}
|
||||
|
||||
let settings = await center.notificationSettings()
|
||||
let authorized = isAuthorized(settings.authorizationStatus)
|
||||
self.enabled = authorized
|
||||
if authorized {
|
||||
UIApplication.shared.registerForRemoteNotifications()
|
||||
}
|
||||
return authorized
|
||||
}
|
||||
|
||||
/// Call only in response to an explicit user action such as saving the
|
||||
/// Notifications toggle. Startup synchronization never presents a prompt.
|
||||
@discardableResult
|
||||
func requestAuthorization() async -> Bool {
|
||||
installDelegate()
|
||||
let settings = await center.notificationSettings()
|
||||
let authorized: Bool
|
||||
switch settings.authorizationStatus {
|
||||
case .notDetermined:
|
||||
authorized = (try? await center.requestAuthorization(options: [.alert, .badge, .sound])) == true
|
||||
case .authorized, .provisional, .ephemeral:
|
||||
authorized = true
|
||||
case .denied:
|
||||
authorized = false
|
||||
@unknown default:
|
||||
authorized = false
|
||||
}
|
||||
|
||||
enabled = authorized
|
||||
if authorized {
|
||||
UIApplication.shared.registerForRemoteNotifications()
|
||||
}
|
||||
return authorized
|
||||
}
|
||||
|
||||
func schedule(_ signal: PlatformThreadSignal) async {
|
||||
guard enabled else { return }
|
||||
let settings = await center.notificationSettings()
|
||||
guard [.authorized, .provisional, .ephemeral].contains(settings.authorizationStatus) else {
|
||||
return
|
||||
}
|
||||
|
||||
let content = UNMutableNotificationContent()
|
||||
content.title = notificationTitle(for: signal.kind)
|
||||
content.body = signal.thread.title
|
||||
content.sound = .default
|
||||
content.threadIdentifier = signal.thread.id
|
||||
if let url = PlatformRoute.thread(
|
||||
environmentID: signal.thread.environmentID,
|
||||
threadID: signal.thread.wireID ?? signal.thread.id
|
||||
).url {
|
||||
content.userInfo = ["t3_route": url.absoluteString]
|
||||
}
|
||||
|
||||
let request = UNNotificationRequest(
|
||||
identifier: "thread:\(signal.thread.id):\(signal.thread.state.rawValue)",
|
||||
content: content,
|
||||
trigger: nil
|
||||
)
|
||||
try? await center.add(request)
|
||||
}
|
||||
|
||||
func didRegisterForRemoteNotifications(deviceToken: Data) {
|
||||
tokenSink.registered(token: deviceToken.map { String(format: "%02x", $0) }.joined())
|
||||
}
|
||||
|
||||
func didFailToRegisterForRemoteNotifications(_ error: Error) {
|
||||
tokenSink.registrationFailed(error)
|
||||
}
|
||||
|
||||
nonisolated func userNotificationCenter(
|
||||
_ center: UNUserNotificationCenter,
|
||||
didReceive response: UNNotificationResponse
|
||||
) async {
|
||||
guard let route = PlatformNotificationPayload.route(
|
||||
from: response.notification.request.content.userInfo
|
||||
) else { return }
|
||||
PlatformRouteMailbox.shared.put(route)
|
||||
await MainActor.run {
|
||||
NotificationCenter.default.post(
|
||||
name: .platformRouteReceived,
|
||||
object: nil,
|
||||
userInfo: ["route": route]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated func userNotificationCenter(
|
||||
_ center: UNUserNotificationCenter,
|
||||
willPresent notification: UNNotification
|
||||
) async -> UNNotificationPresentationOptions {
|
||||
await MainActor.run { enabled ? [.banner, .sound] : [] }
|
||||
}
|
||||
|
||||
private func notificationTitle(for kind: PlatformFeedbackKind) -> String {
|
||||
switch kind {
|
||||
case .success:
|
||||
"Task completed"
|
||||
case .warning:
|
||||
"T3 Code needs you"
|
||||
case .error:
|
||||
"Task failed"
|
||||
}
|
||||
}
|
||||
|
||||
private func isAuthorized(_ status: UNAuthorizationStatus) -> Bool {
|
||||
switch status {
|
||||
case .authorized, .provisional, .ephemeral:
|
||||
true
|
||||
case .notDetermined, .denied:
|
||||
false
|
||||
@unknown default:
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class T3PlatformAppDelegate: NSObject, UIApplicationDelegate {
|
||||
func application(
|
||||
_ application: UIApplication,
|
||||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
|
||||
) -> Bool {
|
||||
PlatformNotificationService.shared.installDelegate()
|
||||
if let payload = launchOptions?[.remoteNotification] as? [AnyHashable: Any],
|
||||
let route = PlatformNotificationPayload.route(from: payload) {
|
||||
PlatformRouteMailbox.shared.put(route)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func application(
|
||||
_ application: UIApplication,
|
||||
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
|
||||
) {
|
||||
PlatformNotificationService.shared.didRegisterForRemoteNotifications(deviceToken: deviceToken)
|
||||
}
|
||||
|
||||
func application(
|
||||
_ application: UIApplication,
|
||||
didFailToRegisterForRemoteNotificationsWithError error: Error
|
||||
) {
|
||||
PlatformNotificationService.shared.didFailToRegisterForRemoteNotifications(error)
|
||||
}
|
||||
|
||||
func application(
|
||||
_ application: UIApplication,
|
||||
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
|
||||
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
|
||||
) {
|
||||
guard let route = PlatformNotificationPayload.route(from: userInfo) else {
|
||||
completionHandler(.noData)
|
||||
return
|
||||
}
|
||||
PlatformRouteMailbox.shared.put(route)
|
||||
NotificationCenter.default.post(
|
||||
name: .platformRouteReceived,
|
||||
object: nil,
|
||||
userInfo: ["route": route]
|
||||
)
|
||||
completionHandler(.newData)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import SwiftUI
|
||||
|
||||
struct PlatformRootView: View {
|
||||
@SwiftUI.Environment(\.scenePhase) private var scenePhase
|
||||
@Bindable private var model: FeatureRootModel
|
||||
|
||||
@State private var navigationRequest: FeatureWorkspaceNavigationRequest?
|
||||
@State private var pendingRoute: PlatformRoute?
|
||||
@State private var previousThreads: [String: FeatureThread]?
|
||||
@State private var lastNotificationPreference: Bool?
|
||||
|
||||
init(model: FeatureRootModel) {
|
||||
self.model = model
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
FeatureRootView(
|
||||
model: model,
|
||||
navigationRequest: navigationRequest,
|
||||
onNavigationRequestConsumed: { requestID in
|
||||
guard navigationRequest?.id == requestID else { return }
|
||||
navigationRequest = nil
|
||||
}
|
||||
)
|
||||
.onOpenURL { url in
|
||||
handle(url: url, letOnboardingConfirmConnection: true)
|
||||
}
|
||||
.onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { activity in
|
||||
guard let url = activity.webpageURL else { return }
|
||||
handle(url: url, letOnboardingConfirmConnection: false)
|
||||
}
|
||||
.onReceive(NotificationCenter.default.publisher(for: .platformRouteReceived)) { note in
|
||||
guard let route = note.userInfo?["route"] as? PlatformRoute else { return }
|
||||
_ = PlatformRouteMailbox.shared.take()
|
||||
handle(route)
|
||||
}
|
||||
.onChange(of: model.isLoading, initial: true) { _, isLoading in
|
||||
guard !isLoading else { return }
|
||||
processThreadChanges()
|
||||
synchronizeNotificationPreference()
|
||||
consumePendingRouteIfPossible()
|
||||
consumeMailboxRouteIfAvailable()
|
||||
}
|
||||
.onChange(of: model.homePresentationRevision) { _, _ in
|
||||
processThreadChanges()
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
if phase == .active {
|
||||
consumeMailboxRouteIfAvailable()
|
||||
synchronizeNotificationPreference()
|
||||
}
|
||||
}
|
||||
.onChange(of: model.snapshot.settings.notificationsEnabled) { _, _ in
|
||||
synchronizeNotificationPreference()
|
||||
}
|
||||
}
|
||||
|
||||
private var shouldShowWorkspace: Bool {
|
||||
FeatureRootPresentation.showsWorkspace(
|
||||
snapshot: model.snapshot,
|
||||
isManagingConnections: model.isManagingConnections
|
||||
)
|
||||
}
|
||||
|
||||
private func handle(url: URL, letOnboardingConfirmConnection: Bool) {
|
||||
do {
|
||||
let route = try PlatformDeepLinkParser.parse(url)
|
||||
if case .connection = route,
|
||||
letOnboardingConfirmConnection,
|
||||
!shouldShowWorkspace {
|
||||
// ConnectionOnboardingView owns the confirmation UI for cold pairing links.
|
||||
return
|
||||
}
|
||||
handle(route)
|
||||
} catch {
|
||||
model.errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ route: PlatformRoute) {
|
||||
guard !model.isLoading else {
|
||||
pendingRoute = route
|
||||
return
|
||||
}
|
||||
Task { @MainActor in
|
||||
await consume(route)
|
||||
}
|
||||
}
|
||||
|
||||
private func consumePendingRouteIfPossible() {
|
||||
guard let route = pendingRoute else { return }
|
||||
pendingRoute = nil
|
||||
handle(route)
|
||||
}
|
||||
|
||||
private func consumeMailboxRouteIfAvailable() {
|
||||
guard !model.isLoading, let route = PlatformRouteMailbox.shared.take() else { return }
|
||||
handle(route)
|
||||
}
|
||||
|
||||
private func synchronizeNotificationPreference() {
|
||||
guard !model.isLoading else { return }
|
||||
let preference = model.snapshot.settings.notificationsEnabled
|
||||
let previous = lastNotificationPreference
|
||||
lastNotificationPreference = preference
|
||||
|
||||
Task {
|
||||
let authorized: Bool
|
||||
if preference, previous == false {
|
||||
// The model changes only after Settings is explicitly saved.
|
||||
authorized = await PlatformNotificationService.shared.requestAuthorization()
|
||||
} else {
|
||||
authorized = await PlatformNotificationService.shared.synchronize(enabled: preference)
|
||||
}
|
||||
guard preference, !authorized, model.snapshot.settings.notificationsEnabled else {
|
||||
return
|
||||
}
|
||||
|
||||
// Keep the app toggle honest when authorization is absent or revoked.
|
||||
var settings = model.snapshot.settings
|
||||
settings.notificationsEnabled = false
|
||||
await model.saveSettings(settings)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func consume(_ route: PlatformRoute) async {
|
||||
switch route {
|
||||
case let .connection(endpoint, token):
|
||||
if await model.pair(endpoint: endpoint, token: token) {
|
||||
PlatformHapticEngine.shared.emit(
|
||||
.success,
|
||||
enabled: model.snapshot.settings.hapticsEnabled
|
||||
)
|
||||
}
|
||||
case let .environment(id):
|
||||
guard await activateEnvironmentIfNeeded(id) else { return }
|
||||
PlatformHapticEngine.shared.selection(
|
||||
enabled: model.snapshot.settings.hapticsEnabled
|
||||
)
|
||||
case let .thread(environmentID, threadID):
|
||||
guard await activateEnvironmentIfNeeded(environmentID),
|
||||
let thread = PlatformRouteResolver.thread(
|
||||
in: model.snapshot,
|
||||
environmentID: environmentID,
|
||||
id: threadID
|
||||
)
|
||||
else {
|
||||
if model.errorMessage == nil { model.errorMessage = "That thread is not available on this device." }
|
||||
return
|
||||
}
|
||||
navigationRequest = FeatureWorkspaceNavigationRequest(
|
||||
destination: .thread(id: thread.id)
|
||||
)
|
||||
PlatformHapticEngine.shared.selection(
|
||||
enabled: model.snapshot.settings.hapticsEnabled
|
||||
)
|
||||
case let .project(environmentID, projectID):
|
||||
guard await activateEnvironmentIfNeeded(environmentID),
|
||||
let project = PlatformRouteResolver.project(
|
||||
in: model.snapshot,
|
||||
environmentID: environmentID,
|
||||
id: projectID
|
||||
)
|
||||
else {
|
||||
if model.errorMessage == nil { model.errorMessage = "That project is not available on this device." }
|
||||
return
|
||||
}
|
||||
navigationRequest = FeatureWorkspaceNavigationRequest(
|
||||
destination: .project(id: project.id)
|
||||
)
|
||||
PlatformHapticEngine.shared.selection(
|
||||
enabled: model.snapshot.settings.hapticsEnabled
|
||||
)
|
||||
case let .newTask(environmentID, projectID):
|
||||
guard await activateEnvironmentIfNeeded(environmentID) else { return }
|
||||
let resolvedProject = projectID.flatMap {
|
||||
PlatformRouteResolver.project(
|
||||
in: model.snapshot,
|
||||
environmentID: environmentID,
|
||||
id: $0
|
||||
)
|
||||
}
|
||||
if projectID != nil, resolvedProject == nil {
|
||||
model.errorMessage = "That project is not available on this device."
|
||||
return
|
||||
}
|
||||
navigationRequest = FeatureWorkspaceNavigationRequest(
|
||||
destination: .newTask(projectID: resolvedProject?.id)
|
||||
)
|
||||
PlatformHapticEngine.shared.selection(
|
||||
enabled: model.snapshot.settings.hapticsEnabled
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func activateEnvironmentIfNeeded(_ id: String?) async -> Bool {
|
||||
guard let id else { return true }
|
||||
guard let environment = model.snapshot.environments.first(where: { $0.id == id }) else {
|
||||
model.errorMessage = "That environment is not saved on this device."
|
||||
return false
|
||||
}
|
||||
guard !environment.isActive else { return true }
|
||||
await model.activateEnvironment(id)
|
||||
return model.snapshot.environments.contains { $0.id == id && $0.isActive }
|
||||
}
|
||||
|
||||
/// Home revisions are coalesced by FeatureRootModel, so this performs one
|
||||
/// bounded scan per meaningful snapshot change rather than on every render.
|
||||
private func processThreadChanges() {
|
||||
let current = Dictionary(uniqueKeysWithValues: model.snapshot.threads.map { ($0.id, $0) })
|
||||
let signals = PlatformThreadTransitionClassifier.signals(
|
||||
previous: previousThreads,
|
||||
current: model.snapshot.threads
|
||||
)
|
||||
previousThreads = current
|
||||
PlatformRecentThreadStore.shared.update(from: model.snapshot.threads)
|
||||
|
||||
for signal in signals {
|
||||
if scenePhase == .active {
|
||||
PlatformHapticEngine.shared.emit(
|
||||
signal.kind,
|
||||
enabled: model.snapshot.settings.hapticsEnabled
|
||||
)
|
||||
} else if model.snapshot.settings.notificationsEnabled {
|
||||
Task { await PlatformNotificationService.shared.schedule(signal) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
|
||||
enum PlatformRouteResolver {
|
||||
static func thread(
|
||||
in snapshot: FeatureSnapshot,
|
||||
environmentID: String?,
|
||||
id: String
|
||||
) -> FeatureThread? {
|
||||
let activeID = snapshot.environments.first(where: \.isActive)?.id
|
||||
return snapshot.threads
|
||||
.filter { thread in
|
||||
(environmentID == nil || thread.environmentID == environmentID)
|
||||
&& (thread.id == id || thread.wireID == id)
|
||||
}
|
||||
.sorted { lhs, rhs in
|
||||
let lhsIsActive = lhs.environmentID == activeID
|
||||
let rhsIsActive = rhs.environmentID == activeID
|
||||
if lhsIsActive != rhsIsActive { return lhsIsActive }
|
||||
return lhs.updatedAt > rhs.updatedAt
|
||||
}
|
||||
.first
|
||||
}
|
||||
|
||||
static func project(
|
||||
in snapshot: FeatureSnapshot,
|
||||
environmentID: String?,
|
||||
id: String
|
||||
) -> FeatureProject? {
|
||||
let activeID = snapshot.environments.first(where: \.isActive)?.id
|
||||
return snapshot.projects
|
||||
.filter { project in
|
||||
(environmentID == nil || project.environmentID == environmentID)
|
||||
&& (project.id == id || project.wireID == id)
|
||||
}
|
||||
.sorted { lhs, rhs in
|
||||
let lhsIsActive = lhs.environmentID == activeID
|
||||
let rhsIsActive = rhs.environmentID == activeID
|
||||
if lhsIsActive != rhsIsActive { return lhsIsActive }
|
||||
return lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending
|
||||
}
|
||||
.first
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import AppIntents
|
||||
import Foundation
|
||||
|
||||
struct PlatformRecentThreadRecord: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let environmentID: String?
|
||||
let wireID: String
|
||||
let title: String
|
||||
let environmentName: String?
|
||||
let updatedAt: Date
|
||||
}
|
||||
|
||||
final class PlatformRecentThreadStore: @unchecked Sendable {
|
||||
static let shared = PlatformRecentThreadStore()
|
||||
|
||||
private let defaults: UserDefaults
|
||||
private let key: String
|
||||
private let lock = NSLock()
|
||||
|
||||
init(defaults: UserDefaults = .standard, key: String = "swift-ios.recent-threads.v1") {
|
||||
self.defaults = defaults
|
||||
self.key = key
|
||||
}
|
||||
|
||||
func update(from threads: [FeatureThread]) {
|
||||
let records = threads
|
||||
.filter { !$0.isArchived }
|
||||
.sorted { lhs, rhs in
|
||||
if lhs.updatedAt != rhs.updatedAt { return lhs.updatedAt > rhs.updatedAt }
|
||||
return lhs.id < rhs.id
|
||||
}
|
||||
.prefix(12)
|
||||
.map {
|
||||
PlatformRecentThreadRecord(
|
||||
id: $0.id,
|
||||
environmentID: $0.environmentID,
|
||||
wireID: $0.wireID ?? $0.id,
|
||||
title: $0.title,
|
||||
environmentName: $0.environmentName,
|
||||
updatedAt: $0.updatedAt
|
||||
)
|
||||
}
|
||||
lock.withLock {
|
||||
defaults.set(try? JSONEncoder().encode(records), forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
func records() -> [PlatformRecentThreadRecord] {
|
||||
lock.withLock {
|
||||
guard let data = defaults.data(forKey: key) else { return [] }
|
||||
return (try? JSONDecoder().decode([PlatformRecentThreadRecord].self, from: data)) ?? []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlatformRecentThreadEntity: AppEntity {
|
||||
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "T3 Code Thread")
|
||||
static let defaultQuery = PlatformRecentThreadQuery()
|
||||
|
||||
let id: String
|
||||
let environmentID: String?
|
||||
let wireID: String
|
||||
let title: String
|
||||
let environmentName: String?
|
||||
|
||||
var displayRepresentation: DisplayRepresentation {
|
||||
DisplayRepresentation(
|
||||
title: "\(title)",
|
||||
subtitle: environmentName.map { "\($0)" }
|
||||
)
|
||||
}
|
||||
|
||||
init(record: PlatformRecentThreadRecord) {
|
||||
id = record.id
|
||||
environmentID = record.environmentID
|
||||
wireID = record.wireID
|
||||
title = record.title
|
||||
environmentName = record.environmentName
|
||||
}
|
||||
}
|
||||
|
||||
struct PlatformRecentThreadQuery: EntityQuery {
|
||||
func entities(for identifiers: [String]) async throws -> [PlatformRecentThreadEntity] {
|
||||
let requested = Set(identifiers)
|
||||
return PlatformRecentThreadStore.shared.records()
|
||||
.filter { requested.contains($0.id) }
|
||||
.map(PlatformRecentThreadEntity.init)
|
||||
}
|
||||
|
||||
func suggestedEntities() async throws -> [PlatformRecentThreadEntity] {
|
||||
PlatformRecentThreadStore.shared.records().map(PlatformRecentThreadEntity.init)
|
||||
}
|
||||
}
|
||||
|
||||
struct NewT3TaskIntent: AppIntent {
|
||||
static let title: LocalizedStringResource = "New T3 Code Task"
|
||||
static let description = IntentDescription("Open the native composer and start a task.")
|
||||
static let openAppWhenRun = true
|
||||
|
||||
func perform() async throws -> some IntentResult {
|
||||
PlatformRouteMailbox.shared.put(.newTask(environmentID: nil, projectID: nil))
|
||||
return .result()
|
||||
}
|
||||
}
|
||||
|
||||
struct OpenRecentT3ThreadIntent: AppIntent {
|
||||
static let title: LocalizedStringResource = "Open Recent T3 Code Thread"
|
||||
static let description = IntentDescription("Open a recent thread in T3 Code.")
|
||||
static let openAppWhenRun = true
|
||||
|
||||
@Parameter(title: "Thread")
|
||||
var thread: PlatformRecentThreadEntity
|
||||
|
||||
func perform() async throws -> some IntentResult {
|
||||
PlatformRouteMailbox.shared.put(
|
||||
.thread(environmentID: thread.environmentID, threadID: thread.wireID)
|
||||
)
|
||||
return .result()
|
||||
}
|
||||
}
|
||||
|
||||
struct T3PlatformShortcuts: AppShortcutsProvider {
|
||||
static var appShortcuts: [AppShortcut] {
|
||||
AppShortcut(
|
||||
intent: NewT3TaskIntent(),
|
||||
phrases: [
|
||||
"Start a task in \(.applicationName)",
|
||||
"New task in \(.applicationName)",
|
||||
],
|
||||
shortTitle: "New Task",
|
||||
systemImageName: "square.and.pencil"
|
||||
)
|
||||
AppShortcut(
|
||||
intent: OpenRecentT3ThreadIntent(),
|
||||
phrases: [
|
||||
"Open a recent thread in \(.applicationName)",
|
||||
],
|
||||
shortTitle: "Open Thread",
|
||||
systemImageName: "bubble.left.and.bubble.right"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,20 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
@MainActor
|
||||
struct T3CodeApp: App {
|
||||
@State private var client = NativeFeatureClient()
|
||||
@UIApplicationDelegateAdaptor(T3PlatformAppDelegate.self) private var appDelegate
|
||||
@State private var model: FeatureRootModel
|
||||
|
||||
init() {
|
||||
let client = NativeFeatureClient()
|
||||
_model = State(initialValue: FeatureRootModel(client: client))
|
||||
}
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
RootView {
|
||||
FeatureRootView(client: client)
|
||||
PlatformRootView(model: model)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,23 @@ import SwiftUI
|
||||
|
||||
public struct FeatureRootView: View {
|
||||
@State private var model: FeatureRootModel
|
||||
private let navigationRequest: FeatureWorkspaceNavigationRequest?
|
||||
private let onNavigationRequestConsumed: @MainActor (UUID) -> Void
|
||||
|
||||
public init(client: any FeatureClient) {
|
||||
_model = State(initialValue: FeatureRootModel(client: client))
|
||||
navigationRequest = nil
|
||||
onNavigationRequestConsumed = { _ in }
|
||||
}
|
||||
|
||||
init(
|
||||
model: FeatureRootModel,
|
||||
navigationRequest: FeatureWorkspaceNavigationRequest? = nil,
|
||||
onNavigationRequestConsumed: @escaping @MainActor (UUID) -> Void = { _ in }
|
||||
) {
|
||||
_model = State(initialValue: model)
|
||||
self.navigationRequest = navigationRequest
|
||||
self.onNavigationRequestConsumed = onNavigationRequestConsumed
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
@@ -14,6 +28,8 @@ public struct FeatureRootView: View {
|
||||
} else if shouldShowWorkspace {
|
||||
WorkspaceView(
|
||||
model: model,
|
||||
navigationRequest: navigationRequest,
|
||||
onNavigationRequestConsumed: onNavigationRequestConsumed,
|
||||
submitNewTask: { request in
|
||||
await model.startTask(request)
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ public struct NewThreadView: View {
|
||||
let onCreated: (FeatureThread) -> Void
|
||||
let onCreateProject: @MainActor () -> Void
|
||||
private let draftStore: FeatureComposerDraftStore
|
||||
private let initialProjectID: String?
|
||||
|
||||
@State private var projectID = ""
|
||||
@State private var prompt = ""
|
||||
@@ -34,12 +35,14 @@ public struct NewThreadView: View {
|
||||
submit: @escaping (NewTaskRequest) async -> FeatureThread?,
|
||||
onCreated: @escaping (FeatureThread) -> Void,
|
||||
onCreateProject: @escaping @MainActor () -> Void = {},
|
||||
initialProjectID: String? = nil,
|
||||
draftStore: FeatureComposerDraftStore = .shared
|
||||
) {
|
||||
self.model = model
|
||||
self.submit = submit
|
||||
self.onCreated = onCreated
|
||||
self.onCreateProject = onCreateProject
|
||||
self.initialProjectID = initialProjectID
|
||||
self.draftStore = draftStore
|
||||
}
|
||||
|
||||
@@ -84,7 +87,10 @@ public struct NewThreadView: View {
|
||||
}
|
||||
.onAppear {
|
||||
if projectID.isEmpty {
|
||||
selectInitialProject(creationProjects.first?.id ?? "")
|
||||
let initialID = creationProjects.first(where: { $0.id == initialProjectID })?.id
|
||||
?? creationProjects.first?.id
|
||||
?? ""
|
||||
selectInitialProject(initialID)
|
||||
}
|
||||
}
|
||||
.onChange(of: projectID) { prepareProjectIfNeeded(projectID) }
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
import SwiftUI
|
||||
|
||||
struct FeatureWorkspaceNavigationRequest: Equatable, Sendable {
|
||||
enum Destination: Equatable, Sendable {
|
||||
case thread(id: String)
|
||||
case project(id: String)
|
||||
case newTask(projectID: String?)
|
||||
}
|
||||
|
||||
let id: UUID
|
||||
let destination: Destination
|
||||
|
||||
init(id: UUID = UUID(), destination: Destination) {
|
||||
self.id = id
|
||||
self.destination = destination
|
||||
}
|
||||
}
|
||||
|
||||
public struct WorkspaceView: View {
|
||||
@SwiftUI.Environment(\.dynamicTypeSize) private var dynamicTypeSize
|
||||
|
||||
@Bindable var model: FeatureRootModel
|
||||
private let navigationRequest: FeatureWorkspaceNavigationRequest?
|
||||
private let onNavigationRequestConsumed: @MainActor (UUID) -> Void
|
||||
private let submitNewTask: (NewTaskRequest) async -> FeatureThread?
|
||||
private let submitMessage: (FeatureMessageSubmission) async -> Bool
|
||||
|
||||
@@ -16,6 +34,7 @@ public struct WorkspaceView: View {
|
||||
@State private var isArchiveExpanded = false
|
||||
@State private var settledLimit = 12
|
||||
@State private var showingNewTask = false
|
||||
@State private var newTaskInitialProjectID: String?
|
||||
@State private var showingAddProject = false
|
||||
@State private var showingSettings = false
|
||||
@State private var renamingThread: FeatureThread?
|
||||
@@ -29,8 +48,26 @@ public struct WorkspaceView: View {
|
||||
model: FeatureRootModel,
|
||||
submitNewTask: ((NewTaskRequest) async -> FeatureThread?)? = nil,
|
||||
submitMessage: ((FeatureMessageSubmission) async -> Bool)? = nil
|
||||
) {
|
||||
self.init(
|
||||
model: model,
|
||||
navigationRequest: nil,
|
||||
onNavigationRequestConsumed: { _ in },
|
||||
submitNewTask: submitNewTask,
|
||||
submitMessage: submitMessage
|
||||
)
|
||||
}
|
||||
|
||||
init(
|
||||
model: FeatureRootModel,
|
||||
navigationRequest: FeatureWorkspaceNavigationRequest?,
|
||||
onNavigationRequestConsumed: @escaping @MainActor (UUID) -> Void,
|
||||
submitNewTask: ((NewTaskRequest) async -> FeatureThread?)? = nil,
|
||||
submitMessage: ((FeatureMessageSubmission) async -> Bool)? = nil
|
||||
) {
|
||||
self.model = model
|
||||
self.navigationRequest = navigationRequest
|
||||
self.onNavigationRequestConsumed = onNavigationRequestConsumed
|
||||
self.submitNewTask = submitNewTask ?? { request in
|
||||
do {
|
||||
let thread = try await model.client.createThreadAndSend(
|
||||
@@ -94,7 +131,8 @@ public struct WorkspaceView: View {
|
||||
openThread(thread.id)
|
||||
showingNewTask = false
|
||||
},
|
||||
onCreateProject: openProjectCreation
|
||||
onCreateProject: openProjectCreation,
|
||||
initialProjectID: newTaskInitialProjectID
|
||||
)
|
||||
}
|
||||
.sheet(isPresented: $showingAddProject) {
|
||||
@@ -129,6 +167,9 @@ public struct WorkspaceView: View {
|
||||
.onChange(of: selectedProjectIsAvailable) { _, isAvailable in
|
||||
if !isAvailable { selectedProjectID = nil }
|
||||
}
|
||||
.onChange(of: navigationRequest?.id, initial: true) { _, _ in
|
||||
consumeNavigationRequest()
|
||||
}
|
||||
.task(id: nextSidebarBoundary) {
|
||||
guard let boundary = nextSidebarBoundary else { return }
|
||||
do {
|
||||
@@ -553,13 +594,51 @@ public struct WorkspaceView: View {
|
||||
}
|
||||
|
||||
private func openNewTaskOrProjectCreation() {
|
||||
openNewTaskOrProjectCreation(initialProjectID: nil)
|
||||
}
|
||||
|
||||
private func openNewTaskOrProjectCreation(initialProjectID: String?) {
|
||||
if creationProjects.isEmpty {
|
||||
showingAddProject = true
|
||||
} else {
|
||||
newTaskInitialProjectID = initialProjectID
|
||||
showingNewTask = true
|
||||
}
|
||||
}
|
||||
|
||||
private func consumeNavigationRequest() {
|
||||
guard let navigationRequest else { return }
|
||||
switch navigationRequest.destination {
|
||||
case let .thread(id):
|
||||
guard model.snapshot.threads.contains(where: { $0.id == id }) else { return }
|
||||
dismissTransientPresentations()
|
||||
openThread(id)
|
||||
case let .project(id):
|
||||
guard model.snapshot.projects.contains(where: { $0.id == id }) else { return }
|
||||
dismissTransientPresentations()
|
||||
selectedProjectID = id
|
||||
closeSelectedThread()
|
||||
case let .newTask(projectID):
|
||||
if let projectID,
|
||||
model.snapshot.projects.contains(where: { $0.id == projectID }) {
|
||||
selectedProjectID = projectID
|
||||
}
|
||||
dismissTransientPresentations()
|
||||
Task { @MainActor in
|
||||
await Task.yield()
|
||||
openNewTaskOrProjectCreation(initialProjectID: projectID)
|
||||
}
|
||||
}
|
||||
onNavigationRequestConsumed(navigationRequest.id)
|
||||
}
|
||||
|
||||
private func dismissTransientPresentations() {
|
||||
showingNewTask = false
|
||||
showingAddProject = false
|
||||
showingSettings = false
|
||||
renamingThread = nil
|
||||
}
|
||||
|
||||
private func projectMenuTitle(_ project: FeatureProject) -> String {
|
||||
guard model.snapshot.environments.count > 1,
|
||||
let environment = model.snapshot.environments.first(where: {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import T3Code
|
||||
|
||||
@Suite("Platform deep links")
|
||||
struct PlatformDeepLinkTests {
|
||||
@Test
|
||||
func parsesWidgetThreadRoute() throws {
|
||||
let route = try PlatformDeepLinkParser.parse(
|
||||
"t3code://threads/environment-1/thread-7"
|
||||
)
|
||||
|
||||
#expect(route == .thread(environmentID: "environment-1", threadID: "thread-7"))
|
||||
}
|
||||
|
||||
@Test
|
||||
func parsesProjectAndEnvironmentQueryRoutes() throws {
|
||||
#expect(
|
||||
try PlatformDeepLinkParser.parse("t3code://projects/project-7?environment=environment-1")
|
||||
== .project(environmentID: "environment-1", projectID: "project-7")
|
||||
)
|
||||
#expect(
|
||||
try PlatformDeepLinkParser.parse("t3code://environments/environment-2")
|
||||
== .environment(id: "environment-2")
|
||||
)
|
||||
#expect(
|
||||
try PlatformDeepLinkParser.parse("t3code://new-task?environment=environment-2&project=project-8")
|
||||
== .newTask(environmentID: "environment-2", projectID: "project-8")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func unwrapsPairingURL() throws {
|
||||
let route = try PlatformDeepLinkParser.parse(
|
||||
"t3code://pair?pairingUrl=https%3A%2F%2Fremote.example.com%2Fpair%23token%3DPAIR"
|
||||
)
|
||||
|
||||
#expect(route == .connection(endpoint: "https://remote.example.com", token: "PAIR"))
|
||||
}
|
||||
|
||||
@Test
|
||||
func parsesTrustedWebThreadRoute() throws {
|
||||
let route = try PlatformDeepLinkParser.parse(
|
||||
"https://app.t3.codes/environment-1/thread-7"
|
||||
)
|
||||
|
||||
#expect(route == .thread(environmentID: "environment-1", threadID: "thread-7"))
|
||||
}
|
||||
|
||||
@Test
|
||||
func rejectsUntrustedWebNavigationRoute() {
|
||||
#expect(throws: PlatformDeepLinkError.unsupportedURL) {
|
||||
try PlatformDeepLinkParser.parse("https://malicious.example/threads/env/thread")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func routeURLsRoundTrip() throws {
|
||||
let routes: [PlatformRoute] = [
|
||||
.environment(id: "environment 1"),
|
||||
.project(environmentID: "environment 1", projectID: "project/1"),
|
||||
.thread(environmentID: "environment 1", threadID: "thread 1"),
|
||||
.newTask(environmentID: "environment 1", projectID: "project 1"),
|
||||
.connection(endpoint: "https://remote.example.com", token: "PAIR"),
|
||||
]
|
||||
|
||||
for route in routes {
|
||||
let url = try #require(route.url)
|
||||
#expect(try PlatformDeepLinkParser.parse(url) == route)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func mailboxConsumesExactlyOnce() throws {
|
||||
let suiteName = "PlatformDeepLinkTests.\(UUID().uuidString)"
|
||||
let defaults = try #require(UserDefaults(suiteName: suiteName))
|
||||
defer { defaults.removePersistentDomain(forName: suiteName) }
|
||||
let mailbox = PlatformRouteMailbox(defaults: defaults, key: "pending")
|
||||
let route = PlatformRoute.thread(environmentID: "env", threadID: "thread")
|
||||
|
||||
mailbox.put(route)
|
||||
|
||||
#expect(mailbox.peek() == route)
|
||||
#expect(mailbox.take() == route)
|
||||
#expect(mailbox.take() == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func resolverScopesDuplicateWireIDsAndPrefersActiveEnvironment() throws {
|
||||
let active = FeatureEnvironment(
|
||||
id: "active",
|
||||
name: "Active",
|
||||
endpoint: "https://active.example",
|
||||
isActive: true
|
||||
)
|
||||
let passive = FeatureEnvironment(
|
||||
id: "passive",
|
||||
name: "Passive",
|
||||
endpoint: "https://passive.example"
|
||||
)
|
||||
let activeProject = FeatureProject(
|
||||
id: "project-active",
|
||||
wireID: "shared-project",
|
||||
environmentID: active.id,
|
||||
name: "Active project",
|
||||
path: "/active"
|
||||
)
|
||||
let passiveProject = FeatureProject(
|
||||
id: "project-passive",
|
||||
wireID: "shared-project",
|
||||
environmentID: passive.id,
|
||||
name: "Passive project",
|
||||
path: "/passive"
|
||||
)
|
||||
let activeThread = FeatureThread(
|
||||
id: "thread-active",
|
||||
wireID: "shared-thread",
|
||||
projectID: activeProject.id,
|
||||
environmentID: active.id,
|
||||
title: "Active thread"
|
||||
)
|
||||
let passiveThread = FeatureThread(
|
||||
id: "thread-passive",
|
||||
wireID: "shared-thread",
|
||||
projectID: passiveProject.id,
|
||||
environmentID: passive.id,
|
||||
title: "Passive thread"
|
||||
)
|
||||
let snapshot = FeatureSnapshot(
|
||||
environments: [active, passive],
|
||||
projects: [passiveProject, activeProject],
|
||||
threads: [passiveThread, activeThread]
|
||||
)
|
||||
|
||||
#expect(
|
||||
PlatformRouteResolver.thread(
|
||||
in: snapshot,
|
||||
environmentID: nil,
|
||||
id: "shared-thread"
|
||||
)?.id == activeThread.id
|
||||
)
|
||||
#expect(
|
||||
PlatformRouteResolver.thread(
|
||||
in: snapshot,
|
||||
environmentID: passive.id,
|
||||
id: "shared-thread"
|
||||
)?.id == passiveThread.id
|
||||
)
|
||||
#expect(
|
||||
PlatformRouteResolver.project(
|
||||
in: snapshot,
|
||||
environmentID: passive.id,
|
||||
id: "shared-project"
|
||||
)?.id == passiveProject.id
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import T3Code
|
||||
|
||||
@Suite("Platform feedback")
|
||||
struct PlatformFeedbackTests {
|
||||
@Test
|
||||
func initialSnapshotDoesNotEmitSignals() {
|
||||
let current = [thread(id: "one", state: .waitingForApproval)]
|
||||
|
||||
#expect(PlatformThreadTransitionClassifier.signals(previous: nil, current: current).isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func classifiesAttentionFailureAndCompletionTransitions() {
|
||||
let previousThreads = [
|
||||
thread(id: "approval", state: .working),
|
||||
thread(id: "failure", state: .working),
|
||||
thread(id: "complete", state: .working),
|
||||
thread(id: "idle-complete", state: .idle),
|
||||
]
|
||||
let previous = Dictionary(uniqueKeysWithValues: previousThreads.map { ($0.id, $0) })
|
||||
let current = [
|
||||
thread(id: "approval", state: .waitingForApproval),
|
||||
thread(id: "failure", state: .failed),
|
||||
thread(id: "complete", state: .completed),
|
||||
thread(id: "idle-complete", state: .completed),
|
||||
]
|
||||
|
||||
let signals = PlatformThreadTransitionClassifier.signals(previous: previous, current: current)
|
||||
|
||||
#expect(signals.map(\.thread.id) == ["approval", "failure", "complete"])
|
||||
#expect(signals.map(\.kind) == [.warning, .error, .success])
|
||||
}
|
||||
|
||||
@Test
|
||||
func notificationPayloadSupportsURLAndServerFields() {
|
||||
let routeFromURL = PlatformNotificationPayload.route(from: [
|
||||
"deep_link": "t3code://threads/environment/thread",
|
||||
])
|
||||
let routeFromFields = PlatformNotificationPayload.route(from: [
|
||||
"environmentId": "environment",
|
||||
"threadId": "thread",
|
||||
])
|
||||
|
||||
#expect(routeFromURL == .thread(environmentID: "environment", threadID: "thread"))
|
||||
#expect(routeFromFields == .thread(environmentID: "environment", threadID: "thread"))
|
||||
}
|
||||
|
||||
@Test
|
||||
func recentThreadStoreSortsLimitsAndSkipsArchived() throws {
|
||||
let suiteName = "PlatformFeedbackTests.\(UUID().uuidString)"
|
||||
let defaults = try #require(UserDefaults(suiteName: suiteName))
|
||||
defer { defaults.removePersistentDomain(forName: suiteName) }
|
||||
let store = PlatformRecentThreadStore(defaults: defaults, key: "recent")
|
||||
var threads = (0 ..< 14).map { index in
|
||||
thread(
|
||||
id: "thread-\(index)",
|
||||
state: .idle,
|
||||
updatedAt: Date(timeIntervalSince1970: TimeInterval(index))
|
||||
)
|
||||
}
|
||||
threads[13].isArchived = true
|
||||
|
||||
store.update(from: threads)
|
||||
let records = store.records()
|
||||
|
||||
#expect(records.count == 12)
|
||||
#expect(records.first?.id == "thread-12")
|
||||
#expect(!records.contains { $0.id == "thread-13" })
|
||||
}
|
||||
|
||||
private func thread(
|
||||
id: String,
|
||||
state: FeatureThreadState,
|
||||
updatedAt: Date = .now
|
||||
) -> FeatureThread {
|
||||
FeatureThread(
|
||||
id: id,
|
||||
wireID: "wire-\(id)",
|
||||
projectID: "project",
|
||||
environmentID: "environment",
|
||||
title: "Thread \(id)",
|
||||
updatedAt: updatedAt,
|
||||
state: state
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user