Add native composer attachments with upload state and previews
27 files changed,
+1,534
−35
docs/superpowers/plans/CONTROLLER-REPORT-native-attachments.md+126 −0native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings+198 −0native/apple/Sources/EquipoKit/API/Attachments.swift+36 −0native/apple/Sources/EquipoKit/API/Client.swift+5 −3native/apple/Sources/EquipoKit/API/Thin.swift+1 −0native/apple/Sources/EquipoKit/API/Transport.swift+13 −4native/apple/Sources/EquipoKit/API/UploadProgress.swift+17 −0native/apple/Sources/EquipoKit/Attachments/AttachmentDraft.swift+73 −0native/apple/Sources/EquipoKit/Attachments/AttachmentFile.swift+79 −0native/apple/Sources/EquipoKit/Attachments/AttachmentViews.swift+158 −0native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift+81 −0native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift+74 −0native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings+198 −0native/apple/Sources/EquipoKit/Session/EquipoSession.swift+15 −7native/apple/Sources/EquipoKit/UI/RosterViews.swift+8 −2native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift+15 −7native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift+12 −0native/apple/Sources/EquipoMac/EquipoMacApp.swift+2 −1native/apple/Sources/EquipoMac/LiveTranscript.swift+14 −3native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift+36 −0native/apple/Sources/EquipoMac/MacComposer.swift+64 −6native/apple/Tests/EquipoKitTests/AttachmentHTTPTests.swift+72 −0native/apple/Tests/EquipoKitTests/AttachmentTests.swift+185 −0native/apple/Tests/EquipoKitTests/MacAttachmentTests.swift+30 −0native/ios/project.yml+2 −0native/scripts/check-parity.py+1 −1native/scripts/strings.json+19 −1
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-native-attachments.md b/docs/superpowers/plans/CONTROLLER-REPORT-native-attachments.md| new file mode 100644 |
| index 00000000..24d67e5d |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-native-attachments.md |
| @@ -0,0 +1,126 @@ |
| +# Native composer attachments |
| + |
| +Branch: `native/attachments`, in its own physical-TMPDIR worktree, based on |
| +`origin/main` at `2950f604`, then rebased before its first push onto landed main |
| +`4024216e` (including the stopped-work release follow-up). String catalogs |
| +were regenerated from the union of both slices' reviewed keys; both debug |
| +fixture entry points and the landed stopped-work behavior were retained. |
| + |
| +## Behavior |
| + |
| +The conversation composer accepts up to five attachments. On iPhone, the |
| +plus menu offers Photos (PhotosPicker), Camera, Files, and Paste. PhotosPicker |
| +does not request full-library access. HEIC/HEIF photos convert to JPEG with |
| +orientation applied and source metadata omitted. Mac clipboard TIFF images |
| +also convert to JPEG. Mac supports image/file paste and drag-and-drop through |
| +the AppKit composer. Area capture is omitted as agreed with the controller: |
| +a permission-free area capture path was not established; ScreenCaptureKit |
| +capture requires Screen Recording permission. |
| + |
| +The source file is checked before upload: at most 10 MiB, 12,000 pixels per |
| +side, and 40 megapixels. These constants are POST /attachments' published v1 |
| +contract and `internal/attach/attach.go`; /capabilities does not publish |
| +configurable attachment limits. Converted JPEG bytes are checked again. |
| +Files are read with a maximum byte count; image dimensions are read before |
| +raster conversion. |
| + |
| +Each item has upload progress, failure, retry, and remove. Failed and uploading |
| +items block sending. Removing an item prevents a late response from restoring |
| +it. Sending carries the uploaded ids in /messages, including attachment-only |
| +messages. The session keeps attachment metadata with a pending outgoing |
| +message; retry keeps its ids and idempotency key. Signing out clears the draft. |
| + |
| +Sent bubbles fetch thumbnails through authenticated /attachments/{id}/preview |
| +reads. Tapping opens the original through /attachments/{id}, full screen on |
| +iPhone and in a sheet on Mac. Images, text files, and PDFs have native previews. |
| +The transport remains ephemeral, without cookie storage or redirects, including |
| +the upload delegate. No server route changed. |
| + |
| +Share extension, recent-screenshot offers, area capture, and task-thread |
| +attachments are outside this slice. |
| + |
| +## Copy |
| + |
| +The web's chat.attach.* and api.attachment_* entries are copied into the |
| +catalog byte-identically, except the existing %s to %@ native format conversion. |
| +team.close is the existing reviewed web word. Parity covers these namespaces. |
| + |
| +The five native-only entries were approved by Luna through the controller on |
| +2026-11-25: |
| + |
| +| Key | Value | Use | |
| +| --- | --- | --- | |
| +| native.attach.photos | Photos | Picker menu | |
| +| native.attach.camera | Camera | Picker menu | |
| +| native.attach.files | Files | Picker menu | |
| +| native.attach.paste | Paste | Picker menu | |
| +| native.attach.camera_usage | Use your camera to take a photo to attach to your message. | Camera purpose string | |
| + |
| +Approval is recorded beside the menu labels and Info.plist source in |
| +project.yml. Fixture message text is illustrative user content, not runtime |
| +interface copy. No further copy questions. |
| + |
| +## Test-first evidence |
| + |
| +`swift test --package-path native/apple --filter AttachmentTests` first |
| +failed because AttachmentLimits, AttachmentFile, AttachmentDraft and attachment |
| +API methods were absent. The initial tests covered byte/pixel/type limits, |
| +HEIC conversion, upload headers, message attachment ids, image delivery to a |
| +fake Coordinator, failed upload retry, removal, and the send gate. |
| + |
| +The expanded `swift test --package-path native/apple --filter Attachment` |
| +passed 10 tests in three suites. It also covers reservation of all five slots |
| +while uploading, an invalid image never reaching the upload endpoint, late |
| +completion after removal, duplicate ids, clearing the draft after send and |
| +sign-out, and the Mac paste/drop entry point. |
| + |
| +A real loopback HTTP server test exercises URLSession's raw upload and progress |
| +delegate. The server resolves the submitted message ids to uploaded image |
| +bytes before exposing the fake Coordinator's received image; the test compares |
| +those bytes with the source image. The server binds only 127.0.0.1 and is |
| +terminated after the test. |
| + |
| +The actual Coordinator already converts attachments to Claude image content |
| +and Codex localImage input, covered by |
| +`internal/headless/attachments_test.go:TestHeadlessAttachments`. The local |
| +command `GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0 go test ./internal/headless -run |
| +TestHeadlessAttachments -count=1` could not build on macOS because |
| +`internal/toolproxy/stdio.go` uses Linux `unix.O_PATH`. Linux hub CI remains |
| +the gate for those server tests. |
| + |
| +## Mutations |
| + |
| +`python3 "$TMPDIR/attachments-mutations.py"` ran the focused |
| +`swift test --package-path native/apple --filter Attachment` suite for each |
| +mutation, required a failed assertion or thrown test error, and restored each |
| +source file in a finally block. All 13 mutations were caught: |
| + |
| +| Deliberately broken behavior | Result | |
| +| --- | --- | |
| +| Byte limit removed | Caught | |
| +| Side-length limit removed | Caught | |
| +| Pixel-count limit removed | Caught | |
| +| Dimension validation before upload removed | Caught | |
| +| HEIC result advertised as HEIC instead of JPEG | Caught | |
| +| Five-item draft limit removed | Caught | |
| +| Uploading/failed items allowed to send | Caught | |
| +| Remove keeps the item | Caught | |
| +| Retry never uploads | Caught | |
| +| Message attachment ids omitted | Caught | |
| +| Upload bearer omitted | Caught | |
| +| Uploaded bytes replaced with an empty body | Caught | |
| +| Mac image paste/drop entry point disabled | Caught | |
| + |
| +The first remove mutator produced invalid Swift; it was not counted. It was |
| +corrected to a compiling no-op remove and the assertions then failed. |
| + |
| +Initial full native gate passed: 217 tests in 28 suites, one existing known |
| +issue, 125 parity strings, Mac build and iPhone Simulator build. Final gate |
| +and Linux CI are recorded with the final branch SHA. |
| + |
| +Native captures are under |
| +`polish-audit/equipo-daily-driver/site/build/slice2/`: |
| +`iphone-composer.png`, `iphone-sent.png`, and `mac-drop.png`. |
| +The debug fixtures use the production composer, message views and API client |
| +with a fake transport. The Mac capture enters the same pasteboard handler as |
| +performDragOperation. No real account or screenshot permission is used. |
diff --git a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings| index 2835fe1f..f32fe8ad 100644 |
| --- a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings |
| @@ -145,6 +145,61 @@ |
| } |
| } |
| }, |
| + "api.attachment_heic": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "HEIC photos cannot be read yet. Share it as a JPEG and try again." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_limit": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Too many files are waiting to send. Send or remove some first." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_pixels": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That image is too large: at most 12,000 pixels on a side and 40 megapixels." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_too_large": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That file is over 10 MB." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_type": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files." |
| + } |
| + } |
| + } |
| + }, |
| "api.card_answered": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -464,6 +519,94 @@ |
| } |
| } |
| }, |
| + "chat.attach.add": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attach" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.failed": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Could not upload. Try again." |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.file": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "File" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.image": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Photo or image" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.list": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attachments" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.remove": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Remove %@" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.too_many": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "At most 5 files in one message." |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.uploading": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Uploading…" |
| + } |
| + } |
| + } |
| + }, |
| "chat.card.answer": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -1058,6 +1201,61 @@ |
| } |
| } |
| }, |
| + "native.attach.camera": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Camera" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.camera_usage": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Use your camera to take a photo to attach to your message." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.files": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Files" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.paste": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Paste" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.photos": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Photos" |
| + } |
| + } |
| + } |
| + }, |
| "native.step.log_tail": { |
| "extractionState": "manual", |
| "localizations": { |
diff --git a/native/apple/Sources/EquipoKit/API/Attachments.swift b/native/apple/Sources/EquipoKit/API/Attachments.swift| new file mode 100644 |
| index 00000000..a09bf647 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/Attachments.swift |
| @@ -0,0 +1,36 @@ |
| +import Foundation |
| + |
| +public struct MessageAttachment: Codable, Sendable, Equatable, Identifiable { |
| + public let id: String |
| + public let revision: Int64 |
| + public let kind: String |
| + public let name: String |
| + public let mediaType: String |
| + public let size: Int64 |
| + public let sha256: String |
| + public let width: Int |
| + public let height: Int |
| + public let messageId: String |
| + public let createdAt: Date |
| +} |
| + |
| +extension EquipoClient { |
| + public func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> MessageAttachment { |
| + var request = APIRequest("POST", "/attachments", body: file.data, bearer: token) |
| + request.contentType = file.mediaType |
| + let escaped = file.name.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? "file" |
| + request.contentDisposition = "attachment; filename*=UTF-8''" + escaped |
| + request.uploadProgress = UploadProgress(progress) |
| + return try await send(request) |
| + } |
| + |
| + public func attachmentData(_ id: String, preview: Bool = false) async throws -> Data { |
| + let id = id.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(CharacterSet(charactersIn: "_-"))) ?? "" |
| + var request = APIRequest("GET", "/attachments/\(id)" + (preview ? "/preview" : ""), bearer: token) |
| + request.maximumResponseBytes = AttachmentLimits.maxBytes |
| + let response = try await transport.send(request) |
| + guard (200..<300).contains(response.status) else { throw Self.error(response) } |
| + guard response.data.count <= AttachmentLimits.maxBytes else { throw EquipoAPIError.tooLarge } |
| + return response.data |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/API/Client.swift b/native/apple/Sources/EquipoKit/API/Client.swift| index 82d6e233..374f6303 100644 |
| --- a/native/apple/Sources/EquipoKit/API/Client.swift |
| +++ b/native/apple/Sources/EquipoKit/API/Client.swift |
| @@ -46,10 +46,12 @@ public struct EquipoClient: Sendable { |
| // MARK: Writes. Each takes a PendingWrite so a retry is the same request. |
| /// A message; the engine takes its key in the body as well as the header. |
| - public static func message(_ text: String, projectID: String? = nil) throws -> PendingWrite { |
| + public static func message(_ text: String, projectID: String? = nil, attachments: [String] = []) throws -> PendingWrite { |
| let key = UUID().uuidString.lowercased() |
| - var body = ["text": text, "idempotency_key": key] |
| - if let projectID { body["project_id"] = projectID } |
| + var body: [String: AnyEncodable] = ["text": .init(text), "idempotency_key": .init(key)] |
| + guard attachments.count <= AttachmentLimits.maxCount, Set(attachments).count == attachments.count else { throw EquipoAPIError.status(422) } |
| + if let projectID { body["project_id"] = .init(projectID) } |
| + if !attachments.isEmpty { body["attachments"] = .init(attachments) } |
| return PendingWrite(body: try EquipoJSON.encoder.encode(body), key: key) |
| } |
| public func send(_ write: PendingWrite) async throws -> Sent { try await post("/messages", write) } |
diff --git a/native/apple/Sources/EquipoKit/API/Thin.swift b/native/apple/Sources/EquipoKit/API/Thin.swift| index 021878c5..df16c7d6 100644 |
| --- a/native/apple/Sources/EquipoKit/API/Thin.swift |
| +++ b/native/apple/Sources/EquipoKit/API/Thin.swift |
| @@ -16,6 +16,7 @@ public struct ThinMe: Codable, Sendable, Equatable { |
| } |
| public struct ThinMessage: Codable, Sendable, Identifiable, Equatable { |
| + public var attachments: [MessageAttachment]? = nil |
| public var projectId: String? = nil |
| public var id: String |
| public var revision: Int64 |
diff --git a/native/apple/Sources/EquipoKit/API/Transport.swift b/native/apple/Sources/EquipoKit/API/Transport.swift| index e7501610..60403085 100644 |
| --- a/native/apple/Sources/EquipoKit/API/Transport.swift |
| +++ b/native/apple/Sources/EquipoKit/API/Transport.swift |
| @@ -11,6 +11,10 @@ public struct APIRequest: Sendable, Equatable { |
| public var idempotencyKey: String? |
| public var ifMatch: Int64? |
| public var nativeSession: NativeSession? |
| + var contentType = "application/json" |
| + var contentDisposition: String? |
| + var uploadProgress: UploadProgress? |
| + var maximumResponseBytes = 4 * 1024 * 1024 |
| public init(_ method: String, _ path: String, query: [URLQueryItem] = [], body: Data? = nil, |
| bearer: String? = nil, idempotencyKey: String? = nil, ifMatch: Int64? = nil, nativeSession: NativeSession? = nil) { |
| @@ -34,8 +38,9 @@ public struct APIRequest: Sendable, Equatable { |
| r.setValue("application/json", forHTTPHeaderField: "Accept") |
| if let body { |
| r.httpBody = body |
| - r.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| + r.setValue(contentType, forHTTPHeaderField: "Content-Type") |
| } |
| + if let contentDisposition { r.setValue(contentDisposition, forHTTPHeaderField: "Content-Disposition") } |
| if let nativeSession { |
| // Only the bridge may send a cookie. Engine and pairing requests |
| // stay bearer-only, including after renewal. |
| @@ -96,12 +101,16 @@ public final class URLSessionTransport: NSObject, EquipoTransport, URLSessionTas |
| } |
| public func send(_ request: APIRequest) async throws -> APIResponse { |
| - let r = try request.urlRequest(origin: origin) |
| + var r = try request.urlRequest(origin: origin) |
| do { |
| - let (data, response) = try await session.data(for: r) |
| + let data: Data, response: URLResponse |
| + if let progress = request.uploadProgress, let body = request.body { |
| + r.httpBody = nil |
| + (data, response) = try await session.upload(for: r, from: body, delegate: UploadDelegate(progress)) |
| + } else { (data, response) = try await session.data(for: r) } |
| guard let http = response as? HTTPURLResponse else { throw EquipoAPIError.offline } |
| observe(.responded(status: http.statusCode)) |
| - guard data.count <= Self.maxBytes else { throw EquipoAPIError.tooLarge } |
| + guard data.count <= request.maximumResponseBytes else { throw EquipoAPIError.tooLarge } |
| return APIResponse(status: http.statusCode, data: data) |
| } catch let error as URLError where error.code == .cancelled { |
| // This app stopped asking (the stream closed, pairing cancelled): |
diff --git a/native/apple/Sources/EquipoKit/API/UploadProgress.swift b/native/apple/Sources/EquipoKit/API/UploadProgress.swift| new file mode 100644 |
| index 00000000..459508e7 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/UploadProgress.swift |
| @@ -0,0 +1,17 @@ |
| +import Foundation |
| + |
| +/// Request-local progress survives the lifetime and credential-renewal wrappers. |
| +final class UploadProgress: Sendable, Equatable { |
| + let report: @Sendable (Double) -> Void |
| + init(_ report: @escaping @Sendable (Double) -> Void) { self.report = report } |
| + static func == (lhs: UploadProgress, rhs: UploadProgress) -> Bool { lhs === rhs } |
| +} |
| + |
| +final class UploadDelegate: NSObject, URLSessionTaskDelegate, Sendable { |
| + let progress: UploadProgress |
| + init(_ progress: UploadProgress) { self.progress = progress } |
| + func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { |
| + if totalBytesExpectedToSend > 0 { progress.report(min(1, Double(totalBytesSent) / Double(totalBytesExpectedToSend))) } |
| + } |
| + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { nil } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/EquipoKit/Attachments/AttachmentDraft.swift| new file mode 100644 |
| index 00000000..79cfba36 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Attachments/AttachmentDraft.swift |
| @@ -0,0 +1,73 @@ |
| +import Foundation |
| +import Observation |
| + |
| +@MainActor @Observable public final class AttachmentDraft { |
| + public struct Item: Identifiable, Sendable { |
| + public enum State: Sendable { case uploading(Double), ready(MessageAttachment), 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? |
| + var client: EquipoClient |
| + public init(client: EquipoClient) { self.client = client } |
| + |
| + public var readyAttachments: [MessageAttachment] { 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 add(url: URL) async { await add(.file(url), name: url.lastPathComponent) } |
| + private func add(_ source: Source, name: String) async { |
| + guard items.count < AttachmentLimits.maxCount else { notice = EquipoStrings.text("chat.attach.too_many"); return } |
| + notice = nil |
| + let id = UUID() |
| + items.append(Item(id: id, name: name, state: .uploading(0), source: source)) |
| + await upload(id) |
| + } |
| + public func remove(_ id: UUID) { items.removeAll { $0.id == id }; notice = nil } |
| + public func clear() { items = []; notice = nil } |
| + 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 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 |
| + 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 error = error as? EquipoAPIError, let code = error.code, |
| + ["attachment_too_large", "attachment_pixels", "attachment_type", "attachment_heic", "attachment_limit"].contains(code) { |
| + words = EquipoStrings.text(String.LocalizationValue("api." + code)) |
| + } |
| + else { words = EquipoStrings.text("chat.attach.failed") } |
| + items[i].state = .failed(words) |
| + } |
| + } |
| + private func index(_ id: UUID, _ generation: UUID) -> Int? { items.firstIndex { $0.id == id && $0.generation == generation } } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Attachments/AttachmentFile.swift b/native/apple/Sources/EquipoKit/Attachments/AttachmentFile.swift| new file mode 100644 |
| index 00000000..f40b41dd |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Attachments/AttachmentFile.swift |
| @@ -0,0 +1,79 @@ |
| +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 |
| + public static let maxCount = 5 |
| + public static let maxSide = 12_000 |
| + public static let maxPixels = 40_000_000 |
| + 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 var words: String { |
| + switch self { |
| + case .tooLarge: EquipoStrings.text("api.attachment_too_large") |
| + case .pixels: EquipoStrings.text("api.attachment_pixels") |
| + case .type: EquipoStrings.text("api.attachment_type") |
| + } |
| + } |
| +} |
| + |
| +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 { |
| + guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| + 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 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 |
| + try AttachmentLimits.checkDimensions(width: width, height: height) |
| + if type.conforms(to: .heic) || type.conforms(to: .heif) || type == .tiff { |
| + // 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: max(width, height)] |
| + guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { throw AttachmentFailure.type } |
| + let output = NSMutableData() |
| + guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { throw AttachmentFailure.type } |
| + CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.9] as CFDictionary) |
| + guard CGImageDestinationFinalize(destination) else { throw AttachmentFailure.type } |
| + guard output.length <= AttachmentLimits.maxBytes 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) |
| + } |
| + 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) |
| + } |
| + if data.starts(with: Data("%PDF-".utf8)) { return Self(data: data, name: name, mediaType: "application/pdf", width: 0, height: 0) } |
| + let types = ["txt": "text/plain", "log": "text/plain", "md": "text/markdown", "markdown": "text/markdown", "csv": "text/csv", "json": "application/json"] |
| + guard let media = types[(name as NSString).pathExtension.lowercased()], String(data: data, encoding: .utf8) != nil, |
| + !data.contains(0) else { throw AttachmentFailure.type } |
| + return Self(data: data, name: name, mediaType: media, width: 0, height: 0) |
| + } |
| + |
| + 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.maxBytes + 1) ?? Data() |
| + guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| + return data |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Attachments/AttachmentViews.swift b/native/apple/Sources/EquipoKit/Attachments/AttachmentViews.swift| new file mode 100644 |
| index 00000000..6939a1d2 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Attachments/AttachmentViews.swift |
| @@ -0,0 +1,158 @@ |
| +import SwiftUI |
| +import ImageIO |
| +import PDFKit |
| + |
| +/// Shared composer attachment list. State belongs to the session's draft. |
| +public struct AttachmentDraftStrip: View { |
| + 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(Palette.surface2) |
| + .clipShape(.rect(cornerRadius: 8)) |
| + Button { draft.remove(item.id) } label: { |
| + Image(systemName: "xmark.circle.fill").symbolRenderingMode(.palette) |
| + .foregroundStyle(Palette.text, Palette.surface).frame(width: 44, height: 44) |
| + } |
| + .buttonStyle(.plain) |
| + .accessibilityLabel(String(format: EquipoStrings.text("chat.attach.remove"), item.name)) |
| + } |
| + Text(item.name).font(Typo.caption).lineLimit(1).truncationMode(.middle) |
| + switch item.state { |
| + case .uploading(let progress): |
| + ProgressView(value: progress).accessibilityLabel(EquipoStrings.text("chat.attach.uploading")) |
| + Text(EquipoStrings.text("chat.attach.uploading")).font(Typo.caption).foregroundStyle(Palette.secondary) |
| + case .failed(let words): |
| + Text(words).font(Typo.caption).foregroundStyle(Palette.negative).fixedSize(horizontal: false, vertical: true) |
| + Button(EquipoStrings.text("read.retry")) { Task { await draft.retry(item.id) } } |
| + .font(Typo.caption).frame(minHeight: 28) |
| + case .ready: EmptyView() |
| + } |
| + }.frame(width: 140, alignment: .leading) |
| + } |
| + }.padding(.vertical, 4) |
| + } |
| + .accessibilityLabel(EquipoStrings.text("chat.attach.list")) |
| + } |
| + if let notice = draft.notice { Text(notice).font(Typo.caption).foregroundStyle(Palette.negative) } |
| + } |
| + } |
| +} |
| + |
| +struct AttachmentPicture: View { |
| + 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(Palette.secondary).accessibilityLabel(name) |
| + } |
| + }.task(id: data) { image = data.flatMap { Self.thumbnail($0, side: 512) } } |
| + } |
| + 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: [MessageAttachment] |
| + let client: EquipoClient |
| + @State private var selected: MessageAttachment? |
| + public init(_ attachments: [MessageAttachment], client: EquipoClient) { |
| + self.attachments = attachments; self.client = client |
| + } |
| + public var body: some View { |
| + ScrollView(.horizontal) { |
| + HStack(spacing: 8) { |
| + ForEach(attachments) { file in |
| + Button { selected = file } label: { SentAttachmentTile(file: file, client: client) } |
| + .buttonStyle(.plain).accessibilityLabel(file.name) |
| + } |
| + } |
| + } |
| + .frame(height: 112) |
| + #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 { |
| + let file: MessageAttachment |
| + let client: EquipoClient |
| + @State private var data: Data? |
| + var body: some View { |
| + VStack(spacing: 4) { |
| + AttachmentPicture(data: data, name: file.name).frame(width: 140, height: 86) |
| + .background(Palette.surface2).clipShape(.rect(cornerRadius: 8)) |
| + Text(file.name).font(Typo.caption).lineLimit(1).truncationMode(.middle).frame(width: 140) |
| + } |
| + .task(id: file.id) { |
| + if file.kind == "image" { data = try? await client.attachmentData(file.id, preview: true) } |
| + } |
| + } |
| +} |
| + |
| +private struct AttachmentPreview: View { |
| + let file: MessageAttachment |
| + let client: EquipoClient |
| + @Environment(\.dismiss) private var dismiss |
| + @State private var data: Data? |
| + @State private var failure = false |
| + var body: some View { |
| + NavigationStack { |
| + Group { |
| + if let data { |
| + if let image = AttachmentPicture.thumbnail(data, side: 4096) { |
| + 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(EquipoStrings.text("read.failed_title")) |
| + Button(EquipoStrings.text("read.retry")) { Task { await load() } } |
| + } |
| + } else { ProgressView().accessibilityLabel(file.name) } |
| + } |
| + .frame(maxWidth: .infinity, maxHeight: .infinity) |
| + .background(Palette.background).navigationTitle(file.name) |
| + .toolbar { ToolbarItem(placement: .confirmationAction) { Button(EquipoStrings.text("team.close")) { dismiss() } } } |
| + }.task { await load() } |
| + } |
| + private func load() async { |
| + failure = false |
| + do { data = try await client.attachmentData(file.id) } |
| + 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/EquipoKit/Attachments/AttachmentsFixture.swift b/native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift| new file mode 100644 |
| index 00000000..b39a2dba |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift |
| @@ -0,0 +1,81 @@ |
| +#if DEBUG |
| +import SwiftUI |
| +import ImageIO |
| +import UniformTypeIdentifiers |
| +import CoreText |
| + |
| +/// Offline visual fixture: no saved account, keychain or real server. |
| +public struct AttachmentsFixture: View { |
| + @State private var session = Self.makeSession() |
| + public init() {} |
| + public var body: some View { |
| + NavigationStack { |
| + ConversationScreen(session: session) { _ in } |
| + .navigationTitle(EquipoStrings.text("tab.conversation")) |
| + #if os(iOS) |
| + .navigationBarTitleDisplayMode(.inline) |
| + #endif |
| + }.task { |
| + await session.refresh() |
| + if ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != "sent" { |
| + await Self.seedDraft(session) |
| + } |
| + } |
| + } |
| + public static func makeSession() -> EquipoSession { |
| + let transport = AttachmentFixtureTransport() |
| + var account = DeviceAccount.new(origin: transport.origin, label: "Fixture") |
| + account.credential = DeviceCredential(id: "fixture", token: "fixture", audience: "equipo.person.v1", instanceId: "fixture", expiresAt: .distantFuture) |
| + return EquipoSession(account: account, accounts: DeviceAccounts(store: MemorySecretStore()), transport: transport) |
| + } |
| + public static func seedDraft(_ session: EquipoSession) async { |
| + async let first: Void = session.attachments.add(data: image, name: "Home.png") |
| + async let second: Void = session.attachments.add(data: image, name: "Home-failed.png") |
| + _ = await (first, second) |
| + } |
| + nonisolated public 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 |
| + } |
| +} |
| + |
| +private struct AttachmentFixtureTransport: EquipoTransport { |
| + let origin = URL(string: "https://fixture.invalid")! |
| + func send(_ request: APIRequest) async throws -> APIResponse { |
| + if request.path == "/attachments" { |
| + if request.contentDisposition?.contains("failed") == true { throw EquipoAPIError.offline } |
| + request.uploadProgress?.report(0.42) |
| + try await Task.sleep(for: .seconds(3600)) |
| + return APIResponse(status: 201, data: try JSONSerialization.data(withJSONObject: attachment)) |
| + } |
| + if request.path.hasPrefix("/attachments/") { return APIResponse(status: 200, data: AttachmentsFixture.image) } |
| + let body: [String: Any] |
| + switch request.path { |
| + case "/snapshot": |
| + body = ["me": ["id": "fixture", "address": "paul@example.com", "role": "owner", "team_id": "fixture", "team_name": "Oficina", "revision": 1], "cursor": 1, "tasks": [], "messages": messages, "turns": [], "cards": [], "projects": []] |
| + default: body = ["items": []] |
| + } |
| + return APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: body)) |
| + } |
| + func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { AsyncThrowingStream { $0.finish() } } |
| + private var attachment: [String: Any] { |
| + ["id": "at_fixture", "revision": 1, "kind": "image", "name": "Home.png", "media_type": "image/png", "size": 8000, "sha256": "fixture", "width": 360, "height": 640, "message_id": "message", "created_at": "2026-11-25T10:51:00Z"] |
| + } |
| + private var messages: [[String: Any]] { |
| + [["id": "message", "revision": 1, "role": "person", "text": "Home’s sign-in button is cut off on my phone.", "turn_id": "", "created_at": "2026-11-25T10:51:00Z", "attachments": [attachment]]] |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift b/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift| new file mode 100644 |
| index 00000000..422edee7 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift |
| @@ -0,0 +1,74 @@ |
| +#if os(iOS) |
| +import SwiftUI |
| +import PhotosUI |
| +import UniformTypeIdentifiers |
| + |
| +struct PhoneAttachmentPicker: View { |
| + let draft: AttachmentDraft |
| + @State private var photos: [PhotosPickerItem] = [] |
| + @State private var files = false |
| + @State private var camera = false |
| + var body: some View { |
| + Menu { |
| + // COPY APPROVED: Luna, 2026-11-25, all native.attach.* source labels. |
| + PhotosPicker(selection: $photos, maxSelectionCount: max(1, AttachmentLimits.maxCount - draft.items.count), matching: .images) { |
| + Label(EquipoStrings.text("native.attach.photos"), systemImage: "photo") |
| + } |
| + if UIImagePickerController.isSourceTypeAvailable(.camera) { |
| + Button { camera = true } label: { Label(EquipoStrings.text("native.attach.camera"), systemImage: "camera") } |
| + } |
| + Button { files = true } label: { Label(EquipoStrings.text("native.attach.files"), systemImage: "folder") } |
| + Button { paste() } label: { Label(EquipoStrings.text("native.attach.paste"), systemImage: "document.on.clipboard") } |
| + } label: { |
| + Image(systemName: "plus").font(.system(size: 20)).frame(width: 44, height: 44) |
| + } |
| + .accessibilityLabel(EquipoStrings.text("chat.attach.add")) |
| + .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 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/EquipoKit/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings| index 2835fe1f..f32fe8ad 100644 |
| --- a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings |
| @@ -145,6 +145,61 @@ |
| } |
| } |
| }, |
| + "api.attachment_heic": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "HEIC photos cannot be read yet. Share it as a JPEG and try again." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_limit": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Too many files are waiting to send. Send or remove some first." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_pixels": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That image is too large: at most 12,000 pixels on a side and 40 megapixels." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_too_large": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "That file is over 10 MB." |
| + } |
| + } |
| + } |
| + }, |
| + "api.attachment_type": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files." |
| + } |
| + } |
| + } |
| + }, |
| "api.card_answered": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -464,6 +519,94 @@ |
| } |
| } |
| }, |
| + "chat.attach.add": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attach" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.failed": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Could not upload. Try again." |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.file": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "File" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.image": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Photo or image" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.list": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Attachments" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.remove": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Remove %@" |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.too_many": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "At most 5 files in one message." |
| + } |
| + } |
| + } |
| + }, |
| + "chat.attach.uploading": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Uploading…" |
| + } |
| + } |
| + } |
| + }, |
| "chat.card.answer": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -1058,6 +1201,61 @@ |
| } |
| } |
| }, |
| + "native.attach.camera": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Camera" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.camera_usage": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Use your camera to take a photo to attach to your message." |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.files": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Files" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.paste": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Paste" |
| + } |
| + } |
| + } |
| + }, |
| + "native.attach.photos": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Photos" |
| + } |
| + } |
| + } |
| + }, |
| "native.step.log_tail": { |
| "extractionState": "manual", |
| "localizations": { |
diff --git a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift| index 44de5f95..c9fc5bf9 100644 |
| --- a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| +++ b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| @@ -18,6 +18,7 @@ public final class EquipoSession { |
| public let id: String |
| public let text: String |
| public let taskID: String? |
| + public var attachments: [MessageAttachment] = [] |
| public var notice: String? = nil |
| public var projectName: String? = nil |
| public var state: State |
| @@ -50,6 +51,7 @@ public final class EquipoSession { |
| public private(set) var tasks: [ThinTask] = [] |
| /// nil until loaded: an unknown count is not zero. |
| public private(set) var needsYou: [ThinTask]? |
| + public let attachments: AttachmentDraft |
| public let projectCatalog: ProjectCatalog |
| public var projects: [String: ThinProject] { projectCatalog.projects } |
| public private(set) var answerNotices: [String: String] = [:] |
| @@ -88,6 +90,7 @@ public final class EquipoSession { |
| self.revocationTransport = transport |
| let client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) |
| self.client = client |
| + attachments = AttachmentDraft(client: client) |
| projectCatalog = ProjectCatalog(client: client, lifetime: lifetime) |
| if !account.isUsable() { status = .signedOut } |
| } |
| @@ -332,14 +335,17 @@ public final class EquipoSession { |
| // MARK: Sending |
| public func sendFromComposer(_ text: String) -> Task<Void, Never> { |
| + guard lifetime.isActive, attachments.canSend(text: text) else { return Task {} } |
| + let files = attachments.readyAttachments |
| + attachments.clear() |
| let projectID = projectCatalog.takeSelection() |
| - return Task { await send(text, projectID: projectID) } |
| + return Task { await send(text, projectID: projectID, attachments: files) } |
| } |
| - public func send(_ text: String, inThreadOf taskID: String? = nil, projectID: String? = nil) async { |
| + public func send(_ text: String, inThreadOf taskID: String? = nil, projectID: String? = nil, attachments: [MessageAttachment] = []) async { |
| let text = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| - guard lifetime.isActive, !text.isEmpty, let write = try? EquipoClient.message(text, projectID: taskID == nil ? projectID : nil) else { return } |
| - outgoing.append(Outgoing(id: write.key, text: text, taskID: taskID, projectName: taskID == nil ? projectID.flatMap { projects[$0]?.displayName } : nil, state: .sending, write: write)) |
| + guard lifetime.isActive, !text.isEmpty || !attachments.isEmpty, taskID == nil || attachments.isEmpty, let write = try? EquipoClient.message(text, projectID: taskID == nil ? projectID : nil, attachments: attachments.map(\.id)) else { return } |
| + outgoing.append(Outgoing(id: write.key, text: text, taskID: taskID, attachments: attachments, projectName: taskID == nil ? projectID.flatMap { projects[$0]?.displayName } : nil, state: .sending, write: write)) |
| await deliver(write.key) |
| } |
| @@ -347,7 +353,7 @@ public final class EquipoSession { |
| public func retry(_ id: String) async { |
| if let i = outgoing.firstIndex(where: { $0.id == id }), outgoing[i].goneProject { |
| // A definitive 404 rejected this send. A changed body is a new operation. |
| - guard let write = try? EquipoClient.message(outgoing[i].text) else { return } |
| + guard let write = try? EquipoClient.message(outgoing[i].text, attachments: outgoing[i].attachments.map(\.id)) else { return } |
| outgoing[i].write = write; outgoing[i].projectName = nil; outgoing[i].goneProject = false |
| } |
| await deliver(id) |
| @@ -384,8 +390,8 @@ public final class EquipoSession { |
| // A proxy 404, another API code, or a missing task is not evidence about that project. |
| if case .server(404, let body) = error, body.code == "not_found", body.copyKey == "api.not_found", |
| item.taskID == nil, |
| - let fields = try? JSONSerialization.jsonObject(with: item.write.body) as? [String: String], |
| - let project = fields["project_id"], !project.isEmpty { |
| + let fields = try? JSONSerialization.jsonObject(with: item.write.body) as? [String: Any], |
| + let project = fields["project_id"] as? String, !project.isEmpty { |
| outgoing[i].goneProject = true |
| outgoing[i].projectName = nil |
| outgoing[i].notice = EquipoStrings.text("projects.selection_lost") |
| @@ -496,6 +502,7 @@ public final class EquipoSession { |
| revocationTransport = transport |
| client = EquipoClient(transport: LifetimeTransport(inner: transport, lifetime: lifetime), token: account.credential?.token) |
| projectCatalog.client = client |
| + attachments.client = client |
| if status == .signedOut { status = .loading } |
| } |
| @@ -510,6 +517,7 @@ public final class EquipoSession { |
| /// not prevent a completed network response from reaching persistence. |
| func invalidate() { |
| lifetime.end() |
| + attachments.clear() |
| markdown.removeAll() |
| status = .signedOut |
| drafts = [:] |
diff --git a/native/apple/Sources/EquipoKit/UI/RosterViews.swift b/native/apple/Sources/EquipoKit/UI/RosterViews.swift| index 79e81cc3..a435a483 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/RosterViews.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/RosterViews.swift |
| @@ -562,14 +562,20 @@ public struct CoordinatorMessage: View { |
| } |
| struct OwnMessage: View { |
| let text: String |
| + var attachments: [MessageAttachment] = [] |
| + var client: EquipoClient? = nil |
| var body: some View { |
| - Text(text).font(Typo.message).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + VStack(alignment: .trailing, spacing: 8) { |
| + if !attachments.isEmpty, let client { MessageAttachments(attachments, client: client) } |
| + if !text.isEmpty { Text(text).font(Typo.message).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true) |
| + .accessibilityLabel(Text(String(localized: "message.own_spoken \(text)", bundle: .module))) } |
| + } |
| .padding(.horizontal, 14).padding(.vertical, 10) |
| .background(Palette.soft, in: RoundedRectangle(cornerRadius: 18, style: .continuous)) |
| .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Palette.lightRim.opacity(0.7), lineWidth: 1)) |
| .padding(.leading, 48) |
| .frame(maxWidth: .infinity, alignment: .trailing) |
| - .accessibilityLabel(Text(String(localized: "message.own_spoken \(text)", bundle: .module))) |
| + .accessibilityElement(children: .contain) |
| } |
| } |
| /// One line: the mark, the real activity, elapsed time and a quiet Stop. |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift| index dce40e57..8db46c80 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift |
| @@ -43,7 +43,7 @@ public struct ConversationScreen: View { |
| .safeAreaInset(edge: .bottom, spacing: 0) { |
| VStack(spacing: 0) { |
| ProjectSelectionChip(catalog: session.projectCatalog) |
| - Composer(placeholder: String(localized: "conversation.placeholder", bundle: .module)) { text in |
| + Composer(placeholder: String(localized: "conversation.placeholder", bundle: .module), attachments: session.attachments) { text in |
| _ = sendFromComposer(text) |
| } |
| } |
| @@ -75,8 +75,8 @@ public struct ConversationScreen: View { |
| } else { |
| switch item { |
| case .draft, .coordinator, .notice: EmptyView() |
| - case .own(let m): OwnMessage(text: m.text) |
| - case .outgoing(let o): OutgoingMessage(item: o) { Task { await session.retry(o.id) } } |
| + case .own(let m): OwnMessage(text: m.text, attachments: m.attachments ?? [], client: session.client) |
| + case .outgoing(let o): OutgoingMessage(item: o, client: session.client) { Task { await session.retry(o.id) } } |
| case .report(_, let byline, let report, let compact): |
| VStack(alignment: .leading, spacing: 8) { |
| Byline(byline: byline) |
| @@ -104,11 +104,12 @@ public struct ConversationScreen: View { |
| /// A message this device is still sending, and how it is going. |
| struct OutgoingMessage: View { |
| let item: EquipoSession.Outgoing |
| + var client: EquipoClient? = nil |
| var retry: () -> Void |
| var body: some View { |
| VStack(alignment: .trailing, spacing: 4) { |
| if let project = item.projectName { ProjectChip(name: project) } |
| - OwnMessage(text: item.text).opacity(item.state == .sending ? 0.7 : 1) |
| + OwnMessage(text: item.text, attachments: item.attachments, client: client).opacity(item.state == .sending ? 0.7 : 1) |
| if let notice = item.notice { Text(notice).font(Typo.secondary).foregroundStyle(Palette.negative) } |
| switch item.state { |
| case .sending: Text(String(localized: "message.sending", bundle: .module)).font(Typo.caption).foregroundStyle(Palette.faint) |
| @@ -127,13 +128,19 @@ struct OutgoingMessage: View { |
| /// The composer: a pill with a send button centred in it. |
| struct Composer: View { |
| let placeholder: String |
| + var attachments: AttachmentDraft? = nil |
| var onSend: (String) -> Void |
| @State private var text = "" |
| @FocusState private var focused: Bool |
| var body: some View { |
| - let has = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| + let has = attachments?.canSend(text: text) ?? !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| let shape = RoundedRectangle(cornerRadius: 22, style: .continuous) |
| - HStack(alignment: .bottom, spacing: 0) { |
| + VStack(spacing: 4) { |
| + if let attachments { AttachmentDraftStrip(draft: attachments) } |
| + HStack(alignment: .bottom, spacing: 0) { |
| + #if os(iOS) |
| + if let attachments { PhoneAttachmentPicker(draft: attachments) } |
| + #endif |
| TextField("", text: $text, prompt: Text(placeholder).foregroundColor(Palette.placeholder), axis: .vertical) |
| .font(Typo.body).foregroundStyle(Palette.controlText).textFieldStyle(.plain) |
| .lineLimit(1...6).focused($focused) |
| @@ -152,13 +159,14 @@ struct Composer: View { |
| } |
| .background(Palette.surface, in: shape) |
| .overlay(shape.strokeBorder(focused ? Palette.accent : Palette.controlBorder, lineWidth: 1)) |
| + } |
| .padding(.horizontal, 16).padding(.top, 10).padding(.bottom, 8) |
| .frame(maxWidth: 760).frame(maxWidth: .infinity) |
| .background(.bar) |
| } |
| private func send() { |
| let value = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| - guard !value.isEmpty else { return } |
| + guard attachments?.canSend(text: value) ?? !value.isEmpty else { return } |
| onSend(value); text = "" |
| } |
| } |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift| index 849710e5..86bf0d9d 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/PhoneRoot.swift |
| @@ -9,6 +9,18 @@ public struct PhoneRoot: View { |
| public init(model: EquipoAppModel = EquipoAppModel()) { _model = State(initialValue: model) } |
| public var body: some View { |
| + Group { |
| + #if DEBUG |
| + if ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { AttachmentsFixture() } |
| + else { signedInContent } |
| + #else |
| + signedInContent |
| + #endif |
| + } |
| + .tint(Palette.accent) |
| + } |
| + |
| + @ViewBuilder private var signedInContent: some View { |
| Group { |
| if let session = model.session, session.status != .signedOut { |
| PhoneTabs(model: model, session: session) |
diff --git a/native/apple/Sources/EquipoMac/EquipoMacApp.swift b/native/apple/Sources/EquipoMac/EquipoMacApp.swift| index 1b8cb729..9fd262c9 100644 |
| --- a/native/apple/Sources/EquipoMac/EquipoMacApp.swift |
| +++ b/native/apple/Sources/EquipoMac/EquipoMacApp.swift |
| @@ -19,7 +19,7 @@ import SwiftUI |
| #if DEBUG |
| // Offline fixture captures must run this build, without an updater |
| // replacing it with a published app during the capture. |
| - if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil { return nil } |
| + if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { return nil } |
| #endif |
| return NativeUpdater(policy: .quiet) |
| }() |
| @@ -31,6 +31,7 @@ import SwiftUI |
| #if DEBUG |
| if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"]?.hasPrefix("conversation-") == true { StoppedConversationFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil { StoppedWorkFixture() } |
| + else if ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { MacAttachmentsFixture() } |
| else { MacRoot(model: model) } |
| #else |
| MacRoot(model: model) |
diff --git a/native/apple/Sources/EquipoMac/LiveTranscript.swift b/native/apple/Sources/EquipoMac/LiveTranscript.swift| index c28db873..b3fa495d 100644 |
| --- a/native/apple/Sources/EquipoMac/LiveTranscript.swift |
| +++ b/native/apple/Sources/EquipoMac/LiveTranscript.swift |
| @@ -70,6 +70,7 @@ final class LiveTranscript: NSView { |
| addSubview(scroll) |
| addSubview(composer) |
| addSubview(selectionHost) |
| + composer.attach(session.attachments) |
| composer.onHeightChange = { [weak self] in self?.needsLayout = true } |
| composer.onSend = { [weak self] text in |
| guard let self else { return } |
| @@ -200,11 +201,12 @@ final class LiveTranscript: NSView { |
| } |
| switch item { |
| case .own(let message): |
| - place(ownBubble(message.text, width: width), x: width - ownWidth(message.text, width: width)) |
| + let bubble = ownBubble(message.text, attachments: message.attachments ?? [], width: width) |
| + place(bubble, x: width - bubble.frame.width) |
| case .coordinator, .draft, .notice: break |
| case .outgoing(let outgoing): |
| if let project = outgoing.projectName { place(makeText(project, MacType.caption, .webSecondary, width: width), gapAfter: 4) } |
| - let bubble = ownBubble(outgoing.text, width: width) |
| + let bubble = ownBubble(outgoing.text, attachments: outgoing.attachments, width: width) |
| bubble.alphaValue = outgoing.state == .sending ? 0.6 : 1 |
| place(bubble, x: width - bubble.frame.width, gapAfter: 4) |
| if let notice = outgoing.notice { |
| @@ -259,7 +261,16 @@ final class LiveTranscript: NSView { |
| private func ownWidth(_ text: String, width: CGFloat) -> CGFloat { |
| makeText(text, MacType.line, .webText, width: min(width * 0.7, 520) - 28, lineSpacing: 2).frame.width + 28 |
| } |
| - private func ownBubble(_ value: String, width: CGFloat) -> NSView { |
| + private func ownBubble(_ value: String, attachments: [MessageAttachment] = [], width: CGFloat) -> NSView { |
| + if !attachments.isEmpty { |
| + let host = NSHostingView(rootView: VStack(alignment: .trailing, spacing: 8) { |
| + MessageAttachments(attachments, client: session.client) |
| + if !value.isEmpty { Text(value).textSelection(.enabled) } |
| + }.padding(14).frame(width: min(width * 0.8, 520)) |
| + .background(Color(nsColor: .webSoft), in: .rect(cornerRadius: 16))) |
| + host.frame.size = NSSize(width: min(width * 0.8, 520), height: ceil(host.fittingSize.height)) |
| + return host |
| + } |
| let label = makeText(value, MacType.line, .webText, width: min(width * 0.7, 520) - 28, lineSpacing: 2, selectable: true) |
| let card = PaintView(frame: NSRect(x: 0, y: 0, width: label.frame.width + 28, height: label.frame.height + 20)) { r in |
| let p = NSBezierPath(roundedRect: r.insetBy(dx: 0.5, dy: 0.5), xRadius: 16, yRadius: 16) |
diff --git a/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift b/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift| new file mode 100644 |
| index 00000000..5b60af8e |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift |
| @@ -0,0 +1,36 @@ |
| +#if DEBUG |
| +import AppKit |
| +import SwiftUI |
| +import EquipoKit |
| + |
| +struct MacAttachmentsFixture: NSViewRepresentable { |
| + func makeNSView(context: Context) -> LiveTranscript { |
| + let session = AttachmentsFixture.makeSession() |
| + let view = LiveTranscript(session: session, openTask: { _ in }) |
| + Task { @MainActor [weak view] in |
| + await session.refresh() |
| + guard let view else { return } |
| + view.update(items: Feed.build(session)) |
| + view.composer.setText("Home’s sign-in button is cut off on my phone.") |
| + // Same pasteboard entry point used by performDragOperation. |
| + let board = NSPasteboard.withUniqueName() |
| + board.setData(AttachmentsFixture.image, forType: .png) |
| + view.composer.acceptAttachments(board) |
| + board.releaseGlobally() |
| + try? await Task.sleep(for: .seconds(2)) |
| + guard let path = ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_CAPTURE"], |
| + let window = view.window, let content = window.contentView else { return } |
| + window.appearance = NSAppearance(named: .aqua) |
| + try? await Task.sleep(for: .milliseconds(200)) |
| + window.setContentSize(NSSize(width: 1000, height: 760)) |
| + content.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| + if let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) { |
| + content.cacheDisplay(in: content.bounds, to: bitmap) |
| + _ = FileManager.default.createFile(atPath: path, contents: bitmap.representation(using: .png, properties: [:])) |
| + } |
| + } |
| + return view |
| + } |
| + func updateNSView(_ view: LiveTranscript, context: Context) {} |
| +} |
| +#endif |
diff --git a/native/apple/Sources/EquipoMac/MacComposer.swift b/native/apple/Sources/EquipoMac/MacComposer.swift| index 7ff677ee..af449297 100644 |
| --- a/native/apple/Sources/EquipoMac/MacComposer.swift |
| +++ b/native/apple/Sources/EquipoMac/MacComposer.swift |
| @@ -1,11 +1,25 @@ |
| import AppKit |
| import EquipoKit |
| +import SwiftUI |
| +import Observation |
| /// The composer's text view: Return sends, Shift-Return starts a new line, |
| /// and an input method's marked text is never sent half typed. |
| final class ComposerEditor: NSTextView { |
| var onSubmit: (() -> Void)? |
| var placeholder = "" |
| + var onAttachments: ((NSPasteboard) -> Bool)? |
| + override func paste(_ sender: Any?) { |
| + if onAttachments?(NSPasteboard.general) != true { super.paste(sender) } |
| + } |
| + override func draggingEntered(_ sender: any NSDraggingInfo) -> NSDragOperation { |
| + if sender.draggingPasteboard.availableType(from: [.fileURL, .png, .tiff]) != nil { return .copy } |
| + return super.draggingEntered(sender) |
| + } |
| + override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool { |
| + if onAttachments?(sender.draggingPasteboard) == true { return true } |
| + return super.performDragOperation(sender) |
| + } |
| override func draw(_ dirtyRect: NSRect) { |
| super.draw(dirtyRect) |
| if string.isEmpty { |
| @@ -33,7 +47,7 @@ final class ComposerPill: NSView { |
| } |
| } |
| -/// The conversation's composer, text only in slice 1: a pill that grows to |
| +/// The conversation's composer: attachments above a pill that grows to |
| /// six lines, then scrolls, with a 44-point send target centred on its last |
| /// line. |
| final class MacComposer: NSView, NSTextViewDelegate { |
| @@ -46,6 +60,48 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| var onHeightChange: (() -> Void)? |
| private(set) var desiredHeight: CGFloat = 44 |
| private var updating = false |
| + private var draft: AttachmentDraft? |
| + private var attachmentHost: NSHostingView<AnyView>? |
| + private var attachmentHeight: CGFloat = 0 |
| + |
| + func attach(_ draft: AttachmentDraft) { |
| + self.draft = draft |
| + let host = NSHostingView(rootView: AnyView(AttachmentDraftStrip(draft: draft).fixedSize(horizontal: false, vertical: true) |
| + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { [weak self] height in |
| + Task { @MainActor in |
| + guard let self, self.attachmentHeight != height else { return } |
| + self.attachmentHeight = height; self.refresh() |
| + } |
| + })) |
| + attachmentHost = host; addSubview(host) |
| + editor.registerForDraggedTypes([.fileURL, .png, .tiff]) |
| + editor.onAttachments = { [weak self] pasteboard in self?.acceptAttachments(pasteboard) ?? false } |
| + observeDraft() |
| + } |
| + |
| + @discardableResult func acceptAttachments(_ pasteboard: NSPasteboard) -> Bool { |
| + guard let draft else { return false } |
| + 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 |
| + } |
| + |
| + private func observeDraft() { |
| + withObservationTracking { |
| + _ = draft?.items; _ = draft?.notice |
| + } onChange: { [weak self] in |
| + Task { @MainActor in self?.refresh(); self?.observeDraft() } |
| + } |
| + refresh() |
| + } |
| init() { |
| super.init(frame: .zero) |
| @@ -81,7 +137,7 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| required init?(coder: NSCoder) { fatalError() } |
| var text: String { editor.string } |
| - private var canSend: Bool { !editor.string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } |
| + private var canSend: Bool { draft?.canSend(text: editor.string) ?? !editor.string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } |
| func textDidChange(_ notification: Notification) { refresh() } |
| func textDidBeginEditing(_ notification: Notification) { pill.needsDisplay = true } |
| @@ -91,7 +147,7 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| func submit() { |
| let value = editor.string.trimmingCharacters(in: .whitespacesAndNewlines) |
| - guard !value.isEmpty else { return } |
| + guard canSend else { return } |
| editor.string = ""; editor.needsDisplay = true |
| refresh(); onSend?(value) |
| window?.makeFirstResponder(editor) |
| @@ -115,13 +171,15 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| let used = editor.layoutManager?.usedRect(for: editor.textContainer!).height ?? 24 |
| let contentHeight = max(24, ceil(used)) |
| let height = min(164, contentHeight + 20) |
| - pill.frame = NSRect(x: 0, y: 0, width: pillWidth, height: height) |
| + attachmentHost?.frame = NSRect(x: 0, y: 0, width: pillWidth, height: attachmentHeight) |
| + let attachmentSpace = attachmentHeight > 0 ? attachmentHeight + 8 : 0 |
| + pill.frame = NSRect(x: 0, y: attachmentSpace, width: pillWidth, height: height) |
| textScroll.frame = NSRect(x: 0, y: 10, width: editorWidth, height: height - 20) |
| editor.frame.size = NSSize(width: editorWidth, height: contentHeight) |
| textScroll.hasVerticalScroller = contentHeight > 144 |
| send.frame = NSRect(x: pillWidth - 44, y: height - 44, width: 44, height: 44) |
| - let changed = desiredHeight != height |
| - desiredHeight = height |
| + let changed = desiredHeight != height + attachmentSpace |
| + desiredHeight = height + attachmentSpace |
| updating = false |
| if changed { onHeightChange?() } |
| } |
diff --git a/native/apple/Tests/EquipoKitTests/AttachmentHTTPTests.swift b/native/apple/Tests/EquipoKitTests/AttachmentHTTPTests.swift| new file mode 100644 |
| index 00000000..8c47d60c |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/AttachmentHTTPTests.swift |
| @@ -0,0 +1,72 @@ |
| +#if os(macOS) |
| +import Foundation |
| +import Synchronization |
| +import Testing |
| +@testable import EquipoKit |
| + |
| +/// A loopback fake server exercises URLSession's raw upload and progress |
| +/// delegate, then resolves message attachment ids to the coordinator's bytes. |
| +@Suite struct AttachmentHTTPTests { |
| + @Test func imageReachesCoordinatorOverHTTP() async throws { |
| + let process = Process(), output = Pipe() |
| + process.executableURL = URL(fileURLWithPath: "/usr/bin/python3") |
| + process.standardOutput = output |
| + let sent: Sent = try Fixture.decode("thin/sent") |
| + let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| + process.arguments = ["-u", "-c", Self.server, |
| + AttachmentServer.attachment, |
| + String(decoding: try encoder.encode(sent), as: UTF8.self)] |
| + try process.run() |
| + defer { process.terminate(); process.waitUntilExit() } |
| + var port = Data() |
| + while let byte = try output.fileHandleForReading.read(upToCount: 1), !byte.isEmpty { |
| + if byte == Data([10]) { break }; port.append(byte) |
| + } |
| + let origin = try #require(URL(string: "http://127.0.0.1:" + String(decoding: port, as: UTF8.self))) |
| + let client = EquipoClient(transport: URLSessionTransport(origin: origin, observe: { _ in }), token: "fixture-http") |
| + let file = try AttachmentFile.prepare(AttachmentTests.image(width: 512, height: 512), name: "screen.png") |
| + let progress = Mutex<[Double]>([]) |
| + let attachment = try await client.upload(file) { value in progress.withLock { $0.append(value) } } |
| + let response = try await client.send(EquipoClient.message("", attachments: [attachment.id])) |
| + #expect(response.message.attachments?.first?.id == attachment.id) |
| + #expect(try await client.attachmentData(attachment.id) == file.data) |
| + #expect(progress.withLock { $0.contains { $0 > 0 && $0 <= 1 } }) |
| + } |
| + |
| + static let server = #""" |
| +import http.server,json,sys |
| +attachment=json.loads(sys.argv[1]); sent=json.loads(sys.argv[2]) |
| +uploaded=b''; delivered=b'' |
| +class Handler(http.server.BaseHTTPRequestHandler): |
| + def log_message(self,*args): pass |
| + def answer(self,status,data,kind='application/json'): |
| + self.send_response(status); self.send_header('Content-Type',kind) |
| + self.send_header('Content-Length',str(len(data))); self.end_headers(); self.wfile.write(data) |
| + def do_POST(self): |
| + global uploaded,delivered |
| + body=self.rfile.read(int(self.headers.get('Content-Length','0'))) |
| + if self.headers.get('Authorization')!='Bearer fixture-http' or self.headers.get('Cookie'): |
| + return self.answer(403,b'{}') |
| + if self.path=='/api/v1/attachments': |
| + if self.headers.get('Content-Type')!='image/png' or not body.startswith(bytes([137])+b'PNG'): |
| + return self.answer(415,b'{}') |
| + uploaded=body |
| + return self.answer(201,json.dumps(attachment).encode()) |
| + if self.path=='/api/v1/messages': |
| + message=json.loads(body) |
| + if message.get('attachments')!=[attachment['id']] or not uploaded: |
| + return self.answer(422,b'{}') |
| + delivered=uploaded |
| + sent['message']['attachments']=[attachment] |
| + return self.answer(201,json.dumps(sent).encode()) |
| + self.answer(404,b'{}') |
| + def do_GET(self): |
| + if self.path=='/api/v1/attachments/'+attachment['id']: |
| + return self.answer(200,delivered,'image/png') |
| + self.answer(404,b'{}') |
| +server=http.server.HTTPServer(('127.0.0.1',0),Handler) |
| +print(server.server_address[1],flush=True) |
| +server.serve_forever() |
| +"""# |
| +} |
| +#endif |
diff --git a/native/apple/Tests/EquipoKitTests/AttachmentTests.swift b/native/apple/Tests/EquipoKitTests/AttachmentTests.swift| new file mode 100644 |
| index 00000000..e2c0ca98 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/AttachmentTests.swift |
| @@ -0,0 +1,185 @@ |
| +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<String, Error> { 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(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<APIResponse, Error>] = [] |
| + 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<String, Error> { AsyncThrowingStream { $0.finish() } } |
| +} |
diff --git a/native/apple/Tests/EquipoKitTests/MacAttachmentTests.swift b/native/apple/Tests/EquipoKitTests/MacAttachmentTests.swift| new file mode 100644 |
| index 00000000..158a7246 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/MacAttachmentTests.swift |
| @@ -0,0 +1,30 @@ |
| +#if os(macOS) |
| +import AppKit |
| +import Testing |
| +@testable import EquipoKit |
| +@testable import EquipoMac |
| + |
| +@MainActor @Suite struct MacAttachmentTests { |
| + @Test func pastedAndDroppedImagesUseTheDraftAndGateSend() async throws { |
| + let server = AttachmentServer() |
| + let draft = AttachmentDraft(client: EquipoClient(transport: server, token: "fixture")) |
| + let composer = MacComposer(); composer.attach(draft) |
| + let pasteboard = NSPasteboard.withUniqueName() |
| + defer { pasteboard.releaseGlobally() } |
| + pasteboard.setData(try AttachmentTests.image(), forType: .png) |
| + // Both NSTextView.paste and performDragOperation call this entry point. |
| + #expect(composer.acceptAttachments(pasteboard)) |
| + for _ in 0..<500 { |
| + if !draft.readyAttachments.isEmpty { break } |
| + try await Task.sleep(for: .milliseconds(10)) |
| + } |
| + #expect(draft.readyAttachments.count == 1) |
| + var sent: String? |
| + composer.onSend = { sent = $0 } |
| + composer.submit() |
| + #expect(sent == "") |
| + pasteboard.clearContents(); pasteboard.setString("ordinary text", forType: .string) |
| + #expect(!composer.acceptAttachments(pasteboard)) |
| + } |
| +} |
| +#endif |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index 174305ff..23de6ca9 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -56,6 +56,8 @@ targets: |
| CFBundleName: Equipo |
| # HTTPS only, through the system: exempt from export documentation. |
| ITSAppUsesNonExemptEncryption: false |
| + # COPY APPROVED (Luna, 2026-11-25): native.attach.camera_usage |
| + NSCameraUsageDescription: Use your camera to take a photo to attach to your message. |
| # Interface text is English in slice 1; dates and numbers follow the |
| # reader's locale through Foundation's format styles. |
| CFBundleLocalizations: |
diff --git a/native/scripts/check-parity.py b/native/scripts/check-parity.py| index 64023c8a..1a90115f 100755 |
| --- a/native/scripts/check-parity.py |
| +++ b/native/scripts/check-parity.py |
| @@ -22,7 +22,7 @@ for key in sorted(set(re.findall(r'"(work\.reason\.[^"]+)":', copy))): |
| if key not in strings: |
| problems.append(f'{key}: native must carry every reviewed stop reason') |
| for key, text in sorted(strings.items()): |
| - if not key.startswith(('chat.card.', 'chat.paste.', 'work.tl.', 'roster.', 'projects.', 'work.star.', 'api.', 'nav.projects', 'chat.connections.connected', 'counts.unavailable', 'team.close', 'work.pause.', 'work.reason.', 'work.needs.', 'chat.held.', 'work.hold.', 'work.stage.', 'time.', 'work.hold.run_now', 'work.recover')): |
| + if not key.startswith(('chat.card.', 'chat.paste.', 'chat.attach.', 'work.tl.', 'roster.', 'projects.', 'work.star.', 'api.', 'nav.projects', 'chat.connections.connected', 'counts.unavailable', 'team.close', 'work.pause.', 'work.reason.', 'work.needs.', 'chat.held.', 'work.hold.', 'work.stage.', 'time.', 'work.hold.run_now', 'work.recover')): |
| continue |
| found = re.findall(r'"' + re.escape(key) + r'":\s*"((?:[^"\\]|\\.)*)"', copy) |
| if len(found) != 1: |
diff --git a/native/scripts/strings.json b/native/scripts/strings.json| index 8afa74bb..0bc02699 100644 |
| --- a/native/scripts/strings.json |
| +++ b/native/scripts/strings.json |
| @@ -352,5 +352,23 @@ |
| "native.step.log_tail": "Last lines of the log", |
| "time.when_in": "%@ (%@)", |
| "team.close": "Close", |
| - "work.recover": "Recover" |
| + "work.recover": "Recover", |
| + "chat.attach.add": "Attach", |
| + "chat.attach.image": "Photo or image", |
| + "chat.attach.file": "File", |
| + "chat.attach.list": "Attachments", |
| + "chat.attach.remove": "Remove %@", |
| + "chat.attach.uploading": "Uploading…", |
| + "chat.attach.failed": "Could not upload. Try again.", |
| + "chat.attach.too_many": "At most 5 files in one message.", |
| + "api.attachment_too_large": "That file is over 10 MB.", |
| + "api.attachment_type": "Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files.", |
| + "api.attachment_heic": "HEIC photos cannot be read yet. Share it as a JPEG and try again.", |
| + "api.attachment_pixels": "That image is too large: at most 12,000 pixels on a side and 40 megapixels.", |
| + "api.attachment_limit": "Too many files are waiting to send. Send or remove some first.", |
| + "native.attach.photos": "Photos", |
| + "native.attach.camera": "Camera", |
| + "native.attach.files": "Files", |
| + "native.attach.paste": "Paste", |
| + "native.attach.camera_usage": "Use your camera to take a photo to attach to your message." |
| } |