Copy Equipo's files code into BaseKit, made to compile and nothing more
Task 12 of the native slice 2 part 1 plan (R5, P7), from Equipo origin/main 8bd40ed1; each file starts with its source path and SHA. - Attachments/AttachmentFile.swift (EquipoShareCore's, with the refusals' words), FileAttachment.swift, AttachmentDraft.swift, AttachmentViews.swift, PhoneAttachmentPicker.swift (without the recent screenshot rows), AttachmentPromises.swift (MacComposer.receive as a function of its own) and MacPasteboard.swift (MacComposer's pasteboard reading only; ComposerEditor isn't copied). - Base names, Base's palette and faces, BaseText with the web's words (chat.html data-w-*), and an AttachmentClient protocol (upload, delete, data(id:preview:), download(id:to:)) in place of EquipoClient; AskAttachment for MessageAttachment (now Identifiable); refusals by code through AttachmentRefusal. Behaviour is unchanged. - Tests: AttachmentTests, AttachmentReviewTests and MacAttachmentTests, copied in Swift Testing as Equipo has them, against a fake AttachmentClient. uploadingItemsCountTowardLimitAndRemovedItemsStayGone is disabled as "Base differs: Task 14" (two at a time, Remove deletes). Tests of Equipo-only subjects (its client's message builder, session, bearer reads, redirect delegate, ComposerEditor's drags) aren't copied; each file's header says where Base covers them. - Fixtures: Fixtures/attachments/large.webp, and Tests/BaseSnapshots/AttachmentFixtures.swift (Equipo's pictures drawn in code, a draft uploading and failed, sent files; no session or network). - Strings: the web's words for every refusal, Uploading, Remove, Attach files and Attached files; drafts for Luna: Try again, "This file isn't available any more.", and Equipo's Photos, Camera, Files and Paste. Gate: swift test -j 4 --filter 'BaseKitTests.Attachment|BaseKitTests.MacAttachment': 20 tests passed (1 disabled for Task 14). check-native.sh (the first of its two runs): strings ok, 164 XCTests and the Swift Testing suites passed, BaseMac builds, BasePhone builds for the iOS Simulator. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Task 12: Equipo's files code copied into BaseKit
14 files changed,
+1,415
−1
native/apple/Sources/BaseKit/API/Models.swift+1 −1native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift+122 −0native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift+139 −0native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift+45 −0native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift+189 −0native/apple/Sources/BaseKit/Attachments/FileAttachment.swift+69 −0native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift+31 −0native/apple/Sources/BaseKit/Attachments/PhoneAttachmentPicker.swift+89 −0native/apple/Sources/BaseKit/Resources/Localizable.xcstrings+204 −0native/apple/Tests/BaseKitTests/AttachmentReviewTests.swift+140 −0native/apple/Tests/BaseKitTests/AttachmentTests.swift+161 −0native/apple/Tests/BaseKitTests/Fixtures/attachments/large.webpbinarynative/apple/Tests/BaseKitTests/MacAttachmentTests.swift+148 −0native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift+77 −0
CI passed — run details
CI log
=== build === CGO_ENABLED=0 go build ./... === vet === go vet ./... === fmt-check === === staticcheck === go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... === govulncheck === go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./... No vulnerabilities found. === gitleaks === [90m9:21PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net [90m9:21PM[0m [32mINF[0m [1m1 commits scanned.[0m [90m9:21PM[0m [32mINF[0m [1mscanned ~3022034 bytes (3.02 MB) in 268ms[0m [90m9:21PM[0m [32mINF[0m [1mno leaks found[0m === budget === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size budget size: 22 directories within budget === script-test === scripts/prepare-apps_test.sh ok releases lookup failure stops before ship ok app owned elsewhere stops the script ok apps listing failure stops before create ok ambiguous release dir is refused ok explicit version resolves the ambiguity ok releases match is exact, not substring ok shipped version is only promoted, existing app not created ok fresh account creates, ships, promotes to edge, enables ok failing promote stops the script ok ship is retried while uploads are rate limited all passed hack/fonts_test.sh fonts_test: ok === test === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./... receipt: test step 9.145s against a 60s target (the gate's other steps are not in this figure) receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed receipt: slow package 8.401s amadan.net/oficina/base/internal/webtest receipt: slow package 1.035s amadan.net/oficina/base/internal/issuer receipt: slow package 622ms amadan.net/oficina/base/internal/equipo receipt: slow package 584ms amadan.net/oficina/base/internal/operations receipt: slow package 180ms amadan.net/oficina/base/internal/consumer receipt: slow test 1.51s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce receipt: slow test 800ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp receipt: slow test 610ms amadan.net/oficina/base/internal/webtest TestAskUploadStalledBodyFreesItsSlot receipt: slow test 510ms amadan.net/oficina/base/internal/operations TestOperationsRefusals === native === strings: copy review's strings.json is not here (git-ignored); its comparison skipped strings: 167 in the catalog, 164 used worktree-lib_test: ok
diff --git a/native/apple/Sources/BaseKit/API/Models.swift b/native/apple/Sources/BaseKit/API/Models.swift| index 2c81e86..ce64636 100644 |
| --- a/native/apple/Sources/BaseKit/API/Models.swift |
| +++ b/native/apple/Sources/BaseKit/API/Models.swift |
| @@ -182,7 +182,7 @@ public struct AskMessage: Decodable, Sendable, Equatable, Identifiable { |
| /// One of a message's files (docs/api/base-native-v1.md, Attachment). |
| /// Until the app draws files (slice 2), only its name shows. A kind the |
| /// app doesn't know is a file. |
| -public struct AskAttachment: Decodable, Sendable, Equatable { |
| +public struct AskAttachment: Decodable, Sendable, Equatable, Identifiable { |
| public var id: String |
| public var kind: String |
| public var name: String |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift| new file mode 100644 |
| index 0000000..a99d610 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift |
| @@ -0,0 +1,122 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoKit/Attachments/AttachmentDraft.swift |
| +// (R5). Task 12 makes it compile and nothing more: AttachmentClient for |
| +// EquipoClient, AskAttachment for MessageAttachment, BaseText for its words. |
| +// Base's rules (P8) come in Tasks 14 and 15. |
| +import Foundation |
| +import Observation |
| + |
| +@MainActor @Observable public final class AttachmentDraft { |
| + public struct Item: Identifiable, Sendable { |
| + public enum State: Sendable { case uploading(Double), ready(AskAttachment), failed(String) } |
| + public let id: UUID |
| + public let name: String |
| + public var state: State |
| + public var file: AttachmentFile? |
| + var generation = UUID() |
| + var source: Source |
| + public var failure: String? { if case .failed(let words) = state { return words }; return nil } |
| + } |
| + enum Source: Sendable { case data(Data), file(URL), load(@Sendable () async throws -> Data) } |
| + public private(set) var items: [Item] = [] |
| + public private(set) var notice: String? |
| + @ObservationIgnored private var uploads: [UUID: (generation: UUID, task: Task<Void, Never>)] = [:] |
| + @ObservationIgnored private var stagedDirectories: [UUID: URL] = [:] |
| + deinit { for directory in stagedDirectories.values { try? FileManager.default.removeItem(at: directory) } } |
| + @ObservationIgnored var fileAccess: any AttachmentFileAccess = SystemAttachmentFileAccess() |
| + var client: any AttachmentClient |
| + public init(client: any AttachmentClient) { self.client = client } |
| + |
| + public var readyAttachments: [AskAttachment] { items.compactMap { if case .ready(let value) = $0.state { return value }; return nil } } |
| + public func canSend(text: String) -> Bool { |
| + items.allSatisfy { if case .ready = $0.state { return true }; return false } && (!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !items.isEmpty) |
| + } |
| + public func add(data: Data, name: String) async { await add(.data(data), name: name) } |
| + public func add(name: String, load: @escaping @Sendable () async throws -> Data) async { await add(.load(load), name: name) } |
| + public func refuseFile() { notice = AttachmentFailure.type.words } |
| + public func add(url: URL) async { |
| + do { try AttachmentFile.checkRegularFile(url, access: fileAccess) } |
| + catch { refuseFile(); return } |
| + await add(.file(url), name: url.lastPathComponent) |
| + } |
| + /// Takes ownership of this private staging directory, including on refusal. |
| + public func add(staged file: FileAttachment, directory: URL) async { |
| + await add(.file(file.url), name: file.name, ownedDirectory: directory) |
| + } |
| + private func add(_ source: Source, name: String, ownedDirectory: URL? = nil) async { |
| + guard items.count < AttachmentLimits.maxCount else { |
| + if let ownedDirectory { try? FileManager.default.removeItem(at: ownedDirectory) } |
| + notice = BaseText.text("native.attach.too_many"); return |
| + } |
| + notice = nil |
| + let id = UUID() |
| + stagedDirectories[id] = ownedDirectory |
| + items.append(Item(id: id, name: name, state: .uploading(0), source: source)) |
| + await upload(id) |
| + } |
| + public func remove(_ id: UUID) { uploads.removeValue(forKey: id)?.task.cancel(); items.removeAll { $0.id == id }; cleanStaged(id); notice = nil } |
| + public func clear() { for upload in uploads.values { upload.task.cancel() }; uploads = [:]; items = []; for id in Array(stagedDirectories.keys) { cleanStaged(id) }; notice = nil } |
| + private func cleanStaged(_ id: UUID) { if let directory = stagedDirectories.removeValue(forKey: id) { try? FileManager.default.removeItem(at: directory) } } |
| + public func retry(_ id: UUID) async { |
| + guard let i = items.firstIndex(where: { $0.id == id }), items[i].failure != nil else { return } |
| + items[i].generation = UUID(); items[i].state = .uploading(0) |
| + await upload(id) |
| + } |
| + private func upload(_ id: UUID) async { |
| + guard let generation = items.first(where: { $0.id == id })?.generation else { return } |
| + let task = Task { await performUpload(id) } |
| + uploads[id] = (generation, task) |
| + await withTaskCancellationHandler { await task.value } onCancel: { task.cancel() } |
| + if uploads[id]?.generation == generation { uploads[id] = nil } |
| + } |
| + private func performUpload(_ id: UUID) async { |
| + guard let item = items.first(where: { $0.id == id }) else { return } |
| + do { |
| + let file = try await Task.detached { |
| + let bytes: Data |
| + switch item.source { case .data(let data): bytes = data; case .file(let url): bytes = try AttachmentFile.read(url); case .load(let load): bytes = try await load() } |
| + return try AttachmentFile.prepare(bytes, name: item.name) |
| + }.value |
| + try Task.checkCancellation() |
| + guard let i = index(id, item.generation) else { return } |
| + items[i].file = file |
| + let attachment = try await client.upload(file) { [weak self] fraction in |
| + Task { @MainActor [weak self] in |
| + guard let self, let i = self.index(id, item.generation), case .uploading = self.items[i].state else { return } |
| + self.items[i].state = .uploading(fraction) |
| + } |
| + } |
| + guard let i = index(id, item.generation) else { return } |
| + items[i].state = .ready(attachment) |
| + } catch { |
| + guard let i = index(id, item.generation) else { return } |
| + let words: String |
| + if let failure = error as? AttachmentFailure { words = failure.words } |
| + else if let code = (error as? AttachmentRefusal)?.code, let key = AttachmentRefusal.keys[code] { |
| + words = BaseText.text(key) |
| + } |
| + else { words = BaseText.text("native.attach.failed") } |
| + items[i].state = .failed(words) |
| + } |
| + } |
| + private func index(_ id: UUID, _ generation: UUID) -> Int? { items.firstIndex { $0.id == id && $0.generation == generation } } |
| +} |
| + |
| +/// What the draft needs of Base (Task 13's BaseClient): Equipo's client's |
| +/// four calls, over Base's relay. |
| +public protocol AttachmentClient: Sendable { |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment |
| + func delete(_ id: String) async throws |
| + func data(id: String, preview: Bool) async throws -> Data |
| + func download(id: String, to destination: URL) async throws |
| +} |
| + |
| +/// An upload Base or Equipo refused with a code (`attachment_type`, …): |
| +/// the draft shows the web's words for it. |
| +public struct AttachmentRefusal: Error, Equatable, Sendable { |
| + public let code: String |
| + public init(code: String) { self.code = code } |
| + /// The codes with words of their own, and their catalog keys. |
| + static let keys = ["attachment_too_large": "native.attach.too_large", "attachment_pixels": "native.attach.pixels", |
| + "attachment_type": "native.attach.type", "attachment_heic": "native.attach.heic", |
| + "attachment_limit": "native.attach.limit"] |
| +} |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift| new file mode 100644 |
| index 0000000..bc6ab29 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift |
| @@ -0,0 +1,139 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/share/Sources/EquipoShareCore/AttachmentFile.swift, |
| +// with the refusals' words from native/apple/Sources/EquipoKit/Attachments/AttachmentFile.swift (R5). |
| +import Foundation |
| +import ImageIO |
| +import UniformTypeIdentifiers |
| + |
| +/// POST /attachments' v1 contract (internal/attach/attach.go). /capabilities |
| +/// publishes authentication/version support, not configurable upload limits. |
| +public enum AttachmentLimits { |
| + public static let maxBytes = 10 << 20 |
| + // Bound local file reads before thumbnailing, independently of the upload cap. |
| + public static let maxInputBytes = 128 << 20 |
| + public static let imageLongEdge = 2560 |
| + public static let maxCount = 5 |
| + public static let maxSide = 12_000 |
| + public static let maxPixels = 40_000_000 |
| + public static func checkDimensions(width: Int, height: Int) throws { |
| + guard width > 0, height > 0 else { throw AttachmentFailure.type } |
| + guard width <= maxSide, height <= maxSide, width * height <= maxPixels else { throw AttachmentFailure.pixels } |
| + } |
| +} |
| + |
| +public enum AttachmentFailure: Error, Equatable, Sendable { |
| + case tooLarge, pixels, type |
| + |
| +} |
| + |
| +public protocol AttachmentFileAccess: Sendable { |
| + func start(_ url: URL) -> Bool |
| + func stop(_ url: URL) |
| + func isRegularFile(_ url: URL) throws -> Bool |
| +} |
| + |
| +public struct SystemAttachmentFileAccess: AttachmentFileAccess { |
| + public init() {} |
| + public func start(_ url: URL) -> Bool { url.startAccessingSecurityScopedResource() } |
| + public func stop(_ url: URL) { url.stopAccessingSecurityScopedResource() } |
| + public func isRegularFile(_ url: URL) throws -> Bool { try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true } |
| +} |
| + |
| +public struct AttachmentFile: Sendable { |
| + public let data: Data |
| + public let name: String |
| + public let mediaType: String |
| + public let width: Int |
| + public let height: Int |
| + |
| + public static func prepare(_ data: Data, name: String) throws -> Self { |
| + try prepare(data, name: name, maximumBytes: AttachmentLimits.maxBytes) |
| + } |
| + |
| + static func prepare(_ data: Data, name: String, maximumBytes: Int) throws -> Self { |
| + guard !data.isEmpty else { throw AttachmentFailure.type } |
| + let name = URL(fileURLWithPath: name).lastPathComponent |
| + if let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary), |
| + let image = try prepareImage(source, name: name, maximumBytes: maximumBytes, original: { data }) { return image } |
| + guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| + if data.starts(with: Data("%PDF-".utf8)) { return Self(data: data, name: name, mediaType: "application/pdf", width: 0, height: 0) } |
| + let suffix = (name as NSString).pathExtension.lowercased() |
| + guard !["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "hif", "pdf"].contains(suffix), |
| + let text = String(data: data, encoding: .utf8), |
| + text.unicodeScalars.allSatisfy({ $0.value >= 32 && $0.value != 127 || [9, 10, 12, 13].contains($0.value) }) |
| + else { throw AttachmentFailure.type } |
| + // The server accepts UTF-8 source files and extensionless files too. |
| + var media = ["md": "text/markdown", "markdown": "text/markdown", "csv": "text/csv"][suffix] ?? "text/plain" |
| + if suffix == "json", (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)) != nil { media = "application/json" } |
| + return Self(data: data, name: name, mediaType: media, width: 0, height: 0) |
| + } |
| + |
| + static func prepareImage(_ source: CGImageSource, name: String, maximumBytes: Int, original: () throws -> Data) throws -> Self? { |
| + if let typeID = CGImageSourceGetType(source) as String?, let type = UTType(typeID), type.conforms(to: .image) { |
| + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] |
| + let width = (properties?[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue ?? 0 |
| + let height = (properties?[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue ?? 0 |
| + guard width > 0, height > 0 else { throw AttachmentFailure.type } |
| + if type.conforms(to: .heic) || type.conforms(to: .heif) || type == .tiff || (type != .gif && max(width, height) > AttachmentLimits.imageLongEdge) { |
| + // TIFF is the Mac clipboard's native image representation. |
| + // Apply orientation and omit source metadata, including location. |
| + let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: AttachmentLimits.imageLongEdge, kCGImageSourceShouldCacheImmediately: true] |
| + guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { throw AttachmentFailure.type } |
| + // The web canvas flattens transparency on white before JPEG encoding. |
| + let flattened: CGImage |
| + if (properties?[kCGImagePropertyHasAlpha] as? Bool) == false || [.none, .noneSkipFirst, .noneSkipLast].contains(image.alphaInfo) { |
| + // Opaque images need no backing canvas. Avoid retaining a |
| + // second 2560-pixel bitmap in the share extension. |
| + flattened = image |
| + } else { |
| + guard let canvas = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw AttachmentFailure.type } |
| + canvas.setFillColor(CGColor(gray: 1, alpha: 1)); canvas.fill(CGRect(x: 0, y: 0, width: image.width, height: image.height)) |
| + canvas.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) |
| + guard let opaque = canvas.makeImage() else { throw AttachmentFailure.type } |
| + flattened = opaque |
| + } |
| + let output = NSMutableData() |
| + guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { throw AttachmentFailure.type } |
| + CGImageDestinationAddImage(destination, flattened, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary) |
| + guard CGImageDestinationFinalize(destination) else { throw AttachmentFailure.type } |
| + guard output.length <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| + return Self(data: output as Data, name: (name as NSString).deletingPathExtension + ".jpg", mediaType: "image/jpeg", width: image.width, height: image.height) |
| + } |
| + try AttachmentLimits.checkDimensions(width: width, height: height) |
| + let data = try original() |
| + guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| + let types: [UTType: String] = [.png: "image/png", .jpeg: "image/jpeg", .gif: "image/gif", .webP: "image/webp"] |
| + guard let media = types[type] else { throw AttachmentFailure.type } |
| + let suffix = type.preferredFilenameExtension ?? "png" |
| + return Self(data: data, name: (name as NSString).deletingPathExtension + "." + suffix, mediaType: media, width: width, height: height) |
| + } |
| + return nil |
| + } |
| + |
| + public static func checkRegularFile(_ url: URL, access: any AttachmentFileAccess) throws { |
| + guard url.isFileURL else { throw AttachmentFailure.type } |
| + let started = access.start(url) |
| + defer { if started { access.stop(url) } } |
| + guard try access.isRegularFile(url) else { throw AttachmentFailure.type } |
| + } |
| + |
| + public static func read(_ url: URL) throws -> Data { |
| + let access = url.startAccessingSecurityScopedResource() |
| + defer { if access { url.stopAccessingSecurityScopedResource() } } |
| + let handle = try FileHandle(forReadingFrom: url) |
| + defer { try? handle.close() } |
| + let data = try handle.read(upToCount: AttachmentLimits.maxInputBytes + 1) ?? Data() |
| + guard data.count <= AttachmentLimits.maxInputBytes else { throw AttachmentFailure.tooLarge } |
| + return data |
| + } |
| +} |
| + |
| +extension AttachmentFailure { |
| + /// The web's words (chat.html data-w-*). |
| + public var words: String { |
| + switch self { |
| + case .tooLarge: BaseText.text("native.attach.too_large") |
| + case .pixels: BaseText.text("native.attach.pixels") |
| + case .type: BaseText.text("native.attach.type") |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift| new file mode 100644 |
| index 0000000..815b867 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift |
| @@ -0,0 +1,45 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoMac/AttachmentPromises.swift (R5). |
| +#if os(macOS) |
| +import AppKit |
| + |
| +/// Each accepted drop owns a private directory for the lifetime of its readers. |
| +/// Read inside NSFilePromiseReceiver's coordinated callback, then hand bytes to |
| +/// the draft so retry does not depend on the temporary file remaining on disk. |
| +private final class PromiseDirectory: @unchecked Sendable { |
| + let url: URL |
| + init() throws { |
| + url = FileManager.default.temporaryDirectory.appendingPathComponent("base-drop-" + UUID().uuidString, isDirectory: true) |
| + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) |
| + } |
| + deinit { try? FileManager.default.removeItem(at: url) } |
| +} |
| + |
| +/// Equipo's MacComposer.receive, as a function of its own: Base has no |
| +/// composer view of that kind (plan Task 17). |
| +enum AttachmentPromises { |
| + @MainActor static func receive(_ promises: [NSFilePromiseReceiver], into draft: AttachmentDraft) { |
| + do { |
| + let directory = try PromiseDirectory() |
| + let queue = OperationQueue(); queue.maxConcurrentOperationCount = 1 |
| + for promise in promises { |
| + promise.receivePromisedFiles(atDestination: directory.url, options: [:], operationQueue: queue) { [directory] url, error in |
| + let result = Result<Data, Error> { |
| + if let error { throw error } |
| + guard url.isFileURL, |
| + url.standardizedFileURL.deletingLastPathComponent() == directory.url.standardizedFileURL, |
| + (try url.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else { throw AttachmentFailure.type } |
| + return try AttachmentFile.read(url) |
| + } |
| + if url.standardizedFileURL.deletingLastPathComponent() == directory.url.standardizedFileURL { try? FileManager.default.removeItem(at: url) } |
| + Task { @MainActor in |
| + switch result { |
| + case .success(let data): await draft.add(data: data, name: url.lastPathComponent) |
| + case .failure: draft.refuseFile() |
| + } |
| + } |
| + } |
| + } |
| + } catch { draft.refuseFile() } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift| new file mode 100644 |
| index 0000000..3cd6f7f |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift |
| @@ -0,0 +1,189 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoKit/Attachments/AttachmentViews.swift |
| +// (R5). Task 12 makes it compile: Base's palette, faces and words, and |
| +// AttachmentClient. Tasks 17 to 19 draw Base's chips and bubble; Task 19 |
| +// deletes the full-size preview, which Quick Look replaces. |
| +import SwiftUI |
| +import ImageIO |
| +import PDFKit |
| + |
| +/// Shared composer attachment list. State belongs to the session's draft. |
| +public struct AttachmentDraftStrip: View { |
| + @Environment(\.colorScheme) private var scheme |
| + private var p: Palette { Palette(scheme) } |
| + let draft: AttachmentDraft |
| + public init(draft: AttachmentDraft) { self.draft = draft } |
| + public var body: some View { |
| + VStack(alignment: .leading, spacing: 6) { |
| + if !draft.items.isEmpty { |
| + ScrollView(.horizontal) { |
| + HStack(alignment: .top, spacing: 12) { |
| + ForEach(draft.items) { item in |
| + VStack(alignment: .leading, spacing: 4) { |
| + ZStack(alignment: .topTrailing) { |
| + AttachmentPicture(data: item.file?.data, name: item.name) |
| + .frame(width: 140, height: 86).background(p[.chip]) |
| + .clipShape(.rect(cornerRadius: 8)) |
| + HStack(spacing: 0) { |
| + if item.failure != nil { |
| + Button { Task { await draft.retry(item.id) } } label: { |
| + Image(systemName: "arrow.clockwise") |
| + .font(.system(size: 14, weight: .semibold)) |
| + .foregroundStyle(p[.focus]) |
| + .padding(7).background(p[.glassBase], in: Circle()) |
| + .frame(width: 44, height: 44).contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain) |
| + .accessibilityLabel(BaseText.text("native.attach.retry")) |
| + } |
| + Button { draft.remove(item.id) } label: { |
| + Image(systemName: "xmark.circle.fill").symbolRenderingMode(.palette) |
| + .foregroundStyle(p[.frost], p[.glassBase]).frame(width: 44, height: 44).contentShape(Rectangle()) |
| + } |
| + .buttonStyle(.plain) |
| + .accessibilityLabel(BaseText.format("native.attach.remove", ["name": item.name])) |
| + } |
| + } |
| + Text(item.name).font(BaseFont.body(12, relativeTo: .caption)).lineLimit(1).truncationMode(.middle) |
| + switch item.state { |
| + case .uploading(let progress): |
| + ProgressView(value: progress).accessibilityLabel(BaseText.text("native.attach.uploading")) |
| + Text(BaseText.text("native.attach.uploading")).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.haze]) |
| + case .failed(let words): |
| + Text(words).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.ember]).fixedSize(horizontal: false, vertical: true) |
| + case .ready: EmptyView() |
| + } |
| + }.frame(width: 140, alignment: .leading) |
| + } |
| + }.padding(.vertical, 4) |
| + } |
| + .accessibilityLabel(BaseText.text("native.attach.list")) |
| + } |
| + if let notice = draft.notice { Text(notice).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.ember]) } |
| + } |
| + } |
| +} |
| + |
| +struct AttachmentPicture: View { |
| + @Environment(\.colorScheme) private var scheme |
| + private var p: Palette { Palette(scheme) } |
| + let data: Data? |
| + let name: String |
| + @State private var image: CGImage? |
| + var body: some View { |
| + Group { |
| + if let image { |
| + Image(decorative: image, scale: 1).resizable().scaledToFit().accessibilityLabel(name) |
| + } else { |
| + Image(systemName: "doc").font(.title2).foregroundStyle(p[.haze]).accessibilityLabel(name) |
| + } |
| + }.task(id: data) { |
| + let bytes = data |
| + let decoded = await Task.detached { bytes.flatMap { Self.thumbnail($0, side: 512) } }.value |
| + guard !Task.isCancelled else { return } |
| + image = decoded |
| + } |
| + } |
| + nonisolated static func thumbnail(_ data: Data, side: Int) -> CGImage? { |
| + guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil } |
| + return CGImageSourceCreateThumbnailAtIndex(source, 0, [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: side] as CFDictionary) |
| + } |
| +} |
| + |
| +/// Sent thumbnails use authenticated API reads, never bare remote-image URLs. |
| +public struct MessageAttachments: View { |
| + let attachments: [AskAttachment] |
| + let client: any AttachmentClient |
| + @State private var selected: AskAttachment? |
| + public init(_ attachments: [AskAttachment], client: any AttachmentClient) { |
| + self.attachments = attachments; self.client = client |
| + } |
| + public var body: some View { |
| + LazyVGrid(columns: [GridItem(.adaptive(minimum: 120, maximum: 180), alignment: .leading)], alignment: .leading, spacing: 8) { |
| + ForEach(attachments) { file in |
| + Button { selected = file } label: { SentAttachmentTile(file: file, client: client) } |
| + .buttonStyle(.plain).accessibilityLabel(file.name) |
| + } |
| + } |
| + #if os(iOS) |
| + .fullScreenCover(item: $selected) { AttachmentPreview(file: $0, client: client) } |
| + #else |
| + .sheet(item: $selected) { AttachmentPreview(file: $0, client: client).frame(minWidth: 600, minHeight: 500) } |
| + #endif |
| + } |
| +} |
| + |
| +private struct SentAttachmentTile: View { |
| + @Environment(\.colorScheme) private var scheme |
| + private var p: Palette { Palette(scheme) } |
| + let file: AskAttachment |
| + let client: any AttachmentClient |
| + @State private var data: Data? |
| + var body: some View { |
| + VStack(alignment: .leading, spacing: 4) { |
| + AttachmentPicture(data: data, name: file.name).frame(height: 100).frame(maxWidth: .infinity) |
| + .background(p[.chip]).clipShape(.rect(cornerRadius: 8)) |
| + Text(file.name).font(BaseFont.body(12, relativeTo: .caption)).lineLimit(1).truncationMode(.middle).frame(maxWidth: .infinity, alignment: .leading) |
| + } |
| + .task(id: file.id) { |
| + if file.kind == "image" { data = try? await client.data(id: file.id, preview: true) } |
| + } |
| + } |
| +} |
| + |
| +private struct AttachmentPreview: View { |
| + @Environment(\.colorScheme) private var scheme |
| + private var p: Palette { Palette(scheme) } |
| + let file: AskAttachment |
| + let client: any AttachmentClient |
| + @Environment(\.dismiss) private var dismiss |
| + @State private var data: Data? |
| + @State private var failure = false |
| + @State private var image: CGImage? |
| + var body: some View { |
| + NavigationStack { |
| + Group { |
| + if let data { |
| + if let image { |
| + ScrollView([.horizontal, .vertical]) { |
| + Image(decorative: image, scale: 1).resizable().scaledToFit() |
| + .containerRelativeFrame(.horizontal).accessibilityLabel(file.name) |
| + } |
| + } else if file.mediaType == "application/pdf" { AttachmentPDF(data: data) } |
| + else { ScrollView { Text(String(decoding: data, as: UTF8.self)).font(.system(.body, design: .monospaced)).textSelection(.enabled).padding() } } |
| + } else if failure { |
| + VStack { |
| + Text(BaseText.text("native.attach.gone")) |
| + Button(BaseText.text("native.attach.retry")) { Task { await load() } } |
| + } |
| + } else { ProgressView().accessibilityLabel(file.name) } |
| + } |
| + .frame(maxWidth: .infinity, maxHeight: .infinity) |
| + .background(p[.menuBase]).navigationTitle(file.name) |
| + .toolbar { ToolbarItem(placement: .confirmationAction) { Button(BaseText.text("ask.close")) { dismiss() } } } |
| + }.task { await load() } |
| + } |
| + private func load() async { |
| + failure = false |
| + do { |
| + let bytes = try await client.data(id: file.id, preview: false) |
| + let decoded = await Task.detached { AttachmentPicture.thumbnail(bytes, side: 4096) }.value |
| + guard !Task.isCancelled else { return } |
| + image = decoded; data = bytes |
| + } |
| + catch { failure = true } |
| + } |
| +} |
| + |
| +#if os(iOS) |
| +private struct AttachmentPDF: UIViewRepresentable { |
| + let data: Data |
| + func makeUIView(context: Context) -> PDFView { let view = PDFView(); view.autoScales = true; view.document = PDFDocument(data: data); return view } |
| + func updateUIView(_ view: PDFView, context: Context) {} |
| +} |
| +#else |
| +private struct AttachmentPDF: NSViewRepresentable { |
| + let data: Data |
| + func makeNSView(context: Context) -> PDFView { let view = PDFView(); view.autoScales = true; view.document = PDFDocument(data: data); return view } |
| + func updateNSView(_ view: PDFView, context: Context) {} |
| +} |
| +#endif |
diff --git a/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift b/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift| new file mode 100644 |
| index 0000000..ea19900 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift |
| @@ -0,0 +1,69 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/share/Sources/EquipoShareCore/FileAttachment.swift (R5). |
| +import Foundation |
| +import ImageIO |
| + |
| +public struct FileAttachment: Sendable, Identifiable { |
| + public let id: UUID |
| + public let url: URL |
| + public let name: String |
| + public let mediaType: String |
| + public let width: Int |
| + public let height: Int |
| +} |
| +extension AttachmentFile { |
| + /// Copy while the provider's URL and security scope are valid. Bounded chunks, |
| + /// no mmap or whole-original allocation; caller runs serially off the main actor. |
| + public static func stage(_ source: URL, directory: URL, maximumBytes: Int = AttachmentLimits.maxInputBytes, |
| + access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> URL { |
| + guard source.isFileURL else { throw AttachmentFailure.type } |
| + let started = access.start(source); defer { if started { access.stop(source) } } |
| + guard try access.isRegularFile(source) else { throw AttachmentFailure.type } |
| + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) |
| + let target = directory.appendingPathComponent(UUID().uuidString).appendingPathExtension(source.pathExtension) |
| + var attributes: [FileAttributeKey: Any] = [.posixPermissions: 0o600] |
| + #if os(iOS) |
| + attributes[.protectionKey] = FileProtectionType.complete |
| + #endif |
| + guard FileManager.default.createFile(atPath: target.path, contents: nil, attributes: attributes) else { throw AttachmentFailure.type } |
| + var completed = false |
| + defer { if !completed { try? FileManager.default.removeItem(at: target) } } |
| + let input = try FileHandle(forReadingFrom: source); defer { try? input.close() } |
| + let output = try FileHandle(forWritingTo: target); defer { try? output.close() } |
| + var count = 0 |
| + while let chunk = try input.read(upToCount: 64 * 1024), !chunk.isEmpty { |
| + try Task.checkCancellation() |
| + count += chunk.count |
| + guard count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| + try output.write(contentsOf: chunk) |
| + } |
| + guard count > 0 else { throw AttachmentFailure.type } |
| + completed = true |
| + return target |
| + } |
| + public static func prepareFile(_ source: URL, directory: URL, name: String? = nil, |
| + access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> FileAttachment { |
| + let staged = try stage(source, directory: directory, access: access) |
| + defer { try? FileManager.default.removeItem(at: staged) } |
| + func boundedData() throws -> Data { |
| + let handle = try FileHandle(forReadingFrom: staged); defer { try? handle.close() } |
| + let data = try handle.read(upToCount: AttachmentLimits.maxBytes + 1) ?? Data() |
| + guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| + return data |
| + } |
| + let filename = URL(fileURLWithPath: name ?? source.lastPathComponent).lastPathComponent |
| + let file: AttachmentFile |
| + if let image = CGImageSourceCreateWithURL(staged as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), |
| + let prepared = try prepareImage(image, name: filename, maximumBytes: AttachmentLimits.maxBytes, original: boundedData) { |
| + file = prepared |
| + } else { file = try prepare(boundedData(), name: filename) } |
| + try Task.checkCancellation() |
| + guard file.data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| + let id = UUID(), destination = directory.appendingPathComponent(UUID().uuidString) |
| + #if os(iOS) |
| + try file.data.write(to: destination, options: [.atomic, .completeFileProtection]) |
| + #else |
| + try file.data.write(to: destination, options: .atomic) |
| + #endif |
| + return FileAttachment(id: id, url: destination, name: file.name, mediaType: file.mediaType, width: file.width, height: file.height) |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift b/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift| new file mode 100644 |
| index 0000000..c01967a |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift |
| @@ -0,0 +1,31 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoMac/MacComposer.swift, |
| +// the pasteboard reading only (ComposerEditor.accepts and |
| +// MacComposer.acceptAttachments) (R5). ComposerEditor, the NSTextView |
| +// subclass, isn't copied: Base's composer is a SwiftUI field (plan Task 17). |
| +#if os(macOS) |
| +import AppKit |
| + |
| +enum MacPasteboard { |
| + static func accepts(_ board: NSPasteboard) -> Bool { |
| + board.availableType(from: [.fileURL, .png, .tiff] + NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }) != nil |
| + } |
| + |
| + @MainActor @discardableResult static func acceptAttachments(_ pasteboard: NSPasteboard, into draft: AttachmentDraft) -> Bool { |
| + if let promises = pasteboard.readObjects(forClasses: [NSFilePromiseReceiver.self]) as? [NSFilePromiseReceiver], !promises.isEmpty { |
| + AttachmentPromises.receive(promises, into: draft) |
| + return true |
| + } |
| + if let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty { |
| + for url in urls { Task { await draft.add(url: url) } } |
| + return true |
| + } |
| + for type in [NSPasteboard.PasteboardType.png, .tiff] { |
| + if let data = pasteboard.data(forType: type) { |
| + Task { await draft.add(data: data, name: type == .png ? "image.png" : "image.tiff") } |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/BaseKit/Attachments/PhoneAttachmentPicker.swift b/native/apple/Sources/BaseKit/Attachments/PhoneAttachmentPicker.swift| new file mode 100644 |
| index 0000000..c9fe9cd |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/PhoneAttachmentPicker.swift |
| @@ -0,0 +1,89 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift |
| +// (R5), without the recent-screenshot rows (RecentScreenshot needs Photos |
| +// permission, spec 7.6). Task 18 brings Base's sources and names. |
| +#if os(iOS) |
| +import SwiftUI |
| +import PhotosUI |
| +import UniformTypeIdentifiers |
| + |
| +struct PhoneAttachmentPicker: View { |
| + let draft: AttachmentDraft |
| + @Environment(\.colorScheme) private var scheme |
| + @State private var photos: [PhotosPickerItem] = [] |
| + @State private var choosingPhotos = false |
| + @State private var files = false |
| + @State private var camera = false |
| + var body: some View { |
| + sources |
| + .buttonStyle(.plain) |
| + .accessibilityLabel(BaseText.text("native.attach.add")) |
| + .photosPicker(isPresented: $choosingPhotos, selection: $photos, maxSelectionCount: max(1, AttachmentLimits.maxCount - draft.items.count), matching: .images) |
| + .fileImporter(isPresented: $files, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in |
| + if case .success(let urls) = result { for url in urls { Task { await draft.add(url: url) } } } |
| + } |
| + .fullScreenCover(isPresented: $camera) { |
| + CameraAttachment { data in |
| + camera = false |
| + if let data { Task { await draft.add(data: data, name: "photo.jpg") } } |
| + }.ignoresSafeArea() |
| + } |
| + .onChange(of: photos) { _, selected in |
| + photos = [] |
| + for photo in selected { |
| + Task { |
| + await draft.add(name: "photo") { |
| + guard let data = try await photo.loadTransferable(type: Data.self) else { throw AttachmentFailure.type } |
| + return data |
| + } |
| + } |
| + } |
| + } |
| + } |
| + private var plus: some View { |
| + |
| + Image(systemName: "plus").font(.system(size: 16, weight: .semibold)) |
| + .foregroundStyle(Palette(scheme)[.haze]) |
| + .frame(width: 34, height: 34).background(Palette(scheme)[.chip], in: Circle()) |
| + .frame(width: 44, height: 44).contentShape(Circle()) |
| + } |
| + private var sources: some View { |
| + Menu { |
| + // Equipo's approved labels (Luna, 2026-11-25), drafts for Base's review. |
| + Button { choosingPhotos = true } label: { |
| + Label(BaseText.text("native.attach.photos"), systemImage: "photo") |
| + } |
| + if UIImagePickerController.isSourceTypeAvailable(.camera) { |
| + Button { camera = true } label: { Label(BaseText.text("native.attach.camera"), systemImage: "camera") } |
| + } |
| + Button { files = true } label: { Label(BaseText.text("native.attach.files"), systemImage: "folder") } |
| + Button { paste() } label: { Label(BaseText.text("native.attach.paste"), systemImage: "document.on.clipboard") } |
| + } label: { plus } |
| + } |
| + private func paste() { |
| + let pasteboard = UIPasteboard.general |
| + for type in [UTType.png, .jpeg, .heic, .heif, .gif, .webP, .tiff] { |
| + if let data = pasteboard.data(forPasteboardType: type.identifier) { |
| + Task { await draft.add(data: data, name: "image." + (type.preferredFilenameExtension ?? "png")) }; return |
| + } |
| + } |
| + if let urls = pasteboard.urls { for url in urls where url.isFileURL { Task { await draft.add(url: url) } } } |
| + } |
| +} |
| + |
| +private struct CameraAttachment: UIViewControllerRepresentable { |
| + let completed: (Data?) -> Void |
| + func makeCoordinator() -> Coordinator { Coordinator(completed: completed) } |
| + func makeUIViewController(context: Context) -> UIImagePickerController { |
| + let picker = UIImagePickerController(); picker.sourceType = .camera; picker.delegate = context.coordinator; return picker |
| + } |
| + func updateUIViewController(_ view: UIImagePickerController, context: Context) {} |
| + final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { |
| + let completed: (Data?) -> Void |
| + init(completed: @escaping (Data?) -> Void) { self.completed = completed } |
| + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { completed(nil) } |
| + func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { |
| + completed((info[.originalImage] as? UIImage)?.jpegData(compressionQuality: 0.9)) |
| + } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings| index 2c990cc..63bec22 100644 |
| --- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings |
| @@ -541,6 +541,210 @@ |
| } |
| } |
| }, |
| + "native.attach.add": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-attach). The paperclip's (Mac) and the + menu's (iPhone) label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attach files" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.camera": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: take a photo. Equipo's approved label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Camera" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.failed": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-failed). A file's chip when its upload failed for any other reason.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Couldn’t upload. Try again." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.files": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: choose from Files. Equipo's approved label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Files" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.gone": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). Opening a sent file Base no longer has (a 404).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "This file isn't available any more." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.heic": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-heic). A photo's chip when Equipo refuses HEIC (the app converts HEIC first, so rarely seen).", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "HEIC photos can’t be read yet. Share it as a JPEG and try again." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.limit": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-limit). A file's chip when 20 uploads already wait unsent.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Too many files are waiting to send. Send or remove some first." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.list": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-files). The chips' accessibility label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attached files" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.paste": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: attach what's on the clipboard. Equipo's approved label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Paste" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.photos": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: choose from Photos. Equipo's approved label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Photos" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.pixels": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-pixels). An image's chip when it has too many pixels.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "This image is too large. Use one no larger than 12,000 pixels on a side and 40 megapixels in all." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.remove": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-remove). A chip's remove button and VoiceOver action. {name} is the file's name.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Remove {name}" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.retry": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). A failed file's chip: its Retry button and VoiceOver action.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Try again" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.too_large": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-too-large). A file's chip when it is too large.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "This file is over the 10 MB limit." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.too_many": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-too-many). The line under the chips when a sixth file is added.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "You can attach up to 5 files to a message." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.type": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-type). A file's chip, or the line under the chips, when its type can't be attached.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attach images (PNG, JPEG, WebP or GIF) or text, Markdown, CSV, JSON or PDF files." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.uploading": { |
| + "comment": "Base on the web's approved copy (chat.html data-w-uploading). A file's chip while it uploads, and its ring's label.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Uploading…" |
| + } |
| + } |
| + } |
| + }, |
| "native.colophon": { |
| "comment": "Under the Help menu on the Mac: the list of open-source parts and fonts the app uses, with their licences. Same word as the other Oficina apps.", |
| "extractionState": "manual", |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentReviewTests.swift b/native/apple/Tests/BaseKitTests/AttachmentReviewTests.swift| new file mode 100644 |
| index 0000000..2f7caaa |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentReviewTests.swift |
| @@ -0,0 +1,140 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Tests/EquipoKitTests/AttachmentReviewTests.swift |
| +// (R5), against a fake AttachmentClient in place of Equipo's transport. |
| +// |
| +// Not copied, because their subject is Equipo's own: |
| +// - failedDraftCannotSendAndThreadsRejectAttachments and |
| +// lostProjectRetryKeepsAttachmentIDs: EquipoSession, its threads and |
| +// projects. Base's sending is AskModel's (Task 15). |
| +// - readsCarryBearerAndRefuseOversizedResponses: Equipo's client. Base's |
| +// bounded reads are BaseClient's (Task 13, ClientTests). |
| +// - uploadDelegateRefusesRedirects: Equipo's URLSession delegate. Base's |
| +// uploads go through the kit's NativeHTTP.upload, whose tests refuse a |
| +// redirect (testAnUploadFollowsNoRedirect). |
| +@testable import BaseKit |
| +import Foundation |
| +import ImageIO |
| +import Testing |
| +import UniformTypeIdentifiers |
| + |
| +@Suite struct AttachmentReviewTests { |
| + @Test func largeHEICAndWebPMatchWebSizing() throws { |
| + let heic = try AttachmentTests.image(.heic, width: 8064, height: 6048) |
| + let url = try #require(Bundle.module.url(forResource: "large", withExtension: "webp", subdirectory: "Fixtures/attachments")) |
| + for (bytes, name, height) in [(heic, "photo.heic", 1920), (try Data(contentsOf: url), "large.webp", 1280)] { |
| + let file = try AttachmentFile.prepare(bytes, name: name) |
| + #expect(file.mediaType == "image/jpeg") |
| + #expect(file.width == 2560 && file.height == height) |
| + #expect(file.data.count <= AttachmentLimits.maxBytes) |
| + } |
| + } |
| + |
| + @Test func conversionStripsMetadataAndAppliesOrientation() throws { |
| + let source = try #require(CGImageSourceCreateWithData(AttachmentTests.image() as CFData, nil)) |
| + let image = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil)) |
| + let bytes = NSMutableData() |
| + let dest = try #require(CGImageDestinationCreateWithData(bytes, UTType.heic.identifier as CFString, 1, nil)) |
| + let metadata: [CFString: Any] = [kCGImagePropertyOrientation: 6, |
| + kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 53.3, kCGImagePropertyGPSLatitudeRef: "N", kCGImagePropertyGPSLongitude: 6.2, kCGImagePropertyGPSLongitudeRef: "W"], |
| + kCGImagePropertyExifDictionary: [kCGImagePropertyExifUserComment: "private fixture metadata"]] |
| + CGImageDestinationAddImage(dest, image, metadata as CFDictionary) |
| + #expect(CGImageDestinationFinalize(dest)) |
| + let file = try AttachmentFile.prepare(bytes as Data, name: "private.heic") |
| + #expect(file.width == 8 && file.height == 12) |
| + let converted = try #require(CGImageSourceCreateWithData(file.data as CFData, nil)) |
| + let properties = try #require(CGImageSourceCopyPropertiesAtIndex(converted, 0, nil) as? [CFString: Any]) |
| + #expect(properties[kCGImagePropertyGPSDictionary] == nil) |
| + #expect((properties[kCGImagePropertyExifDictionary] as? [CFString: Any])?[kCGImagePropertyExifUserComment] == nil) |
| + } |
| + |
| + @Test func convertedBytesAreCheckedAgain() throws { |
| + let input = try AttachmentTests.image(.heic) |
| + #expect(throws: AttachmentFailure.tooLarge) { try AttachmentFile.prepare(input, name: "photo.heic", maximumBytes: 1) } |
| + } |
| + |
| + @Test func emptyAndBoundedFileReads() throws { |
| + #expect(throws: AttachmentFailure.type) { try AttachmentFile.prepare(Data(), name: "empty.txt") } |
| + let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| + defer { try? FileManager.default.removeItem(at: url) } |
| + FileManager.default.createFile(atPath: url.path, contents: nil) |
| + let handle = try FileHandle(forWritingTo: url) |
| + try handle.truncate(atOffset: 128 * 1024 * 1024 + 1); try handle.close() |
| + #expect(throws: AttachmentFailure.tooLarge) { try AttachmentFile.read(url) } |
| + } |
| +} |
| + |
| +/// Base's stand-in for Equipo's AttachmentReviewServer. |
| +actor AttachmentReviewServer: AttachmentClient { |
| + var uploads = 0 |
| + var callbacks: [@Sendable (Double) -> Void] = [] |
| + var code: String? |
| + var hold = false |
| + var pending: [CheckedContinuation<AskAttachment, Error>] = [] |
| + func configure(code: String? = nil, hold: Bool = false) { self.code = code; self.hold = hold } |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { |
| + uploads += 1 |
| + callbacks.append(progress) |
| + if let code { self.code = nil; throw AttachmentRefusal(code: code) } |
| + if hold { return try await withCheckedThrowingContinuation { pending.append($0) } } |
| + return AttachmentServer.attachment |
| + } |
| + func emit(_ index: Int, _ value: Double) { callbacks[index](value) } |
| + func finish() { for c in pending { c.resume(returning: AttachmentServer.attachment) }; pending = [] } |
| + func delete(_ id: String) async throws {} |
| + func data(id: String, preview: Bool) async throws -> Data { Data("{}".utf8) } |
| + func download(id: String, to destination: URL) async throws {} |
| +} |
| + |
| +extension AttachmentReviewTests { |
| + @MainActor @Test func retryIsSingleAndOldProgressCannotOverwriteNewOrReadyState() async throws { |
| + let server = AttachmentReviewServer(); await server.configure(code: "attachment_type") |
| + let draft = AttachmentDraft(client: server) |
| + await draft.add(data: try AttachmentTests.image(), name: "screen.png") |
| + let id = try #require(draft.items.first?.id) |
| + await server.configure(hold: true) |
| + let first = Task { await draft.retry(id) } |
| + for _ in 0..<100 { if await server.callbacks.count >= 2 { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + let second = Task { await draft.retry(id) } |
| + try await Task.sleep(for: .milliseconds(40)) |
| + #expect(await server.callbacks.count == 2) |
| + await server.emit(0, 0.99) |
| + try await Task.sleep(for: .milliseconds(30)) |
| + if case .uploading(let progress) = draft.items.first?.state { #expect(progress == 0) } else { Issue.record("Expected retry upload") } |
| + await server.finish(); await first.value; await second.value |
| + await server.emit(1, 0.2) |
| + try await Task.sleep(for: .milliseconds(30)) |
| + #expect(draft.readyAttachments.count == 1) |
| + } |
| + |
| + @MainActor @Test(arguments: ["attachment_too_large", "attachment_pixels", "attachment_type", "attachment_heic", "attachment_limit"]) |
| + func serverCodesUseReviewedWords(_ code: String) async throws { |
| + let server = AttachmentReviewServer(); await server.configure(code: code) |
| + let draft = AttachmentDraft(client: server) |
| + await draft.add(data: try AttachmentTests.image(), name: "screen.png") |
| + #expect(draft.items.first?.failure == BaseText.text(try #require(AttachmentRefusal.keys[code]))) |
| + } |
| + |
| + @MainActor @Test func removalCancelsTheActualUpload() async throws { |
| + let server = CancellableAttachmentServer() |
| + let draft = AttachmentDraft(client: server) |
| + let adding = Task { await draft.add(data: try AttachmentTests.image(), name: "screen.png") } |
| + for _ in 0..<100 { if await server.started { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + draft.remove(try #require(draft.items.first?.id)) |
| + for _ in 0..<100 { if await server.cancelled { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + #expect(await server.cancelled) |
| + adding.cancel() |
| + try await adding.value |
| + } |
| +} |
| + |
| +private actor CancellableAttachmentServer: AttachmentClient { |
| + var started = false |
| + var cancelled = false |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { |
| + started = true |
| + do { try await Task.sleep(for: .seconds(30)) } catch { cancelled = true; throw error } |
| + return AttachmentServer.attachment |
| + } |
| + func delete(_ id: String) async throws {} |
| + func data(id: String, preview: Bool) async throws -> Data { Data() } |
| + func download(id: String, to destination: URL) async throws {} |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentTests.swift b/native/apple/Tests/BaseKitTests/AttachmentTests.swift| new file mode 100644 |
| index 0000000..2eced0a |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentTests.swift |
| @@ -0,0 +1,161 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Tests/EquipoKitTests/AttachmentTests.swift |
| +// (R5), against a fake AttachmentClient in place of Equipo's transport. |
| +// |
| +// Not copied, because their subject is Equipo's own and Base's is tested |
| +// where it lives: |
| +// - uploadAndAttachmentOnlyMessageReachFakeCoordinator: Equipo's client and |
| +// wire. Base's upload is BaseClient's (Task 13, ClientTests), over the |
| +// kit's NativeHTTP.upload (rastrillo/native NativeHTTPUploadTests). |
| +// - messageRejectsTooManyOrDuplicateIDs: Equipo's message builder. Base's |
| +// send with files is Task 13's. |
| +// - composerSendsTheUploadedImageAndClearsDraft: EquipoSession. Base's is |
| +// AskModel's (Task 15, AskModelTests). |
| +@testable import BaseKit |
| +import Foundation |
| +import ImageIO |
| +import Testing |
| +import UniformTypeIdentifiers |
| + |
| +@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) |
| + } |
| + |
| + @MainActor @Test func draftGatesSendAndKeepsFailureForRetry() async throws { |
| + let server = AttachmentServer(); await server.failNext() |
| + let draft = AttachmentDraft(client: server) |
| + 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: "")) |
| + } |
| +} |
| + |
| +/// Base's stand-in for Equipo's AttachmentServer: the draft's client, as |
| +/// Base's relay answers it. |
| +actor AttachmentServer: AttachmentClient { |
| + var uploads: [AttachmentFile] = [] |
| + var reads: [(id: String, preview: Bool)] = [] |
| + var deleted: [String] = [] |
| + private var bytes = Data() |
| + private var fail = false |
| + func failNext() { fail = true } |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { |
| + uploads.append(file) |
| + if fail { fail = false; throw BaseAPIError.offline } |
| + bytes = file.data |
| + return Self.attachment |
| + } |
| + func delete(_ id: String) async throws { deleted.append(id) } |
| + func data(id: String, preview: Bool) async throws -> Data { reads.append((id, preview)); return bytes } |
| + func download(id: String, to destination: URL) async throws { try bytes.write(to: destination) } |
| + static let attachment = AskAttachment(id: "at_fixture", kind: "image", name: "screen.png", mediaType: "image/png", size: 100, width: 12, height: 8) |
| +} |
| + |
| +extension AttachmentTests { |
| + @MainActor @Test func invalidImageNeverReachesUpload() async throws { |
| + let server = AttachmentServer() |
| + let draft = AttachmentDraft(client: server) |
| + await draft.add(data: try Self.image(.gif, width: 12_001, height: 1), name: "wide.png") |
| + #expect(draft.items.first?.failure == BaseText.text("native.attach.pixels")) |
| + #expect(await server.uploads.isEmpty) |
| + } |
| + |
| + // Base differs: Task 14. Five files upload at once here; Base admits two |
| + // at a time (P8.2), and its Remove deletes the upload (P8.1). |
| + @MainActor @Test(.disabled("Base differs: Task 14")) func uploadingItemsCountTowardLimitAndRemovedItemsStayGone() async throws { |
| + let server = HeldAttachmentServer() |
| + let draft = AttachmentDraft(client: server) |
| + 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 == BaseText.text("native.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: "")) |
| + } |
| +} |
| + |
| +actor HeldAttachmentServer: AttachmentClient { |
| + private var pending: [CheckedContinuation<AskAttachment, Error>] = [] |
| + var pendingCount: Int { pending.count } |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { |
| + progress(0.45) |
| + return try await withCheckedThrowingContinuation { pending.append($0) } |
| + } |
| + func complete() { |
| + for continuation in pending { continuation.resume(returning: AttachmentServer.attachment) } |
| + pending = [] |
| + } |
| + func delete(_ id: String) async throws {} |
| + func data(id: String, preview: Bool) async throws -> Data { Data() } |
| + func download(id: String, to destination: URL) async throws {} |
| +} |
| + |
| +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") |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/attachments/large.webp b/native/apple/Tests/BaseKitTests/Fixtures/attachments/large.webp| new file mode 100644 |
| index 0000000..8ffb3be |
| Binary files /dev/null and b/native/apple/Tests/BaseKitTests/Fixtures/attachments/large.webp differ |
diff --git a/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift b/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift| new file mode 100644 |
| index 0000000..4ee3b74 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift |
| @@ -0,0 +1,148 @@ |
| +// Copied from Equipo origin/main 8bd40ed1: native/apple/Tests/EquipoKitTests/MacAttachmentTests.swift |
| +// (R5), against MacPasteboard and AttachmentPromises, the parts of Equipo's |
| +// MacComposer Base copied. |
| +// |
| +// Not copied: textDragFallsThroughTheWholeNativeLifecycle, |
| +// fullDragLifecycleAcceptsImages' dragging calls and |
| +// webURLDropAndPasteInsertTextWithoutAttachments' typing, which test |
| +// ComposerEditor, Equipo's NSTextView subclass. Base's composer is a |
| +// SwiftUI field that takes drops on the pane (Task 17, Spike M); what those |
| +// tests check of the pasteboard is checked here. |
| +#if os(macOS) |
| +import AppKit |
| +@testable import BaseKit |
| +import Foundation |
| +import Testing |
| + |
| +@MainActor @Suite(.serialized) struct MacAttachmentTests { |
| + @Test func pastedAndDroppedImagesUseTheDraftAndGateSend() async throws { |
| + let server = AttachmentServer() |
| + let draft = AttachmentDraft(client: server) |
| + let pasteboard = NSPasteboard.withUniqueName() |
| + defer { pasteboard.releaseGlobally() } |
| + pasteboard.setData(try AttachmentTests.image(), forType: .png) |
| + // Paste and drop both come here. |
| + #expect(MacPasteboard.acceptAttachments(pasteboard, into: draft)) |
| + for _ in 0..<500 { |
| + if !draft.readyAttachments.isEmpty { break } |
| + try await Task.sleep(for: .milliseconds(10)) |
| + } |
| + #expect(draft.readyAttachments.count == 1) |
| + #expect(draft.canSend(text: "")) |
| + pasteboard.clearContents(); pasteboard.setString("ordinary text", forType: .string) |
| + #expect(!MacPasteboard.acceptAttachments(pasteboard, into: draft)) |
| + } |
| +} |
| + |
| +extension MacAttachmentTests { |
| + @Test(arguments: [NSPasteboard.PasteboardType.png, .tiff, .fileURL]) |
| + func imagesAndFilesAreAccepted(_ type: NSPasteboard.PasteboardType) async throws { |
| + let server = AttachmentServer(), board = NSPasteboard.withUniqueName() |
| + defer { board.releaseGlobally() } |
| + let draft = AttachmentDraft(client: server) |
| + let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png") |
| + defer { try? FileManager.default.removeItem(at: url) } |
| + if type == .fileURL { try AttachmentTests.image().write(to: url); board.writeObjects([url as NSURL]) } |
| + else { board.setData(try AttachmentTests.image(type == .tiff ? .tiff : .png), forType: type) } |
| + #expect(MacPasteboard.accepts(board)) |
| + #expect(MacPasteboard.acceptAttachments(board, into: draft)) |
| + for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + #expect(draft.readyAttachments.count == 1) |
| + } |
| + |
| + @Test func foldersAreRefusedBeforeAddingItems() async throws { |
| + let server = AttachmentServer(), board = NSPasteboard.withUniqueName() |
| + defer { board.releaseGlobally() } |
| + let draft = AttachmentDraft(client: server) |
| + board.writeObjects([FileManager.default.temporaryDirectory as NSURL]) |
| + _ = MacPasteboard.acceptAttachments(board, into: draft) |
| + try await Task.sleep(for: .milliseconds(40)) |
| + #expect(draft.items.isEmpty) |
| + #expect(draft.notice == BaseText.text("native.attach.type")) |
| + #expect(await server.uploads.isEmpty) |
| + } |
| + |
| + @Test func aWebURLIsNotAnAttachment() { |
| + let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| + board.writeObjects([URL(string: "https://example.com/photo.png")! as NSURL]) |
| + let draft = AttachmentDraft(client: AttachmentServer()) |
| + #expect(!MacPasteboard.acceptAttachments(board, into: draft)) |
| + #expect(draft.items.isEmpty) |
| + } |
| +} |
| + |
| +@MainActor private final class FixturePromise: NSFilePromiseReceiver { |
| + let bytes: Data |
| + var destination: URL? |
| + var permissions: Int? |
| + init(_ bytes: Data) { self.bytes = bytes; super.init() } |
| + required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError() } |
| + override func receivePromisedFiles(atDestination destinationDir: URL, options: [AnyHashable: Any] = [:], operationQueue: OperationQueue, reader: @escaping (URL, (any Error)?) -> Void) { |
| + destination = destinationDir |
| + permissions = (try? FileManager.default.attributesOfItem(atPath: destinationDir.path)[.posixPermissions]) as? Int |
| + let url = destinationDir.appendingPathComponent("promise.png") |
| + do { try bytes.write(to: url); reader(url, nil) } catch { reader(url, error) } |
| + } |
| +} |
| + |
| +extension MacAttachmentTests { |
| + @Test func promisedFilesUsePrivateStorageAndRemoveItAfterReading() async throws { |
| + let server = AttachmentServer(), draft = AttachmentDraft(client: server) |
| + let promise = FixturePromise(try AttachmentTests.image()) |
| + AttachmentPromises.receive([promise], into: draft) |
| + let destination = try #require(promise.destination) |
| + #expect(promise.permissions == 0o700) |
| + for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + #expect(draft.readyAttachments.count == 1) |
| + #expect(!FileManager.default.fileExists(atPath: destination.path)) |
| + let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| + for type in NSFilePromiseReceiver.readableDraggedTypes { |
| + board.clearContents(); board.setData(Data(), forType: NSPasteboard.PasteboardType(type)) |
| + #expect(MacPasteboard.accepts(board)) |
| + } |
| + } |
| +} |
| + |
| +@MainActor private final class HeldFilePromise: NSFilePromiseReceiver { |
| + var destination: URL? |
| + var reader: ((URL, (any Error)?) -> Void)? |
| + override init() { super.init() } |
| + required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError() } |
| + override func receivePromisedFiles(atDestination destinationDir: URL, options: [AnyHashable: Any] = [:], operationQueue: OperationQueue, reader: @escaping (URL, (any Error)?) -> Void) { |
| + destination = destinationDir |
| + self.reader = reader |
| + } |
| +} |
| + |
| +extension MacAttachmentTests { |
| + @Test func promiseDeletesEachFileWhileOtherReadersStillOwnDirectory() async throws { |
| + let server = AttachmentServer(), draft = AttachmentDraft(client: server) |
| + let promise = HeldFilePromise() |
| + AttachmentPromises.receive([promise], into: draft) |
| + let directory = try #require(promise.destination) |
| + defer { promise.reader = nil } |
| + let url = directory.appendingPathComponent("delivered.png") |
| + try AttachmentTests.image().write(to: url) |
| + promise.reader?(url, nil) |
| + #expect(FileManager.default.fileExists(atPath: directory.path)) |
| + #expect(!FileManager.default.fileExists(atPath: url.path)) |
| + for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + #expect(draft.readyAttachments.count == 1) |
| + } |
| + |
| + @Test func promiseCannotReadOutsideItsPrivateDirectory() async throws { |
| + let server = AttachmentServer(), draft = AttachmentDraft(client: server) |
| + let promise = HeldFilePromise() |
| + AttachmentPromises.receive([promise], into: draft) |
| + let outside = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".png") |
| + try AttachmentTests.image().write(to: outside) |
| + defer { promise.reader = nil; try? FileManager.default.removeItem(at: outside) } |
| + promise.reader?(outside, nil) |
| + for _ in 0..<100 { if draft.notice != nil || !draft.items.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + #expect(draft.notice == AttachmentFailure.type.words) |
| + #expect(draft.items.isEmpty) |
| + #expect(await server.uploads.isEmpty) |
| + #expect(FileManager.default.fileExists(atPath: outside.path)) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift b/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift| new file mode 100644 |
| index 0000000..55dbc32 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift |
| @@ -0,0 +1,77 @@ |
| +// Adapted from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift |
| +// and native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift (R5): the |
| +// same pictures, drawn in code, as draft items and sent files, with no |
| +// session, keychain or server. |
| +import BaseKit |
| +import CoreText |
| +import Foundation |
| +import ImageIO |
| +import SwiftUI |
| +import UniformTypeIdentifiers |
| + |
| +@MainActor enum AttachmentFixtures { |
| + /// Landscape JPEG fixture exercises mixed image aspect ratios in a sent bubble. |
| + nonisolated static var landscape: Data { |
| + let context = CGContext(data: nil, width: 640, height: 360, bitsPerComponent: 8, bytesPerRow: 640 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! |
| + context.setFillColor(CGColor(red: 0.55, green: 0.76, blue: 0.9, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 640, height: 360)) |
| + context.setFillColor(CGColor(red: 0.97, green: 0.88, blue: 0.56, alpha: 1)); context.fillEllipse(in: CGRect(x: 470, y: 245, width: 60, height: 60)) |
| + context.setFillColor(CGColor(red: 0.25, green: 0.46, blue: 0.37, alpha: 1)) |
| + context.move(to: CGPoint(x: 0, y: 0)); context.addLine(to: CGPoint(x: 0, y: 125)); context.addCurve(to: CGPoint(x: 640, y: 155), control1: CGPoint(x: 230, y: 320), control2: CGPoint(x: 340, y: 30)); context.addLine(to: CGPoint(x: 640, y: 0)); context.closePath(); context.fillPath() |
| + let data = NSMutableData() |
| + let destination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil)! |
| + CGImageDestinationAddImage(destination, context.makeImage()!, nil); CGImageDestinationFinalize(destination) |
| + return data as Data |
| + } |
| + nonisolated static var image: Data { |
| + let context = CGContext(data: nil, width: 360, height: 640, bitsPerComponent: 8, bytesPerRow: 360 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! |
| + context.setFillColor(CGColor(red: 0.98, green: 0.97, blue: 0.94, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 360, height: 640)) |
| + context.setFillColor(CGColor(gray: 1, alpha: 1)); context.fill(CGRect(x: 20, y: 240, width: 320, height: 230)) |
| + func line(_ text: String, _ y: CGFloat, _ size: CGFloat) { |
| + let value = NSAttributedString(string: text, attributes: [.font: CTFontCreateWithName("Helvetica" as CFString, size, nil), .foregroundColor: CGColor(gray: 0.15, alpha: 1)]) |
| + context.textPosition = CGPoint(x: 32, y: y); CTLineDraw(CTLineCreateWithAttributedString(value), context) |
| + } |
| + line("Home", 570, 30); line("Sign in", 425, 24); line("Your address", 370, 16) |
| + context.setStrokeColor(CGColor(gray: 0.75, alpha: 1)); context.stroke(CGRect(x: 32, y: 305, width: 296, height: 42)) |
| + line("paul@example.com", 320, 16) |
| + context.setFillColor(CGColor(red: 0.15, green: 0.32, blue: 0.8, alpha: 1)); context.fill(CGRect(x: 32, y: 240, width: 296, height: 42)) |
| + let data = NSMutableData() |
| + let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)! |
| + CGImageDestinationAddImage(destination, context.makeImage()!, nil); CGImageDestinationFinalize(destination) |
| + return data as Data |
| + } |
| + |
| + /// A draft as the mockups show it: Home.png uploading (42%) and |
| + /// Home-failed.png failed. Its uploads never finish. |
| + static func draft() async -> AttachmentDraft { |
| + let draft = AttachmentDraft(client: FixtureAttachmentClient()) |
| + for name in ["Home.png", "Home-failed.png"] { |
| + Task { await draft.add(data: image, name: name) } |
| + while !draft.items.contains(where: { $0.name == name }) { await Task.yield() } |
| + } |
| + for _ in 0..<500 { |
| + if draft.items.allSatisfy({ if case .uploading(let p) = $0.state { return p > 0 }; return true }) { break } |
| + try? await Task.sleep(for: .milliseconds(10)) |
| + } |
| + return draft |
| + } |
| + |
| + /// A sent message's files: a portrait PNG and a landscape JPEG. |
| + nonisolated static let sent = [AskAttachment(id: "at_fixture", kind: "image", name: "Home.png", mediaType: "image/png", size: 8000, width: 360, height: 640), |
| + AskAttachment(id: "at_landscape", kind: "image", name: "Landscape.jpg", mediaType: "image/jpeg", size: 21_000, width: 640, height: 360)] |
| +} |
| + |
| +/// Answers as Base's relay would, from the pictures above: an upload named |
| +/// "failed" fails, any other reports 42% and never finishes. |
| +struct FixtureAttachmentClient: AttachmentClient { |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { |
| + if file.name.contains("failed") { throw BaseAPIError.offline } |
| + progress(0.42) |
| + try await Task.sleep(for: .seconds(3600)) |
| + return AttachmentFixtures.sent[0] |
| + } |
| + func delete(_ id: String) async throws {} |
| + func data(id: String, preview: Bool) async throws -> Data { |
| + id == "at_landscape" ? AttachmentFixtures.landscape : AttachmentFixtures.image |
| + } |
| + func download(id: String, to destination: URL) async throws { try await data(id: id, preview: false).write(to: destination) } |
| +} |