@testable import EquipoShareCore import Foundation import ImageIO import Testing import UniformTypeIdentifiers @testable import EquipoKit @Suite struct AttachmentTests { static func image(_ type: UTType = .png, width: Int = 12, height: Int = 8) throws -> Data { let color = CGColorSpaceCreateDeviceRGB() let context = try #require(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: color, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) 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)) let data = NSMutableData() let destination = try #require(CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil)) CGImageDestinationAddImage(destination, try #require(context.makeImage()), nil) #expect(CGImageDestinationFinalize(destination)) return data as Data } @Test func limitsMatchTheServerAndRejectBeforeUpload() throws { #expect(AttachmentLimits.maxBytes == 10 << 20) #expect(AttachmentLimits.maxCount == 5) #expect(AttachmentLimits.maxSide == 12_000) #expect(AttachmentLimits.maxPixels == 40_000_000) #expect(throws: AttachmentFailure.tooLarge) { try AttachmentFile.prepare(Data(repeating: 65, count: (10 << 20) + 1), name: "large.txt") } #expect(throws: AttachmentFailure.pixels) { try AttachmentLimits.checkDimensions(width: 12_001, height: 1) } #expect(throws: AttachmentFailure.pixels) { try AttachmentLimits.checkDimensions(width: 8_000, height: 5_001) } #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data([0, 1, 2, 3]), name: "app.exe") } } @Test func heicIsConvertedAndPNGIsPreserved() throws { let original = try Self.image() let png = try AttachmentFile.prepare(original, name: "screen.png") #expect(png.data == original); #expect(png.mediaType == "image/png") let heic = try AttachmentFile.prepare(Self.image(.heic), name: "photo.HEIC") #expect(heic.mediaType == "image/jpeg"); #expect(heic.name == "photo.jpg") #expect(heic.data.starts(with: [0xff, 0xd8])) #expect(heic.width == 12 && heic.height == 8) } @Test func uploadAndAttachmentOnlyMessageReachFakeCoordinator() async throws { let server = AttachmentServer() let client = EquipoClient(transport: server, token: "fixture-bearer") let file = try AttachmentFile.prepare(Self.image(), name: "screen shot.png") let uploaded = try await client.upload(file) { _ in } let pending = try EquipoClient.message("", attachments: [uploaded.id]) let sent = try await client.send(pending) #expect(sent.message.attachments?.first?.id == uploaded.id) #expect(await server.coordinatorImages == [file.data]) let reads = try await client.attachmentData(uploaded.id, preview: true) #expect(reads == file.data) let requests = await server.requests let request = try #require(requests.first) let url = try request.urlRequest(origin: server.origin) #expect(url.httpBody == file.data) #expect(url.value(forHTTPHeaderField: "Content-Type") == "image/png") #expect(url.value(forHTTPHeaderField: "Content-Disposition")?.contains("filename") == true) #expect(url.value(forHTTPHeaderField: "Authorization") == "Bearer fixture-bearer") #expect(!url.httpShouldHandleCookies) #expect(requests.last?.path == "/attachments/at_fixture/preview") } @MainActor @Test func draftGatesSendAndKeepsFailureForRetry() async throws { let server = AttachmentServer(); await server.failNext() let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) await draft.add(data: try Self.image(), name: "screen.png") #expect(draft.items.count == 1) #expect(!draft.canSend(text: "a note")) let id = try #require(draft.items.first?.id) #expect(draft.items.first?.failure != nil) await draft.retry(id) #expect(draft.canSend(text: "")) #expect(draft.readyAttachments.map(\.id) == ["at_fixture"]) draft.remove(id) #expect(draft.items.isEmpty); #expect(!draft.canSend(text: "")) } } actor AttachmentServer: EquipoTransport { nonisolated let origin = URL(string: "https://fixture.invalid")! var requests: [APIRequest] = [] var coordinatorImages: [Data] = [] private var bytes = Data() private var fail = false func failNext() { fail = true } func send(_ request: APIRequest) async throws -> APIResponse { requests.append(request) if request.path == "/attachments", request.method == "POST" { if fail { fail = false; throw EquipoAPIError.offline } bytes = request.body ?? Data() return APIResponse(status: 201, data: Data(Self.attachment.utf8)) } if request.path == "/messages" { let body = try JSONSerialization.jsonObject(with: request.body!) as! [String: Any] #expect(body["attachments"] as? [String] == ["at_fixture"]) #expect(body["idempotency_key"] as? String == request.idempotencyKey) if body["attachments"] as? [String] == ["at_fixture"] { coordinatorImages.append(bytes) } var sent: Sent = try Fixture.decode("thin/sent") sent.message.attachments = [try EquipoJSON.decoder.decode(MessageAttachment.self, from: Data(Self.attachment.utf8))] let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 return APIResponse(status: 201, data: try encoder.encode(sent)) } return APIResponse(status: 200, data: bytes) } func lines(_ request: APIRequest) async throws -> AsyncThrowingStream { AsyncThrowingStream { $0.finish() } } static let attachment = """ {"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"} """ } extension AttachmentTests { @MainActor @Test func invalidImageNeverReachesUpload() async throws { let server = AttachmentServer() let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) await draft.add(data: try Self.image(.gif, width: 12_001, height: 1), name: "wide.png") #expect(draft.items.first?.failure == EquipoStrings.text("api.attachment_pixels")) #expect(await server.requests.isEmpty) } @MainActor @Test func uploadingItemsCountTowardLimitAndRemovedItemsStayGone() async throws { let server = HeldAttachmentServer() let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) let image = try Self.image() let tasks = (0..<5).map { n in Task { await draft.add(data: image, name: "screen\(n).png") } } for _ in 0..<500 { if await server.pendingCount == 5 { break } try await Task.sleep(for: .milliseconds(10)) } #expect(await server.pendingCount == 5) #expect(!draft.canSend(text: "a note")) let sixth = Task { await draft.add(data: image, name: "sixth.png") } for _ in 0..<100 { if draft.notice != nil || draft.items.count > 5 { break } try await Task.sleep(for: .milliseconds(10)) } #expect(draft.items.count == 5) #expect(draft.notice == EquipoStrings.text("chat.attach.too_many")) for _ in 0..<500 { if await server.pendingCount == draft.items.count { break } try await Task.sleep(for: .milliseconds(10)) } let id = try #require(draft.items.first?.id) if case .uploading(let progress) = draft.items.first?.state { #expect(progress == 0.45) } else { Issue.record("Expected an upload in progress") } draft.remove(id) await server.complete() for task in tasks { await task.value } await sixth.value #expect(draft.items.count == 4) #expect(!draft.items.contains { $0.id == id }) #expect(draft.canSend(text: "")) } @Test func messageRejectsTooManyOrDuplicateIDs() { #expect(throws: (any Error).self) { try EquipoClient.message("", attachments: (0..<6).map { "at_\($0)" }) } #expect(throws: (any Error).self) { try EquipoClient.message("", attachments: ["at_a", "at_a"]) } } @MainActor @Test func composerSendsTheUploadedImageAndClearsDraft() async throws { let server = AttachmentServer() let session = EquipoSession(account: .new(origin: server.origin, label: "Fixture"), accounts: DeviceAccounts(store: MemorySecretStore()), transport: server) let data = try Self.image() await session.attachments.add(data: data, name: "screen.png") await session.sendFromComposer("").value #expect(session.attachments.items.isEmpty) #expect(await server.coordinatorImages == [data]) await session.attachments.add(data: data, name: "another.png") session.invalidate() #expect(session.attachments.items.isEmpty) } } actor HeldAttachmentServer: EquipoTransport { nonisolated let origin = URL(string: "https://held.example")! private var pending: [CheckedContinuation] = [] var pendingCount: Int { pending.count } func send(_ request: APIRequest) async throws -> APIResponse { request.uploadProgress?.report(0.45) return try await withCheckedThrowingContinuation { pending.append($0) } } func complete() { for continuation in pending { continuation.resume(returning: APIResponse(status: 201, data: Data(AttachmentServer.attachment.utf8))) } pending = [] } func lines(_ request: APIRequest) async throws -> AsyncThrowingStream { AsyncThrowingStream { $0.finish() } } } extension AttachmentTests { @Test func textDetectionMatchesServerInsteadOfRestrictingExtensions() throws { for name in ["README", "main.swift", "change.patch", "error.log"] { let file = try AttachmentFile.prepare(Data("let answer = 42\n".utf8), name: name) #expect(file.mediaType == "text/plain") } #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data([65, 1, 66]), name: "bad.txt") } #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data("not an image".utf8), name: "bad.png") } #expect(try AttachmentFile.prepare(Data("not json".utf8), name: "bad.json").mediaType == "text/plain") } }