fix(actions): report uncertain results and preserve drafts
Sources/Oldsky/AppModel.swift+118−15
| @@ -1,6 +1,16 @@ | ||
import Foundation | ||
import SwiftUI | ||
| ||
struct ComposerDraftKey: Hashable { | ||
let replyTo: String? | ||
let quotePostID: String? | ||
} | ||
| ||
struct ComposerDraft { | ||
var text: String | ||
var attachments: [ImageAttachment] | ||
} | ||
| ||
@MainActor | ||
final class AppModel: ObservableObject { | ||
@Published private(set) var account: Account? | ||
| @@ -15,6 +25,14 @@ final class AppModel: ObservableObject { | ||
@Published private(set) var requiresAuthFactorToken = false | ||
@Published private(set) var authFactorErrorMessage: String? | ||
@Published private(set) var isPublishing = false | ||
@Published private(set) var publishErrorMessage: String? | ||
@Published private(set) var publishResultUnknown = false | ||
private var composerDrafts: [ComposerDraftKey: ComposerDraft] = [:] | ||
@Published private(set) var activePostActions: Set<String> = [] | ||
@Published private(set) var activeFollowIDs: Set<String> = [] | ||
@Published private(set) var uncertainPostIDs: Set<String> = [] | ||
@Published private(set) var uncertainFollowIDs: Set<String> = [] | ||
@Published private(set) var uncertainDraftKeys: Set<ComposerDraftKey> = [] | ||
@Published private(set) var isLoadingPost = false | ||
@Published private(set) var loadingProfileIDs: Set<String> = [] | ||
@Published private(set) var errorMessage: String? | ||
| @@ -40,6 +58,7 @@ final class AppModel: ObservableObject { | ||
| ||
private var moderationSession = UUID() | ||
private let service: any BlueskyService | ||
private var sessionGeneration = UUID() | ||
private var cursor: String? | ||
private var notificationsCursor: String? | ||
private var failedNotificationsPage = false | ||
| @@ -118,8 +137,18 @@ final class AppModel: ObservableObject { | ||
defer { isSigningOut = false } | ||
do { | ||
try await service.signOut() | ||
sessionGeneration = UUID() | ||
moderationSession = UUID() | ||
account = nil | ||
composerDrafts = [:] | ||
activePostActions = [] | ||
activeFollowIDs = [] | ||
uncertainPostIDs = [] | ||
uncertainFollowIDs = [] | ||
uncertainDraftKeys = [] | ||
isPublishing = false | ||
publishErrorMessage = nil | ||
publishResultUnknown = false | ||
posts = [] | ||
notifications = [] | ||
notificationPageStarts = [] | ||
| @@ -221,40 +250,70 @@ final class AppModel: ObservableObject { | ||
} | ||
| ||
func toggleLike(postID: String) async { | ||
guard var updated = post(id: postID) else { return } | ||
guard account != nil, !isSigningOut, !uncertainPostIDs.contains(postID), let original = post(id: postID), activePostActions.insert(postID).inserted else { return } | ||
let generation = sessionGeneration | ||
defer { if generation == sessionGeneration { activePostActions.remove(postID) } } | ||
do { | ||
updated.likeURI = try await service.toggleLike(post: updated, liked: !updated.isLiked) | ||
updated.isLiked.toggle() | ||
updated.likeCount = max(0, updated.likeCount + (updated.isLiked ? 1 : -1)) | ||
let uri = try await service.toggleLike(post: original, liked: !original.isLiked) | ||
guard generation == sessionGeneration, var updated = post(id: postID) else { return } | ||
let liked = !original.isLiked | ||
if updated.isLiked != liked { | ||
updated.likeCount = max(0, updated.likeCount + (liked ? 1 : -1)) | ||
} | ||
updated.likeURI = uri | ||
updated.isLiked = liked | ||
updatePost(updated) | ||
} catch { | ||
errorMessage = error.localizedDescription | ||
guard generation == sessionGeneration else { return } | ||
if error is ActionNotSentError || (error as? ServiceError).map({ if case .noSession = $0 { return true }; return false }) == true { | ||
errorMessage = error.localizedDescription | ||
} else { | ||
uncertainPostIDs.insert(postID) | ||
errorMessage = "\(error.localizedDescription)\n\nBluesky may have received this change. This post's actions are unavailable for this session." | ||
} | ||
} | ||
} | ||
| ||
func toggleRepost(postID: String) async { | ||
guard var updated = post(id: postID) else { return } | ||
guard account != nil, !isSigningOut, !uncertainPostIDs.contains(postID), let original = post(id: postID), activePostActions.insert(postID).inserted else { return } | ||
let generation = sessionGeneration | ||
defer { if generation == sessionGeneration { activePostActions.remove(postID) } } | ||
do { | ||
updated.repostURI = try await service.toggleRepost(post: updated, reposted: !updated.isReposted) | ||
updated.isReposted.toggle() | ||
updated.repostCount = max(0, updated.repostCount + (updated.isReposted ? 1 : -1)) | ||
let uri = try await service.toggleRepost(post: original, reposted: !original.isReposted) | ||
guard generation == sessionGeneration, var updated = post(id: postID) else { return } | ||
let reposted = !original.isReposted | ||
if updated.isReposted != reposted { | ||
updated.repostCount = max(0, updated.repostCount + (reposted ? 1 : -1)) | ||
} | ||
updated.repostURI = uri | ||
updated.isReposted = reposted | ||
updatePost(updated) | ||
} catch { | ||
errorMessage = error.localizedDescription | ||
guard generation == sessionGeneration else { return } | ||
if error is ActionNotSentError || (error as? ServiceError).map({ if case .noSession = $0 { return true }; return false }) == true { | ||
errorMessage = error.localizedDescription | ||
} else { | ||
uncertainPostIDs.insert(postID) | ||
errorMessage = "\(error.localizedDescription)\n\nBluesky may have received this change. This post's actions are unavailable for this session." | ||
} | ||
} | ||
} | ||
| ||
func publish(text: String, replyTo: String? = nil, quotePostID: String? = nil, images: [ImageAttachment] = []) async -> Bool { | ||
let cleaned = text.trimmingCharacters(in: .whitespacesAndNewlines) | ||
guard !cleaned.isEmpty || !images.isEmpty else { return false } | ||
guard !isPublishing else { return false } | ||
let draftKey = ComposerDraftKey(replyTo: replyTo, quotePostID: quotePostID) | ||
guard account != nil, !isSigningOut, !isPublishing, !uncertainDraftKeys.contains(draftKey) else { return false } | ||
isPublishing = true | ||
errorMessage = nil | ||
defer { isPublishing = false } | ||
publishErrorMessage = nil | ||
publishResultUnknown = false | ||
let generation = sessionGeneration | ||
defer { if generation == sessionGeneration { isPublishing = false } } | ||
do { | ||
let reply = replyTo.flatMap(post) | ||
let quote = quotePostID.flatMap(post) | ||
let newPost = try await service.publish(text: cleaned, replyTo: reply, quotePost: quote, images: images) | ||
guard generation == sessionGeneration else { return false } | ||
posts.insert(newPost, at: 0) | ||
timelinePostIDs.insert(newPost.id) | ||
if let replyTo, let parentIndex = posts.firstIndex(where: { $0.id == replyTo }) { | ||
| @@ -262,11 +321,45 @@ final class AppModel: ObservableObject { | ||
} | ||
return true | ||
} catch { | ||
errorMessage = error.localizedDescription | ||
guard generation == sessionGeneration else { return false } | ||
if error is ActionNotSentError || (error as? ServiceError).map({ if case .noSession = $0 { return true }; return false }) == true { | ||
publishErrorMessage = error.localizedDescription | ||
return false | ||
} | ||
switch error as? ServiceError { | ||
case .postTextTooLong, .tooManyImages, .invalidImage, .imageTooLarge, .postReferenceUnavailable, .noSession: | ||
publishErrorMessage = error.localizedDescription | ||
default: | ||
publishResultUnknown = true | ||
uncertainDraftKeys.insert(draftKey) | ||
publishErrorMessage = "\(error.localizedDescription)\n\nBluesky may have received this post. This draft cannot be posted again during this session." | ||
} | ||
return false | ||
} | ||
} | ||
| ||
func composerDraft(for key: ComposerDraftKey) -> ComposerDraft? { | ||
composerDrafts[key] | ||
} | ||
| ||
func saveComposerDraft(_ draft: ComposerDraft, for key: ComposerDraftKey) { | ||
composerDrafts[key] = draft | ||
} | ||
| ||
func clearComposerDraft(for key: ComposerDraftKey) { | ||
composerDrafts[key] = nil | ||
} | ||
| ||
func clearPublishError() { | ||
publishErrorMessage = nil | ||
} | ||
| ||
func discardUncertainDraft(for key: ComposerDraftKey) { | ||
composerDrafts[key] = nil | ||
uncertainDraftKeys.remove(key) | ||
clearPublishError() | ||
} | ||
| ||
func isHidden(_ actorID: String?) -> Bool { | ||
guard let actorID, let state = moderationStates[actorID] else { return false } | ||
return state.isMuted || state.isBlocked | ||
| @@ -337,9 +430,13 @@ final class AppModel: ObservableObject { | ||
} | ||
| ||
func toggleFollow(actorID: String) async { | ||
guard account != nil, !isSigningOut, !uncertainFollowIDs.contains(actorID), activeFollowIDs.insert(actorID).inserted else { return } | ||
let generation = sessionGeneration | ||
defer { if generation == sessionGeneration { activeFollowIDs.remove(actorID) } } | ||
let newValue = !followingActorIDs.contains(actorID) | ||
do { | ||
_ = try await service.setFollowing(newValue, actorID: actorID) | ||
guard generation == sessionGeneration else { return } | ||
if newValue { | ||
followingActorIDs.insert(actorID) | ||
} else { | ||
| @@ -350,7 +447,13 @@ final class AppModel: ObservableObject { | ||
profiles[actorID] = profile | ||
} | ||
} catch { | ||
errorMessage = error.localizedDescription | ||
guard generation == sessionGeneration else { return } | ||
if error is ActionNotSentError || (error as? ServiceError).map({ if case .noSession = $0 { return true }; return false }) == true { | ||
errorMessage = error.localizedDescription | ||
} else { | ||
uncertainFollowIDs.insert(actorID) | ||
errorMessage = "\(error.localizedDescription)\n\nBluesky may have received this change. Follow actions for this account are unavailable for this session." | ||
} | ||
} | ||
} | ||
| ||
Sources/Oldsky/BlueskyService.swift+82−18
| @@ -403,6 +403,7 @@ actor ATProtoBlueskyService: BlueskyService { | ||
| ||
private let defaults: UserDefaults | ||
private let session: URLSession | ||
private let beforeAuthenticatedDispatch: (@Sendable () async -> Void)? | ||
private let keychainService = "com.oldsky.app.credentials" | ||
private let sessionDefaultsKey = "bluesky.sessionID" | ||
private var stored: StoredSession? | ||
| @@ -411,9 +412,10 @@ actor ATProtoBlueskyService: BlueskyService { | ||
private var followRecordURIs: [String: String] = [:] | ||
private let appViewURL = URL(string: "https://public.api.bsky.app")! | ||
| ||
init(defaults: UserDefaults = .standard, session: URLSession = .shared) { | ||
init(defaults: UserDefaults = .standard, session: URLSession = .shared, beforeAuthenticatedDispatch: (@Sendable () async -> Void)? = nil) { | ||
self.defaults = defaults | ||
self.session = session | ||
self.beforeAuthenticatedDispatch = beforeAuthenticatedDispatch | ||
} | ||
| ||
private func apiClient(for url: URL, sessionConfiguration: SessionConfiguration? = nil, capture: ResponseCapture? = nil) async -> ATProtoKit { | ||
| @@ -426,15 +428,33 @@ actor ATProtoBlueskyService: BlueskyService { | ||
request.setValue("did:web:api.bsky.app#bsky_appview", forHTTPHeaderField: "atproto-proxy") | ||
} | ||
} | ||
var (data, response) = try await session.data(for: request) | ||
let isWrite = ["/xrpc/com.atproto.repo.createRecord", "/xrpc/com.atproto.repo.deleteRecord"].contains(request.url?.path ?? "") | ||
func dispatch(_ request: URLRequest) async throws -> (Data, URLResponse) { | ||
if let configuration = sessionConfiguration as? LibrarySession { | ||
guard let self else { throw ActionNotSentError(underlying: ServiceError.noSession) } | ||
return try await self.dispatchAuthenticated(request, generation: configuration.generation) | ||
} | ||
return try await session.data(for: request) | ||
} | ||
var (data, response) = try await dispatch(request) | ||
if (response as? HTTPURLResponse)?.statusCode == 401, let configuration = sessionConfiguration as? LibrarySession, let self { | ||
let token = try await self.refreshSession(generation: configuration.generation, rejectedToken: configuration.token) | ||
let token: String | ||
do { | ||
token = try await self.refreshSession(generation: configuration.generation, rejectedToken: configuration.token) | ||
} catch { | ||
if isWrite { throw ActionNotSentError(underlying: error) } | ||
throw error | ||
} | ||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | ||
(data, response) = try await session.data(for: request) | ||
(data, response) = try await dispatch(request) | ||
} | ||
guard let http = response as? HTTPURLResponse else { throw ServiceError.invalidResponse } | ||
guard (200..<300).contains(http.statusCode) else { | ||
let body = try? JSONDecoder().decode(APIErrorBody.self, from: data) | ||
if isWrite, (http.statusCode == 400 && body?.error != nil || http.statusCode == 401 || http.statusCode == 403) { | ||
let error = ServiceError.requestFailed(body?.message ?? "The server rejected the request (\(http.statusCode)).") | ||
throw ActionNotSentError(underlying: error) | ||
} | ||
if body?.error == "AuthFactorTokenRequired" { throw ServiceError.authFactorTokenRequired } | ||
if let code = body?.error { | ||
throw ServiceError.serverResponse(code: code, message: body?.message ?? code) | ||
| @@ -447,6 +467,16 @@ actor ATProtoBlueskyService: BlueskyService { | ||
return await ATProtoKit(sessionConfiguration: sessionConfiguration, apiClientConfiguration: APIClientConfiguration(responseProvider: executor), pdsURL: url.absoluteString) | ||
} | ||
| ||
private func dispatchAuthenticated(_ request: URLRequest, generation: UUID) async throws -> (Data, URLResponse) { | ||
if request.url?.path == "/xrpc/com.atproto.repo.createRecord" || request.url?.path == "/xrpc/com.atproto.repo.deleteRecord" { | ||
await beforeAuthenticatedDispatch?() | ||
} | ||
guard generation == sessionGeneration, stored != nil else { | ||
throw ActionNotSentError(underlying: ServiceError.noSession) | ||
} | ||
return try await session.data(for: request) | ||
} | ||
| ||
private func authenticatedClient(capture: ResponseCapture? = nil) async throws -> ATProtoKit { | ||
let generation = sessionGeneration | ||
let token = try await accessToken() | ||
| @@ -759,27 +789,34 @@ actor ATProtoBlueskyService: BlueskyService { | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
if liked { | ||
let reference = try strongReference(for: post) | ||
let reference: [String: String] | ||
do { reference = try strongReference(for: post) } | ||
catch { throw ActionNotSentError(underlying: error) } | ||
let record: [String: Any] = ["$type": "app.bsky.feed.like", "subject": reference, "createdAt": ISO8601DateFormatter().string(from: Date())] | ||
return try await createRecord(collection: "app.bsky.feed.like", record: record).uri | ||
} | ||
if let uri = post.likeURI { try await deleteRecord(uri: uri, repository: current.did) } | ||
guard let uri = post.likeURI else { throw ActionNotSentError(underlying: ServiceError.invalidResponse) } | ||
try await deleteRecord(uri: uri, repository: current.did) | ||
return nil | ||
} | ||
| ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
if reposted { | ||
let reference = try strongReference(for: post) | ||
let reference: [String: String] | ||
do { reference = try strongReference(for: post) } | ||
catch { throw ActionNotSentError(underlying: error) } | ||
let record: [String: Any] = ["$type": "app.bsky.feed.repost", "subject": reference, "createdAt": ISO8601DateFormatter().string(from: Date())] | ||
return try await createRecord(collection: "app.bsky.feed.repost", record: record).uri | ||
} | ||
if let uri = post.repostURI { try await deleteRecord(uri: uri, repository: current.did) } | ||
guard let uri = post.repostURI else { throw ActionNotSentError(underlying: ServiceError.invalidResponse) } | ||
try await deleteRecord(uri: uri, repository: current.did) | ||
return nil | ||
} | ||
| ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
let generation = sessionGeneration | ||
var finalText = text | ||
if let quotePost { | ||
var components = URLComponents(string: "https://oldsky.app/post") | ||
| @@ -801,12 +838,15 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
record["reply"] = ["root": root, "parent": parent] | ||
} | ||
do { | ||
if !images.isEmpty { | ||
guard images.count <= 4 else { throw ServiceError.tooManyImages } | ||
var uploadImages: [[String: Any]] = [] | ||
for image in images { | ||
let upload = try Self.prepareImageForUpload(image) | ||
guard generation == sessionGeneration else { throw ServiceError.noSession } | ||
let client = try await authenticatedClient() | ||
guard generation == sessionGeneration else { throw ServiceError.noSession } | ||
do { | ||
let blob = try await client.uploadBlob(upload.data, contentType: upload.mimeType) | ||
if let id = client.sessionConfiguration?.instanceUUID { await UserSessionRegistry.shared.removeSession(for: id) } | ||
| @@ -820,10 +860,14 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
record["embed"] = ["$type": "app.bsky.embed.images", "images": uploadImages] | ||
} | ||
} catch { | ||
throw ActionNotSentError(underlying: error) | ||
} | ||
let facets = await publishFacets(in: finalText) | ||
if !facets.isEmpty { | ||
record["facets"] = facets.map(Self.encodedFacet) | ||
} | ||
guard generation == sessionGeneration else { throw ActionNotSentError(underlying: ServiceError.noSession) } | ||
let result = try await createRecord(collection: "app.bsky.feed.post", record: record) | ||
let postAuthor = Account(handle: current.handle, displayName: current.handle, id: current.did) | ||
return Post(id: result.uri, cid: result.cid, author: Post.Author(id: postAuthor.id, name: postAuthor.displayName, handle: postAuthor.handle), text: finalText, likeCount: 0, repostCount: 0, isLiked: false, isReposted: false, imageURLs: [], replyRootURI: replyTo?.replyRootURI ?? replyTo?.id, replyRootCID: replyTo?.replyRootCID ?? replyTo?.cid, replyParentURI: replyTo?.id, replyParentCID: replyTo?.cid, facets: facets, quote: quotePost.map { Post.Quote(postID: $0.id) }, replyIDs: [], createdAt: createdAt) | ||
| @@ -831,19 +875,26 @@ actor ATProtoBlueskyService: BlueskyService { | ||
| ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
let profile = try await getProfile(actorID: actorID) | ||
let generation = sessionGeneration | ||
let profile: AppBskyLexicon.Actor.ProfileViewDetailedDefinition | ||
do { | ||
profile = try await getProfile(actorID: actorID) | ||
} catch { | ||
throw ActionNotSentError(underlying: error) | ||
} | ||
guard generation == sessionGeneration else { throw ActionNotSentError(underlying: ServiceError.noSession) } | ||
let subjectDID = profile.actorDID | ||
if following { | ||
let record: [String: Any] = ["$type": "app.bsky.graph.follow", "subject": subjectDID, "createdAt": ISO8601DateFormatter().string(from: Date())] | ||
let uri = try await createRecord(collection: "app.bsky.graph.follow", record: record).uri | ||
followRecordURIs[actorID] = uri | ||
if generation == sessionGeneration { followRecordURIs[actorID] = uri } | ||
return uri | ||
} | ||
let followURI = followRecordURIs.removeValue(forKey: actorID) | ||
?? profile.viewer?.followingURI | ||
if let followURI { | ||
try await deleteRecord(uri: followURI, repository: current.did) | ||
guard let followURI = followRecordURIs[actorID] ?? profile.viewer?.followingURI else { | ||
throw ActionNotSentError(underlying: ServiceError.invalidResponse) | ||
} | ||
try await deleteRecord(uri: followURI, repository: current.did) | ||
if generation == sessionGeneration { followRecordURIs.removeValue(forKey: actorID) } | ||
return nil | ||
} | ||
| ||
| @@ -921,9 +972,10 @@ actor ATProtoBlueskyService: BlueskyService { | ||
| ||
private func createRecord(collection: String, record: [String: Any]) async throws -> CreateRecordResponse { | ||
guard let current = stored else { throw ServiceError.noSession } | ||
let libraryRecord: UnknownType | ||
do { | ||
let data = try JSONSerialization.data(withJSONObject: record) | ||
let decoder = JSONDecoder() | ||
let libraryRecord: UnknownType | ||
switch collection { | ||
case "app.bsky.feed.post": | ||
libraryRecord = .record(try decoder.decode(AppBskyLexicon.Feed.PostRecord.self, from: data)) | ||
| @@ -936,7 +988,12 @@ actor ATProtoBlueskyService: BlueskyService { | ||
default: | ||
throw ServiceError.invalidResponse | ||
} | ||
let client = try await authenticatedClient() | ||
} catch { | ||
throw ActionNotSentError(underlying: error) | ||
} | ||
let client: ATProtoKit | ||
do { client = try await authenticatedClient() } | ||
catch { throw ActionNotSentError(underlying: error) } | ||
do { | ||
let reference = try await client.createRecord(repositoryDID: current.did, collection: collection, record: libraryRecord) | ||
if let id = client.sessionConfiguration?.instanceUUID { await UserSessionRegistry.shared.removeSession(for: id) } | ||
| @@ -949,8 +1006,10 @@ actor ATProtoBlueskyService: BlueskyService { | ||
| ||
private func deleteRecord(uri: String, repository: String) async throws { | ||
let parts = uri.split(separator: "/") | ||
guard parts.count >= 4 else { throw ServiceError.postReferenceUnavailable } | ||
let client = try await authenticatedClient() | ||
guard parts.count >= 4 else { throw ActionNotSentError(underlying: ServiceError.postReferenceUnavailable) } | ||
let client: ATProtoKit | ||
do { client = try await authenticatedClient() } | ||
catch { throw ActionNotSentError(underlying: error) } | ||
do { | ||
try await client.deleteRecord(repositoryDID: repository, collection: String(parts[2]), recordKey: String(parts[3])) | ||
} catch { | ||
| @@ -1436,6 +1495,11 @@ actor ATProtoBlueskyService: BlueskyService { | ||
} | ||
} | ||
| ||
struct ActionNotSentError: LocalizedError { | ||
let underlying: Error | ||
var errorDescription: String? { underlying.localizedDescription } | ||
} | ||
| ||
enum ServiceError: LocalizedError { | ||
case invalidCredentials | ||
case authFactorTokenRequired | ||
Sources/Oldsky/OldskyApp.swift+58−5
| @@ -1188,14 +1188,21 @@ struct PostRow: View { | ||
} | ||
} | ||
| ||
if model.uncertainPostIDs.contains(post.id) { | ||
Text("Like and repost status unknown") | ||
.font(.footnote) | ||
.foregroundStyle(.secondary) | ||
} | ||
HStack(spacing: 8) { | ||
actionButton(title: "\(post.likeCount)", label: post.isLiked ? "Unlike" : "Like", icon: post.isLiked ? "heart.fill" : "heart", tint: post.isLiked ? AppPalette.accent : .secondary, active: post.isLiked) { | ||
actionButton(title: model.uncertainPostIDs.contains(post.id) ? "—" : "\(post.likeCount)", label: model.uncertainPostIDs.contains(post.id) ? "Like status unknown" : (post.isLiked ? "Unlike" : "Like"), icon: post.isLiked && !model.uncertainPostIDs.contains(post.id) ? "heart.fill" : "heart", tint: post.isLiked && !model.uncertainPostIDs.contains(post.id) ? AppPalette.accent : .secondary, active: post.isLiked && !model.uncertainPostIDs.contains(post.id)) { | ||
Task { await model.toggleLike(postID: post.id) } | ||
} | ||
.disabled(model.activePostActions.contains(post.id) || model.uncertainPostIDs.contains(post.id)) | ||
.sensoryFeedback(.success, trigger: post.isLiked) { _, liked in liked } | ||
actionButton(title: "\(post.repostCount)", label: post.isReposted ? "Undo repost" : "Repost", icon: "arrow.2.squarepath", tint: post.isReposted ? AppPalette.reply : .secondary, active: post.isReposted) { | ||
actionButton(title: model.uncertainPostIDs.contains(post.id) ? "—" : "\(post.repostCount)", label: model.uncertainPostIDs.contains(post.id) ? "Repost status unknown" : (post.isReposted ? "Undo repost" : "Repost"), icon: "arrow.2.squarepath", tint: post.isReposted && !model.uncertainPostIDs.contains(post.id) ? AppPalette.reply : .secondary, active: post.isReposted && !model.uncertainPostIDs.contains(post.id)) { | ||
Task { await model.toggleRepost(postID: post.id) } | ||
} | ||
.disabled(model.activePostActions.contains(post.id) || model.uncertainPostIDs.contains(post.id)) | ||
.sensoryFeedback(.success, trigger: post.isReposted) { _, reposted in reposted } | ||
actionButton(title: "Reply", label: "Reply", icon: "bubble") { openComposer(post.id, nil) } | ||
.labelStyle(.iconOnly) | ||
| @@ -2996,9 +3003,11 @@ struct ComposeView: View { | ||
@State private var selectedItems: [PhotosPickerItem] = [] | ||
@State private var attachments: [ImageAttachment] = [] | ||
@State private var isLoadingImages = false | ||
@State private var confirmsDiscardUncertainDraft = false | ||
@FocusState private var textIsFocused: Bool | ||
| ||
private let characterLimit = 300 | ||
private var draftKey: ComposerDraftKey { ComposerDraftKey(replyTo: replyTo, quotePostID: quotePostID) } | ||
| ||
var body: some View { | ||
VStack(spacing: 0) { | ||
| @@ -3016,6 +3025,7 @@ struct ComposeView: View { | ||
.scrollContentBackground(.hidden) | ||
.focused($textIsFocused) | ||
.accessibilityIdentifier("composeTextField") | ||
.disabled(model.isPublishing) | ||
.overlay(alignment: .topLeading) { | ||
if text.isEmpty { | ||
Text("What would you like to share?") | ||
| @@ -3032,6 +3042,15 @@ struct ComposeView: View { | ||
if !attachments.isEmpty { | ||
attachmentStrip | ||
} | ||
if model.uncertainDraftKeys.contains(draftKey) { | ||
VStack(spacing: 8) { | ||
Text("Bluesky may have received this post. Check your profile before you post it again.") | ||
.font(.footnote) | ||
.foregroundStyle(.secondary) | ||
Button("Discard draft and start over") { confirmsDiscardUncertainDraft = true } | ||
} | ||
.padding() | ||
} | ||
| ||
Spacer(minLength: 12) | ||
Divider() | ||
| @@ -3075,14 +3094,42 @@ struct ComposeView: View { | ||
} | ||
} | ||
} | ||
.disabled(!canPublish || model.isPublishing || isLoadingImages) | ||
.disabled(!canPublish || model.isPublishing || isLoadingImages || model.uncertainDraftKeys.contains(draftKey)) | ||
.accessibilityIdentifier("publishButton") | ||
} | ||
} | ||
.alert(model.publishResultUnknown ? "Post status unknown" : "Post not sent", isPresented: Binding( | ||
get: { model.publishErrorMessage != nil }, | ||
set: { if !$0 { model.clearPublishError() } } | ||
)) { | ||
Button("OK", role: .cancel) { model.clearPublishError() } | ||
} message: { | ||
Text(model.publishErrorMessage ?? "Try again.") | ||
} | ||
.confirmationDialog("Discard this draft?", isPresented: $confirmsDiscardUncertainDraft, titleVisibility: .visible) { | ||
Button("Discard draft", role: .destructive) { | ||
text = "" | ||
attachments = [] | ||
model.discardUncertainDraft(for: draftKey) | ||
} | ||
} message: { | ||
Text("Bluesky may have received this post. Discarding the draft will not remove a post from Bluesky.") | ||
} | ||
.onChange(of: selectedItems) { _, items in | ||
Task { await loadImages(items) } | ||
} | ||
.task { textIsFocused = true } | ||
.task { | ||
model.clearPublishError() | ||
if let draft = model.composerDraft(for: draftKey) { | ||
text = draft.text | ||
attachments = draft.attachments | ||
} | ||
textIsFocused = true | ||
} | ||
.onDisappear { | ||
model.saveComposerDraft(ComposerDraft(text: text, attachments: attachments), for: draftKey) | ||
} | ||
.interactiveDismissDisabled(model.isPublishing) | ||
} | ||
| ||
private var canPublish: Bool { | ||
| @@ -3124,6 +3171,7 @@ struct ComposeView: View { | ||
.padding(.vertical, 12) | ||
} | ||
.accessibilityIdentifier("imageAttachments") | ||
.disabled(model.isPublishing) | ||
} | ||
| ||
private func contextRow(title: String, post: Post) -> some View { | ||
| @@ -3163,6 +3211,11 @@ struct ComposeView: View { | ||
| ||
private func publish() async { | ||
let succeeded = await model.publish(text: text, replyTo: replyTo, quotePostID: quotePostID, images: attachments) | ||
if succeeded { dismiss() } | ||
if succeeded { | ||
text = "" | ||
attachments = [] | ||
model.clearComposerDraft(for: draftKey) | ||
dismiss() | ||
} | ||
} | ||
} | ||
Sources/Oldsky/ProfileView.swift+7−1
| @@ -280,17 +280,23 @@ struct ProfileView: View { | ||
} | ||
Spacer(minLength: 4) | ||
if author?.id != model.account?.id { | ||
if isFollowing { | ||
if model.uncertainFollowIDs.contains(actorID) { | ||
Text("Follow status unknown") | ||
.font(.footnote) | ||
.foregroundStyle(.secondary) | ||
} else if isFollowing { | ||
Button { Task { await model.toggleFollow(actorID: actorID) } } label: { | ||
Text("Following").fontWeight(.semibold) | ||
} | ||
.buttonStyle(.bordered) | ||
.disabled(model.activeFollowIDs.contains(actorID) || model.uncertainFollowIDs.contains(actorID)) | ||
.accessibilityIdentifier("followButton") | ||
} else { | ||
Button { Task { await model.toggleFollow(actorID: actorID) } } label: { | ||
Text("Follow").fontWeight(.semibold) | ||
} | ||
.buttonStyle(.borderedProminent) | ||
.disabled(model.activeFollowIDs.contains(actorID) || model.uncertainFollowIDs.contains(actorID)) | ||
.accessibilityIdentifier("followButton") | ||
} | ||
} | ||
Tests/OldskyTests/AppModelTests.swift+274−5
| @@ -410,7 +410,208 @@ final class AppModelTests: XCTestCase { | ||
let success = await model.publish(text: "This will fail") | ||
XCTAssertFalse(success) | ||
XCTAssertEqual(model.posts.count, initialCount) | ||
XCTAssertNotNil(model.errorMessage) | ||
XCTAssertNotNil(model.publishErrorMessage) | ||
} | ||
| ||
func testUnknownActionsKeepStateAndBlockRepeats() async throws { | ||
let service = ActionFailureTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.loadProfile(actorID: "mae") | ||
let original = try XCTUnwrap(model.post(id: "post-1")) | ||
let following = model.followingActorIDs.contains("mae") | ||
await model.toggleLike(postID: original.id) | ||
await model.toggleLike(postID: original.id) | ||
await model.toggleRepost(postID: original.id) | ||
XCTAssertEqual(service.likeCalls, 1) | ||
XCTAssertEqual(service.repostCalls, 0) | ||
XCTAssertEqual(model.post(id: original.id), original) | ||
await model.toggleRepost(postID: "post-2") | ||
await model.toggleRepost(postID: "post-2") | ||
XCTAssertEqual(service.repostCalls, 1) | ||
await model.toggleFollow(actorID: "mae") | ||
await model.toggleFollow(actorID: "mae") | ||
XCTAssertEqual(service.followCalls, 1) | ||
XCTAssertEqual(model.followingActorIDs.contains("mae"), following) | ||
XCTAssertEqual(model.profile(actorID: "mae")?.isFollowing, following) | ||
} | ||
| ||
func testActionErrorsKeepDetailsAndWarnAboutUnknownResult() async { | ||
let service = ActionFailureTestService() | ||
service.publishFailure = ServiceError.postTextTooLong | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.toggleLike(postID: "post-1") | ||
XCTAssertTrue(model.errorMessage?.contains(ServiceError.invalidResponse.localizedDescription) == true) | ||
XCTAssertTrue(model.errorMessage?.contains("may have received") == true) | ||
await model.toggleRepost(postID: "post-1") | ||
XCTAssertTrue(model.errorMessage?.contains("may have received") == true) | ||
await model.toggleFollow(actorID: "mae") | ||
XCTAssertTrue(model.errorMessage?.contains("may have received") == true) | ||
_ = await model.publish(text: "A post") | ||
XCTAssertEqual(model.publishErrorMessage, ServiceError.postTextTooLong.localizedDescription) | ||
XCTAssertFalse(model.publishResultUnknown) | ||
} | ||
| ||
func testRefreshDuringActionDoesNotAdjustCountsTwice() async throws { | ||
let service = ActionFailureTestService() | ||
service.failActions = false | ||
service.actionDelay = 100_000_000 | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
var refreshed = try XCTUnwrap(model.post(id: "post-1")) | ||
let initialLikes = refreshed.likeCount | ||
let initialReposts = refreshed.repostCount | ||
let like = Task { await model.toggleLike(postID: "post-1") } | ||
while !model.activePostActions.contains("post-1") { await Task.yield() } | ||
refreshed.isLiked = true | ||
refreshed.likeCount += 1 | ||
service.refreshedPost = refreshed | ||
await model.loadFeed() | ||
await like.value | ||
XCTAssertEqual(model.post(id: "post-1")?.likeCount, initialLikes + 1) | ||
| ||
let repost = Task { await model.toggleRepost(postID: "post-1") } | ||
while !model.activePostActions.contains("post-1") { await Task.yield() } | ||
refreshed.isReposted = true | ||
refreshed.repostCount += 1 | ||
service.refreshedPost = refreshed | ||
await model.loadFeed() | ||
await repost.value | ||
XCTAssertEqual(model.post(id: "post-1")?.repostCount, initialReposts + 1) | ||
} | ||
| ||
func testComposerDraftsKeepTextAndAttachmentsForEachTarget() async { | ||
let model = AppModel(service: MockBlueskyService()) | ||
let key = ComposerDraftKey(replyTo: "post-1", quotePostID: nil) | ||
let other = ComposerDraftKey(replyTo: nil, quotePostID: nil) | ||
let image = ImageAttachment(data: Data([1, 2, 3]), altText: "A boat", mimeType: "image/jpeg") | ||
model.saveComposerDraft(ComposerDraft(text: "My reply", attachments: [image]), for: key) | ||
XCTAssertEqual(model.composerDraft(for: key)?.text, "My reply") | ||
XCTAssertEqual(model.composerDraft(for: key)?.attachments, [image]) | ||
XCTAssertNil(model.composerDraft(for: other)) | ||
model.clearComposerDraft(for: key) | ||
XCTAssertNil(model.composerDraft(for: key)) | ||
} | ||
| ||
func testDuplicatePostActionWaitsForFirstRequest() async { | ||
let service = ActionFailureTestService() | ||
service.actionDelay = 100_000_000 | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
let first = Task { await model.toggleLike(postID: "post-1") } | ||
while !model.activePostActions.contains("post-1") { await Task.yield() } | ||
await model.toggleLike(postID: "post-1") | ||
await model.toggleRepost(postID: "post-1") | ||
await first.value | ||
XCTAssertEqual(service.likeCalls, 1) | ||
XCTAssertEqual(service.repostCalls, 0) | ||
XCTAssertFalse(model.activePostActions.contains("post-1")) | ||
} | ||
| ||
func testPublishFailureCanRetryWithSameTextAndAttachment() async { | ||
let service = ActionFailureTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
let image = ImageAttachment(data: Data([1, 2, 3]), altText: "A red boat", mimeType: "image/jpeg") | ||
let initialCount = model.posts.count | ||
let first = await model.publish(text: "A post", images: [image]) | ||
XCTAssertFalse(first) | ||
XCTAssertEqual(model.posts.count, initialCount) | ||
XCTAssertNotNil(model.publishErrorMessage) | ||
XCTAssertTrue(model.publishResultUnknown) | ||
let second = await model.publish(text: "A post", images: [image]) | ||
XCTAssertFalse(second) | ||
XCTAssertEqual(service.publishedTexts, ["A post"]) | ||
XCTAssertEqual(service.publishedImages.first?.first?.altText, "A red boat") | ||
XCTAssertEqual(service.publishedImages.first?.first?.data, image.data) | ||
} | ||
| ||
func testDiscardingUncertainDraftAllowsNewPost() async { | ||
let service = ActionFailureTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
let key = ComposerDraftKey(replyTo: nil, quotePostID: nil) | ||
let image = ImageAttachment(data: Data([1, 2, 3]), altText: "A boat", mimeType: "image/jpeg") | ||
model.saveComposerDraft(ComposerDraft(text: "Original", attachments: [image]), for: key) | ||
let failed = await model.publish(text: "Original", images: [image]) | ||
XCTAssertFalse(failed) | ||
XCTAssertEqual(model.composerDraft(for: key)?.attachments, [image]) | ||
XCTAssertTrue(model.uncertainDraftKeys.contains(key)) | ||
| ||
model.discardUncertainDraft(for: key) | ||
XCTAssertNil(model.composerDraft(for: key)) | ||
XCTAssertFalse(model.uncertainDraftKeys.contains(key)) | ||
let succeeded = await model.publish(text: "A different post") | ||
XCTAssertTrue(succeeded) | ||
XCTAssertEqual(service.publishedTexts, ["Original", "A different post"]) | ||
} | ||
| ||
func testSignOutClearsUncertainActionsAndDrafts() async { | ||
let service = ActionFailureTestService() | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.toggleLike(postID: "post-1") | ||
await model.toggleFollow(actorID: "mae") | ||
_ = await model.publish(text: "Original") | ||
XCTAssertFalse(model.uncertainPostIDs.isEmpty) | ||
XCTAssertFalse(model.uncertainFollowIDs.isEmpty) | ||
XCTAssertFalse(model.uncertainDraftKeys.isEmpty) | ||
await model.signOut() | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
XCTAssertTrue(model.uncertainPostIDs.isEmpty) | ||
XCTAssertTrue(model.uncertainFollowIDs.isEmpty) | ||
XCTAssertTrue(model.uncertainDraftKeys.isEmpty) | ||
} | ||
| ||
func testDelayedActionsDoNotChangeNextSession() async { | ||
let service = ActionFailureTestService() | ||
service.actionDelay = 200_000_000 | ||
service.followDelay = 200_000_000 | ||
service.publishDelay = 200_000_000 | ||
service.failActions = false | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
let like = Task { await model.toggleLike(postID: "post-1") } | ||
let repost = Task { await model.toggleRepost(postID: "post-2") } | ||
let follow = Task { await model.toggleFollow(actorID: "mae") } | ||
let publish = Task { await model.publish(text: "Old session") } | ||
while service.likeCalls == 0 || service.repostCalls == 0 || service.followCalls == 0 || service.publishedTexts.isEmpty { await Task.yield() } | ||
await model.signOut() | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
let original = model.posts | ||
await like.value | ||
await repost.value | ||
await follow.value | ||
let result = await publish.value | ||
XCTAssertFalse(result) | ||
XCTAssertEqual(model.posts, original) | ||
XCTAssertFalse(model.followingActorIDs.contains("mae")) | ||
XCTAssertNil(model.errorMessage) | ||
XCTAssertFalse(model.isPublishing) | ||
} | ||
| ||
func testKnownFailureAllowsRetry() async { | ||
let service = ActionFailureTestService() | ||
service.likeFailure = ActionNotSentError(underlying: ServiceError.invalidResponse) | ||
service.followFailure = ActionNotSentError(underlying: ServiceError.invalidResponse) | ||
service.publishFailure = ActionNotSentError(underlying: ServiceError.invalidUploadResponse) | ||
let model = AppModel(service: service) | ||
await model.signIn(handle: "demo.bsky.social", appPassword: "test-only") | ||
await model.toggleLike(postID: "post-1") | ||
await model.toggleFollow(actorID: "mae") | ||
let failed = await model.publish(text: "A post") | ||
XCTAssertFalse(failed) | ||
XCTAssertTrue(model.uncertainPostIDs.isEmpty) | ||
XCTAssertTrue(model.uncertainFollowIDs.isEmpty) | ||
XCTAssertTrue(model.uncertainDraftKeys.isEmpty) | ||
await model.toggleLike(postID: "post-1") | ||
await model.toggleFollow(actorID: "mae") | ||
let succeeded = await model.publish(text: "A post") | ||
XCTAssertTrue(succeeded) | ||
XCTAssertEqual(service.likeCalls, 2) | ||
XCTAssertEqual(service.followCalls, 2) | ||
XCTAssertEqual(service.publishedTexts.count, 2) | ||
} | ||
| ||
func testGIFDecoderRejectsOversizedDimensions() throws { | ||
| @@ -740,6 +941,12 @@ final class AppModelTests: XCTestCase { | ||
let loaded = await model.loadModeration(actorID: "alex") | ||
await model.setModeration(actorID: "mae", block: true) | ||
let reported = await model.submitReport(.account("mae"), reason: "reason") | ||
await model.toggleLike(postID: "post-1") | ||
await model.toggleRepost(postID: "post-1") | ||
await model.toggleFollow(actorID: "mae") | ||
let published = await model.publish(text: "A post") | ||
XCTAssertFalse(published) | ||
XCTAssertEqual(service.postActionCalls, 0) | ||
XCTAssertFalse(loaded) | ||
XCTAssertFalse(reported) | ||
XCTAssertTrue(service.actions.isEmpty) | ||
| @@ -874,6 +1081,67 @@ final class AppModelTests: XCTestCase { | ||
} | ||
} | ||
| ||
@MainActor | ||
private final class ActionFailureTestService: BlueskyService { | ||
let base = MockBlueskyService() | ||
var likeCalls = 0 | ||
var actionDelay: UInt64 = 0 | ||
var failActions = true | ||
var refreshedPost: Post? | ||
var publishFailure: Error = ServiceError.invalidResponse | ||
var likeFailure: Error = ServiceError.invalidResponse | ||
var followFailure: Error = ServiceError.invalidResponse | ||
var publishDelay: UInt64 = 0 | ||
var followDelay: UInt64 = 0 | ||
var repostCalls = 0 | ||
var followCalls = 0 | ||
var publishedTexts: [String] = [] | ||
var publishedImages: [[ImageAttachment]] = [] | ||
| ||
func restoreAccount() async throws -> Account? { try await base.restoreAccount() } | ||
func signIn(handle: String, appPassword: String, authFactorToken: String?) async throws -> Account { | ||
try await base.signIn(handle: handle, appPassword: appPassword, authFactorToken: authFactorToken) | ||
} | ||
func signOut() async throws { try await base.signOut() } | ||
func loadFollowingFeed(cursor: String?) async throws -> FeedPage { | ||
let page = try await base.loadFollowingFeed(cursor: cursor) | ||
guard let refreshedPost else { return page } | ||
return FeedPage(posts: page.posts.map { $0.id == refreshedPost.id ? refreshedPost : $0 }, cursor: page.cursor, replyContexts: page.replyContexts, repostedBy: page.repostedBy) | ||
} | ||
func loadNotifications(cursor: String?) async throws -> NotificationPage { try await base.loadNotifications(cursor: cursor) } | ||
func markNotificationsRead(seenAt: Date) async throws { try await base.markNotificationsRead(seenAt: seenAt) } | ||
func loadPost(uri: String) async throws -> [Post] { try await base.loadPost(uri: uri) } | ||
func loadProfile(actorID: String) async throws -> Profile? { try await base.loadProfile(actorID: actorID) } | ||
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage { | ||
try await base.loadAuthorPosts(actorID: actorID, cursor: cursor) | ||
} | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { | ||
likeCalls += 1 | ||
if actionDelay > 0 { try await Task.sleep(nanoseconds: actionDelay) } | ||
if failActions && likeCalls == 1 { throw likeFailure } | ||
return try await base.toggleLike(post: post, liked: liked) | ||
} | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { | ||
repostCalls += 1 | ||
if actionDelay > 0 { try await Task.sleep(nanoseconds: actionDelay) } | ||
if failActions && repostCalls == 1 { throw ServiceError.invalidResponse } | ||
return try await base.toggleRepost(post: post, reposted: reposted) | ||
} | ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? { | ||
followCalls += 1 | ||
if followDelay > 0 { try await Task.sleep(nanoseconds: followDelay) } | ||
if failActions && followCalls == 1 { throw followFailure } | ||
return try await base.setFollowing(following, actorID: actorID) | ||
} | ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { | ||
publishedTexts.append(text) | ||
publishedImages.append(images) | ||
if publishDelay > 0 { try await Task.sleep(nanoseconds: publishDelay) } | ||
if failActions && publishedTexts.count == 1 { throw publishFailure } | ||
return try await base.publish(text: text, replyTo: replyTo, quotePost: quotePost, images: images) | ||
} | ||
} | ||
| ||
private final class ModerationTestService: BlueskyService { | ||
private let base = MockBlueskyService() | ||
var fail = false | ||
| @@ -888,6 +1156,7 @@ private final class ModerationTestService: BlueskyService { | ||
var failSignOut = false | ||
var suspendBlock = false | ||
var pendingBlock: CheckedContinuation<String?, Error>? | ||
var postActionCalls = 0 | ||
func restoreAccount() async throws -> Account? { nil } | ||
func signIn(handle: String, appPassword: String, authFactorToken: String?) async throws -> Account { try await base.signIn(handle: handle, appPassword: appPassword, authFactorToken: authFactorToken) } | ||
func signOut() async throws { | ||
| @@ -900,10 +1169,10 @@ private final class ModerationTestService: BlueskyService { | ||
func loadPost(uri: String) async throws -> [Post] { try await base.loadPost(uri: uri) } | ||
func loadProfile(actorID: String) async throws -> Profile? { try await base.loadProfile(actorID: actorID) } | ||
func loadAuthorPosts(actorID: String, cursor: String?) async throws -> FeedPage { try await base.loadAuthorPosts(actorID: actorID, cursor: cursor) } | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { nil } | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { nil } | ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { try await base.publish(text: text, replyTo: replyTo, quotePost: quotePost, images: images) } | ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? { nil } | ||
func toggleLike(post: Post, liked: Bool) async throws -> String? { postActionCalls += 1; return nil } | ||
func toggleRepost(post: Post, reposted: Bool) async throws -> String? { postActionCalls += 1; return nil } | ||
func publish(text: String, replyTo: Post?, quotePost: Post?, images: [ImageAttachment]) async throws -> Post { postActionCalls += 1; return try await base.publish(text: text, replyTo: replyTo, quotePost: quotePost, images: images) } | ||
func setFollowing(_ following: Bool, actorID: String) async throws -> String? { postActionCalls += 1; return nil } | ||
func moderationState(actorID: String) async throws -> ModerationState { | ||
if suspendLoad { return await withCheckedContinuation { pendingLoad = $0 } } | ||
return state | ||
Tests/OldskyTests/ATProtoServiceTests.swift+127−0
| @@ -2,6 +2,29 @@ import Foundation | ||
import XCTest | ||
@testable import Oldsky | ||
| ||
private actor WriteDispatchGate { | ||
private var paused = false | ||
private var waiter: CheckedContinuation<Void, Never>? | ||
private var releaseWaiter: CheckedContinuation<Void, Never>? | ||
| ||
func pause() async { | ||
paused = true | ||
waiter?.resume() | ||
waiter = nil | ||
await withCheckedContinuation { releaseWaiter = $0 } | ||
} | ||
| ||
func waitUntilPaused() async { | ||
if paused { return } | ||
await withCheckedContinuation { waiter = $0 } | ||
} | ||
| ||
func release() { | ||
releaseWaiter?.resume() | ||
releaseWaiter = nil | ||
} | ||
} | ||
| ||
final class ATProtoServiceTests: XCTestCase { | ||
func testModerationRequestsAndFailure() async throws { | ||
let suite = "ModerationTests.\(UUID().uuidString)" | ||
| @@ -483,6 +506,110 @@ final class ATProtoServiceTests: XCTestCase { | ||
try await service.signOut() | ||
} | ||
| ||
func testRecordWriteRejectionAndAmbiguousResponseClassification() async throws { | ||
let cases: [(status: Int, body: String, rejected: Bool)] = [ | ||
(400, "{\"error\":\"InvalidRequest\",\"message\":\"Rejected\"}", true), | ||
(400, "{\"error\":\"AuthFactorTokenRequired\"}", true), | ||
(400, "", false), | ||
(400, "not json", false), | ||
(499, "{\"error\":\"InvalidRequest\"}", false), | ||
(503, "{\"error\":\"InvalidRequest\"}", false), | ||
(401, "{\"error\":\"InvalidRequest\"}", true) | ||
] | ||
for testCase in cases { | ||
let status = testCase.status | ||
let suiteName = "OldskyWriteFailureTests.\(UUID().uuidString)" | ||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [StubURLProtocol.self] | ||
let session = URLSession(configuration: configuration) | ||
let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) | ||
let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString() | ||
.replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") | ||
let token = "header.\(payload).signature" | ||
StubURLProtocol.clearRequests() | ||
StubURLProtocol.handler = { request in | ||
switch request.url?.path { | ||
case "/xrpc/com.atproto.identity.resolveHandle": | ||
return (200, Data("{\"did\":\"did:plc:write\"}".utf8)) | ||
case "/did:plc:write": | ||
return (200, Data("{\"id\":\"did:plc:write\",\"service\":[{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":\"https://write-pds.example.test\"}]}".utf8)) | ||
case "/xrpc/com.atproto.server.createSession": | ||
return (200, Data("{\"handle\":\"write.example\",\"did\":\"did:plc:write\",\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}".utf8)) | ||
case "/xrpc/app.bsky.actor.getProfile": | ||
return (200, Data("{\"did\":\"did:plc:write\",\"handle\":\"write.example\"}".utf8)) | ||
case "/xrpc/com.atproto.repo.createRecord": | ||
return (status, Data(testCase.body.utf8)) | ||
case "/xrpc/com.atproto.server.refreshSession": | ||
return (503, Data("{\"error\":\"Unavailable\"}".utf8)) | ||
default: | ||
return (404, Data("{\"error\":\"NotFound\"}".utf8)) | ||
} | ||
} | ||
let service = ATProtoBlueskyService(defaults: defaults, session: session) | ||
do { | ||
_ = try await service.signIn(handle: "write.example", appPassword: "test-password", authFactorToken: nil) | ||
do { | ||
_ = try await service.publish(text: "A post", replyTo: nil, quotePost: nil, images: []) | ||
XCTFail("Expected a write failure") | ||
} catch { | ||
XCTAssertEqual(error is ActionNotSentError, testCase.rejected, "HTTP \(status), body \(testCase.body): \(error)") | ||
} | ||
XCTAssertEqual(StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" }.count, 1) | ||
if status == 401 { | ||
XCTAssertEqual(StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/com.atproto.server.refreshSession" }.count, 1) | ||
} | ||
try await service.signOut() | ||
} catch { | ||
XCTFail("Unexpected setup failure: \(error)") | ||
} | ||
StubURLProtocol.handler = nil | ||
session.invalidateAndCancel() | ||
defaults.removePersistentDomain(forName: suiteName) | ||
} | ||
} | ||
| ||
func testSignOutBeforeRecordDispatchPreventsWrite() async throws { | ||
let suiteName = "OldskyWriteDispatchTests.\(UUID().uuidString)" | ||
let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) | ||
let configuration = URLSessionConfiguration.ephemeral | ||
configuration.protocolClasses = [StubURLProtocol.self] | ||
let session = URLSession(configuration: configuration) | ||
let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) | ||
let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString() | ||
.replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") | ||
let token = "header.\(payload).signature" | ||
let gate = WriteDispatchGate() | ||
StubURLProtocol.clearRequests() | ||
StubURLProtocol.handler = { request in | ||
switch request.url?.path { | ||
case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:write\"}".utf8)) | ||
case "/did:plc:write": return (200, Data("{\"id\":\"did:plc:write\",\"service\":[{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":\"https://write-pds.example.test\"}]}".utf8)) | ||
case "/xrpc/com.atproto.server.createSession": return (200, Data("{\"handle\":\"write.example\",\"did\":\"did:plc:write\",\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh\"}".utf8)) | ||
case "/xrpc/app.bsky.actor.getProfile": return (200, Data("{\"did\":\"did:plc:write\",\"handle\":\"write.example\"}".utf8)) | ||
default: return (404, Data("{\"error\":\"NotFound\"}".utf8)) | ||
} | ||
} | ||
defer { | ||
StubURLProtocol.handler = nil | ||
session.invalidateAndCancel() | ||
defaults.removePersistentDomain(forName: suiteName) | ||
} | ||
let service = ATProtoBlueskyService(defaults: defaults, session: session, beforeAuthenticatedDispatch: { await gate.pause() }) | ||
_ = try await service.signIn(handle: "write.example", appPassword: "test-password", authFactorToken: nil) | ||
let write = Task { try await service.publish(text: "A post", replyTo: nil, quotePost: nil, images: []) } | ||
await gate.waitUntilPaused() | ||
try await service.signOut() | ||
await gate.release() | ||
do { | ||
_ = try await write.value | ||
XCTFail("Expected a rejected write") | ||
} catch { | ||
XCTAssertTrue(error is ActionNotSentError) | ||
} | ||
XCTAssertFalse(StubURLProtocol.recordedRequests.contains { $0.url?.path == "/xrpc/com.atproto.repo.createRecord" }) | ||
} | ||
| ||
func testConcurrentRequestsShareTokenRefresh() async throws { | ||
try await exerciseRefreshRace(signOutDuringRefresh: false) | ||
} | ||