diff --git a/apps/swift-ios/App/Cloud/T3ConnectCapability.swift b/apps/swift-ios/App/Cloud/T3ConnectCapability.swift index 89c0e1d7a2..baf691167a 100644 --- a/apps/swift-ios/App/Cloud/T3ConnectCapability.swift +++ b/apps/swift-ios/App/Cloud/T3ConnectCapability.swift @@ -224,8 +224,6 @@ public final class T3ConnectController { unavailableReason ?? "T3 Connect is unavailable in this build." ) } - busyEnvironmentID = environmentID - defer { busyEnvironmentID = nil } let token = try await loadedRelayToken(auth) let records = try await relay.listEnvironments(clerkToken: token) guard let environment = records.first(where: { $0.environmentId == environmentID }) else { diff --git a/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift b/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift index 1bf26ba9da..55849e4d14 100644 --- a/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift +++ b/apps/swift-ios/App/Cloud/T3ConnectManagedAuthorization.swift @@ -190,7 +190,11 @@ public actor T3ConnectManagedEnvironmentAuthorizer { ) async throws -> URL { guard let httpBaseURL = authorization.endpoint.httpBaseURL, - let webSocketBaseURL = authorization.endpoint.webSocketBaseURL + let webSocketBaseURL = authorization.endpoint.webSocketBaseURL, + httpBaseURL.scheme?.lowercased() == "https", + httpBaseURL.host?.isEmpty == false, + webSocketBaseURL.scheme?.lowercased() == "wss", + webSocketBaseURL.host?.isEmpty == false else { throw T3ConnectRelayError.invalidConfiguration( "The managed environment endpoint is invalid." @@ -204,6 +208,9 @@ public actor T3ConnectManagedEnvironmentAuthorizer { ticketRequest.httpMethod = "POST" ticketRequest = try await authorize(ticketRequest, using: authorization) let ticket = try await send(ticketRequest, as: WebSocketTicketResponse.self) + guard !ticket.ticket.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw T3ConnectRelayError.invalidResponse + } var components = URLComponents( url: webSocketBaseURL, @@ -344,11 +351,14 @@ public actor T3ConnectRuntimeAuthorization: ManagedEnvironmentAuthorizing { } let refreshID = UUID() refreshTasks[environment.id] = InFlightRefresh(id: refreshID, task: task) - Task.detached { [weak self] in - _ = await task.result - await self?.finishRefresh(environmentID: environment.id, id: refreshID) + do { + let credential = try await task.value + finishRefresh(environmentID: environment.id, id: refreshID) + return credential + } catch { + finishRefresh(environmentID: environment.id, id: refreshID) + throw error } - return try await task.value } private func finishRefresh(environmentID: String, id: UUID) { diff --git a/apps/swift-ios/App/Cloud/T3ConnectRelayClient.swift b/apps/swift-ios/App/Cloud/T3ConnectRelayClient.swift index 07ef72df82..162c9717f8 100644 --- a/apps/swift-ios/App/Cloud/T3ConnectRelayClient.swift +++ b/apps/swift-ios/App/Cloud/T3ConnectRelayClient.swift @@ -164,6 +164,10 @@ public actor T3ConnectRelayClient { response.environmentId == environment.environmentId, response.endpoint == environment.endpoint else { throw T3ConnectRelayError.environmentMismatch } + guard !response.credential.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + !response.expiresAt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw T3ConnectRelayError.invalidResponse + } return T3ConnectManagedEnvironmentCredential( environmentID: response.environmentId, label: environment.label, @@ -325,7 +329,11 @@ public actor T3ConnectRelayClient { granted: response.scope ) } - guard response.tokenType == "DPoP" else { + guard !response.accessToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + response.issuedTokenType + == "urn:ietf:params:oauth:token-type:access_token", + response.tokenType == "DPoP", + response.expiresIn > 0 else { throw T3ConnectRelayError.invalidResponse } return CachedToken( diff --git a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift index 711b7cb019..a0f7187107 100644 --- a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift +++ b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift @@ -184,7 +184,6 @@ final class PlatformAgentAwarenessCoordinator { private var activityUpdateTask: Task? private var lastSignature: Signature? private var inFlightSignature: Signature? - private var latestSynchronization: Synchronization? private var synchronizationGeneration = 0 init( @@ -225,17 +224,23 @@ final class PlatformAgentAwarenessCoordinator { enabled: liveActivitiesEnabled, now: now ) - latestSynchronization = synchronization - guard signature != lastSignature, signature != inFlightSignature else { return } + if signature == lastSignature { + if inFlightSignature != nil { + activityUpdateTask?.cancel() + synchronizationGeneration &+= 1 + inFlightSignature = nil + activityUpdateTask = nil + } + return + } + guard signature != inFlightSignature else { return } let widgetSnapshot = T3TaskWidgetSnapshot( updatedAt: aggregate.updatedAt, tasks: aggregate.activities ) - Task.detached(priority: .utility) { - try? T3TaskWidgetSnapshotStore.save(widgetSnapshot) - WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget") - } + try? T3TaskWidgetSnapshotStore.save(widgetSnapshot) + WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget") schedule(synchronization) } @@ -248,7 +253,8 @@ final class PlatformAgentAwarenessCoordinator { let generation = synchronizationGeneration lastSignature = nil inFlightSignature = nil - latestSynchronization = nil + try? T3TaskWidgetSnapshotStore.save(.empty) + WidgetCenter.shared.reloadTimelines(ofKind: "T3RecentTasksWidget") activityUpdateTask = Task { @MainActor [weak self] in guard let self else { return } await endLiveActivities() diff --git a/apps/swift-ios/Features/Root/FeatureRootView.swift b/apps/swift-ios/Features/Root/FeatureRootView.swift index 844a70347f..6019b62cd2 100644 --- a/apps/swift-ios/Features/Root/FeatureRootView.swift +++ b/apps/swift-ios/Features/Root/FeatureRootView.swift @@ -76,7 +76,8 @@ enum FeatureRootPresentation { snapshot: FeatureSnapshot, isManagingConnections: Bool ) -> Bool { - snapshot.connection.state != .disconnected + isManagingConnections + || snapshot.connection.state != .disconnected || !snapshot.environments.isEmpty || !snapshot.projects.isEmpty || !snapshot.threads.isEmpty diff --git a/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift b/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift index 00fe5387fa..760a85b02d 100644 --- a/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift +++ b/apps/swift-ios/Features/Shared/FeatureComposerDraftStore.swift @@ -159,13 +159,22 @@ public actor FeatureComposerDraftStore { } public func draft(for key: String) throws -> FeatureComposerDraft? { - try loadIfNeeded()[key]?.featureValue + guard let draft = try loadIfNeeded()[key]?.featureValue, + !draft.isEmpty else { return nil } + return draft } public func setDraft(_ draft: FeatureComposerDraft, for key: String) throws { var drafts = try loadIfNeeded() if draft.isEmpty { - drafts.removeValue(forKey: key) + if let importedShareIDs = drafts[key]?.importedShareIDs, + !importedShareIDs.isEmpty { + var persisted = PersistedDraft(draft) + persisted.importedShareIDs = importedShareIDs + drafts[key] = persisted + } else { + drafts.removeValue(forKey: key) + } } else { var persisted = PersistedDraft(draft) // Preserve the crash-replay ledger while the composer performs its diff --git a/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift b/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift index be1805845d..77758bdac9 100644 --- a/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift +++ b/apps/swift-ios/Features/SourceControl/FeatureSourceControlView.swift @@ -21,13 +21,18 @@ public struct FeatureSourceControlView: View { if isLoading, status == nil { ProgressView("Loading repository…") .frame(maxWidth: .infinity, maxHeight: .infinity) - } else if let status { + } else if let status, status.isRepository { statusList(status) } else { ContentUnavailableView( "Source control unavailable", systemImage: "arrow.triangle.branch", - description: Text(errorMessage ?? "Repository status could not be loaded.") + description: Text( + errorMessage + ?? (status?.isRepository == false + ? "This workspace is not a Git repository." + : "Repository status could not be loaded.") + ) ) } } diff --git a/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift b/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift index f25255ba88..ff1255abca 100644 --- a/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift +++ b/apps/swift-ios/Tests/CoreTests/T3ConnectRuntimeTests.swift @@ -487,6 +487,41 @@ final class T3ConnectRuntimeTests: XCTestCase { ) } + func testManagedWebSocketRejectsUnencryptedEndpointBeforeMintingTicket() async throws { + let signer = try testSigner() + let transport = T3ConnectScriptedHTTPTransport { request, _ in + throw T3ConnectTestError.unexpectedPath(request.url?.path) + } + let authorizer = T3ConnectManagedEnvironmentAuthorizer( + transport: transport, + signer: signer + ) + let authorization = T3ConnectEnvironmentAccessToken( + environmentID: "managed-1", + label: "Managed Studio", + endpoint: T3ConnectManagedEndpoint( + httpBaseUrl: "https://managed.example", + wsBaseUrl: "ws://managed.example/ws", + providerKind: .t3Relay + ), + accessToken: "access-token", + expiresAt: Date().addingTimeInterval(300), + scopes: T3ConnectManagedEnvironmentAuthorizer.standardScopes, + proofKeyThumbprint: try await signer.thumbprint() + ) + + do { + _ = try await authorizer.webSocketURL(using: authorization) + XCTFail("An unencrypted managed WebSocket endpoint was accepted") + } catch let error as T3ConnectRelayError { + guard case .invalidConfiguration = error else { + return XCTFail("Unexpected T3 Connect error: \(error)") + } + } + let requests = await transport.requests + XCTAssertTrue(requests.isEmpty) + } + func testEnvironmentExchangeRejectsMalformedTokenContracts() async throws { let signer = try testSigner() let bootstrap = try await bootstrapCredential(signer: signer) @@ -685,6 +720,87 @@ final class T3ConnectRuntimeTests: XCTestCase { } } + func testRelayRejectsMalformedAccessTokenContracts() async throws { + let invalidTokens = [ + Data.relayToken("", scope: "mobile:registration"), + Data( + #"{"access_token":"token","issued_token_type":"wrong","token_type":"DPoP","expires_in":300,"scope":"mobile:registration"}"#.utf8 + ), + Data( + #"{"access_token":"token","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"DPoP","expires_in":0,"scope":"mobile:registration"}"#.utf8 + ), + ] + + for token in invalidTokens { + let signer = try testSigner() + let transport = T3ConnectScriptedHTTPTransport { _, _ in (token, 200) } + 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 malformed relay access token was accepted") + } catch T3ConnectRelayError.invalidResponse { + // Expected contract rejection. + } + } + } + + func testRelayRejectsBlankBootstrapCredential() async throws { + let signer = try testSigner() + let transport = T3ConnectScriptedHTTPTransport { _, ordinal in + switch ordinal { + case 1: + return (.relayToken("relay-connect", scope: "environment:connect"), 200) + case 2: + return ( + Data( + #"{"environmentId":"managed-1","endpoint":{"httpBaseUrl":"https://managed.example","wsBaseUrl":"wss://managed.example","providerKind":"t3_relay"},"credential":"","expiresAt":""}"#.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 + ) + let environment = T3ConnectRelayEnvironment( + environmentId: "managed-1", + label: "Managed Studio", + endpoint: T3ConnectManagedEndpoint( + httpBaseUrl: "https://managed.example", + wsBaseUrl: "wss://managed.example", + providerKind: .t3Relay + ), + linkedAt: "2026-08-01T12:00:00.000Z" + ) + + do { + _ = try await relay.connect( + to: environment, + clerkToken: clerkJWT(subject: "mobile-account") + ) + XCTFail("A blank environment bootstrap credential was accepted") + } catch T3ConnectRelayError.invalidResponse { + // Expected contract rejection. + } + } + private func testDeviceRegistration() -> T3ConnectDeviceRegistration { T3ConnectDeviceRegistration( deviceID: "phone-1", diff --git a/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift b/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift index 92ffaf4a36..4bc32c9016 100644 --- a/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/ComposerDraftStoreTests.swift @@ -48,6 +48,33 @@ struct ComposerDraftStoreTests { #expect(try await store.draft(for: key) == nil) } + @Test func clearingDraftPreservesImportedShareIdempotency() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let store = FeatureComposerDraftStore( + fileURL: directory.appendingPathComponent("drafts.json") + ) + let key = "environment:test:thread:one" + + _ = try await store.importSharedContent( + shareID: "share-1", + text: "Imported once", + attachments: [], + for: key + ) + try await store.setDraft(FeatureComposerDraft(), for: key) + let replayed = try await store.importSharedContent( + shareID: "share-1", + text: "Imported once", + attachments: [], + for: key + ) + + #expect(replayed.isEmpty) + #expect(try await store.draft(for: key) == nil) + } + @Test func environmentRemovalLeavesOtherDraftsAlone() async throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift index ad8da25e57..a04668495e 100644 --- a/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/FeatureRootModelTests.swift @@ -31,11 +31,17 @@ struct FeatureRootModelTests { ) ) #expect( - !FeatureRootPresentation.showsWorkspace( + FeatureRootPresentation.showsWorkspace( snapshot: FeatureSnapshot(connection: .init(state: .disconnected)), isManagingConnections: true ) ) + #expect( + !FeatureRootPresentation.showsWorkspace( + snapshot: FeatureSnapshot(connection: .init(state: .disconnected)), + isManagingConnections: false + ) + ) } @Test diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift index c09c0faeec..74d2146237 100644 --- a/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift +++ b/apps/swift-ios/Tests/PlatformTests/PlatformAgentAwarenessTests.swift @@ -141,6 +141,44 @@ struct PlatformAgentAwarenessTests { #expect(recorder.endCount == 1) } + @Test + @MainActor + func latestSnapshotCancelsAnInFlightReversionToOlderState() async { + let recorder = GatedPlatformAgentAwarenessRecorder() + let coordinator = PlatformAgentAwarenessCoordinator( + updateLiveActivity: { _, _, _ in + await recorder.recordUpdate() + }, + endLiveActivities: {} + ) + let ready = FeatureSnapshot() + let project = FeatureProject( + id: "project", + environmentID: "environment", + name: "t3code", + path: "/repo" + ) + let working = FeatureSnapshot( + projects: [project], + threads: [Self.thread(id: "working", state: .working, updatedAt: .now)] + ) + + coordinator.synchronize(snapshot: ready, liveActivitiesEnabled: true) + await recorder.waitForUpdateCount(1) + await Task.yield() + + coordinator.synchronize(snapshot: working, liveActivitiesEnabled: true) + await recorder.waitForUpdateCount(2) + coordinator.synchronize(snapshot: ready, liveActivitiesEnabled: true) + recorder.releaseSecondUpdate() + await Task.yield() + await Task.yield() + + coordinator.synchronize(snapshot: ready, liveActivitiesEnabled: true) + await Task.yield() + #expect(recorder.updateCount == 2) + } + private static func thread( id: String, state: FeatureThreadState, @@ -160,6 +198,37 @@ struct PlatformAgentAwarenessTests { } } +@MainActor +private final class GatedPlatformAgentAwarenessRecorder { + private(set) var updateCount = 0 + private var secondUpdateContinuation: CheckedContinuation? + private var updateWaiters: [(Int, CheckedContinuation)] = [] + + func recordUpdate() async { + updateCount += 1 + let ready = updateWaiters.filter { updateCount >= $0.0 } + updateWaiters.removeAll { updateCount >= $0.0 } + ready.forEach { $0.1.resume() } + if updateCount == 2 { + await withCheckedContinuation { continuation in + secondUpdateContinuation = continuation + } + } + } + + func waitForUpdateCount(_ count: Int) async { + guard updateCount < count else { return } + await withCheckedContinuation { continuation in + updateWaiters.append((count, continuation)) + } + } + + func releaseSecondUpdate() { + secondUpdateContinuation?.resume() + secondUpdateContinuation = nil + } +} + @MainActor private final class PlatformAgentAwarenessOperationRecorder { private(set) var updateCount = 0