oficina / base Public

The client's files: upload, remove, discard, read, download and send with files

Task 13 of the native slice 2 part 1 plan.

- AskSnapshot.canAttach decodes can_attach, false when missing.
- upload goes through the kit's NativeUploadTransport.upload to
  /ask/attachments and decodes 201. A refusal with a code throws
  AttachmentRefusal (attachment_too_large, _type, _heic, _pixels, _limit,
  and busy with its Retry-After); Base's plain-text 400 (its body deadline)
  is BaseAPIError.uploadFailed; 401 unauthenticated calls rejected (S1).
- deleteAttachment: 204 and 404 are done; 409 attachment_sent is
  .alreadySent.
- discard(ids:): five ids a call, best effort, never acting on a refused
  session (it runs as a session ends).
- attachmentData(id, preview:): bounded at 2 MiB for a preview, at the
  10 MiB file limit otherwise. downloadAttachment uses the transport's
  download.
- send(text, key, attachments:) repeats the field in order. On send,
  409 files:"unavailable" is .filesUnavailable and 422 files:"stale" is
  .filesStale; they come before the state, so neither reads as a phase.
- BaseClient conforms to AttachmentClient. AskModel's switches take the
  new cases as failures; Task 15 handles D5.

Gate: swift test -j 4 --filter BaseKitTests.ClientTests: 29 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary

Task 13: the files client
claude agent, operated by paul@keymail.dev d2bc4939610dbbf83ef311105f8ca4b61f7e6aeb parent 468e819
6 files changed, +238 −6
  • native/apple/Sources/BaseKit/API/Client.swift +98 −2
  • native/apple/Sources/BaseKit/API/Models.swift +5 −1
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +2 −2
  • native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift +3 −1
  • native/apple/Tests/BaseKitTests/ClientTests.swift +129 −0
  • native/apple/Tests/BaseKitTests/Fixtures/attachment.json +1 −0
diff --git a/native/apple/Sources/BaseKit/API/Client.swift b/native/apple/Sources/BaseKit/API/Client.swift
index 968ee73..1fa83e1 100644
--- a/native/apple/Sources/BaseKit/API/Client.swift
+++ b/native/apple/Sources/BaseKit/API/Client.swift
@@ -21,6 +21,16 @@ public enum BaseAPIError: Error, Sendable, Equatable {
case notOnThisBase
/// Store's and People's refusals, by their code.
case team(TeamRefusal)
+ /// An upload Base gave up on with a plain-text 400: its body didn't
+ /// arrive in time (a slow link). The chip offers Retry.
+ case uploadFailed
+ /// `409 attachment_sent` on Remove: the file went with a message.
+ case alreadySent
+ /// `409 {"files":"unavailable"}` on send (D5): the runner can't take
+ /// files now; nothing was stored, and Ask stays ready.
+ case filesUnavailable
+ /// `422 {"files":"stale"}` on send (D5): an upload is gone.
+ case filesStale
}
/// What Store and People refuse with (docs/api/base-native-v1.md).
@@ -111,8 +121,81 @@ public struct BaseClient: Sendable {
// MARK: Ask's writes (the forms ask.js posts)
- public func send(_ text: String, key: String) async throws(BaseAPIError) -> AskSent {
- try await post("/ask/messages", form: [("text", text), ("key", key)])
+ /// Ask's message, with the person's uploads' ids (repeated, in order).
+ public func send(_ text: String, key: String, attachments: [String] = []) async throws(BaseAPIError) -> AskSent {
+ try await post("/ask/messages", form: [("text", text)] + attachments.map { ("attachments", $0) } + [("key", key)])
+ }
+
+ // MARK: Files (docs/api/base-native-v1.md "Files")
+
+ /// The upload codes with words of their own, and Base's busy.
+ static let uploadCodes: Set<String> = ["attachment_too_large", "attachment_type", "attachment_heic", "attachment_pixels", "attachment_limit", "busy"]
+
+ /// `POST /ask/attachments`: one file, through the kit's upload. A refusal
+ /// with a code throws `AttachmentRefusal` (`busy` with its Retry-After);
+ /// Base's plain-text 400, `.uploadFailed`; anything else as every call.
+ public func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment {
+ let response: NativeResponse
+ do {
+ response = try await transport.upload("/ask/attachments", body: file.data, contentType: file.mediaType, filename: file.name,
+ maxBytes: nativeDefaultMaxBytes, progress: progress)
+ } catch {
+ throw await mapped(error)
+ }
+ if response.status == 201 || response.status == 200 {
+ do { return try JSONDecoder().decode(AskAttachment.self, from: response.data) } catch { throw BaseAPIError.badResponse }
+ }
+ let fields = (try? JSONSerialization.jsonObject(with: response.data)) as? [String: Any]
+ if let code = fields?["code"] as? String, Self.uploadCodes.contains(code) {
+ throw AttachmentRefusal(code: code, retryAfter: response.header("Retry-After").flatMap { Int($0.trimmingCharacters(in: .whitespaces)) })
+ }
+ if response.status == 400, fields == nil { throw BaseAPIError.uploadFailed }
+ throw await refused(status: response.status, body: response.data)
+ }
+
+ /// `DELETE /ask/attachments/{id}`: Remove. `204`, and `404` (gone
+ /// already), are done; one that went with a message is `.alreadySent`.
+ public func deleteAttachment(_ id: String) async throws(BaseAPIError) {
+ let response: NativeResponse
+ do { response = try await transport.responseDetails("/ask/attachments/\(Self.segment(id))", method: "DELETE", body: nil) } catch { throw await mapped(error) }
+ if (200..<300).contains(response.status) || response.status == 404 { return }
+ let fields = (try? JSONSerialization.jsonObject(with: response.data)) as? [String: Any]
+ if response.status == 409, fields?["code"] as? String == "attachment_sent" { throw .alreadySent }
+ throw await refused(status: response.status, body: response.data)
+ }
+
+ /// `POST /ask/attachments/discard`: unsent uploads, five a call, as best
+ /// Base can. Nothing is reported, and a refused session isn't acted on:
+ /// it runs as a session ends.
+ public func discard(ids: [String]) async {
+ for start in stride(from: 0, to: ids.count, by: 5) {
+ let chunk = ids[start..<min(start + 5, ids.count)].map { ("id", $0) }
+ _ = try? await transport.responseDetails("/ask/attachments/discard", method: "POST", body: Data(Self.form(Array(chunk)).utf8),
+ contentType: "application/x-www-form-urlencoded")
+ }
+ }
+
+ /// A preview's bound: Base's thumbnails are small.
+ public static let previewMaxBytes = 2 << 20
+
+ /// `GET /ask/attachments/{id}` (or its `/preview`): the bytes, bounded
+ /// at 2 MiB for a preview and at the file limit otherwise.
+ public func attachmentData(_ id: String, preview: Bool) async throws(BaseAPIError) -> Data {
+ let path = "/ask/attachments/\(Self.segment(id))" + (preview ? "/preview" : "")
+ let response: NativeResponse
+ do {
+ response = try await transport.responseDetails(path, method: "GET", body: nil,
+ maxBytes: preview ? Self.previewMaxBytes : AttachmentLimits.maxBytes)
+ } catch {
+ throw await mapped(error)
+ }
+ guard response.status == 200 else { throw await refused(status: response.status, body: response.data) }
+ return response.data
+ }
+
+ /// The file, streamed to `destination` by the kit (never replacing one).
+ public func downloadAttachment(_ id: String, to destination: URL) async throws(BaseAPIError) {
+ do { try await transport.download("/ask/attachments/\(Self.segment(id))", to: destination) } catch { throw await mapped(error) }
}
public func cancel(turn id: String, key: String) async throws(BaseAPIError) {
@@ -230,6 +313,12 @@ public struct BaseClient: Sendable {
await rejected()
return .unauthenticated
}
+ // D5: a send whose files couldn't go.
+ switch fields?["files"] as? String {
+ case "unavailable": return .filesUnavailable
+ case "stale": return .filesStale
+ default: break
+ }
return .server(status: status, code: code, state: state)
}
@@ -279,6 +368,13 @@ public struct BaseClient: Sendable {
}
}
+/// The draft's client is Base's.
+extension BaseClient: AttachmentClient {
+ public func delete(_ id: String) async throws { try await deleteAttachment(id) }
+ public func data(id: String, preview: Bool) async throws -> Data { try await attachmentData(id, preview: preview) }
+ public func download(id: String, to destination: URL) async throws { try await downloadAttachment(id, to: destination) }
+}
+
/// The SSE parser behind one stream, shared by its line callbacks.
actor SSEStream {
private var parser = SSEParser()
diff --git a/native/apple/Sources/BaseKit/API/Models.swift b/native/apple/Sources/BaseKit/API/Models.swift
index ce64636..9d7e9b8 100644
--- a/native/apple/Sources/BaseKit/API/Models.swift
+++ b/native/apple/Sources/BaseKit/API/Models.swift
@@ -335,8 +335,11 @@ public struct AskSnapshot: Decodable, Sendable, Equatable {
/// The member disconnected Ask (on any client) and hasn't set it up
/// again: no set-up by itself. Nil from a Base that doesn't say.
public var disconnected: Bool?
+ /// Whether files may be attached now: only in `ready`, when Equipo says
+ /// the person's runner can read them. False when the server says nothing.
+ public var canAttach: Bool
enum CodingKeys: String, CodingKey {
- case state, messages, jobs, cards, turn, status, cursor, disconnected
+ case state, messages, jobs, cards, turn, status, cursor, disconnected, canAttach = "can_attach"
case renewAfter = "renew_after", equipoOrigin = "equipo_origin"
}
public init(from decoder: Decoder) throws {
@@ -347,6 +350,7 @@ public struct AskSnapshot: Decodable, Sendable, Equatable {
status = c.value(.status, ""); cursor = c.value(.cursor, 0)
renewAfter = c.date(.renewAfter); equipoOrigin = c.webURL(.equipoOrigin)
disconnected = c.optional(.disconnected)
+ canAttach = c.value(.canAttach, false)
}
}
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index 8352a1a..3ae9810 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -395,7 +395,7 @@ import SwiftUI
static func tryAgain(_ error: BaseAPIError) -> Bool {
switch error {
case .unauthenticated: false
- case .offline, .badResponse, .notOnThisBase, .team: true
+ case .offline, .badResponse, .notOnThisBase, .team, .uploadFailed, .alreadySent, .filesUnavailable, .filesStale: true
case .server(let code, _, let state):
code != 409 && !(state.map { [.connect, .pending, .reconnect, .norunner, .oldrunner, .notLinked].contains(AskPhase(server: $0)) } ?? false)
}
@@ -421,7 +421,7 @@ import SwiftUI
} else if code != 409 {
status = BaseText.text("ask.not_sent")
}
- case .badResponse, .notOnThisBase, .team:
+ case .badResponse, .notOnThisBase, .team, .uploadFailed, .alreadySent, .filesUnavailable, .filesStale:
// An unreadable answer (or the request cancelled once it may
// have reached Base) leaves the outcome unknown: the key stays,
// so sending again is the same write.
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
index a99d610..9508f78 100644
--- a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
+++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
@@ -114,7 +114,9 @@ public protocol AttachmentClient: Sendable {
/// the draft shows the web's words for it.
public struct AttachmentRefusal: Error, Equatable, Sendable {
public let code: String
- public init(code: String) { self.code = code }
+ /// Base's `503 busy`: seconds to wait first.
+ public let retryAfter: Int?
+ public init(code: String, retryAfter: Int? = nil) { self.code = code; self.retryAfter = retryAfter }
/// The codes with words of their own, and their catalog keys.
static let keys = ["attachment_too_large": "native.attach.too_large", "attachment_pixels": "native.attach.pixels",
"attachment_type": "native.attach.type", "attachment_heic": "native.attach.heic",
diff --git a/native/apple/Tests/BaseKitTests/ClientTests.swift b/native/apple/Tests/BaseKitTests/ClientTests.swift
index e4041a0..30f9538 100644
--- a/native/apple/Tests/BaseKitTests/ClientTests.swift
+++ b/native/apple/Tests/BaseKitTests/ClientTests.swift
@@ -228,3 +228,132 @@ extension ClientTests {
XCTAssertEqual(rejections.count, 2)
}
}
+
+/// Task 13: files over Base's relay (docs/api/base-native-v1.md "Files").
+extension ClientTests {
+ func file(_ name: String = "Shopfront.jpg") -> AttachmentFile {
+ AttachmentFile(data: Data(repeating: 7, count: 100), name: name, mediaType: "image/jpeg", width: 2, height: 2)
+ }
+
+ func testCanAttachDecodesAndIsFalseWhenMissing() throws {
+ let with = try JSONDecoder().decode(AskSnapshot.self, from: Data(#"{"state":"ready","can_attach":true}"#.utf8))
+ XCTAssertTrue(with.canAttach)
+ let without = try JSONDecoder().decode(AskSnapshot.self, from: Data(#"{"state":"ready"}"#.utf8))
+ XCTAssertFalse(without.canAttach)
+ }
+
+ func testUploadGoesThroughTheTransportsUploadAndDecodes() async throws {
+ let t = ScriptedTransport([.respond(status: 201, body: Fixture.data("attachment.json"))])
+ let uploaded = try await client(t).upload(file("Shop front.jpg")) { _ in }
+ XCTAssertEqual(uploaded, AskAttachment(id: "at_1", kind: "image", name: "Shopfront.jpg", mediaType: "image/jpeg", size: 2_100_000, width: 2560, height: 1920))
+ let call = try XCTUnwrap(t.calls.first)
+ XCTAssertEqual(call.kind, .upload)
+ XCTAssertEqual(call.path, "/ask/attachments")
+ XCTAssertEqual(call.filename, "Shop front.jpg")
+ XCTAssertEqual(call.contentType, "image/jpeg")
+ XCTAssertEqual(call.body?.count, 100)
+ }
+
+ func testUploadRefusalsCarryTheirCodes() async throws {
+ let steps: [ScriptedTransport.Step] = [json(413, #"{"code":"attachment_too_large"}"#), json(415, #"{"code":"attachment_type"}"#),
+ json(415, #"{"code":"attachment_heic"}"#), json(413, #"{"code":"attachment_pixels"}"#),
+ json(409, #"{"code":"attachment_limit"}"#),
+ .respond(status: 503, body: Data(#"{"code":"busy"}"#.utf8), headers: ["Retry-After": "7"])]
+ let c = client(ScriptedTransport(steps))
+ var got: [AttachmentRefusal] = []
+ for _ in steps {
+ do { _ = try await c.upload(file()) { _ in }; XCTFail("no refusal") } catch let refusal as AttachmentRefusal { got.append(refusal) }
+ }
+ XCTAssertEqual(got.map(\.code), ["attachment_too_large", "attachment_type", "attachment_heic", "attachment_pixels", "attachment_limit", "busy"])
+ XCTAssertEqual(got.last?.retryAfter, 7)
+ XCTAssertNil(got.first?.retryAfter)
+ }
+
+ /// Base's body deadline on a slow link answers a plain-text 400.
+ func testAPlainTextFourHundredIsAFailedUpload() async {
+ let c = client(ScriptedTransport([.respond(status: 400, body: Data("bad request\n".utf8))]))
+ do { _ = try await c.upload(file()) { _ in }; XCTFail("no error") } catch { XCTAssertEqual(error as? BaseAPIError, .uploadFailed) }
+ }
+
+ func testAnUploadBaseRefusesTellsTheKit() async {
+ let rejections = Rejections()
+ let c = client(ScriptedTransport([json(401, #"{"code":"unauthenticated"}"#), .offline(),
+ json(409, #"{"state":"reconnect"}"#)]), rejections)
+ do { _ = try await c.upload(file()) { _ in } } catch { XCTAssertEqual(error as? BaseAPIError, .unauthenticated) }
+ XCTAssertEqual(rejections.count, 1)
+ do { _ = try await c.upload(file()) { _ in } } catch { XCTAssertEqual(error as? BaseAPIError, .offline) }
+ do { _ = try await c.upload(file()) { _ in } } catch { XCTAssertEqual(error as? BaseAPIError, .server(status: 409, code: nil, state: "reconnect")) }
+ }
+
+ func testDeleteIsDoneUnlessItWasSent() async throws {
+ let t = ScriptedTransport([.respond(status: 204), .respond(status: 404), json(409, #"{"state":"ready","code":"attachment_sent"}"#)])
+ let c = client(t)
+ try await c.deleteAttachment("at_1")
+ try await c.deleteAttachment("at/2")
+ await XCTAssertThrows(.alreadySent) { try await c.deleteAttachment("at_3") }
+ XCTAssertEqual(t.calls.map(\.method), ["DELETE", "DELETE", "DELETE"])
+ XCTAssertEqual(t.calls.map(\.path), ["/ask/attachments/at_1", "/ask/attachments/at%2F2", "/ask/attachments/at_3"])
+ }
+
+ func testDiscardSendsFiveIDsACall() async {
+ let t = ScriptedTransport(responder: { _ in .respond(status: 204) })
+ await client(t).discard(ids: (1...7).map { "at_\($0)" })
+ XCTAssertEqual(t.calls.map(\.path), ["/ask/attachments/discard", "/ask/attachments/discard"])
+ let first = String(decoding: t.calls[0].body ?? Data(), as: UTF8.self)
+ XCTAssertEqual(first, "id=at_1&id=at_2&id=at_3&id=at_4&id=at_5")
+ XCTAssertEqual(String(decoding: t.calls[1].body ?? Data(), as: UTF8.self), "id=at_6&id=at_7")
+ }
+
+ /// A discard is best effort: even Base refusing the session is dropped,
+ /// never a reason to sign in again (the session is ending anyway).
+ func testADiscardThatIsRefusedIsDroppedSilently() async {
+ let rejections = Rejections()
+ await client(ScriptedTransport([json(401, #"{"code":"unauthenticated"}"#)]), rejections).discard(ids: ["at_1"])
+ XCTAssertEqual(rejections.count, 0)
+ }
+
+ func testPreviewsAreBoundedAtTwoMiB() async throws {
+ let c = client(ScriptedTransport([.respond(status: 200, body: Data(repeating: 1, count: 2 << 20)),
+ .respond(status: 200, body: Data(repeating: 1, count: (2 << 20) + 1)),
+ .respond(status: 200, body: Data(repeating: 1, count: 5 << 20))]))
+ let fine = try await c.attachmentData("at_1", preview: true)
+ XCTAssertEqual(fine.count, 2 << 20)
+ do { _ = try await c.attachmentData("at_1", preview: true); XCTFail("an oversized preview passed") } catch {}
+ let original = try await c.attachmentData("at_1", preview: false)
+ XCTAssertEqual(original.count, 5 << 20, "a file itself is bounded at 10 MiB")
+ }
+
+ func testDownloadUsesTheTransportsDownload() async throws {
+ let t = ScriptedTransport([.respond(status: 200, body: Data("hello".utf8))])
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: url) }
+ try await client(t).downloadAttachment("at_1", to: url)
+ XCTAssertEqual(t.calls.first?.kind, .download)
+ XCTAssertEqual(t.calls.first?.path, "/ask/attachments/at_1")
+ XCTAssertEqual(try Data(contentsOf: url), Data("hello".utf8))
+ }
+
+ func testSendRepeatsTheAttachmentsInOrder() async throws {
+ let t = ScriptedTransport([json(200, #"{"message":{"id":"m1","role":"person","text":"","turn_id":"t1"},"turn":{"id":"t1","kind":"chat","state":"queued"}}"#)])
+ _ = try await client(t).send("", key: "k1", attachments: ["at_b", "at_a"])
+ XCTAssertEqual(String(decoding: t.calls[0].body!, as: UTF8.self), "text=&attachments=at_b&attachments=at_a&key=k1")
+ }
+
+ func testSendsFilesRefusalsAreTyped() async {
+ let c = client(ScriptedTransport([json(409, #"{"state":"ready","files":"unavailable"}"#), json(422, #"{"state":"ready","files":"stale"}"#)]))
+ await XCTAssertThrows(.filesUnavailable) { _ = try await c.send("hi", key: "k", attachments: ["at_1"]) }
+ await XCTAssertThrows(.filesStale) { _ = try await c.send("hi", key: "k", attachments: ["at_1"]) }
+ }
+
+ /// BaseClient is the draft's client.
+ func testBaseClientIsAnAttachmentClient() async throws {
+ let t = ScriptedTransport([.respond(status: 201, body: Fixture.data("attachment.json")), .respond(status: 204),
+ .respond(status: 200, body: Data("p".utf8))])
+ let c: any AttachmentClient = client(t)
+ _ = try await c.upload(file()) { _ in }
+ try await c.delete("at_1")
+ let preview = try await c.data(id: "at_1", preview: true)
+ XCTAssertEqual(preview, Data("p".utf8))
+ XCTAssertEqual(t.calls.map(\.path), ["/ask/attachments", "/ask/attachments/at_1", "/ask/attachments/at_1/preview"])
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/Fixtures/attachment.json b/native/apple/Tests/BaseKitTests/Fixtures/attachment.json
new file mode 100644
index 0000000..88f99f4
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/Fixtures/attachment.json
@@ -0,0 +1 @@
+{"id":"at_1","revision":1,"kind":"image","name":"Shopfront.jpg","media_type":"image/jpeg","size":2100000,"sha256":"x","width":2560,"height":1920,"message_id":"","created_at":"2026-11-28T10:00:00Z"}