oficina / base Public

The draft's rules: Remove deletes, two at a time, busy retried, discard at sign-out, uploads in the background

Task 14 of the native slice 2 part 1 plan (P8.1 to P8.5).

- P8.1: Remove takes the chip away at once and deletes the upload; one
  that went with a message (.alreadySent), or any failure to delete, just
  goes, with nothing shown. Remove waits while a send is in flight
  (draft.sending, canRemove).
- P8.2: AttachGate admits two files at a time, in the order they were
  added, from preparing through to their upload's answer. A sixth file is
  refused with the web's words.
- P8.3: a 503 busy is retried three times, after max(Retry-After, 2, 4,
  8 s), each a fresh try with its ring from 0; then the chip says "Too many
  uploads at once. Try again in a moment." with Retry.
- P8.4: BaseSession.end() reads the draft's unsent ids and keeps the old
  client before anything is cleared, then discards them (five a call) in a
  task given up after 2 s, never holding end() up. The bound holds even
  for a transport that ignores cancellation (a task group would wait). A
  refused discard is dropped silently (the client's). Nothing is
  discarded in the background.
- P8.5: an upload in flight runs as a background task (BackgroundWork:
  UIApplication's on the iPhone, nothing on the Mac). Its expiry cancels
  the upload and the chip offers Retry. In the background the gate admits
  nothing new, so queued files wait for the foreground. A lost answer
  offers Retry.
- A PDF's chip says the web's "Ask can’t read PDFs yet."
- AskModel owns the draft (attachments), cleared on dispose.
- The copied Equipo test disabled for Task 14 is turned around: two at a
  time, Remove cancelling.

Gate: swift test -j 4 --filter 'AttachmentDraftTests|SessionTests|Attachment|MacAttachment':
12 + 25 XCTests and 20 Swift Testing tests passed (AttachmentDraftTests
three times over); build-iphone.sh simulator succeeded.

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

Summary

Task 14: the draft's rules
claude agent, operated by paul@keymail.dev 02240f8e5baf697b996cb73d00e28b0fb67cab93 parent d2bc493
7 files changed, +544 −27
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +4 −0
  • native/apple/Sources/BaseKit/Attachments/AttachGate.swift +91 −0
  • native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift +84 −15
  • native/apple/Sources/BaseKit/Resources/Localizable.xcstrings +24 −0
  • native/apple/Sources/BaseKit/Session/BaseSession.swift +39 −0
  • native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift +279 −0
  • native/apple/Tests/BaseKitTests/AttachmentTests.swift +23 −12
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index 3ae9810..e7bef6f 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -113,6 +113,8 @@ import SwiftUI
// MARK: Wiring
let client: BaseClient
+ /// The files waiting to go with the next message (slice 2).
+ public let attachments: AttachmentDraft
/// Runs `body` after `delay` (tests run it at once, or never).
let schedule: @MainActor (Duration, @escaping @MainActor () -> Void) -> Void
/// Says a line to VoiceOver once (a failed Carry on now's; tests record
@@ -123,6 +125,7 @@ import SwiftUI
schedule: @escaping @MainActor (Duration, @escaping @MainActor () -> Void) -> Void = AskModel.later,
announce: @escaping @MainActor (String) -> Void = AskModel.announce) {
self.client = client
+ self.attachments = AttachmentDraft(client: client)
self.schedule = schedule
self.announce = announce
}
@@ -195,6 +198,7 @@ import SwiftUI
/// Signed out, or another account: this model is done for good.
public func dispose() {
pause()
+ attachments.clear()
disposed = true
}
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachGate.swift b/native/apple/Sources/BaseKit/Attachments/AttachGate.swift
new file mode 100644
index 0000000..f8cf0ae
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Attachments/AttachGate.swift
@@ -0,0 +1,91 @@
+import Foundation
+#if os(iOS)
+import UIKit
+#endif
+
+/// One gate for preparing and uploading (plan P8.2, S8): two files at a
+/// time, admitted in the order they were added, from preparing through to
+/// their upload's answer. Five 48 MP photos picked at once never decode
+/// together. While the app is in the background it admits nothing new, so
+/// files still queued wait for the foreground rather than fail (P8.5).
+@MainActor final class AttachGate {
+ let capacity: Int
+ private var active = 0
+ private var paused = false
+ private var waiters: [(id: UUID, resume: CheckedContinuation<Void, Error>)] = []
+
+ init(capacity: Int = 2) { self.capacity = capacity }
+
+ func acquire() async throws {
+ if !paused, active < capacity, waiters.isEmpty { active += 1; return }
+ let id = UUID()
+ try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in
+ if Task.isCancelled { c.resume(throwing: CancellationError()) } else { waiters.append((id, c)) }
+ }
+ } onCancel: {
+ Task { @MainActor in self.cancel(id) }
+ }
+ }
+
+ func release() {
+ active -= 1
+ admit()
+ }
+
+ func pause() { paused = true }
+ func resume() { paused = false; admit() }
+
+ private func admit() {
+ while !paused, active < capacity, !waiters.isEmpty {
+ let next = waiters.removeFirst()
+ active += 1
+ next.resume.resume()
+ }
+ }
+
+ private func cancel(_ id: UUID) {
+ guard let i = waiters.firstIndex(where: { $0.id == id }) else { return }
+ waiters.remove(at: i).resume.resume(throwing: CancellationError())
+ }
+}
+
+/// Lets an upload in flight finish after the app goes to the background
+/// (P8.5): the iPhone's `beginBackgroundTask`; nothing on the Mac.
+@MainActor public protocol BackgroundWork {
+ /// Starts background time; `expired` runs if the system ends it first.
+ func begin(expired: @escaping @MainActor () -> Void) -> Int
+ func end(_ token: Int)
+}
+
+/// The Mac's: an app there keeps running in the background.
+public struct NoBackgroundWork: BackgroundWork {
+ public init() {}
+ public func begin(expired: @escaping @MainActor () -> Void) -> Int { 0 }
+ public func end(_ token: Int) {}
+}
+
+#if os(iOS)
+/// The iPhone's: UIApplication's background tasks.
+public struct ApplicationBackgroundWork: BackgroundWork {
+ /// Tasks the system expired, which were ended there and then.
+ @MainActor private static var expired: Set<Int> = []
+ public init() {}
+ public func begin(expired: @escaping @MainActor () -> Void) -> Int {
+ var task = UIBackgroundTaskIdentifier.invalid
+ task = UIApplication.shared.beginBackgroundTask(withName: "Base upload") {
+ MainActor.assumeIsolated {
+ expired()
+ Self.expired.insert(task.rawValue)
+ UIApplication.shared.endBackgroundTask(task)
+ }
+ }
+ return task.rawValue
+ }
+ public func end(_ token: Int) {
+ let task = UIBackgroundTaskIdentifier(rawValue: token)
+ guard task != .invalid, Self.expired.remove(token) == nil else { return }
+ UIApplication.shared.endBackgroundTask(task)
+ }
+}
+#endif
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
index 9508f78..31dcc0d 100644
--- a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
+++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
@@ -12,6 +12,8 @@ import Observation
public let name: String
public var state: State
public var file: AttachmentFile?
+ /// A line under the chip that isn't a failure: a PDF's.
+ public var note: String?
var generation = UUID()
var source: Source
public var failure: String? { if case .failed(let words) = state { return words }; return nil }
@@ -24,7 +26,30 @@ import Observation
deinit { for directory in stagedDirectories.values { try? FileManager.default.removeItem(at: directory) } }
@ObservationIgnored var fileAccess: any AttachmentFileAccess = SystemAttachmentFileAccess()
var client: any AttachmentClient
- public init(client: any AttachmentClient) { self.client = client }
+ /// Base: two at a time, preparing and uploading (P8.2).
+ @ObservationIgnored let gate = AttachGate()
+ @ObservationIgnored let background: any BackgroundWork
+ @ObservationIgnored let sleep: @MainActor (Duration) async throws -> Void
+ /// Set by Ask while a message is sending: Remove waits (P8.1).
+ public var sending = false
+ public var canRemove: Bool { !sending }
+
+ public init(client: any AttachmentClient, background: (any BackgroundWork)? = nil,
+ sleep: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) {
+ self.client = client
+ #if os(iOS)
+ self.background = background ?? ApplicationBackgroundWork()
+ #else
+ self.background = background ?? NoBackgroundWork()
+ #endif
+ self.sleep = sleep
+ }
+
+ /// The uploads not sent yet, for the discard when the session ends.
+ public var unsentIDs: [String] { readyAttachments.map(\.id) }
+ /// The app went to the background: files still queued wait (P8.5).
+ public func suspend() { gate.pause() }
+ public func resume() { gate.resume() }
public var readyAttachments: [AskAttachment] { items.compactMap { if case .ready(let value) = $0.state { return value }; return nil } }
public func canSend(text: String) -> Bool {
@@ -53,7 +78,17 @@ import Observation
items.append(Item(id: id, name: name, state: .uploading(0), source: source))
await upload(id)
}
- public func remove(_ id: UUID) { uploads.removeValue(forKey: id)?.task.cancel(); items.removeAll { $0.id == id }; cleanStaged(id); notice = nil }
+ /// Remove: the chip goes at once and the upload is deleted (P8.1). One
+ /// that went with a message (`.alreadySent`), or any other failure to
+ /// delete, just goes: Equipo drops an unsent upload after 24 hours.
+ public func remove(_ id: UUID) {
+ guard canRemove, let item = items.first(where: { $0.id == id }) else { return }
+ uploads.removeValue(forKey: id)?.task.cancel(); items.removeAll { $0.id == id }; cleanStaged(id); notice = nil
+ if case .ready(let uploaded) = item.state {
+ let client = self.client
+ Task { try? await client.delete(uploaded.id) }
+ }
+ }
public func clear() { for upload in uploads.values { upload.task.cancel() }; uploads = [:]; items = []; for id in Array(stagedDirectories.keys) { cleanStaged(id) }; notice = nil }
private func cleanStaged(_ id: UUID) { if let directory = stagedDirectories.removeValue(forKey: id) { try? FileManager.default.removeItem(at: directory) } }
public func retry(_ id: UUID) async {
@@ -68,8 +103,15 @@ import Observation
await withTaskCancellationHandler { await task.value } onCancel: { task.cancel() }
if uploads[id]?.generation == generation { uploads[id] = nil }
}
+ /// Base's upload (P8.2, P8.3, P8.5): behind the gate, preparing and
+ /// uploading; as a background task; a busy Base retried three times.
private func performUpload(_ id: UUID) async {
guard let item = items.first(where: { $0.id == id }) else { return }
+ do { try await gate.acquire() } catch { return }
+ defer { gate.release() }
+ guard index(id, item.generation) != nil else { return }
+ let token = background.begin { [weak self] in self?.expire(id, item.generation) }
+ defer { background.end(token) }
do {
let file = try await Task.detached {
let bytes: Data
@@ -79,25 +121,52 @@ import Observation
try Task.checkCancellation()
guard let i = index(id, item.generation) else { return }
items[i].file = file
- let attachment = try await client.upload(file) { [weak self] fraction in
- Task { @MainActor [weak self] in
- guard let self, let i = self.index(id, item.generation), case .uploading = self.items[i].state else { return }
- self.items[i].state = .uploading(fraction)
+ if file.mediaType == "application/pdf" { items[i].note = BaseText.text("native.attach.pdf") }
+ let backoff: [Duration] = [.seconds(2), .seconds(4), .seconds(8)]
+ var retries = 0
+ while true {
+ do {
+ 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)
+ return
+ } catch let refusal as AttachmentRefusal where refusal.code == "busy" && retries < backoff.count {
+ // A busy Base: wait, then a fresh try, its ring from 0.
+ try await sleep(max(backoff[retries], .seconds(refusal.retryAfter ?? 0)))
+ retries += 1
+ try Task.checkCancellation()
+ guard let i = index(id, item.generation) else { return }
+ items[i].state = .uploading(0)
}
}
- guard let i = index(id, item.generation) else { return }
- items[i].state = .ready(attachment)
} catch {
guard let i = index(id, item.generation) else { return }
- let words: String
- if let failure = error as? AttachmentFailure { words = failure.words }
- else if let code = (error as? AttachmentRefusal)?.code, let key = AttachmentRefusal.keys[code] {
- words = BaseText.text(key)
- }
- else { words = BaseText.text("native.attach.failed") }
- items[i].state = .failed(words)
+ items[i].state = .failed(Self.words(error))
}
}
+
+ /// The system is ending the app's background time: the upload stops
+ /// and its chip offers Retry.
+ private func expire(_ id: UUID, _ generation: UUID) {
+ guard uploads[id]?.generation == generation else { return }
+ uploads[id]?.task.cancel()
+ }
+
+ /// The web's words for a failure (chat.html data-w-*).
+ static func words(_ error: Error) -> String {
+ if let failure = error as? AttachmentFailure { return failure.words }
+ if let refusal = error as? AttachmentRefusal {
+ if refusal.code == "busy" { return BaseText.text("native.attach.busy") }
+ if let key = AttachmentRefusal.keys[refusal.code] { return BaseText.text(key) }
+ }
+ return BaseText.text("native.attach.failed")
+ }
+
private func index(_ id: UUID, _ generation: UUID) -> Int? { items.firstIndex { $0.id == id && $0.generation == generation } }
}
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
index 63bec22..c58736a 100644
--- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
@@ -553,6 +553,18 @@
}
}
},
+ "native.attach.busy": {
+ "comment": "Base on the web's approved copy (chat.html data-w-busy). A file's chip once Base was busy after three tries.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Too many uploads at once. Try again in a moment."
+ }
+ }
+ }
+ },
"native.attach.camera": {
"comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: take a photo. Equipo's approved label.",
"extractionState": "manual",
@@ -649,6 +661,18 @@
}
}
},
+ "native.attach.pdf": {
+ "comment": "Base on the web's approved copy (chat.html data-w-pdf). The line under a PDF's chip: it can be sent, but the Assistant can't read it yet.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ask can’t read PDFs yet."
+ }
+ }
+ }
+ },
"native.attach.photos": {
"comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: choose from Photos. Equipo's approved label.",
"extractionState": "manual",
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift
index ded01a0..4147fbf 100644
--- a/native/apple/Sources/BaseKit/Session/BaseSession.swift
+++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift
@@ -79,6 +79,10 @@ import RastrilloApple
/// older generation publishes nothing.
@ObservationIgnored private(set) var generation = 0
@ObservationIgnored private(set) var refreshing: Task<Void, Never>?
+ /// The last ended account's discard of its unsent uploads (P8.4).
+ @ObservationIgnored private(set) var discarding: Task<Void, Never>?
+ /// How long that discard may take before it is given up.
+ static let discardBound = Duration.seconds(2)
/// Ask's set-up running on its own (a state or a write said reconnect):
/// the session owns it, and cancels it on sign-out and in the background.
@ObservationIgnored private(set) var settingUp: Task<Void, Never>?
@@ -155,6 +159,13 @@ import RastrilloApple
/// Signed out, or about to be someone else: the old account's work is
/// cancelled and anything still in flight lands on nothing.
func end() {
+ // The unsent uploads and the client that can still discard them,
+ // read before anything below clears them (P8.4). Best effort,
+ // bounded, never holding end() up. A session another Oficina app
+ // already ended fails here, silently; Equipo drops them in 24 hours.
+ if let client, let ids = ask?.attachments.unsentIDs, !ids.isEmpty {
+ discarding = Task.detached { await Self.bounded(Self.discardBound) { await client.discard(ids: ids) } }
+ }
generation += 1
refreshing?.cancel()
refreshing = nil
@@ -168,6 +179,23 @@ import RastrilloApple
signedIn = nil; me = nil; home = nil
}
+ /// Runs `body` for at most `limit`: then it is cancelled and given up
+ /// on, whether or not it stops. (A task group would wait for it.)
+ nonisolated static func bounded(_ limit: Duration, _ body: @escaping @Sendable () async -> Void) async {
+ let done = Once()
+ await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in
+ let work = Task {
+ await body()
+ if done.claim() { c.resume() }
+ }
+ Task {
+ try? await Task.sleep(for: limit)
+ work.cancel()
+ if done.claim() { c.resume() }
+ }
+ }
+ }
+
/// Reads the member, Home and Ask afresh, for the account it started
/// under only.
public func refresh() async {
@@ -199,6 +227,7 @@ import RastrilloApple
/// The app came forward.
public func foreground() async {
+ ask?.attachments.resume()
await oficina.renewIfNeeded()
await refresh()
}
@@ -207,6 +236,9 @@ import RastrilloApple
public func background() {
settingUp?.cancel()
settingUp = nil
+ // Uploads in flight carry on as background tasks; queued ones wait.
+ // Nothing is discarded (P8.4).
+ ask?.attachments.suspend()
ask?.pause()
}
@@ -324,3 +356,10 @@ final class SwappableTransport: NativeUploadTransport, @unchecked Sendable {
try await current.upload(path, body: body, contentType: contentType, filename: filename, maxBytes: maxBytes, progress: progress)
}
}
+
+/// True for the first caller only.
+final class Once: @unchecked Sendable {
+ private let lock = NSLock()
+ private var claimed = false
+ func claim() -> Bool { lock.withLock { defer { claimed = true }; return !claimed } }
+}
diff --git a/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift b/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift
new file mode 100644
index 0000000..eb78280
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift
@@ -0,0 +1,279 @@
+@testable import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import XCTest
+
+/// Task 14: where Base's draft differs from Equipo's (plan P8).
+@MainActor final class AttachmentDraftTests: XCTestCase {
+ /// A client whose uploads wait for the test, in the order they start.
+ actor Uploads: AttachmentClient {
+ var started: [String] = []
+ var inFlight = 0
+ var most = 0
+ var deleted: [String] = []
+ var deleteAnswer: BaseAPIError?
+ /// Each upload's answer, by file name; a missing one waits for `finish`.
+ var answers: [String: [Result<AskAttachment, Error>]] = [:]
+ private var waiting: [String: CheckedContinuation<AskAttachment, Error>] = [:]
+ var progress: [String: @Sendable (Double) -> Void] = [:]
+
+ func script(_ name: String, _ results: [Result<AskAttachment, Error>]) { answers[name] = results }
+ func failDeletes(_ error: BaseAPIError) { deleteAnswer = error }
+ func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment {
+ started.append(file.name)
+ self.progress[file.name] = progress
+ inFlight += 1; most = max(most, inFlight)
+ defer { inFlight -= 1 }
+ if var queue = answers[file.name], !queue.isEmpty {
+ let next = queue.removeFirst(); answers[file.name] = queue
+ return try next.get()
+ }
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { waiting[file.name] = $0 }
+ } onCancel: { Task { await self.cancel(file.name) } }
+ }
+ func cancel(_ name: String) { waiting.removeValue(forKey: name)?.resume(throwing: CancellationError()) }
+ func finish(_ name: String) { waiting.removeValue(forKey: name)?.resume(returning: Self.uploaded(name)) }
+ func report(_ name: String, _ value: Double) { progress[name]?(value) }
+ func delete(_ id: String) async throws {
+ deleted.append(id)
+ if let deleteAnswer { throw deleteAnswer }
+ }
+ func data(id: String, preview: Bool) async throws -> Data { Data() }
+ func download(id: String, to destination: URL) async throws {}
+ static func uploaded(_ name: String) -> AskAttachment { AskAttachment(id: "at_" + name, kind: "file", name: name, mediaType: "text/plain") }
+ }
+
+ /// A background-task stand-in: records each and can expire them.
+ final class Background: BackgroundWork {
+ var begun = 0, ended = 0
+ var expiries: [@MainActor () -> Void] = []
+ func begin(expired: @escaping @MainActor () -> Void) -> Int { begun += 1; expiries.append(expired); return begun }
+ func end(_ token: Int) { ended += 1 }
+ }
+
+ var slept: [Duration] = []
+ let background = Background()
+
+ func draft(_ client: Uploads) -> AttachmentDraft {
+ AttachmentDraft(client: client, background: background, sleep: { [unowned self] d in self.slept.append(d) })
+ }
+ let text = Data("hello".utf8)
+
+ func settle(_ condition: @escaping () async -> Bool) async throws {
+ for _ in 0..<300 { if await condition() { return }; try await Task.sleep(for: .milliseconds(10)) }
+ XCTFail("timed out")
+ }
+
+ // MARK: P8.1, Remove
+
+ func testRemoveDeletesTheUpload() async throws {
+ let uploads = Uploads(); await uploads.script("a.txt", [.success(Uploads.uploaded("a.txt"))])
+ let d = draft(uploads)
+ await d.add(data: text, name: "a.txt")
+ let id = try XCTUnwrap(d.items.first?.id)
+ d.remove(id)
+ XCTAssertTrue(d.items.isEmpty)
+ try await settle { await uploads.deleted == ["at_a.txt"] }
+ }
+
+ func testAFileThatWentWithAMessageJustGoes() async throws {
+ let uploads = Uploads(); await uploads.script("a.txt", [.success(Uploads.uploaded("a.txt"))])
+ await uploads.failDeletes(.alreadySent)
+ let d = draft(uploads)
+ await d.add(data: text, name: "a.txt")
+ d.remove(try XCTUnwrap(d.items.first?.id))
+ try await settle { await uploads.deleted.count == 1 }
+ try await Task.sleep(for: .milliseconds(30))
+ XCTAssertTrue(d.items.isEmpty)
+ XCTAssertNil(d.notice, "nothing is shown")
+ }
+
+ func testRemoveWaitsWhileSending() async throws {
+ let uploads = Uploads(); await uploads.script("a.txt", [.success(Uploads.uploaded("a.txt"))])
+ let d = draft(uploads)
+ await d.add(data: text, name: "a.txt")
+ d.sending = true
+ XCTAssertFalse(d.canRemove)
+ d.remove(try XCTUnwrap(d.items.first?.id))
+ XCTAssertEqual(d.items.count, 1)
+ d.sending = false
+ XCTAssertTrue(d.canRemove)
+ }
+
+ // MARK: P8.2, two at a time
+
+ func testFiveAtOnceGoTwoAtATimeInOrder() async throws {
+ let uploads = Uploads()
+ let d = draft(uploads)
+ for name in (1...5).map({ "f\($0).txt" }) { Task { await d.add(data: text, name: name) } }
+ try await settle { await uploads.started.count == 2 }
+ try await Task.sleep(for: .milliseconds(50))
+ // Admitted in order; two admitted together prepare side by side, so
+ // either may reach its upload first.
+ let firstTwo = await uploads.started
+ XCTAssertEqual(Set(firstTwo), ["f1.txt", "f2.txt"])
+ XCTAssertEqual(d.items.count, 5, "every chip shows at once")
+ await uploads.finish("f1.txt")
+ try await settle { await uploads.started.count == 3 }
+ await uploads.finish("f2.txt")
+ await uploads.finish("f3.txt")
+ try await settle { await uploads.started.count == 5 }
+ await uploads.finish("f4.txt"); await uploads.finish("f5.txt")
+ try await settle { d.readyAttachments.count == 5 }
+ let order = await uploads.started
+ let most = await uploads.most
+ XCTAssertEqual(Set(order.prefix(2)), ["f1.txt", "f2.txt"])
+ XCTAssertEqual(order[2], "f3.txt", "the third only once one of the first two had answered")
+ XCTAssertEqual(Set(order.suffix(2)), ["f4.txt", "f5.txt"])
+ XCTAssertEqual(most, 2)
+ }
+
+ func testASixthFileIsRefused() async throws {
+ let uploads = Uploads()
+ let d = draft(uploads)
+ for n in 1...5 { Task { await d.add(data: text, name: "f\(n).txt") } }
+ try await settle { d.items.count == 5 }
+ await d.add(data: text, name: "sixth.txt")
+ XCTAssertEqual(d.items.count, 5)
+ XCTAssertEqual(d.notice, "You can attach up to 5 files to a message.")
+ for n in 1...5 { await uploads.finish("f\(n).txt") }
+ for item in d.items { d.remove(item.id) }
+ }
+
+ // MARK: P8.3, busy
+
+ func testBusyIsRetriedThreeTimesWithBackoffThenOffersRetry() async throws {
+ let uploads = Uploads()
+ let busy = AttachmentRefusal(code: "busy", retryAfter: 3)
+ await uploads.script("a.txt", [.failure(busy), .failure(busy), .failure(busy), .failure(busy)])
+ let d = draft(uploads)
+ await d.add(data: text, name: "a.txt")
+ let started = await uploads.started
+ XCTAssertEqual(started.count, 4, "the first try and three retries")
+ XCTAssertEqual(slept, [.seconds(3), .seconds(4), .seconds(8)], "max(Retry-After, 2, 4, 8 s)")
+ XCTAssertEqual(d.items.first?.failure, "Too many uploads at once. Try again in a moment.")
+ // Retry starts it again.
+ await uploads.script("a.txt", [.success(Uploads.uploaded("a.txt"))])
+ await d.retry(try XCTUnwrap(d.items.first?.id))
+ XCTAssertEqual(d.readyAttachments.count, 1)
+ }
+
+ func testTheRingRestartsOnEachTry() async throws {
+ let uploads = Uploads()
+ await uploads.script("a.txt", [.failure(AttachmentRefusal(code: "busy"))])
+ let d = draft(uploads)
+ Task { await d.add(data: text, name: "a.txt") }
+ try await settle { await uploads.started.count == 2 }
+ if case .uploading(let p) = d.items.first?.state { XCTAssertEqual(p, 0, "the second try's ring starts at 0") } else { XCTFail() }
+ await uploads.report("a.txt", 0.6)
+ try await settle { if case .uploading(let p) = d.items.first?.state { return p == 0.6 }; return false }
+ // The second try is a fresh upload: the ring went back to 0 before it.
+ await uploads.finish("a.txt")
+ try await settle { d.readyAttachments.count == 1 }
+ XCTAssertEqual(slept, [.seconds(2)])
+ }
+
+ // MARK: P8.5, the background
+
+ func testAnUploadInFlightRunsAsABackgroundTask() async throws {
+ let uploads = Uploads(); await uploads.script("a.txt", [.success(Uploads.uploaded("a.txt"))])
+ let d = draft(uploads)
+ await d.add(data: text, name: "a.txt")
+ XCTAssertEqual(background.begun, 1)
+ XCTAssertEqual(background.ended, 1)
+ }
+
+ func testExpiryCancelsTheUploadAndOffersRetry() async throws {
+ let uploads = Uploads()
+ let d = draft(uploads)
+ Task { await d.add(data: text, name: "a.txt") }
+ try await settle { await uploads.started.count == 1 }
+ background.expiries.first?()
+ try await settle { d.items.first?.failure != nil }
+ XCTAssertEqual(d.items.first?.failure, "Couldn’t upload. Try again.")
+ XCTAssertEqual(background.ended, 1)
+ }
+
+ func testQueuedFilesWaitForTheForegroundAndDontFail() async throws {
+ let uploads = Uploads()
+ let d = draft(uploads)
+ for n in 1...3 { Task { await d.add(data: text, name: "f\(n).txt") } }
+ try await settle { await uploads.started.count == 2 }
+ d.suspend()
+ await uploads.finish("f1.txt")
+ try await Task.sleep(for: .milliseconds(60))
+ let whileAway = await uploads.started.count
+ XCTAssertEqual(whileAway, 2, "the third waits")
+ XCTAssertNil(d.items[2].failure)
+ d.resume()
+ try await settle { await uploads.started.count == 3 }
+ await uploads.finish("f2.txt"); await uploads.finish("f3.txt")
+ try await settle { d.readyAttachments.count == 3 }
+ }
+
+ func testALostAnswerOffersRetry() async throws {
+ let uploads = Uploads(); await uploads.script("a.txt", [.failure(BaseAPIError.offline)])
+ let d = draft(uploads)
+ await d.add(data: text, name: "a.txt")
+ XCTAssertEqual(d.items.first?.failure, "Couldn’t upload. Try again.")
+ }
+
+ // MARK: The PDF line
+
+ func testAPDFSaysAskCantReadIt() async throws {
+ let uploads = Uploads(); await uploads.script("report.pdf", [.success(Uploads.uploaded("report.pdf"))])
+ let d = draft(uploads)
+ await d.add(data: Data("%PDF-1.7\n".utf8), name: "report.pdf")
+ XCTAssertEqual(d.items.first?.note, "Ask can’t read PDFs yet.")
+ await uploads.script("notes.txt", [.success(Uploads.uploaded("notes.txt"))])
+ await d.add(data: text, name: "notes.txt")
+ XCTAssertNil(d.items.last?.note)
+ }
+}
+
+/// P8.4: discard when the session ends, never in the background.
+extension SessionTests {
+ func readyAsk(_ t: GatedTransport) {
+ t.answer("/api/v1/me", me("alice", "Alice's"))
+ t.answer("/api/v1/home", home("Hello"))
+ t.answer("/ask/state", #"{"state":"ready","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"can_attach":true}"#)
+ t.answer("/ask/attachments", status: 201, #"{"id":"at_one","kind":"file","name":"a.txt","media_type":"text/plain"}"#)
+ for path in ["/api/v1/me", "/api/v1/home", "/ask/state", "/ask/attachments"] { t.release(path) }
+ }
+
+ func testEndingTheSessionDiscardsTheUnsentUploadsWithTheOldClient() async throws {
+ let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults())
+ let t = GatedTransport()
+ readyAsk(t)
+ session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: t)
+ let draft = try XCTUnwrap(session.ask?.attachments)
+ await draft.add(data: Data("hello".utf8), name: "a.txt")
+ XCTAssertEqual(draft.unsentIDs, ["at_one"])
+ // The discard is held; end() doesn't wait for it.
+ session.end()
+ XCTAssertNil(session.client)
+ try await waitUntil { t.calls.contains("/ask/attachments/discard") }
+ let body = t.bodies("/ask/attachments/discard").first.flatMap { $0 }.flatMap { String(data: $0, encoding: .utf8) }
+ XCTAssertEqual(body, "id=at_one")
+ // Bounded: it gives up after two seconds, whether or not Base answered.
+ let bound = try XCTUnwrap(session.discarding)
+ let clock = ContinuousClock(), start = clock.now
+ await bound.value
+ XCTAssertLessThan(clock.now - start, .seconds(3))
+ }
+
+ func testNothingIsDiscardedInTheBackground() async throws {
+ let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults())
+ let t = GatedTransport()
+ readyAsk(t)
+ session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: t)
+ await session.ask?.attachments.add(data: Data("hello".utf8), name: "a.txt")
+ session.background()
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertFalse(t.calls.contains("/ask/attachments/discard"))
+ XCTAssertEqual(session.ask?.attachments.unsentIDs, ["at_one"])
+ session.end()
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/AttachmentTests.swift b/native/apple/Tests/BaseKitTests/AttachmentTests.swift
index 2eced0a..3031e1a 100644
--- a/native/apple/Tests/BaseKitTests/AttachmentTests.swift
+++ b/native/apple/Tests/BaseKitTests/AttachmentTests.swift
@@ -95,18 +95,19 @@ extension AttachmentTests {
#expect(await server.uploads.isEmpty)
}
- // Base differs: Task 14. Five files upload at once here; Base admits two
- // at a time (P8.2), and its Remove deletes the upload (P8.1).
- @MainActor @Test(.disabled("Base differs: Task 14")) func uploadingItemsCountTowardLimitAndRemovedItemsStayGone() async throws {
+ // Base differs (Task 14): Equipo uploads all five at once; Base admits
+ // two at a time, in order (P8.2). The rest is Equipo's test.
+ @MainActor @Test func uploadingItemsCountTowardLimitAndRemovedItemsStayGone() async throws {
let server = HeldAttachmentServer()
let draft = AttachmentDraft(client: server)
let image = try Self.image()
let tasks = (0..<5).map { n in Task { await draft.add(data: image, name: "screen\(n).png") } }
for _ in 0..<500 {
- if await server.pendingCount == 5 { break }
+ if await server.pendingCount == 2, draft.items.count == 5 { break }
try await Task.sleep(for: .milliseconds(10))
}
- #expect(await server.pendingCount == 5)
+ #expect(await server.pendingCount == 2)
+ #expect(draft.items.count == 5)
#expect(!draft.canSend(text: "a note"))
let sixth = Task { await draft.add(data: image, name: "sixth.png") }
for _ in 0..<100 {
@@ -115,15 +116,19 @@ extension AttachmentTests {
}
#expect(draft.items.count == 5)
#expect(draft.notice == BaseText.text("native.attach.too_many"))
- for _ in 0..<500 {
- if await server.pendingCount == draft.items.count { break }
+ let id = try #require(draft.items.first?.id)
+ for _ in 0..<100 {
+ if case .uploading(let p) = draft.items.first?.state, p == 0.45 { 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 _ in 0..<500 {
+ if draft.readyAttachments.count == 4 { break }
+ await server.complete()
+ try await Task.sleep(for: .milliseconds(10))
+ }
for task in tasks { await task.value }
await sixth.value
#expect(draft.items.count == 4)
@@ -133,14 +138,20 @@ extension AttachmentTests {
}
actor HeldAttachmentServer: AttachmentClient {
- private var pending: [CheckedContinuation<AskAttachment, Error>] = []
+ private var pending: [(UUID, CheckedContinuation<AskAttachment, Error>)] = []
var pendingCount: Int { pending.count }
func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment {
progress(0.45)
- return try await withCheckedThrowingContinuation { pending.append($0) }
+ let id = UUID()
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { pending.append((id, $0)) }
+ } onCancel: { Task { await self.cancel(id) } }
+ }
+ private func cancel(_ id: UUID) {
+ if let i = pending.firstIndex(where: { $0.0 == id }) { pending.remove(at: i).1.resume(throwing: CancellationError()) }
}
func complete() {
- for continuation in pending { continuation.resume(returning: AttachmentServer.attachment) }
+ for (_, continuation) in pending { continuation.resume(returning: AttachmentServer.attachment) }
pending = []
}
func delete(_ id: String) async throws {}