| 1 | @testable import EquipoShareCore |
| 2 | import Foundation |
| 3 | import ImageIO |
| 4 | import Testing |
| 5 | import UniformTypeIdentifiers |
| 6 | @testable import EquipoKit |
| 7 | |
| 8 | @Suite struct AttachmentTests { |
| 9 | static func image(_ type: UTType = .png, width: Int = 12, height: Int = 8) throws -> Data { |
| 10 | let color = CGColorSpaceCreateDeviceRGB() |
| 11 | let context = try #require(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: color, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) |
| 12 | context.setFillColor(CGColor(red: 0.1, green: 0.4, blue: 0.8, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: width, height: height)) |
| 13 | let data = NSMutableData() |
| 14 | let destination = try #require(CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil)) |
| 15 | CGImageDestinationAddImage(destination, try #require(context.makeImage()), nil) |
| 16 | #expect(CGImageDestinationFinalize(destination)) |
| 17 | return data as Data |
| 18 | } |
| 19 | |
| 20 | @Test func limitsMatchTheServerAndRejectBeforeUpload() throws { |
| 21 | #expect(AttachmentLimits.maxBytes == 10 << 20) |
| 22 | #expect(AttachmentLimits.maxCount == 5) |
| 23 | #expect(AttachmentLimits.maxSide == 12_000) |
| 24 | #expect(AttachmentLimits.maxPixels == 40_000_000) |
| 25 | #expect(throws: AttachmentFailure.tooLarge) { try AttachmentFile.prepare(Data(repeating: 65, count: (10 << 20) + 1), name: "large.txt") } |
| 26 | #expect(throws: AttachmentFailure.pixels) { try AttachmentLimits.checkDimensions(width: 12_001, height: 1) } |
| 27 | #expect(throws: AttachmentFailure.pixels) { try AttachmentLimits.checkDimensions(width: 8_000, height: 5_001) } |
| 28 | #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data([0, 1, 2, 3]), name: "app.exe") } |
| 29 | } |
| 30 | |
| 31 | @Test func heicIsConvertedAndPNGIsPreserved() throws { |
| 32 | let original = try Self.image() |
| 33 | let png = try AttachmentFile.prepare(original, name: "screen.png") |
| 34 | #expect(png.data == original); #expect(png.mediaType == "image/png") |
| 35 | let heic = try AttachmentFile.prepare(Self.image(.heic), name: "photo.HEIC") |
| 36 | #expect(heic.mediaType == "image/jpeg"); #expect(heic.name == "photo.jpg") |
| 37 | #expect(heic.data.starts(with: [0xff, 0xd8])) |
| 38 | #expect(heic.width == 12 && heic.height == 8) |
| 39 | } |
| 40 | |
| 41 | @Test func uploadAndAttachmentOnlyMessageReachFakeCoordinator() async throws { |
| 42 | let server = AttachmentServer() |
| 43 | let client = EquipoClient(transport: server, token: "fixture-bearer") |
| 44 | let file = try AttachmentFile.prepare(Self.image(), name: "screen shot.png") |
| 45 | let uploaded = try await client.upload(file) { _ in } |
| 46 | let pending = try EquipoClient.message("", attachments: [uploaded.id]) |
| 47 | let sent = try await client.send(pending) |
| 48 | #expect(sent.message.attachments?.first?.id == uploaded.id) |
| 49 | #expect(await server.coordinatorImages == [file.data]) |
| 50 | let reads = try await client.attachmentData(uploaded.id, preview: true) |
| 51 | #expect(reads == file.data) |
| 52 | let requests = await server.requests |
| 53 | let request = try #require(requests.first) |
| 54 | let url = try request.urlRequest(origin: server.origin) |
| 55 | #expect(url.httpBody == file.data) |
| 56 | #expect(url.value(forHTTPHeaderField: "Content-Type") == "image/png") |
| 57 | #expect(url.value(forHTTPHeaderField: "Content-Disposition")?.contains("filename") == true) |
| 58 | #expect(url.value(forHTTPHeaderField: "Authorization") == "Bearer fixture-bearer") |
| 59 | #expect(!url.httpShouldHandleCookies) |
| 60 | #expect(requests.last?.path == "/attachments/at_fixture/preview") |
| 61 | } |
| 62 | |
| 63 | @MainActor @Test func draftGatesSendAndKeepsFailureForRetry() async throws { |
| 64 | let server = AttachmentServer(); await server.failNext() |
| 65 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 66 | await draft.add(data: try Self.image(), name: "screen.png") |
| 67 | #expect(draft.items.count == 1) |
| 68 | #expect(!draft.canSend(text: "a note")) |
| 69 | let id = try #require(draft.items.first?.id) |
| 70 | #expect(draft.items.first?.failure != nil) |
| 71 | await draft.retry(id) |
| 72 | #expect(draft.canSend(text: "")) |
| 73 | #expect(draft.readyAttachments.map(\.id) == ["at_fixture"]) |
| 74 | draft.remove(id) |
| 75 | #expect(draft.items.isEmpty); #expect(!draft.canSend(text: "")) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | actor AttachmentServer: EquipoTransport { |
| 80 | nonisolated let origin = URL(string: "https://fixture.invalid")! |
| 81 | var requests: [APIRequest] = [] |
| 82 | var coordinatorImages: [Data] = [] |
| 83 | private var bytes = Data() |
| 84 | private var fail = false |
| 85 | func failNext() { fail = true } |
| 86 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 87 | requests.append(request) |
| 88 | if request.path == "/attachments", request.method == "POST" { |
| 89 | if fail { fail = false; throw EquipoAPIError.offline } |
| 90 | bytes = request.body ?? Data() |
| 91 | return APIResponse(status: 201, data: Data(Self.attachment.utf8)) |
| 92 | } |
| 93 | if request.path == "/messages" { |
| 94 | let body = try JSONSerialization.jsonObject(with: request.body!) as! [String: Any] |
| 95 | #expect(body["attachments"] as? [String] == ["at_fixture"]) |
| 96 | #expect(body["idempotency_key"] as? String == request.idempotencyKey) |
| 97 | if body["attachments"] as? [String] == ["at_fixture"] { coordinatorImages.append(bytes) } |
| 98 | var sent: Sent = try Fixture.decode("thin/sent") |
| 99 | sent.message.attachments = [try EquipoJSON.decoder.decode(MessageAttachment.self, from: Data(Self.attachment.utf8))] |
| 100 | let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| 101 | return APIResponse(status: 201, data: try encoder.encode(sent)) |
| 102 | } |
| 103 | return APIResponse(status: 200, data: bytes) |
| 104 | } |
| 105 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| 106 | static let attachment = """ |
| 107 | {"id":"at_fixture","revision":1,"kind":"image","name":"screen.png","media_type":"image/png","size":100,"sha256":"fixture","width":12,"height":8,"message_id":"","created_at":"2026-11-25T10:00:00Z"} |
| 108 | """ |
| 109 | } |
| 110 | |
| 111 | extension AttachmentTests { |
| 112 | @MainActor @Test func invalidImageNeverReachesUpload() async throws { |
| 113 | let server = AttachmentServer() |
| 114 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 115 | await draft.add(data: try Self.image(.gif, width: 12_001, height: 1), name: "wide.png") |
| 116 | #expect(draft.items.first?.failure == EquipoStrings.text("api.attachment_pixels")) |
| 117 | #expect(await server.requests.isEmpty) |
| 118 | } |
| 119 | |
| 120 | @MainActor @Test func uploadingItemsCountTowardLimitAndRemovedItemsStayGone() async throws { |
| 121 | let server = HeldAttachmentServer() |
| 122 | let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| 123 | let image = try Self.image() |
| 124 | let tasks = (0..<5).map { n in Task { await draft.add(data: image, name: "screen\(n).png") } } |
| 125 | for _ in 0..<500 { |
| 126 | if await server.pendingCount == 5 { break } |
| 127 | try await Task.sleep(for: .milliseconds(10)) |
| 128 | } |
| 129 | #expect(await server.pendingCount == 5) |
| 130 | #expect(!draft.canSend(text: "a note")) |
| 131 | let sixth = Task { await draft.add(data: image, name: "sixth.png") } |
| 132 | for _ in 0..<100 { |
| 133 | if draft.notice != nil || draft.items.count > 5 { break } |
| 134 | try await Task.sleep(for: .milliseconds(10)) |
| 135 | } |
| 136 | #expect(draft.items.count == 5) |
| 137 | #expect(draft.notice == EquipoStrings.text("chat.attach.too_many")) |
| 138 | for _ in 0..<500 { |
| 139 | if await server.pendingCount == draft.items.count { break } |
| 140 | try await Task.sleep(for: .milliseconds(10)) |
| 141 | } |
| 142 | let id = try #require(draft.items.first?.id) |
| 143 | if case .uploading(let progress) = draft.items.first?.state { #expect(progress == 0.45) } |
| 144 | else { Issue.record("Expected an upload in progress") } |
| 145 | draft.remove(id) |
| 146 | await server.complete() |
| 147 | for task in tasks { await task.value } |
| 148 | await sixth.value |
| 149 | #expect(draft.items.count == 4) |
| 150 | #expect(!draft.items.contains { $0.id == id }) |
| 151 | #expect(draft.canSend(text: "")) |
| 152 | } |
| 153 | |
| 154 | @Test func messageRejectsTooManyOrDuplicateIDs() { |
| 155 | #expect(throws: (any Error).self) { try EquipoClient.message("", attachments: (0..<6).map { "at_\($0)" }) } |
| 156 | #expect(throws: (any Error).self) { try EquipoClient.message("", attachments: ["at_a", "at_a"]) } |
| 157 | } |
| 158 | |
| 159 | @MainActor @Test func composerSendsTheUploadedImageAndClearsDraft() async throws { |
| 160 | let server = AttachmentServer() |
| 161 | let session = EquipoSession(account: .new(origin: server.origin, label: "Fixture"), accounts: DeviceAccounts(store: MemorySecretStore()), transport: server) |
| 162 | let data = try Self.image() |
| 163 | await session.attachments.add(data: data, name: "screen.png") |
| 164 | await session.sendFromComposer("").value |
| 165 | #expect(session.attachments.items.isEmpty) |
| 166 | #expect(await server.coordinatorImages == [data]) |
| 167 | await session.attachments.add(data: data, name: "another.png") |
| 168 | session.invalidate() |
| 169 | #expect(session.attachments.items.isEmpty) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | actor HeldAttachmentServer: EquipoTransport { |
| 174 | nonisolated let origin = URL(string: "https://held.example")! |
| 175 | private var pending: [CheckedContinuation<APIResponse, Error>] = [] |
| 176 | var pendingCount: Int { pending.count } |
| 177 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 178 | request.uploadProgress?.report(0.45) |
| 179 | return try await withCheckedThrowingContinuation { pending.append($0) } |
| 180 | } |
| 181 | func complete() { |
| 182 | for continuation in pending { continuation.resume(returning: APIResponse(status: 201, data: Data(AttachmentServer.attachment.utf8))) } |
| 183 | pending = [] |
| 184 | } |
| 185 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| 186 | } |
| 187 | |
| 188 | extension AttachmentTests { |
| 189 | @Test func textDetectionMatchesServerInsteadOfRestrictingExtensions() throws { |
| 190 | for name in ["README", "main.swift", "change.patch", "error.log"] { |
| 191 | let file = try AttachmentFile.prepare(Data("let answer = 42\n".utf8), name: name) |
| 192 | #expect(file.mediaType == "text/plain") |
| 193 | } |
| 194 | #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data([65, 1, 66]), name: "bad.txt") } |
| 195 | #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data("not an image".utf8), name: "bad.png") } |
| 196 | #expect(try AttachmentFile.prepare(Data("not json".utf8), name: "bad.json").mediaType == "text/plain") |
| 197 | } |
| 198 | } |
| 199 | |