oficina / base Public

Sending with files, and D5

Task 15 of the native slice 2 part 1 plan.

- AskModel.canAttach follows can_attach, and the draft accepts files only
  while it is true (no paperclip or +, and add refuses).
- canSend: the words, or files that haven't failed (still uploading is
  fine: Send waits for every upload). Text may be empty with files. A file
  that failed while Send waited stops it: remove or retry it first.
- send() passes the uploads' ids in order; the sent message's files clear
  the chips. A failed send keeps them, and the resend reuses the key (the
  key follows the words and the ids).
- D5: 409 files:"unavailable" keeps Ask ready, drops canAttach and marks
  every chip with the web's words; Send then sends the words alone and
  the chips go. 422 files:"stale" marks the chips "This file has expired.
  Attach it again." Neither changes the phase.
- Removing is disabled while the send is in flight (the draft's sending).
- The composer's Send follows AskModel.canSend.
- Switching accounts ends the old draft (dispose clears it; Task 14's
  end() discards first).

Gate: swift test -j 4 --filter 'AskModelTests|AttachmentDraftTests|Attachment':
48 XCTests and the Swift Testing suites passed; AskViewTests too.

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

Summary

Task 15: sending with files, and D5
claude agent, operated by paul@keymail.dev bf6602853cde90ac9991bbea45e1ca0a303308a6 parent 02240f8
5 files changed, +213 −7
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +42 −5
  • native/apple/Sources/BaseKit/Ask/Composer.swift +1 −1
  • native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift +32 −1
  • native/apple/Sources/BaseKit/Resources/Localizable.xcstrings +24 −0
  • native/apple/Tests/BaseKitTests/AskModelTests.swift +114 −0

CI passed — run details

CI log
=== build ===
CGO_ENABLED=0 go build ./...
=== vet ===
go vet ./...
=== fmt-check ===
=== staticcheck ===
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...
=== govulncheck ===
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
No vulnerabilities found.
=== gitleaks ===
9:48PM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
9:48PM INF 1 commits scanned.
9:48PM INF scanned ~3069396 bytes (3.07 MB) in 299ms
9:48PM INF no leaks found
=== budget ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 22 directories within budget
=== script-test ===
scripts/prepare-apps_test.sh
ok   releases lookup failure stops before ship
ok   app owned elsewhere stops the script
ok   apps listing failure stops before create
ok   ambiguous release dir is refused
ok   explicit version resolves the ambiguity
ok   releases match is exact, not substring
ok   shipped version is only promoted, existing app not created
ok   fresh account creates, ships, promotes to edge, enables
ok   failing promote stops the script
ok   ship is retried while uploads are rate limited
all passed
hack/fonts_test.sh
fonts_test: ok
=== test ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./...

receipt: test step 9.086s against a 60s target (the gate's other steps are not in this figure)
receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed
receipt: slow package 8.294s amadan.net/oficina/base/internal/webtest
receipt: slow package 1.095s amadan.net/oficina/base/internal/issuer
receipt: slow package 625ms amadan.net/oficina/base/internal/equipo
receipt: slow package 584ms amadan.net/oficina/base/internal/operations
receipt: slow package 191ms amadan.net/oficina/base/internal/consumer
receipt: slow test 1.51s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 860ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp
receipt: slow test 610ms amadan.net/oficina/base/internal/webtest TestAskUploadStalledBodyFreesItsSlot
receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
=== native ===
strings: copy review's strings.json is not here (git-ignored); its comparison skipped
strings: 171 in the catalog, 168 used
worktree-lib_test: ok
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index e7bef6f..63d5790 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -92,6 +92,22 @@ import SwiftUI
/// The composer's text.
public var text = ""
public private(set) var sending = false
+ /// Files may be attached now (`can_attach`): the paperclip and the +
+ /// show only then (P8.6). After D5's `files: unavailable`, false.
+ public private(set) var canAttach = false {
+ didSet { attachments.accepting = canAttach }
+ }
+
+ /// Send can be pressed: the words, or files that haven't failed (they
+ /// may still be uploading: Send waits for them). Without `canAttach`
+ /// the chips don't count, so after D5 the words can go alone.
+ public var canSend: Bool {
+ guard turn == nil, !sending else { return false }
+ let words = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ let files = canAttach ? attachments.items : []
+ if files.isEmpty { return words }
+ return files.allSatisfy { $0.failure == nil }
+ }
/// Cards with an answer on its way, or a paused job's Carry on now:
/// their buttons are disabled.
public private(set) var answering: Set<String> = []
@@ -294,20 +310,40 @@ import SwiftUI
/// known, so sending the same text again after a lost answer is the same
/// message to Equipo; different text gets a fresh key.
public func send() async {
+ guard canSend else { return }
let body = text.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !body.isEmpty, !sending, turn == nil else { return }
- let key = pendingSend?.text == body ? pendingSend!.key : BaseClient.newKey()
- pendingSend = (body, key)
+ let withFiles = canAttach && !attachments.items.isEmpty
sending = true
- defer { sending = false }
+ attachments.sending = true
+ defer { sending = false; attachments.sending = false }
+ if withFiles {
+ await attachments.uploadsSettled()
+ // One failed while it waited: it must be removed or retried first.
+ guard attachments.items.allSatisfy({ if case .ready = $0.state { return true }; return false }) else { return }
+ }
+ let ids = withFiles ? attachments.unsentIDs : []
+ let signature = body + "\n" + ids.joined(separator: ",")
+ let key = pendingSend?.text == signature ? pendingSend!.key : BaseClient.newKey()
+ pendingSend = (signature, key)
do {
- let sent = try await client.send(body, key: key)
+ let sent = try await client.send(body, key: key, attachments: ids)
pendingSend = nil
text = ""
status = ""
+ // The files went with it, or (after D5) were left behind.
+ attachments.clear()
if phase != .ready { phase = .ready }
if let message = sent.message { add(message) }
if let t = sent.turn { setTurn(t) }
+ } catch .filesUnavailable {
+ // D5: the runner can't take files now. Ask stays ready; the
+ // chips say so, and the words can go alone.
+ pendingSend = nil
+ canAttach = false
+ attachments.mark(BaseText.text("native.attach.unavailable"))
+ } catch .filesStale {
+ pendingSend = nil
+ attachments.mark(BaseText.text("native.attach.stale"))
} catch {
refusedWrite(error, keepsKey: { pendingSend = nil })
// The message's own failure line (copy review), in place of
@@ -439,6 +475,7 @@ import SwiftUI
func apply(_ s: AskSnapshot) {
disconnected = s.disconnected
phase = s.state
+ canAttach = s.canAttach
renewAfter = s.renewAfter
if let origin = s.equipoOrigin { equipoOrigin = origin }
guard phase.chatting else { return }
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
index 62d393b..ecf38e3 100644
--- a/native/apple/Sources/BaseKit/Ask/Composer.swift
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -24,7 +24,7 @@ public struct Composer: View {
_focused = focused
}
- private var canSend: Bool { model.turn == nil && !model.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
+ private var canSend: Bool { model.canSend }
public var body: some View {
let p = Palette(scheme)
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
index 31dcc0d..c4da224 100644
--- a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
+++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
@@ -32,6 +32,9 @@ import Observation
@ObservationIgnored let sleep: @MainActor (Duration) async throws -> Void
/// Set by Ask while a message is sending: Remove waits (P8.1).
public var sending = false
+ /// Whether Ask takes files now (`can_attach`): when not, nothing is added.
+ public var accepting = true
+ @ObservationIgnored private var settling: [CheckedContinuation<Void, Never>] = []
public var canRemove: Bool { !sending }
public init(client: any AttachmentClient, background: (any BackgroundWork)? = nil,
@@ -68,6 +71,10 @@ import Observation
await add(.file(file.url), name: file.name, ownedDirectory: directory)
}
private func add(_ source: Source, name: String, ownedDirectory: URL? = nil) async {
+ guard accepting else {
+ if let ownedDirectory { try? FileManager.default.removeItem(at: ownedDirectory) }
+ return
+ }
guard items.count < AttachmentLimits.maxCount else {
if let ownedDirectory { try? FileManager.default.removeItem(at: ownedDirectory) }
notice = BaseText.text("native.attach.too_many"); return
@@ -84,12 +91,13 @@ import Observation
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
+ settle()
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 }
+ public func clear() { for upload in uploads.values { upload.task.cancel() }; uploads = [:]; items = []; for id in Array(stagedDirectories.keys) { cleanStaged(id) }; notice = nil; settle() }
private func cleanStaged(_ id: UUID) { if let directory = stagedDirectories.removeValue(forKey: id) { try? FileManager.default.removeItem(at: directory) } }
public func retry(_ id: UUID) async {
guard let i = items.firstIndex(where: { $0.id == id }), items[i].failure != nil else { return }
@@ -102,6 +110,29 @@ import Observation
uploads[id] = (generation, task)
await withTaskCancellationHandler { await task.value } onCancel: { task.cancel() }
if uploads[id]?.generation == generation { uploads[id] = nil }
+ settle()
+ }
+
+ /// Returns once no file is preparing or uploading: Send waits for them.
+ public func uploadsSettled() async {
+ while items.contains(where: { if case .uploading = $0.state { return true }; return false }) {
+ await withCheckedContinuation { settling.append($0) }
+ }
+ }
+
+ private func settle() {
+ let waiting = settling
+ settling = []
+ for waiter in waiting { waiter.resume() }
+ }
+
+ /// Every chip marked with `words` (D5: files unavailable or stale), its
+ /// upload stopped.
+ public func mark(_ words: String) {
+ for upload in uploads.values { upload.task.cancel() }
+ uploads = [:]
+ for i in items.indices { items[i].state = .failed(words) }
+ settle()
}
/// 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.
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
index c58736a..20a6aec 100644
--- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
@@ -721,6 +721,18 @@
}
}
},
+ "native.attach.stale": {
+ "comment": "Base on the web's approved copy (chat.html data-w-stale). Every chip, when an upload has gone (24 hours unsent, or removed) (D5).",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This file has expired. Attach it again."
+ }
+ }
+ }
+ },
"native.attach.too_large": {
"comment": "Base on the web's approved copy (chat.html data-w-too-large). A file's chip when it is too large.",
"extractionState": "manual",
@@ -757,6 +769,18 @@
}
}
},
+ "native.attach.unavailable": {
+ "comment": "Base on the web's approved copy (chat.html data-w-unavailable). Every chip, when Ask can't take files right now (D5).",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Files can’t be read right now. Remove them to send your message without them."
+ }
+ }
+ }
+ },
"native.attach.uploading": {
"comment": "Base on the web's approved copy (chat.html data-w-uploading). A file's chip while it uploads, and its ring's label.",
"extractionState": "manual",
diff --git a/native/apple/Tests/BaseKitTests/AskModelTests.swift b/native/apple/Tests/BaseKitTests/AskModelTests.swift
index 34ca188..35eaaa8 100644
--- a/native/apple/Tests/BaseKitTests/AskModelTests.swift
+++ b/native/apple/Tests/BaseKitTests/AskModelTests.swift
@@ -460,3 +460,117 @@ import XCTest
XCTAssertTrue(done.connected, "an older open revision doesn't undo the connection")
}
}
+
+/// Task 15: sending with files, and D5 (files design).
+extension AskModelTests {
+ static let readyWithFiles = #"{"state":"ready","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"can_attach":true}"#
+ static let sent = #"{"message":{"id":"m9","role":"person","text":"Here","turn_id":"t9","attachments":[{"id":"at_one","kind":"file","name":"a.txt"}]},"turn":{"id":"t9","kind":"chat","state":"queued"}}"#
+
+ func ready(_ m: AskModel, canAttach: Bool = true) {
+ m.apply(try! JSONDecoder().decode(AskSnapshot.self, from: Data((canAttach ? Self.readyWithFiles : Self.readyWithFiles.replacingOccurrences(of: "true", with: "false")).utf8)))
+ }
+ func uploaded(_ id: String = "at_one") -> ScriptedTransport.Step { json(201, #"{"id":"\#(id)","kind":"file","name":"a.txt","media_type":"text/plain"}"#) }
+ func body(_ call: ScriptedTransport.Call) -> String { String(decoding: call.body ?? Data(), as: UTF8.self) }
+
+ func testSendWaitsForEveryUpload() async throws {
+ let t = GatedTransport()
+ t.answer("/ask/attachments", status: 201, #"{"id":"at_one","kind":"file","name":"a.txt"}"#)
+ t.answer("/ask/messages", Self.sent)
+ t.release("/ask/messages")
+ let m = AskModel(client: BaseClient(transport: t) {}, schedule: { _, _ in })
+ ready(m)
+ Task { await m.attachments.add(data: Data("hi".utf8), name: "a.txt") }
+ try await waitUntil { t.calls.contains("/ask/attachments") }
+ m.text = "Here"
+ XCTAssertTrue(m.canSend, "Send can be pressed while a file uploads")
+ let sending = Task { await m.send() }
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertFalse(t.calls.contains("/ask/messages"), "the message waits for its file")
+ t.release("/ask/attachments")
+ await sending.value
+ XCTAssertEqual(t.bodies("/ask/messages").count, 1)
+ let sent = t.bodies("/ask/messages").first.flatMap { $0 }.map { String(decoding: $0, as: UTF8.self) } ?? ""
+ XCTAssertTrue(sent.hasPrefix("text=Here&attachments=at_one&key="), sent)
+ XCTAssertTrue(m.attachments.items.isEmpty, "the sent message's files clear the chips")
+ XCTAssertEqual(m.text, "")
+ }
+
+ func testFilesMayGoWithoutWords() async throws {
+ let (m, t) = model([uploaded(), json(200, Self.sent)])
+ ready(m)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ XCTAssertTrue(m.canSend)
+ await m.send()
+ XCTAssertTrue(body(t.calls[1]).hasPrefix("text=&attachments=at_one&key="), body(t.calls[1]))
+ XCTAssertTrue(m.attachments.items.isEmpty)
+ }
+
+ func testAFailedSendKeepsTheFilesAndTheResendReusesTheKey() async throws {
+ let (m, t) = model([uploaded(), .offline(), json(200, Self.sent)])
+ ready(m)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ m.text = "Here"
+ await m.send()
+ XCTAssertEqual(m.attachments.readyAttachments.map(\.id), ["at_one"], "kept")
+ await m.send()
+ let first = body(t.calls[1]), second = body(t.calls[2])
+ XCTAssertEqual(first, second, "the same message, the same key")
+ XCTAssertTrue(m.attachments.items.isEmpty)
+ }
+
+ func testAFileThatFailedStopsTheSend() async throws {
+ let (m, t) = model([json(415, #"{"code":"attachment_type"}"#)])
+ ready(m)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ m.text = "Here"
+ XCTAssertFalse(m.canSend, "a failed file must be removed or retried first")
+ await m.send()
+ XCTAssertEqual(t.calls.count, 1, "nothing was sent")
+ }
+
+ func testWithoutCanAttachThereIsNothingToAttachTo() async throws {
+ let (m, t) = model()
+ ready(m, canAttach: false)
+ XCTAssertFalse(m.canAttach)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ XCTAssertTrue(m.attachments.items.isEmpty, "add refuses")
+ XCTAssertTrue(t.calls.isEmpty)
+ }
+
+ /// D5: the runner can't take files now. Ask stays ready; the chips say
+ /// why in the web's words; one more tap sends the words alone.
+ func testFilesUnavailableKeepsAskReadyAndTheWordsGoAlone() async throws {
+ let (m, t) = model([uploaded(), json(409, #"{"state":"ready","files":"unavailable"}"#), json(200, Self.sent)])
+ ready(m)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ m.text = "Here"
+ await m.send()
+ XCTAssertEqual(m.phase, .ready)
+ XCTAssertFalse(m.canAttach)
+ XCTAssertEqual(m.attachments.items.map(\.failure), ["Files can’t be read right now. Remove them to send your message without them."])
+ XCTAssertEqual(m.text, "Here", "the words stay")
+ XCTAssertTrue(m.canSend)
+ await m.send()
+ XCTAssertTrue(body(t.calls[2]).hasPrefix("text=Here&key="), body(t.calls[2]))
+ XCTAssertTrue(m.attachments.items.isEmpty)
+ }
+
+ func testStaleFilesAreMarkedAndAskStaysReady() async throws {
+ let (m, _) = model([uploaded(), json(422, #"{"state":"ready","files":"stale"}"#)])
+ ready(m)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ m.text = "Here"
+ await m.send()
+ XCTAssertEqual(m.phase, .ready)
+ XCTAssertTrue(m.canAttach)
+ XCTAssertEqual(m.attachments.items.map(\.failure), ["This file has expired. Attach it again."])
+ }
+
+ func testEndingTheModelEndsItsDraft() async throws {
+ let (m, _) = model([uploaded()])
+ ready(m)
+ await m.attachments.add(data: Data("hi".utf8), name: "a.txt")
+ m.dispose()
+ XCTAssertTrue(m.attachments.items.isEmpty)
+ }
+}