fix(swift-ios): address native client reliability feedback

This commit is contained in:
Theo Browne committed 2026-08-09 20:55:02 -07:00
1 parent 13bb317da2
commit 2b8a3ca847
18 files changed
+681 -182

No files matched your search

@@ -55,6 +55,7 @@ public final class T3ConnectController {
private let auth: T3ConnectClerkSession?
private let relay: T3ConnectRelayClient?
private var registeredDeviceID: String?
private var refreshGeneration: UInt64 = 0
public init(
resolution: T3ConnectConfigurationResolution = T3ConnectConfiguration.resolve(),
@@ -86,19 +87,26 @@ public final class T3ConnectController {
public func refresh() async {
guard let auth, let relay else { return }
refreshGeneration &+= 1
let generation = refreshGeneration
isRefreshing = true
defer { isRefreshing = false }
defer {
if refreshGeneration == generation { isRefreshing = false }
}
do {
if !auth.isLoaded { try await auth.refresh() }
guard refreshGeneration == generation else { return }
account = auth.account
guard account != nil else {
environments = []
return
}
let token = try await auth.relayToken()
guard refreshGeneration == generation else { return }
let records = try await relay.listEnvironments(clerkToken: token)
guard refreshGeneration == generation else { return }
environments = records.map { T3ConnectCloudEnvironment(environment: $0) }
environments = await withTaskGroup(
let loaded = await withTaskGroup(
of: T3ConnectCloudEnvironment.self,
returning: [T3ConnectCloudEnvironment].self
) { group in
@@ -124,28 +132,43 @@ public final class T3ConnectController {
$0.environment.linkedAt > $1.environment.linkedAt
}
}
guard refreshGeneration == generation else { return }
environments = loaded
} catch {
errorMessage = error.localizedDescription
if refreshGeneration == generation {
errorMessage = error.localizedDescription
}
}
}
public func signIn(with provider: T3ConnectSignInProvider) async {
guard let auth else { return }
refreshGeneration &+= 1
let generation = refreshGeneration
isRefreshing = true
defer { isRefreshing = false }
defer {
if refreshGeneration == generation { isRefreshing = false }
}
do {
try await auth.signIn(with: provider)
guard refreshGeneration == generation else { return }
account = auth.account
await refresh()
} catch {
errorMessage = error.localizedDescription
if refreshGeneration == generation {
errorMessage = error.localizedDescription
}
}
}
public func signOut() async {
guard let auth, let relay else { return }
refreshGeneration &+= 1
let generation = refreshGeneration
isRefreshing = true
defer { isRefreshing = false }
defer {
if refreshGeneration == generation { isRefreshing = false }
}
do {
if let registeredDeviceID,
let token = try? await loadedRelayToken(auth) {
@@ -158,12 +181,15 @@ public final class T3ConnectController {
)
}
try await auth.signOut()
guard refreshGeneration == generation else { return }
await relay.clearTokenCache()
registeredDeviceID = nil
account = nil
environments = []
} catch {
errorMessage = error.localizedDescription
if refreshGeneration == generation {
errorMessage = error.localizedDescription
}
}
}
@@ -90,6 +90,12 @@ public actor T3ConnectManagedEnvironmentAuthorizer {
"The managed environment HTTP URL is invalid."
)
}
let thumbprint = try await signer.thumbprint()
guard thumbprint == credential.proofKeyThumbprint else {
throw T3ConnectRelayError.invalidConfiguration(
"The managed credential is bound to a different device identity."
)
}
let target = endpoint(httpBaseURL, path: ["oauth", "token"])
let proof = try await signer.proof(method: "POST", url: target)
var fields = [
@@ -126,12 +132,6 @@ public actor T3ConnectManagedEnvironmentAuthorizer {
}
throw T3ConnectRelayError.invalidResponse
}
let thumbprint = try await signer.thumbprint()
guard thumbprint == credential.proofKeyThumbprint else {
throw T3ConnectRelayError.invalidConfiguration(
"The managed credential is bound to a different device identity."
)
}
return T3ConnectEnvironmentAccessToken(
environmentID: credential.environmentID,
label: credential.label,
@@ -118,7 +118,7 @@ public actor T3ConnectRelayClient {
method: "DELETE"
)
request.setValue("Bearer \(clerkToken)", forHTTPHeaderField: "Authorization")
_ = try await send(request, as: OKResponse.self)
try requireOK(try await send(request, as: OKResponse.self))
}
public func status(
@@ -184,13 +184,14 @@ public actor T3ConnectRelayClient {
)
}
let body = try JSONEncoder.t3.encode(registration)
let _: OKResponse = try await sendDPoP(
let response: OKResponse = try await sendDPoP(
path: ["v1", "mobile", "devices"],
method: "POST",
body: body,
clerkToken: clerkToken,
scopes: [.mobileRegistration]
)
try requireOK(response)
}
public func registerLiveActivity(
@@ -198,23 +199,25 @@ public actor T3ConnectRelayClient {
clerkToken: String
) async throws {
let body = try JSONEncoder.t3.encode(registration)
let _: OKResponse = try await sendDPoP(
let response: OKResponse = try await sendDPoP(
path: ["v1", "mobile", "live-activities"],
method: "POST",
body: body,
clerkToken: clerkToken,
scopes: [.mobileRegistration]
)
try requireOK(response)
}
public func unregisterDevice(deviceID: String, clerkToken: String) async throws {
let _: OKResponse = try await sendDPoP(
let response: OKResponse = try await sendDPoP(
path: ["v1", "mobile", "devices", deviceID],
method: "DELETE",
body: nil,
clerkToken: clerkToken,
scopes: [.mobileRegistration]
)
try requireOK(response)
}
public func clearTokenCache() {
@@ -351,11 +354,23 @@ public actor T3ConnectRelayClient {
}
private func endpoint(_ path: [String]) -> URL {
path.reduce(configuration.relayHTTPURL) { partial, component in
var components = URLComponents(
url: configuration.relayHTTPURL,
resolvingAgainstBaseURL: false
)
components?.path = ""
components?.query = nil
components?.fragment = nil
let origin = components?.url ?? configuration.relayHTTPURL
return path.reduce(origin) { partial, component in
partial.appendingPathComponent(component)
}
}
private func requireOK(_ response: OKResponse) throws {
guard response.ok else { throw T3ConnectRelayError.invalidResponse }
}
private func send<Response: Decodable & Sendable>(
_ request: URLRequest,
as type: Response.Type
+30 -4
View File
@@ -281,14 +281,16 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
func activateEnvironment(id: String) async throws {
let activated = try await runtime.activate(id: id)
await adoptEnvironment(activated.environment, client: activated)
try await refresh(client: activated)
startPolling(activated)
}
func removeEnvironment(id: String) async throws {
if activeEnvironment?.id == id {
let removesActiveEnvironment = activeEnvironment?.id == id
try await runtime.remove(id: id)
if removesActiveEnvironment {
await clearActiveEnvironment(disconnectClient: false)
}
try await runtime.remove(id: id)
}
func disconnect() async {
@@ -1095,6 +1097,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
activeThreadID = route.uiID
activeThreadEnvironmentID = environment.id
threadHistoryEpoch &+= 1
let historyEpoch = threadHistoryEpoch
pendingOlderThreadPage = nil
activeThreadPage = nil
let supportsPagination = serverConfigsByEnvironmentID[
@@ -1104,7 +1107,10 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
id: route.wireID,
turnLimit: supportsPagination ? Self.initialThreadUserTurnLimit : nil
)
guard isKnownClient(client, environmentID: environment.id, generation: generation) else {
guard isKnownClient(client, environmentID: environment.id, generation: generation),
threadHistoryEpoch == historyEpoch,
activeThreadID == route.uiID,
activeThreadEnvironmentID == environment.id else {
throw CancellationError()
}
activeThreadPage = featurePage(snapshot.page)
@@ -4969,6 +4975,7 @@ enum NativeThreadDetailReducer {
}
var latestTurn = thread.latestTurn
var checkpoints = thread.checkpoints
if role == "assistant", let turnID,
latestTurn == nil || latestTurn?.turnId == turnID {
let turnStillRunning = thread.session?.status == "running"
@@ -4988,9 +4995,28 @@ enum NativeThreadDetailReducer {
completedAt: settlesTurn ? updatedAt : previous?.completedAt,
assistantMessageId: id
)
checkpoints = checkpoints.map { checkpoint in
guard checkpoint.turnId == turnID,
checkpoint.assistantMessageId == nil else { return checkpoint }
return CheckpointSummary(
turnId: checkpoint.turnId,
checkpointTurnCount: checkpoint.checkpointTurnCount,
checkpointRef: checkpoint.checkpointRef,
status: checkpoint.status,
files: checkpoint.files,
assistantMessageId: id,
completedAt: checkpoint.completedAt
)
}
}
return .updated(
replacing(thread, messages: messages, latestTurn: latestTurn, updatedAt: occurredAt)
replacing(
thread,
messages: messages,
checkpoints: checkpoints,
latestTurn: latestTurn,
updatedAt: occurredAt
)
)
}
+75 -19
View File
@@ -956,6 +956,15 @@ public actor T3Client {
/// Owns persisted environment selection and constructs scoped clients without
/// introducing UI-framework state into Core.
public struct EnvironmentPersistenceError: LocalizedError, Sendable {
public let operationError: String
public let rollbackErrors: [String]
public var errorDescription: String? {
"\(operationError) Recovery also failed: \(rollbackErrors.joined(separator: "; "))"
}
}
public actor EnvironmentRuntime {
public let environmentStore: EnvironmentStore
public let credentialStore: any CredentialStore
@@ -1064,39 +1073,86 @@ public actor EnvironmentRuntime {
try await environmentStore.upsert(environment)
try await environmentStore.setActiveEnvironment(id: environment.id)
} catch {
if let previousCredential {
try? await credentialStore.setCredential(
previousCredential,
for: environment.id
)
} else {
try? await credentialStore.removeCredential(for: environment.id)
let operationError = error
var rollbackErrors: [String] = []
do {
if let previousCredential {
try await credentialStore.setCredential(
previousCredential,
for: environment.id
)
} else {
try await credentialStore.removeCredential(for: environment.id)
}
} catch {
rollbackErrors.append("credential: \(error.localizedDescription)")
}
// EnvironmentStore's individual mutations are actor-atomic. Undo
// only this record so a concurrent save for another environment
// cannot be lost while this actor is reentrant across awaits.
let activeIDAfterFailure = try? await environmentStore.activeEnvironmentID()
if let previousEnvironment {
_ = try? await environmentStore.upsert(previousEnvironment)
} else {
_ = try? await environmentStore.remove(id: environment.id)
do {
if let previousEnvironment {
_ = try await environmentStore.upsert(previousEnvironment)
} else {
_ = try await environmentStore.remove(id: environment.id)
}
} catch {
rollbackErrors.append("environment catalog: \(error.localizedDescription)")
}
if activeIDAfterFailure == environment.id {
try? await environmentStore.setActiveEnvironment(id: previousActiveID)
do {
let activeIDAfterFailure = try await environmentStore.activeEnvironmentID()
if activeIDAfterFailure == environment.id {
try await environmentStore.setActiveEnvironment(id: previousActiveID)
}
} catch {
rollbackErrors.append("active environment: \(error.localizedDescription)")
}
throw error
guard rollbackErrors.isEmpty else {
throw EnvironmentPersistenceError(
operationError: operationError.localizedDescription,
rollbackErrors: rollbackErrors
)
}
throw operationError
}
return await client(for: environment)
}
public func remove(id: String) async throws {
if let client = clients.removeValue(forKey: id) {
await client.disconnect()
}
let previousEnvironment = try await environmentStore.load()
.first(where: { $0.id == id })
let previousActiveID = try await environmentStore.activeEnvironmentID()
// Never leave a catalog entry pointing at a credential that was
// already destroyed when the catalog write itself fails.
try await environmentStore.remove(id: id)
try await credentialStore.removeCredential(for: id)
do {
try await credentialStore.removeCredential(for: id)
} catch {
let operationError = error
var rollbackErrors: [String] = []
if let previousEnvironment {
do {
_ = try await environmentStore.upsert(previousEnvironment)
} catch {
rollbackErrors.append("environment catalog: \(error.localizedDescription)")
}
}
do {
try await environmentStore.setActiveEnvironment(id: previousActiveID)
} catch {
rollbackErrors.append("active environment: \(error.localizedDescription)")
}
guard rollbackErrors.isEmpty else {
throw EnvironmentPersistenceError(
operationError: operationError.localizedDescription,
rollbackErrors: rollbackErrors
)
}
throw operationError
}
if let client = clients.removeValue(forKey: id) {
await client.disconnect()
}
}
/// Returns the cached client for a saved environment without changing the
+7 -4
View File
@@ -593,12 +593,15 @@ public actor WebSocketRPCClient {
payload: subscription.payload,
headers: []
)
// Install ownership before suspending in send. A very fast response can
// otherwise arrive before the request is routable, while termination
// during the send must be able to remove the exact in-flight mapping.
subscription.requestID = requestID
subscription.requestConnectionID = connectionID
subscriptions[subscriptionID] = subscription
subscriptionByRequestID[requestID] = subscriptionID
do {
try await connection.send(JSONEncoder.t3.encode(envelope))
subscription.requestID = requestID
subscription.requestConnectionID = connectionID
subscriptions[subscriptionID] = subscription
subscriptionByRequestID[requestID] = subscriptionID
} catch {
// Retain the subscription for the next socket, but make the send
// failure visible to the connection loop by closing this socket.
@@ -10,6 +10,8 @@
<dict>
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationDictionaryVersion</key>
<integer>2</integer>
<key>NSExtensionActivationSupportsImageWithMaxCount</key>
<integer>8</integer>
<key>NSExtensionActivationSupportsText</key>
@@ -42,6 +42,8 @@ struct FeatureImageAttachmentPicker: View {
let isEnabled: Bool
@State private var isAttachmentSourcePresented = false
@State private var isPhotoLibraryPresented = false
@State private var selectedPhotoItems: [PhotosPickerItem] = []
@State private var isCameraPresented = false
@State private var isFileImporterPresented = false
@State private var errorMessage: String?
@@ -75,7 +77,7 @@ struct FeatureImageAttachmentPicker: View {
.accessibilityIdentifier("image-attachment-picker")
.accessibilityHint(attachmentAccessibilityHint)
.confirmationDialog("Add image", isPresented: $isAttachmentSourcePresented) {
Button("Photo Library") { presentPhotoLibrary() }
Button("Photo Library") { isPhotoLibraryPresented = true }
Button("Camera") { isCameraPresented = true }
.disabled(!UIImagePickerController.isSourceTypeAvailable(.camera))
Button("Files") { isFileImporterPresented = true }
@@ -88,6 +90,16 @@ struct FeatureImageAttachmentPicker: View {
)
.ignoresSafeArea()
}
.photosPicker(
isPresented: $isPhotoLibraryPresented,
selection: $selectedPhotoItems,
maxSelectionCount: max(1, remainingCount),
matching: .images,
preferredItemEncoding: .current
)
.onChange(of: selectedPhotoItems) { _, items in
loadPhotoSelections(items)
}
.fileImporter(
isPresented: $isFileImporterPresented,
allowedContentTypes: [.image],
@@ -127,27 +139,25 @@ struct FeatureImageAttachmentPicker: View {
return "Choose a photo, take a photo, or browse image files"
}
private func presentPhotoLibrary() {
// A confirmation dialog remains the active presenter during its action. Dispatch
// independently of the dialog's view task so dismissal cannot cancel presentation.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
FeaturePhotoLibraryPresenter.present(maximumCount: max(1, remainingCount)) { image in
loadPhotoSelection(image)
}
}
}
private func loadPhotoSelection(_ image: Data) {
guard remainingCount > 0 else { return }
let ordinal = attachments.count + preparationState.pendingItemCount + 1
let operation = preparationState.begin(itemCount: 1)
private func loadPhotoSelections(_ items: [PhotosPickerItem]) {
guard !items.isEmpty, canAdd else { return }
let selected = Array(items.prefix(remainingCount))
selectedPhotoItems = []
let firstOrdinal = attachments.count + preparationState.pendingItemCount + 1
let operation = preparationState.begin(itemCount: selected.count)
Task {
defer { preparationState.finish(operation) }
do {
try await appendImage(image, ordinal: ordinal)
} catch {
errorMessage = error.localizedDescription
for (offset, item) in selected.enumerated() {
do {
guard let data = try await item.loadTransferable(type: Data.self) else {
throw FeatureImageAttachmentError.encodingFailed
}
try await appendImage(data, ordinal: firstOrdinal + offset)
} catch {
errorMessage = error.localizedDescription
break
}
}
}
}
@@ -211,92 +221,6 @@ struct FeatureImageAttachmentPicker: View {
}
}
@MainActor
private enum FeaturePhotoLibraryPresenter {
private static var delegates: [ObjectIdentifier: Delegate] = [:]
static func present(maximumCount: Int, onSelect: @escaping (Data) -> Void) {
var configuration = PHPickerConfiguration(photoLibrary: .shared())
configuration.filter = .images
configuration.selectionLimit = maximumCount
configuration.preferredAssetRepresentationMode = .current
let picker = PHPickerViewController(configuration: configuration)
let delegate = Delegate(onSelect: onSelect)
picker.delegate = delegate
delegates[ObjectIdentifier(picker)] = delegate
guard let presenter = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.flatMap(\.windows)
.first(where: \.isKeyWindow)?
.rootViewController?
.topPresentedViewController
else {
delegates.removeValue(forKey: ObjectIdentifier(picker))
return
}
presenter.present(picker, animated: true)
}
private static func finish(_ picker: PHPickerViewController) {
delegates.removeValue(forKey: ObjectIdentifier(picker))
}
final class Delegate: NSObject, PHPickerViewControllerDelegate {
private struct Provider: @unchecked Sendable {
let value: NSItemProvider
}
private let onSelect: (Data) -> Void
init(onSelect: @escaping (Data) -> Void) {
self.onSelect = onSelect
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
guard !results.isEmpty else { return FeaturePhotoLibraryPresenter.finish(picker) }
let providers = results.map { Provider(value: $0.itemProvider) }
Task { @MainActor in
await withTaskGroup(of: Data?.self) { group in
for provider in providers {
group.addTask {
try? await provider.value.imageData()
}
}
for await data in group {
guard let data else { continue }
onSelect(data)
}
}
FeaturePhotoLibraryPresenter.finish(picker)
}
}
}
}
private extension UIViewController {
var topPresentedViewController: UIViewController {
presentedViewController?.topPresentedViewController ?? self
}
}
private extension NSItemProvider {
func imageData() async throws -> Data {
try await withCheckedThrowingContinuation { continuation in
loadDataRepresentation(forTypeIdentifier: UTType.image.identifier) { data, error in
if let data {
continuation.resume(returning: data)
} else {
continuation.resume(throwing: error ?? FeatureImageAttachmentError.encodingFailed)
}
}
}
}
}
struct FeatureAttachmentStrip: View {
@Binding var attachments: [FeatureDraftAttachment]
@@ -64,6 +64,7 @@ struct MarkdownMessageView: View {
}
.task(id: RenderRequest(revision: revision, isStreaming: isStreaming)) {
if !isStreaming {
streamingRenderer.cancel()
// Streaming -> complete usually keeps the final text; promote
// the last streamed render instead of reparsing synchronously.
if let renderedDocument, renderedDocument.revision == revision {
@@ -140,6 +141,7 @@ private final class StreamingMarkdownRenderer {
}
func cancel() {
generation += 1
renderTask?.cancel()
renderTask = nil
pending = nil
@@ -293,7 +295,11 @@ private struct MarkdownTableView: View {
width: columnWidths[columnIndex],
alignment: alignment(for: columnIndex)
)
.frame(minHeight: 44, alignment: alignment(for: columnIndex))
.frame(
minHeight: 44,
maxHeight: .infinity,
alignment: alignment(for: columnIndex)
)
.padding(.horizontal, 11)
.padding(.vertical, 8)
.overlay(alignment: .trailing) {
@@ -131,10 +131,11 @@ public struct ConnectionOnboardingView: View {
.foregroundStyle(T3Colors.textSecondary)
.padding(.top, 12)
if let capability = model.client as? any T3ConnectCapable {
if let capability = model.client as? any T3ConnectCapable,
capability.t3ConnectController.unavailableReason == nil {
NavigationLink {
T3ConnectView(capability: capability) {
await model.reload()
await model.reloadAfterConnection()
onConnected()
}
} label: {
@@ -76,6 +76,11 @@ public final class FeatureRootModel {
}
}
public func reloadAfterConnection() async {
clearDetails()
await reload()
}
public func pair(endpoint: String, token: String?) async -> Bool {
await perform {
try await client.pair(endpoint: endpoint, token: token)
@@ -302,11 +307,6 @@ public final class FeatureRootModel {
mutateThread(id: id) {
$0.pinnedAt = pinned ? Date.now : nil
if pinned {
if $0.isSettled {
$0.isSettled = false
$0.keepsActive = true
$0.settledAt = nil
}
$0.snoozedUntil = nil
$0.snoozedAt = nil
}
@@ -525,7 +525,8 @@ public final class FeatureRootModel {
)
}
public func saveSettings(_ settings: FeatureSettings) async {
@discardableResult
public func saveSettings(_ settings: FeatureSettings) async -> Bool {
await perform {
try await client.saveSettings(settings)
snapshot.settings = settings
@@ -687,24 +688,26 @@ public final class FeatureRootModel {
}
private func store(_ incoming: FeatureThreadDetail) {
let incoming = retainingLocalAttachmentPreviews(in: incoming)
let id = incoming.thread.id
acknowledgeDeliveredMessages(incoming.messages)
let incoming = addingPendingMessages(to: incoming)
let prepared = addingPendingMessages(to: incoming)
let next = details[id].map { current in
FeatureThreadDetail(
thread: incoming.thread,
messages: replacingChangedSuffix(current.messages, with: incoming.messages),
approvals: replacingChangedSuffix(current.approvals, with: incoming.approvals),
userInputs: replacingChangedSuffix(current.userInputs, with: incoming.userInputs),
page: incoming.page
thread: prepared.thread,
messages: replacingChangedSuffix(current.messages, with: prepared.messages),
approvals: replacingChangedSuffix(current.approvals, with: prepared.approvals),
userInputs: replacingChangedSuffix(current.userInputs, with: prepared.userInputs),
page: prepared.page
)
} ?? incoming
} ?? prepared
guard details[id] != next else { return }
details[id] = next
bumpDetailRevision(id: id, change: .full)
}
private func store(_ incoming: FeatureThreadDetail, delta: FeatureDetailDelta) {
let incoming = retainingLocalAttachmentPreviews(in: incoming)
let id = incoming.thread.id
acknowledgeDeliveredMessages(incoming.messages)
let next = addingPendingMessages(to: incoming)
@@ -911,6 +914,38 @@ public final class FeatureRootModel {
return result
}
private func retainingLocalAttachmentPreviews(
in incoming: FeatureThreadDetail
) -> FeatureThreadDetail {
guard let current = details[incoming.thread.id] else { return incoming }
let currentMessages = current.messages.reduce(into: [String: FeatureMessage]()) {
$0[$1.id] = $1
}
var result = incoming
result.messages = incoming.messages.map { message in
guard let local = currentMessages[message.id], !message.attachments.isEmpty else {
return message
}
var message = message
message.attachments = message.attachments.enumerated().map { index, attachment in
guard attachment.previewData == nil else { return attachment }
let matching = local.attachments.first { candidate in
candidate.id == attachment.id
} ?? (
local.attachments.indices.contains(index)
? local.attachments[index]
: nil
)
guard let previewData = matching?.previewData else { return attachment }
var attachment = attachment
attachment.previewData = previewData
return attachment
}
return message
}
return result
}
private func acknowledgeAuthoritativeThread(_ id: String) {
guard pendingThreadsByID[id] != nil,
let submission = pendingSubmissionsByID.values.first(where: {
@@ -8,6 +8,7 @@ public struct SettingsView: View {
@State private var showingDisconnect = false
@State private var showingAddEnvironment = false
@State private var removalTarget: FeatureEnvironment?
@State private var saveErrorMessage: String?
public init(model: FeatureRootModel) {
self.model = model
@@ -71,6 +72,17 @@ public struct SettingsView: View {
} message: { environment in
Text("\(environment.name) will need a new pairing code to be added again.")
}
.alert(
"Couldn’t save settings",
isPresented: Binding(
get: { saveErrorMessage != nil },
set: { if !$0 { saveErrorMessage = nil } }
)
) {
Button("OK") { saveErrorMessage = nil }
} message: {
Text(saveErrorMessage ?? "Something went wrong.")
}
.sheet(isPresented: $showingAddEnvironment) {
ConnectionOnboardingView(
model: model,
@@ -149,6 +161,7 @@ public struct SettingsView: View {
} label: {
Label("Remove", systemImage: "trash")
}
.disabled(environment.isActive)
}
.contextMenu {
Button(role: .destructive) {
@@ -156,6 +169,7 @@ public struct SettingsView: View {
} label: {
Label("Remove saved server", systemImage: "trash")
}
.disabled(environment.isActive)
}
}
@@ -315,10 +329,12 @@ public struct SettingsView: View {
private func save() {
isSaving = true
Task {
await model.saveSettings(settings)
let didSave = await model.saveSettings(settings)
isSaving = false
if model.snapshot.settings == settings {
if didSave {
dismiss()
} else {
saveErrorMessage = model.errorMessage ?? "Settings could not be saved."
}
}
}
@@ -678,6 +678,7 @@ enum FeatureFullDiffHydrator {
var output: [FeatureDiffLine] = []
var nextNewLine = 1
var precedingAnchorOffset: Int?
for (index, line) in patchLines.enumerated() {
if let newLine = line.newLine {
if nextNewLine < newLine {
@@ -695,11 +696,19 @@ enum FeatureFullDiffHydrator {
}
output.append(line)
nextNewLine = max(nextNewLine, newLine + 1)
if let oldLine = line.oldLine {
precedingAnchorOffset = oldLine - newLine
}
} else {
let nextPatchLine = patchLines.dropFirst(index + 1).compactMap(\.newLine).first
?? (newLines.count + 1)
if nextNewLine < nextPatchLine {
for number in nextNewLine ..< nextPatchLine
let insertionLine: Int
if let oldLine = line.oldLine, let precedingAnchorOffset {
insertionLine = oldLine - precedingAnchorOffset
} else {
insertionLine = patchLines.dropFirst(index + 1).compactMap(\.newLine).first
?? (newLines.count + 1)
}
if nextNewLine < insertionLine {
for number in nextNewLine ..< insertionLine
where newLines.indices.contains(number - 1) {
output.append(
FeatureDiffLine(
@@ -711,7 +720,7 @@ enum FeatureFullDiffHydrator {
)
)
}
nextNewLine = nextPatchLine
nextNewLine = insertionLine
}
output.append(line)
}
@@ -192,18 +192,22 @@ public struct FeatureTerminalView: View {
private func sendCommand() {
guard isRunning, !input.isEmpty else { return }
let command = input
input = ""
Task {
await write(command + "\n")
if await write(command + "\r") {
input = ""
}
inputFocused = true
}
}
private func write(_ data: String) async {
@discardableResult
private func write(_ data: String) async -> Bool {
do {
try await client.writeTerminal(threadID: threadID, data: data)
return true
} catch {
errorMessage = error.localizedDescription
return false
}
}
}
@@ -622,6 +622,81 @@ final class T3ConnectRuntimeTests: XCTestCase {
})
}
func testRelayRoutesReplaceConfiguredBasePathAndQuery() async throws {
let signer = try testSigner()
let transport = T3ConnectScriptedHTTPTransport { request, ordinal in
switch ordinal {
case 1:
XCTAssertEqual(request.url?.path, "/v1/client/dpop-token")
XCTAssertNil(request.url?.query)
return (.relayToken("relay-mobile", scope: "mobile:registration"), 200)
case 2:
XCTAssertEqual(request.url?.path, "/v1/mobile/devices")
XCTAssertNil(request.url?.query)
return (Data(#"{"ok":true}"#.utf8), 200)
default:
throw T3ConnectTestError.unexpectedPath(request.url?.path)
}
}
let relay = T3ConnectRelayClient(
configuration: T3ConnectConfiguration(
clerkPublishableKey: "pk_test",
relayHTTPURL: URL(string: "https://relay.example/stale/base?old=true")!
),
transport: transport,
signer: signer
)
try await relay.registerDevice(
testDeviceRegistration(),
clerkToken: clerkJWT(subject: "mobile-account")
)
}
func testRelayRejectsFalseOKResponse() async throws {
let signer = try testSigner()
let transport = T3ConnectScriptedHTTPTransport { _, ordinal in
switch ordinal {
case 1:
return (.relayToken("relay-mobile", scope: "mobile:registration"), 200)
case 2:
return (Data(#"{"ok":false}"#.utf8), 200)
default:
throw T3ConnectTestError.unexpectedPath(nil)
}
}
let relay = T3ConnectRelayClient(
configuration: T3ConnectConfiguration(
clerkPublishableKey: "pk_test",
relayHTTPURL: URL(string: "https://relay.example")!
),
transport: transport,
signer: signer
)
do {
try await relay.registerDevice(
testDeviceRegistration(),
clerkToken: clerkJWT(subject: "mobile-account")
)
XCTFail("A false success envelope was accepted")
} catch T3ConnectRelayError.invalidResponse {
// Expected contract rejection.
}
}
private func testDeviceRegistration() -> T3ConnectDeviceRegistration {
T3ConnectDeviceRegistration(
deviceID: "phone-1",
label: "Big O",
iosMajorVersion: 26,
bundleID: "com.t3tools.t3code.swiftui",
apsEnvironment: .sandbox,
pushToken: "apns-token",
pushToStartToken: "start-token"
)
}
private func refreshFixture(
savedThumbprint: String?,
expiresAt: Date
@@ -266,6 +266,185 @@ final class WebSocketRPCRaceTests: XCTestCase {
XCTAssertTrue(isConnected, "Completing an old stop must not clear a newer socket.")
await client.stop()
}
func testSubscriptionRoutesChunkBeforeSuspendedSendReturns() async throws {
let connection = SubscriptionSendRaceConnection()
let client = WebSocketRPCClient(
connector: SequencedConnector(connections: [connection]),
endpointProvider: { URL(string: "wss://studio.example/ws")! }
)
await client.start()
await connection.waitUntilReceiveCount(1)
let stream = await client.subscribe("thread.events", as: JSONValue.self)
var iterator = stream.makeAsyncIterator()
await connection.waitUntilRequestSuspended()
await connection.waitUntilReceiveCount(2)
await connection.releaseRequest()
let value = try await iterator.next()
XCTAssertEqual(value, .object(["event": .string("ready")]))
await client.stop()
}
func testCancellingSubscriptionWhileSendIsSuspendedInterruptsWithoutResurrection() async {
let connection = SubscriptionSendRaceConnection()
let client = WebSocketRPCClient(
connector: SequencedConnector(connections: [connection]),
endpointProvider: { URL(string: "wss://studio.example/ws")! }
)
await client.start()
await connection.waitUntilReceiveCount(1)
var stream: AsyncThrowingStream<JSONValue, Error>? = await client.subscribe(
"thread.events",
as: JSONValue.self
)
let consumer = Task {
var iterator = stream!.makeAsyncIterator()
return try await iterator.next()
}
await connection.waitUntilRequestSuspended()
consumer.cancel()
stream = nil
_ = try? await consumer.value
let observedInterrupt = await connection.observesInterrupt()
XCTAssertTrue(observedInterrupt)
await connection.releaseRequest()
await client.stop()
}
}
private actor SubscriptionSendRaceConnection: WebSocketConnection {
private var requestID: Int?
private var requestContinuation: CheckedContinuation<Void, Never>?
private var requestWaiters: [CheckedContinuation<Void, Never>] = []
private var receiveContinuation: CheckedContinuation<Data, Error>?
private var receiveCount = 0
private var receiveWaiters: [(Int, CheckedContinuation<Void, Never>)] = []
private var queuedResponses: [Data] = []
private var interruptCount = 0
private var interruptWaiters: [CheckedContinuation<Void, Never>] = []
func send(_ data: Data) async throws {
let envelope = try JSONDecoder.t3.decode(JSONValue.self, from: data)
switch envelope["_tag"]?.stringValue {
case "Request":
guard requestID == nil,
case let .number(rawID)? = envelope["id"],
let id = Int(exactly: rawID) else { return }
requestID = id
enqueue(try chunk(requestID: id))
let waiters = requestWaiters
requestWaiters.removeAll()
waiters.forEach { $0.resume() }
await withCheckedContinuation { continuation in
requestContinuation = continuation
}
enqueue(try exit(requestID: id))
case "Interrupt":
interruptCount += 1
let waiters = interruptWaiters
interruptWaiters.removeAll()
waiters.forEach { $0.resume() }
default:
return
}
}
func receive() async throws -> Data {
receiveCount += 1
let ready = receiveWaiters.filter { receiveCount >= $0.0 }
receiveWaiters.removeAll { receiveCount >= $0.0 }
ready.forEach { $0.1.resume() }
if !queuedResponses.isEmpty { return queuedResponses.removeFirst() }
return try await withCheckedThrowingContinuation { continuation in
receiveContinuation = continuation
}
}
func close() {
requestContinuation?.resume()
requestContinuation = nil
receiveContinuation?.resume(throwing: CancellationError())
receiveContinuation = nil
}
func waitUntilRequestSuspended() async {
guard requestID == nil else { return }
await withCheckedContinuation { continuation in
requestWaiters.append(continuation)
}
}
func waitUntilReceiveCount(_ count: Int) async {
guard receiveCount < count else { return }
await withCheckedContinuation { continuation in
receiveWaiters.append((count, continuation))
}
}
func releaseRequest() {
requestContinuation?.resume()
requestContinuation = nil
}
func observesInterrupt() async -> Bool {
if interruptCount > 0 { return true }
return await withTaskGroup(of: Bool.self) { group in
group.addTask {
await self.waitUntilInterrupt()
return true
}
group.addTask {
try? await Task.sleep(for: .milliseconds(500))
return false
}
let result = await group.next() ?? false
group.cancelAll()
return result
}
}
private func waitUntilInterrupt() async {
guard interruptCount == 0 else { return }
await withCheckedContinuation { continuation in
interruptWaiters.append(continuation)
}
}
private func enqueue(_ data: Data) {
if let receiveContinuation {
self.receiveContinuation = nil
receiveContinuation.resume(returning: data)
} else {
queuedResponses.append(data)
}
}
private func chunk(requestID: Int) throws -> Data {
try JSONEncoder.t3.encode(
JSONValue.object([
"_tag": .string("Chunk"),
"requestId": .number(Double(requestID)),
"values": .array([.object(["event": .string("ready")])]),
])
)
}
private func exit(requestID: Int) throws -> Data {
try JSONEncoder.t3.encode(
JSONValue.object([
"_tag": .string("Exit"),
"requestId": .number(Double(requestID)),
"exit": .object([
"_tag": .string("Success"),
"value": .null,
]),
])
)
}
}
private actor CloseTrackingConnection: WebSocketConnection {
@@ -652,7 +652,7 @@ struct FeatureRootModelTests {
}
@Test
func testPinOptimisticallyPromotesAParkedThread() async {
func testPinOptimisticallyWakesWithoutInventingSettlementOverride() async {
let client = FeatureClientStub()
var thread = FeatureThread(
id: "thread-1",
@@ -672,9 +672,9 @@ struct FeatureRootModelTests {
let updated = model.snapshot.threads[0]
#expect(updated.pinnedAt != nil)
#expect(!updated.isSettled)
#expect(updated.keepsActive)
#expect(updated.settledAt == nil)
#expect(updated.isSettled)
#expect(!updated.keepsActive)
#expect(updated.settledAt != nil)
#expect(updated.snoozedUntil == nil)
}
@@ -841,6 +841,65 @@ struct FeatureRootModelTests {
#expect(model.detailRevisions[thread.id] == 2)
}
@Test
func authoritativeAttachmentRetainsLocalPreviewUntilURLHydrates() async {
let client = FeatureClientStub()
let thread = FeatureThread(
id: "thread-1",
projectID: "project-1",
title: "Image preview"
)
client.snapshot = FeatureSnapshot(threads: [thread])
let preview = Data([0x01, 0x02, 0x03])
let local = FeatureThreadDetail(
thread: thread,
messages: [
FeatureMessage(
id: "message-1",
role: .user,
text: "See image",
attachments: [
FeatureMessageAttachment(
id: "local-attachment",
name: "image.jpg",
mimeType: "image/jpeg",
sizeBytes: 3,
previewData: preview
),
]
),
]
)
let authoritative = FeatureThreadDetail(
thread: thread,
messages: [
FeatureMessage(
id: "message-1",
role: .user,
text: "See image",
attachments: [
FeatureMessageAttachment(
id: "server-attachment",
name: "image.jpg",
mimeType: "image/jpeg",
sizeBytes: 3
),
]
),
]
)
let model = testRootModel(client: client)
let run = Task { await model.start() }
client.emit(.detail(local))
client.emit(.detail(authoritative))
client.finishEvents()
await run.value
#expect(model.details[thread.id]?.messages[0].attachments[0].id == "server-attachment")
#expect(model.details[thread.id]?.messages[0].attachments[0].previewData == preview)
}
@Test
func detailDeltaCarriesAContiguousRenderCursor() async {
let client = FeatureClientStub()
@@ -933,6 +992,42 @@ struct FeatureRootModelTests {
#expect(rendered.text == "Hello")
}
@Test
func detailReducerBindsCheckpointThatArrivedBeforeAssistantMessage() {
let checkpoint = CheckpointSummary(
turnId: "turn-1",
checkpointTurnCount: 1,
checkpointRef: "refs/t3/checkpoint-1",
status: "completed",
files: [],
assistantMessageId: nil,
completedAt: "2026-07-31T20:00:01Z"
)
let thread = orchestrationThread(checkpoints: [checkpoint])
let event = orchestrationEvent(
type: "thread.message-sent",
sequence: 12,
payload: [
"threadId": .string(thread.id),
"messageId": .string("assistant-1"),
"role": .string("assistant"),
"text": .string("Done"),
"turnId": .string("turn-1"),
"streaming": .bool(false),
"createdAt": .string("2026-07-31T20:00:00Z"),
"updatedAt": .string("2026-07-31T20:00:02Z"),
]
)
let reduction = NativeThreadDetailReducer.apply(event, to: thread)
guard case let .updated(updated) = reduction.result else {
Issue.record("Expected an assistant message update")
return
}
#expect(updated.checkpoints.first?.assistantMessageId == "assistant-1")
}
@Test
func activityReducerKeepsLargeSnapshotHistorySharedAndExposesOnlyTheTail() throws {
let historical = (0..<1_000).map { (index: Int) in
@@ -1023,7 +1118,8 @@ private func orchestrationEvent(
private func orchestrationThread(
messages: [OrchestrationMessage] = [],
activities: [OrchestrationActivity] = []
activities: [OrchestrationActivity] = [],
checkpoints: [CheckpointSummary] = []
) -> OrchestrationThread {
OrchestrationThread(
id: "thread-1",
@@ -1046,7 +1142,7 @@ private func orchestrationThread(
deletedAt: nil,
messages: messages,
activities: activities,
checkpoints: [],
checkpoints: checkpoints,
session: nil
)
}
@@ -196,6 +196,32 @@ struct FeatureToolStateTests {
#expect(deleted.map(\.oldLine) == [1])
}
@Test
func fullDiffHydrationKeepsDeletionAtItsPreviousAnchor() {
let file = FeatureReviewFile(
path: "App.swift",
change: .modified,
additions: 1,
deletions: 1,
lines: [
.init(id: "anchor", kind: .context, oldLine: 2, newLine: 2, text: "two"),
.init(id: "deleted", kind: .deletion, oldLine: 3, text: "three"),
.init(id: "later", kind: .addition, newLine: 7, text: "added later"),
]
)
let lines = FeatureFullDiffHydrator.lines(
for: file,
contents: FeatureReviewFileContents(
oldContents: "one\ntwo\nthree\nfour\nfive\nsix\nseven\n",
newContents: "one\ntwo\nfour\nfive\nsix\nseven\nadded later\n"
)
)
#expect(lines.firstIndex { $0.id == "deleted" } == 2)
#expect(lines.prefix(3).map(\.text) == ["one", "two", "three"])
}
@Test
func reviewCommentPromptIncludesActionableFileAndLineContext() {
let draft = FeatureReviewCommentDraft(