fix(swift-ios): address review findings

This commit is contained in:
Theo Browne committed 2026-08-09 20:55:48 -07:00
1 parent e3b3f2f62c
commit 2cbfc2ec3a
17 files changed
+566 -57

No files matched your search

@@ -66,6 +66,8 @@ public final class T3ConnectController {
private let relay: T3ConnectRelayClient?
private var registeredDeviceID: String?
private var refreshGeneration: UInt64 = 0
private var authorizationGeneration: UInt64 = 0
private var isLocalAuthorizationInvalidated = false
private var signOutOperation: (@MainActor @Sendable () async throws -> Void)?
public convenience init(
@@ -132,24 +134,32 @@ public final class T3ConnectController {
public func refresh() async {
guard let auth, let relay else { return }
guard !isLocalAuthorizationInvalidated else { return }
refreshGeneration &+= 1
let generation = refreshGeneration
let authGeneration = authorizationGeneration
isRefreshing = true
defer {
if refreshGeneration == generation { isRefreshing = false }
}
do {
if !auth.isLoaded { try await auth.refresh() }
guard refreshGeneration == generation else { return }
account = auth.account
guard refreshGeneration == generation,
authorizationGeneration == authGeneration,
!isLocalAuthorizationInvalidated else { return }
await adoptAccount(auth.account, relay: relay)
guard account != nil else {
environments = []
return
}
let token = try await auth.relayToken()
guard refreshGeneration == generation else { return }
guard refreshGeneration == generation,
authorizationGeneration == authGeneration,
!isLocalAuthorizationInvalidated else { return }
let records = try await relay.listEnvironments(clerkToken: token)
guard refreshGeneration == generation else { return }
guard refreshGeneration == generation,
authorizationGeneration == authGeneration,
!isLocalAuthorizationInvalidated else { return }
environments = records.map { T3ConnectCloudEnvironment(environment: $0) }
let loaded = await withTaskGroup(
of: T3ConnectCloudEnvironment.self,
@@ -177,7 +187,9 @@ public final class T3ConnectController {
$0.environment.linkedAt > $1.environment.linkedAt
}
}
guard refreshGeneration == generation else { return }
guard refreshGeneration == generation,
authorizationGeneration == authGeneration,
!isLocalAuthorizationInvalidated else { return }
environments = loaded
} catch {
if refreshGeneration == generation {
@@ -186,34 +198,46 @@ public final class T3ConnectController {
}
}
/// A successful authentication flow is the only action that may restore a
/// locally signed-out Clerk session.
public func refreshAfterAuthentication() async {
isLocalAuthorizationInvalidated = false
authorizationGeneration &+= 1
await refresh()
}
public func signOut() async {
guard let relay else { return }
let deviceID = registeredDeviceID
isLocalAuthorizationInvalidated = true
authorizationGeneration &+= 1
refreshGeneration &+= 1
let generation = refreshGeneration
isRefreshing = true
defer {
if refreshGeneration == generation { isRefreshing = false }
}
account = nil
environments = []
registeredDeviceID = nil
await relay.clearTokenCache()
if let auth,
let registeredDeviceID,
let token = try? await loadedRelayToken(auth) {
let deviceID,
let token = try? await auth.relayToken() {
// Remote delivery must not outlive the signed-in session on this
// install. A failed best-effort unregister must not trap the user
// in an account they are trying to leave.
try? await relay.unregisterDevice(
deviceID: registeredDeviceID,
deviceID: deviceID,
clerkToken: token
)
}
await relay.clearTokenCache()
// Local authorization state is security-sensitive and must be cleared
// before Clerk performs network work. A failed remote sign-out can be
// reported, but it cannot leave relay tokens or managed state usable.
await relay.clearTokenCache()
registeredDeviceID = nil
account = nil
environments = []
do {
if let signOutOperation {
try await signOutOperation()
@@ -319,10 +343,34 @@ public final class T3ConnectController {
}
private func loadedRelayToken(_ auth: T3ConnectClerkSession) async throws -> String {
guard !isLocalAuthorizationInvalidated else { throw T3ConnectAuthError.noSession }
let generation = authorizationGeneration
if !auth.isLoaded {
try await auth.refresh()
}
account = auth.account
return try await auth.relayToken()
guard authorizationGeneration == generation,
!isLocalAuthorizationInvalidated else { throw T3ConnectAuthError.noSession }
if let relay {
await adoptAccount(auth.account, relay: relay)
} else {
account = auth.account
}
guard account != nil else { throw T3ConnectAuthError.noSession }
let token = try await auth.relayToken()
guard authorizationGeneration == generation,
!isLocalAuthorizationInvalidated else { throw T3ConnectAuthError.noSession }
return token
}
private func adoptAccount(
_ nextAccount: T3ConnectAccount?,
relay: T3ConnectRelayClient
) async {
if account?.id != nextAccount?.id {
environments = []
registeredDeviceID = nil
await relay.clearTokenCache()
}
account = nextAccount
}
}
+105 -14
View File
@@ -63,6 +63,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
private var threadEnvironmentIDs: [String: String] = [:]
private var threadWireIDs: [String: String] = [:]
private var provisionalThreadRoutes: [String: ProvisionalThreadRoute] = [:]
private var pendingThreadCreations: [PendingThreadCreation] = []
private var environmentConnectionStates: [String: FeatureConnection.State] = [:]
private var environmentConnectionDetails: [String: String] = [:]
private var latestServerConfig: ServerConfigSnapshot?
@@ -341,14 +342,29 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
.map(\.id)
var failureCount = 0
for id in managedIDs {
var cleanupFailed = false
do {
try await runtime.revokeCredential(id: id)
} catch {
cleanupFailed = true
Self.t3ConnectLogger.error(
"Managed credential revocation failed: \(error.localizedDescription, privacy: .private)"
)
}
do {
try await removeEnvironment(id: id)
// `remove` retries credential deletion, so its success
// supersedes an earlier revocation error.
cleanupFailed = false
} catch {
failureCount += 1
cleanupFailed = true
Self.t3ConnectLogger.error(
"Managed environment removal failed: \(error.localizedDescription, privacy: .private)"
)
}
if cleanupFailed {
failureCount += 1
}
}
guard failureCount == 0 else {
throw T3ConnectManagedCleanupError(failureCount: failureCount)
@@ -572,7 +588,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
let task = Task<Data?, Never> {
do {
let resolved = try await client.resolvedAsset(
resource: .projectFavicon(cwd: key.workspaceRoot)
resource: .projectFavicon(cwd: workspaceRoot)
)
let revision = resolved.url.lastPathComponent.removingPercentEncoding
?? resolved.url.lastPathComponent
@@ -782,7 +798,6 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
let client = route.client
let environment = client.environment
let generation = environmentGeneration
let threadID = UUID().uuidString
let model = modelSelection(
selection,
projectID: route.wireID,
@@ -791,18 +806,53 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
)
let resolvedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines)
let threadTitle = resolvedTitle?.isEmpty == false ? resolvedTitle! : "New thread"
_ = try await client.createThread(
threadID: threadID,
projectID: route.wireID,
let signature = ThreadCreationSignature(
projectID: projectID,
title: threadTitle,
model: model,
runtimeMode: .fullAccess
model: model
)
let pending: PendingThreadCreation
if let existing = pendingThreadCreations.first(where: { $0.signature == signature }) {
pending = existing
} else {
pending = PendingThreadCreation(signature: signature, threadID: UUID().uuidString)
pendingThreadCreations.append(pending)
}
var recoveredShell: OrchestrationShellSnapshot?
do {
_ = try await client.createThread(
threadID: pending.threadID,
projectID: route.wireID,
title: threadTitle,
model: model,
runtimeMode: .fullAccess
)
} catch {
guard Self.isAmbiguousDispatchFailure(error) else {
removePendingThreadCreation(threadID: pending.threadID)
throw error
}
if let shell = try? await client.shellSnapshot(),
shell.threads.contains(where: { $0.id == pending.threadID }) {
recoveredShell = shell
} else {
// Keep this ID while the outcome is ambiguous. A retry of the
// same creation attempt must not make another thread.
throw error
}
}
guard isKnownClient(client, environmentID: environment.id, generation: generation) else {
throw CancellationError()
}
registerProvisionalThread(wireID: threadID, environmentID: environment.id)
if let shell = try? await client.shellSnapshot() {
removePendingThreadCreation(threadID: pending.threadID)
registerProvisionalThread(wireID: pending.threadID, environmentID: environment.id)
let refreshedShell: OrchestrationShellSnapshot?
if let recoveredShell {
refreshedShell = recoveredShell
} else {
refreshedShell = try? await client.shellSnapshot()
}
if let shell = refreshedShell {
guard isKnownClient(client, environmentID: environment.id, generation: generation) else {
throw CancellationError()
}
@@ -811,17 +861,20 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
latestShell = shell
}
await emitSnapshot(shell, environment: environment)
if let created = shell.threads.first(where: { $0.id == threadID }) {
if let created = shell.threads.first(where: { $0.id == pending.threadID }) {
provisionalThreadRoutes[FeatureScopedID.thread(
environmentID: environment.id,
wireID: threadID
wireID: pending.threadID
)] = nil
return mapThread(created, environment: environment)
}
}
return FeatureThread(
id: FeatureScopedID.thread(environmentID: environment.id, wireID: threadID),
wireID: threadID,
id: FeatureScopedID.thread(
environmentID: environment.id,
wireID: pending.threadID
),
wireID: pending.threadID,
projectID: route.uiID,
environmentID: environment.id,
environmentName: environment.label,
@@ -1161,6 +1214,33 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
pendingBootstrapSubmissions.removeAll { $0.identity == identity }
}
private func removePendingThreadCreation(threadID: String) {
pendingThreadCreations.removeAll { $0.threadID == threadID }
}
private static func isAmbiguousDispatchFailure(_ error: any Error) -> Bool {
if let error = error as? RPCError {
switch error {
case .connectionUnavailable, .disconnected, .responseTimedOut:
return true
case .remote, .protocolViolation:
return false
}
}
if let error = error as? HTTPError {
switch error {
case .invalidResponse:
return true
case .status, .missingCredential, .incompatibleCredential,
.managedAuthorizationUnavailable:
return false
}
}
// URL loading errors and cancellation can happen after the request
// body crossed the network. Reusing the ID is safe in either case.
return true
}
func renameThread(id: String, title: String) async throws {
let route = try threadRoute(for: id)
_ = try await route.client.rename(threadID: route.wireID, title: title)
@@ -5697,6 +5777,17 @@ private struct PendingBootstrapSubmission {
let worktreeBranchName: String?
}
private struct ThreadCreationSignature: Equatable {
let projectID: String
let title: String
let model: ModelSelection
}
private struct PendingThreadCreation {
let signature: ThreadCreationSignature
let threadID: String
}
private struct TurnSubmissionSignature: Equatable {
let text: String
let model: ModelSelection?
@@ -26,7 +26,7 @@ enum PlatformAgentAwarenessProjection {
guard !thread.isArchived else { return false }
if isActive(thread.state) { return true }
guard thread.state == .completed || thread.state == .failed else { return false }
return now.timeIntervalSince(thread.updatedAt) <= terminalVisibilityWindow
return now.timeIntervalSince(thread.updatedAt) < terminalVisibilityWindow
}
let rows = eligible.compactMap { thread -> T3RelayAgentActivityAggregateRow? in
guard let project = projects[thread.projectID] else { return nil }
@@ -97,6 +97,19 @@ enum PlatformAgentAwarenessProjection {
)
}
static func nextTerminalExpiry(
snapshot: FeatureSnapshot,
now: Date = .now
) -> Date? {
snapshot.threads.lazy
.filter {
!$0.isArchived && ($0.state == .completed || $0.state == .failed)
}
.map { $0.updatedAt.addingTimeInterval(terminalVisibilityWindow) }
.filter { $0 > now }
.min()
}
private static func isActive(_ state: FeatureThreadState) -> Bool {
switch state {
case .queued, .working, .monitoring, .waitingForApproval, .waitingForInput:
@@ -186,10 +199,12 @@ final class PlatformAgentAwarenessCoordinator {
private var activityUpdateTask: Task<Void, Never>?
private var widgetUpdateTask: Task<Void, Never>?
private var terminalExpiryTask: Task<Void, Never>?
private var lastSignature: Signature?
private var inFlightSignature: Signature?
private var synchronizationGeneration = 0
private var widgetGeneration = 0
private var terminalExpiryGeneration = 0
init(
updateLiveActivity: @escaping @MainActor (
@@ -213,6 +228,11 @@ final class PlatformAgentAwarenessCoordinator {
func synchronize(snapshot: FeatureSnapshot, liveActivitiesEnabled: Bool) {
let now = Date.now
scheduleTerminalExpiry(
snapshot: snapshot,
liveActivitiesEnabled: liveActivitiesEnabled,
now: now
)
let aggregate = PlatformAgentAwarenessProjection.aggregate(
snapshot: snapshot,
now: now
@@ -263,6 +283,9 @@ final class PlatformAgentAwarenessCoordinator {
/// removing its activity. Only a later snapshot may publish new content.
func resetAndResynchronizeLiveActivity() {
activityUpdateTask?.cancel()
terminalExpiryTask?.cancel()
terminalExpiryGeneration &+= 1
terminalExpiryTask = nil
synchronizationGeneration &+= 1
let generation = synchronizationGeneration
lastSignature = nil
@@ -321,6 +344,38 @@ final class PlatformAgentAwarenessCoordinator {
}
}
private func scheduleTerminalExpiry(
snapshot: FeatureSnapshot,
liveActivitiesEnabled: Bool,
now: Date
) {
terminalExpiryTask?.cancel()
terminalExpiryGeneration &+= 1
let generation = terminalExpiryGeneration
guard let expiry = PlatformAgentAwarenessProjection.nextTerminalExpiry(
snapshot: snapshot,
now: now
) else {
terminalExpiryTask = nil
return
}
let delay = max(0, expiry.timeIntervalSince(now))
terminalExpiryTask = Task { @MainActor [weak self] in
do {
try await Task.sleep(for: .seconds(delay))
} catch {
return
}
guard let self,
terminalExpiryGeneration == generation else { return }
terminalExpiryTask = nil
synchronize(
snapshot: snapshot,
liveActivitiesEnabled: liveActivitiesEnabled
)
}
}
private static func synchronizeLiveActivity(
aggregate: T3RelayAgentActivityAggregateState,
enabled: Bool,
+2 -4
View File
@@ -55,10 +55,8 @@ public actor LocalNetworkProbe {
} catch {
throw ConnectionProbeError.invalidURL
}
guard let baseURL = URL(string: fields.host),
let host = baseURL.host,
["http", "https"].contains(baseURL.scheme?.lowercased() ?? "")
else {
guard let baseURL = try? PairingURL.httpBaseURL(for: fields.host),
let host = baseURL.host else {
throw ConnectionProbeError.invalidURL
}
+20
View File
@@ -134,6 +134,12 @@ public enum PairingURL {
return value
}
/// Converts any supported pairing transport into the HTTP origin used by
/// onboarding's environment probe.
static func httpBaseURL(for rawValue: String) throws -> URL {
try httpBaseURL(from: normalizedBaseURL(rawValue))
}
private static func extractPairingURL(
from rawValue: String,
qrInput: Bool
@@ -260,6 +266,20 @@ public enum PairingURL {
)
}
private static func httpBaseURL(from baseURL: URL) throws -> URL {
guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)
else {
throw PairingURLError.invalidURL
}
switch components.scheme?.lowercased() {
case "ws": components.scheme = "http"
case "wss": components.scheme = "https"
default: break
}
guard let url = components.url else { throw PairingURLError.invalidURL }
return url
}
private static func requireSupportedScheme(_ scheme: String?) throws {
guard supportedSchemes.contains(scheme?.lowercased() ?? "") else {
throw PairingURLError.unsupportedScheme
+10
View File
@@ -1155,6 +1155,16 @@ public actor EnvironmentRuntime {
}
}
/// Revokes local access before best-effort catalog cleanup. Account
/// sign-out uses this so a failed file write cannot leave a managed DPoP
/// credential usable.
public func revokeCredential(id: String) async throws {
try await credentialStore.removeCredential(for: id)
if let client = clients.removeValue(forKey: id) {
await client.disconnect()
}
}
/// Returns the cached client for a saved environment without changing the
/// environment used for new projects and threads.
public func client(for environment: Environment) async -> T3Client {
@@ -330,7 +330,29 @@ private struct MarkdownBlockParser {
let runLength = runEnd - cursor
for _ in cursor..<runEnd { cell.append("`") }
if codeFenceLength == nil {
codeFenceLength = runLength
// An unmatched backtick run is literal text. Do not let it
// swallow every later pipe in the row.
var probe = runEnd
while probe < characters.count {
if characters[probe] == "\\", probe + 1 < characters.count {
probe += 2
continue
}
guard characters[probe] == "`" else {
probe += 1
continue
}
var closingRunEnd = probe
while closingRunEnd < characters.count,
characters[closingRunEnd] == "`" {
closingRunEnd += 1
}
if closingRunEnd - probe == runLength {
codeFenceLength = runLength
break
}
probe = closingRunEnd
}
} else if codeFenceLength == runLength {
codeFenceLength = nil
}
@@ -207,6 +207,10 @@ private final class QRScannerViewController: UIViewController {
private let captureSession = AVCaptureSession()
private let sessionQueue = DispatchQueue(label: "codes.t3.swift-ios.qr-scanner")
private var previewLayer: AVCaptureVideoPreviewLayer?
private var metadataDelegate: AVCaptureMetadataOutputObjectsDelegate?
private var availabilityChanged: (@MainActor (QRScannerAvailability) -> Void)?
private var isConfiguring = false
private var isRequestingAuthorization = false
override func viewDidLoad() {
super.viewDidLoad()
@@ -223,7 +227,10 @@ private final class QRScannerViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard previewLayer != nil else { return }
guard previewLayer != nil else {
refreshAuthorization()
return
}
let session = captureSession
sessionQueue.async {
if !session.isRunning {
@@ -239,23 +246,30 @@ private final class QRScannerViewController: UIViewController {
func prepare(
delegate: AVCaptureMetadataOutputObjectsDelegate,
availabilityChanged: @escaping (QRScannerAvailability) -> Void
availabilityChanged: @escaping @MainActor (QRScannerAvailability) -> Void
) {
metadataDelegate = delegate
self.availabilityChanged = availabilityChanged
refreshAuthorization()
}
private func refreshAuthorization() {
guard let metadataDelegate, let availabilityChanged else { return }
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
configure(delegate: delegate, availabilityChanged: availabilityChanged)
configure(delegate: metadataDelegate, availabilityChanged: availabilityChanged)
case .notDetermined:
guard !isRequestingAuthorization else { return }
isRequestingAuthorization = true
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
Task { @MainActor in
guard let self else { return }
if granted {
self.configure(
delegate: delegate,
availabilityChanged: availabilityChanged
)
} else {
availabilityChanged(.denied)
self.isRequestingAuthorization = false
guard granted else {
self.availabilityChanged?(.denied)
return
}
self.refreshAuthorization()
}
}
case .denied, .restricted:
@@ -276,8 +290,11 @@ private final class QRScannerViewController: UIViewController {
private func configure(
delegate: AVCaptureMetadataOutputObjectsDelegate,
availabilityChanged: @escaping (QRScannerAvailability) -> Void
availabilityChanged: @escaping @MainActor (QRScannerAvailability) -> Void
) {
guard previewLayer == nil, !isConfiguring else { return }
isConfiguring = true
defer { isConfiguring = false }
guard let camera = AVCaptureDevice.default(for: .video),
let input = try? AVCaptureDeviceInput(device: camera),
captureSession.canAddInput(input)
@@ -7,6 +7,7 @@ public struct T3ConnectView: View {
@Bindable private var controller: T3ConnectController
@State private var isAuthPresented = false
@State private var didFinishInitialRefresh = false
@State private var connectingEnvironmentID: String?
private let connectEnvironment:
@MainActor (T3ConnectManagedEnvironmentCredential) async throws -> Void
private let signOut: @MainActor () async -> Void
@@ -104,7 +105,7 @@ public struct T3ConnectView: View {
private var authenticationView: some View {
if let clerk = controller.clerk {
T3ConnectAuthenticationView {
await controller.refresh()
await controller.refreshAfterAuthentication()
if controller.account != nil {
isAuthPresented = false
return true
@@ -234,7 +235,8 @@ public struct T3ConnectView: View {
Button {
Task { await handleConnect(item.environment) }
} label: {
if controller.busyEnvironmentID == item.id {
if controller.busyEnvironmentID == item.id
|| connectingEnvironmentID == item.id {
ProgressView()
.frame(width: 54)
} else {
@@ -243,12 +245,23 @@ public struct T3ConnectView: View {
}
}
.buttonStyle(.borderless)
.disabled(controller.busyEnvironmentID != nil || item.status?.status == .offline)
.disabled(
controller.busyEnvironmentID != nil
|| connectingEnvironmentID != nil
|| item.status?.status == .offline
)
}
.padding(.vertical, 5)
}
private func handleConnect(_ environment: T3ConnectRelayEnvironment) async {
guard connectingEnvironmentID == nil else { return }
connectingEnvironmentID = environment.environmentId
defer {
if connectingEnvironmentID == environment.environmentId {
connectingEnvironmentID = nil
}
}
do {
let credential = try await controller.credential(for: environment)
try await connectEnvironment(credential)
@@ -151,8 +151,7 @@ enum DailyUXCreationContext {
in snapshot: FeatureSnapshot
) -> [FeatureProvider] {
if let project,
let providers = snapshot.providersByEnvironment?[project.environmentID],
!providers.isEmpty {
let providers = snapshot.providersByEnvironment?[project.environmentID] {
return providers
}
guard let project,
@@ -721,9 +720,11 @@ struct DailyUXModelCatalog {
recentIDs: [String]
) {
let available = providers.filter(\.isAvailable)
let unfiltered = available.flatMap { provider in
let rawOptions = available.flatMap { provider in
provider.models.map { DailyUXModelOption(provider: provider, model: $0) }
}
var seenOptionIDs = Set<String>()
let unfiltered = rawOptions.filter { seenOptionIDs.insert($0.id).inserted }
let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
let matches = normalizedQuery.isEmpty
? unfiltered
@@ -747,7 +748,9 @@ struct DailyUXModelCatalog {
}
recents = recentIDs.compactMap { byID[$0] }.filter { !favoriteIDs.contains($0.id) }
providerGroups = available.compactMap { provider in
var seenProviderIDs = Set<String>()
let uniqueProviders = available.filter { seenProviderIDs.insert($0.id).inserted }
providerGroups = uniqueProviders.compactMap { provider in
let options = matches.filter { $0.provider.id == provider.id }
return options.isEmpty ? nil : (provider, options)
}
@@ -361,6 +361,30 @@ final class TransportReliabilityTests: XCTestCase {
)
}
func testLocalNetworkProbeAcceptsWebSocketPairingSchemes() async throws {
let transport = RecordingHTTPTransport { request in
let body = """
{
"environmentId": "environment-1",
"label": "Studio",
"platform": {"os": "darwin", "arch": "arm64"},
"serverVersion": "1.0.0",
"capabilities": {}
}
"""
return (Data(body.utf8), transportResponse(request))
}
let result = try await LocalNetworkProbe(transport: transport).probe(
address: "wss://studio.example"
)
XCTAssertEqual(result.baseURL.absoluteString, "https://studio.example/")
let requests = await transport.requests
let request = try XCTUnwrap(requests.first)
XCTAssertEqual(request.url?.scheme, "https")
XCTAssertEqual(request.url?.path, "/.well-known/t3/environment")
}
}
private func paginationThreadFixture() -> OrchestrationThread {
@@ -51,6 +51,28 @@ struct DailyUXModelPickerTests {
#expect(catalog.providerGroups.map(\.provider.id) == ["codex", "claude"])
}
@Test
func catalogDeduplicatesRepeatedProviderAndModelIDs() {
let repeated = FeatureProvider(
id: "codex",
name: "Codex",
models: [
FeatureModel(id: "gpt-5.6-sol", name: "Sol"),
FeatureModel(id: "gpt-5.6-sol", name: "Sol again"),
]
)
let catalog = DailyUXModelCatalog(
providers: [repeated, repeated],
query: "",
favoriteIDs: [],
recentIDs: []
)
#expect(catalog.all.map(\.id) == ["codex::gpt-5.6-sol"])
#expect(catalog.providerGroups.map(\.provider.id) == ["codex"])
#expect(catalog.providerGroups.first?.models.count == 1)
}
@Test
func searchIncludesCapabilitiesAndProviderNames() {
let providers = [
@@ -226,6 +226,33 @@ struct DailyUXNewTaskTests {
)
}
@Test
func explicitEmptyProviderCatalogDoesNotRestoreAStaleProjectDefault() {
let project = FeatureProject(
id: "remote-project",
environmentID: "remote",
name: "Remote",
path: "/remote",
defaultSelection: .init(providerID: "claude", modelID: "old-model")
)
let snapshot = FeatureSnapshot(
environments: [
.init(
id: "remote",
name: "Remote",
endpoint: "https://remote.example",
isActive: false,
connectionState: .connected
),
],
projects: [project],
providers: [],
providersByEnvironment: ["remote": []]
)
#expect(DailyUXCreationContext.providers(for: project, in: snapshot).isEmpty)
}
@Test
func projectGroupsOnlyOfferComputersThatContainTheSelectedRepository() throws {
let identity = FeatureRepositoryIdentity(
@@ -119,6 +119,29 @@ struct MarkdownDocumentTests {
)
}
@Test
func unmatchedBacktickDoesNotHideLaterTableSeparators() {
let document = MarkdownDocument(
parsing: """
Left | Middle | Right
--- | --- | ---
x | `y | z
"""
)
#expect(
document.blocks == [
.table(
MarkdownTable(
header: ["Left", "Middle", "Right"],
alignments: [.natural, .natural, .natural],
rows: [["x", "`y", "z"]]
)
),
]
)
}
@Test
func rejectsTableDelimiterCellsWithFewerThanThreeDashes() {
let document = MarkdownDocument(
@@ -320,6 +320,31 @@ final class NativeMultiEnvironmentTests: XCTestCase {
await fixture.client.disconnect()
}
func testPassiveCreateRecoversACommittedThreadAfterItsReplyIsLost() async throws {
let fixture = try await makeFixture()
defer { try? FileManager.default.removeItem(at: fixture.directory) }
let snapshot = try await fixture.client.initialSnapshot()
let project = try XCTUnwrap(
snapshot.projects.first(where: { $0.environmentID == "two" })
)
await fixture.transport.dropNextCreateReply(host: "two.example")
let created = try await fixture.client.createThread(
projectID: project.id,
title: "Recovered task",
selection: nil
)
XCTAssertEqual(created.title, "Recovered task")
XCTAssertEqual(created.environmentID, "two")
let creates = await fixture.transport.dispatchRecords().filter {
$0.command["type"]?.stringValue == "thread.create"
}
XCTAssertEqual(creates.count, 1)
XCTAssertEqual(creates.first?.command["threadId"]?.stringValue, created.wireID)
await fixture.client.disconnect()
}
func testUnarchiveImmediatelyRestoresLiveThreadWhenRefreshIsUnavailable() async throws {
let fixture = try await makeFixture()
defer { try? FileManager.default.removeItem(at: fixture.directory) }
@@ -614,6 +639,7 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
private var reachableHosts: Set<String>
private var shellReadsEnabledHosts: Set<String>
private var dispatched: [MultiEnvironmentDispatchRecord] = []
private var hostsDroppingNextCreateReply = Set<String>()
init(shells: [String: OrchestrationShellSnapshot]) {
self.shells = shells
@@ -650,6 +676,10 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
dispatched
}
func dropNextCreateReply(host: String) {
hostsDroppingNextCreateReply.insert(host)
}
func data(for request: URLRequest) throws -> (Data, HTTPURLResponse) {
let host = request.url?.host ?? ""
guard reachableHosts.contains(host) else {
@@ -675,12 +705,26 @@ private actor MultiEnvironmentHTTPTransport: HTTPTransport {
}
if path == "/api/orchestration/dispatch" {
guard let body = request.httpBody else { throw URLError(.badServerResponse) }
let command = try JSONDecoder.t3.decode(JSONValue.self, from: body)
dispatched.append(
MultiEnvironmentDispatchRecord(
host: host,
command: try JSONDecoder.t3.decode(JSONValue.self, from: body)
)
MultiEnvironmentDispatchRecord(host: host, command: command)
)
if command["type"]?.stringValue == "thread.create",
hostsDroppingNextCreateReply.remove(host) != nil,
let projectID = command["projectId"]?.stringValue,
let threadID = command["threadId"]?.stringValue {
let model = command["modelSelection"]
shellData[host] = try JSONEncoder.t3.encode(
multiEnvironmentShell(
projectID: projectID,
threadID: threadID,
title: command["title"]?.stringValue ?? "New thread",
providerID: model?["instanceId"]?.stringValue ?? "codex",
modelID: model?["model"]?.stringValue ?? "gpt-5.6-sol"
)
)
throw URLError(.networkConnectionLost)
}
return (
try JSONEncoder.t3.encode(DispatchResult(sequence: 2)),
multiEnvironmentResponse(request)
@@ -231,6 +231,60 @@ final class T3ConnectNativeCapabilityTests: XCTestCase {
)
}
func testSignOutRevokesManagedCredentialWhenCatalogRemovalFails() async throws {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("t3-connect-revoke-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: directory) }
let catalogURL = directory.appendingPathComponent("environments.json")
let managed = Environment(
id: "managed-1",
label: "Managed Studio",
httpBaseURL: URL(string: "https://managed.example")!,
webSocketBaseURL: URL(string: "wss://managed.example")!,
kind: .managedDPoP
)
let store = EnvironmentStore(fileURL: catalogURL)
try await store.save([managed])
let credentials = InMemoryCredentialStore(credentials: [
managed.id: .managedDPoP(
accessToken: "managed-secret",
expiresAt: Date().addingTimeInterval(300),
scopes: T3ConnectManagedEnvironmentAuthorizer.standardScopes,
environmentID: managed.id,
proofKeyThumbprint: "proof-key"
),
])
let signer = try testSigner()
let transport = T3ConnectNativeHTTPTransport(descriptorEnvironmentID: managed.id)
let controller = T3ConnectController(
resolution: .available(
T3ConnectConfiguration(
clerkPublishableKey: "pk_test",
relayHTTPURL: URL(string: "https://relay.example")!
)
),
transport: transport,
signer: signer,
signOutOperation: {}
)
let runtime = EnvironmentRuntime(
environmentStore: store,
credentialStore: credentials,
httpTransport: transport,
webSocketConnector: T3ConnectBlockingConnector(),
managedAuthorization: T3ConnectRuntimeAuthorization(controller: controller)
)
let client = NativeFeatureClient(runtime: runtime, t3ConnectController: controller)
try FileManager.default.removeItem(at: catalogURL)
try FileManager.default.createDirectory(at: catalogURL, withIntermediateDirectories: true)
await client.signOutT3Connect()
let remainingCredential = await credentials.credential(for: managed.id)
XCTAssertNil(remainingCredential)
XCTAssertNotNil(controller.errorMessage)
}
func testInjectedManagedRuntimeRequiresItsMatchingController() async throws {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("t3-connect-controller-mismatch-\(UUID().uuidString)")
@@ -131,6 +131,44 @@ struct PlatformAgentAwarenessTests {
#expect(widget.updatedAt == aggregate.updatedAt)
}
@Test
func terminalRowsExposeTheirExpiryAndDisappearAtTheBoundary() throws {
let now = Date(timeIntervalSince1970: 2_000_000_000)
let updatedAt = now.addingTimeInterval(-60)
let expiry = updatedAt.addingTimeInterval(
PlatformAgentAwarenessProjection.terminalVisibilityWindow
)
let project = FeatureProject(
id: "project",
environmentID: "environment",
name: "t3code",
path: "/repo"
)
let snapshot = FeatureSnapshot(
projects: [project],
threads: [Self.thread(id: "done", state: .completed, updatedAt: updatedAt)]
)
#expect(
PlatformAgentAwarenessProjection.nextTerminalExpiry(
snapshot: snapshot,
now: now
) == expiry
)
#expect(
PlatformAgentAwarenessProjection.aggregate(
snapshot: snapshot,
now: expiry.addingTimeInterval(-0.001)
).activities.count == 1
)
#expect(
PlatformAgentAwarenessProjection.aggregate(
snapshot: snapshot,
now: expiry
).activities.isEmpty
)
}
@Test
@MainActor
func signOutEndsActivitiesWithoutRepublishingTheCachedProjection() async {