Answer Fable's code review: S1 to S7 and the cheap nits
Fable's review of native/slice2-part1 at 25b11d1 (approved with changes; native-code-review.md). - S1: background() pauses the upload queue on the iPhone only. The Mac calls it whenever Base isn't in front and keeps running. - S2: QuickLookTracker keeps the item shown, so the iPhone's dismissal (SwiftUI clears the sheet's item first) reaches the cache and returns VoiceOver focus. - S3: the cache counts opens per id, so the same file opened twice isn't removed under the panel; the app delegate takes Quick Look panel control through the responder chain (accepts/begin/endPreviewPanelControl). - S4: a composer that doesn't attach (the menu panel's) sends its words alone, and a failed chip in the window doesn't stop it. - S5: settled signed out with no account here, every account's files go. The session takes its cache root (tests use their own), and the default never falls back to Base's own folder. - S6: an upload Base answers after Remove, clear() or mark() is deleted. - S7: chips keep their uploads' ids (D5's too) for Remove and the discard; mark() bumps the generation so a late failure can't overwrite its words; Retry deletes the marked upload it replaces. - Nits: JPEG and HEIC pastes attach; Paste is AppKit's while Ask can't attach (1); promised files are staged, not read into memory (2); every Mac composer refuses file drops quietly (3); the menu check costs no walk (4); Retry-After capped at 30 s (5); a send removes only the files that went (6); a JPEG is named .jpg everywhere (7); Remove works until the send request starts (8); an upload refused with Ask's state reads it again (9); prepareFile removed (11); clear() cancels downloads and a file is marked open before it downloads (12); cache root as above (13); the thumbnail task keyed by size (14); Forward Delete removes a chip (15); a Store row's double-tap acts (16); a Store read from before a write lands nothing (17). Not taken: 7's photo order, 10. - The plan: P9's path and Task 21's hand checks (Fable's six). Tests: the draft (S6, S7 x2, nits 5 and 6), the session (S1, S5), Ask (S4 x2), the cache (S3, S2's tracker), a JPEG paste, .jpg naming. Gate: swift test -j 4 --filter over the draft, session, Ask, cache, files, paste route and Store suites: 127 XCTests and 21 Swift Testing tests passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Fable's code review answered
21 files changed,
+387
−86
docs/superpowers/plans/2026-11-28-native-slice2-part1.md+17 −2native/apple/Sources/BaseKit/Ask/AskModel.swift+20 −8native/apple/Sources/BaseKit/Ask/Composer.swift+11 −6native/apple/Sources/BaseKit/Attachments/AttachGate.swift+1 −0native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift+21 −5native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift+49 −8native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift+2 −1native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift+8 −3native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift+2 −1native/apple/Sources/BaseKit/Attachments/FileAttachment.swift+2 −26native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift+5 −2native/apple/Sources/BaseKit/Attachments/QuickLook.swift+49 −21native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift+5 −0native/apple/Sources/BaseKit/Session/BaseSession.swift+15 −3native/apple/Sources/BaseKit/Team/StoreModel.swift+7 −0native/apple/Sources/BaseKit/Team/StoreView.swift+4 −0native/apple/Sources/BaseMac/BaseMacApp.swift+7 −0native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift+29 −0native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift+116 −0native/apple/Tests/BaseKitTests/AttachmentFileTests.swift+6 −0native/apple/Tests/BaseKitTests/MacAttachmentTests.swift+11 −0
diff --git a/docs/superpowers/plans/2026-11-28-native-slice2-part1.md b/docs/superpowers/plans/2026-11-28-native-slice2-part1.md| index 987dd5d..ef6a083 100644 |
| --- a/docs/superpowers/plans/2026-11-28-native-slice2-part1.md |
| +++ b/docs/superpowers/plans/2026-11-28-native-slice2-part1.md |
| @@ -159,7 +159,7 @@ so: 22 numbered tasks, one spike, and one conditional task. |
| 9. **The refusal words are the web's** (copy review 13), keyed by code: `attachment_too_large`, `_type`, `_heic`, `_pixels`, `_limit`, `busy`. |
| - A plain-text `400`, which is Base's body deadline on a slow link, shows the web's "Couldn't upload. Try again." with Retry. |
| - **P9. The cache** (spec 7.6 and 7.9, 12, as amended; S11): |
| - - **Path:** `FileManager.urls(.cachesDirectory)/Attachments/<accountKey>/<attachment id>/<name>`. |
| + - **Path:** `FileManager.urls(.cachesDirectory)/<bundle id>/Attachments/<accountKey>/<attachment id>/<name>`. (The bundle's own folder: the Mac app isn't sandboxed, so its Caches is the person's. Fable's code review agreed.) |
| - `accountKey` is P5's. |
| - `<attachment id>` is checked against `[A-Za-z0-9_-]{1,64}`. |
| - `<name>` is the server's name reduced to its last path component, with `/`, `\`, NUL, a leading `.` and `..` removed, and cut to at most 120 bytes of UTF-8 on a character boundary. Its extension is replaced with the media type's (`UTType(mimeType:).preferredFilenameExtension`; `bin` when unknown). |
| @@ -669,7 +669,8 @@ day. |
| - an invite to a test address; |
| - Apps folds, and stays folded after a relaunch and offline; |
| - paste, drop, the paperclip and Quick Look; |
| - - sign-out clears `Caches/Attachments/<accountKey>`; |
| + - sign-out clears `Caches/works.oficina.base/Attachments/<accountKey>`; |
| + - from Fable's code review: three files dropped from Finder without clicking Base all upload (S1); Quick Look on the Mac with Space, Esc, a click back in the window, and the same file twice (S3); on the iPhone, closing Quick Look leaves VoiceOver on the thumbnail (S2); a screenshot pasted in the window, then a message sent from the menu panel goes without it (S4); signed out from another Oficina app with Base quit, Base's files are gone at launch (S5); a HEIC from Photos says "from HEIC" (PhotosPicker may hand over a JPEG); |
| - an upload whose answer is held for 45 s still completes: Task 5's listener helper, run once by hand with a 45 s hold. |
| - [ ] **An independent code review** of the whole branch (Fable, or Codex Astra), with this plan and spec 7.4 to 7.6 as the brief. Answer it on the branch. |
| @@ -786,3 +787,17 @@ its main window shows what attached and what was dropped): |
| **Recommendation:** Task 17 goes ahead as written, retargeting the |
| existing item. Task 16A isn't needed unless the hand-checked drop over the |
| field fails. |
| + |
| +## Fable's code review of the branch (2026-11-28) |
| + |
| +Approved with changes at `25b11d1`: 0 blockers, 7 should-fix, 17 nits |
| +(`.superpowers/sdd/2026-11-28-native-slice2/native-code-review.md`). All |
| +seven fixed, with tests where the code allows: the Mac's queue no longer |
| +pauses when Base isn't in front (S1); the iPhone's Quick Look close reaches |
| +the cache and returns focus (S2); opens are counted per id and the app |
| +delegate takes panel control (S3); the menu panel sends words alone (S4); |
| +a signed-out launch removes every account's files (S5); an upload answered |
| +after Remove is deleted (S6); marked chips keep their uploads and late |
| +failures can't overwrite D5's words (S7). Nits taken: 1 to 6, 7 (`.jpg`), |
| +8, 9, 11 to 17. Left: 7's chip order for photos, and 10 (pixels before |
| +decoding). The hand checks they need are in Task 21 above. |
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift| index 65cdb68..4509c75 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| @@ -103,10 +103,14 @@ import SwiftUI |
| /// 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 { |
| + public var canSend: Bool { canSend(withFiles: true) } |
| + |
| + /// `withFiles` false: a composer that doesn't attach (the menu panel's) |
| + /// sends its words alone, and the window's chips stay (review S4). |
| + public func canSend(withFiles: Bool) -> Bool { |
| guard turn == nil, !sending else { return false } |
| let words = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| - let files = canAttach ? attachments.items : [] |
| + let files = canAttach && withFiles ? attachments.items : [] |
| if files.isEmpty { return words } |
| return files.allSatisfy { $0.failure == nil } |
| } |
| @@ -153,6 +157,7 @@ import SwiftUI |
| self.attachments = attachments ?? AttachmentDraft(client: client, announce: announce) |
| self.schedule = schedule |
| self.announce = announce |
| + self.attachments.onAskState = { [weak self] in self?.reload() } |
| } |
| /// Posts `line` as an accessibility announcement. |
| @@ -318,18 +323,23 @@ import SwiftUI |
| /// Sends the composer's text. Its key is kept until the outcome is |
| /// 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 } |
| + public func send(withFiles files: Bool = true) async { |
| + guard canSend(withFiles: files) else { return } |
| let body = text.trimmingCharacters(in: .whitespacesAndNewlines) |
| - let withFiles = canAttach && !attachments.items.isEmpty |
| + let withFiles = files && canAttach && !attachments.items.isEmpty |
| + // After D5 (files unavailable) the words go alone and the chips with |
| + // them; a composer that doesn't attach leaves them be. |
| + let dropsFiles = files && !canAttach && !attachments.items.isEmpty |
| sending = true |
| - 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 } |
| } |
| + // From here the request starts: Remove waits for its answer (P8.1); |
| + // until now a stuck upload could still be removed (review nit 8). |
| + attachments.sending = true |
| let ids = withFiles ? attachments.unsentIDs : [] |
| let signature = body + "\n" + ids.joined(separator: ",") |
| let key = pendingSend?.text == signature ? pendingSend!.key : BaseClient.newKey() |
| @@ -339,8 +349,10 @@ import SwiftUI |
| pendingSend = nil |
| text = "" |
| status = "" |
| - // The files went with it, or (after D5) were left behind. |
| - attachments.clear() |
| + // The files that went with it leave the composer; after D5 the |
| + // marked ones are deleted. |
| + if withFiles { attachments.removeSent(ids) } |
| + if dropsFiles { attachments.dropAll() } |
| if phase != .ready { phase = .ready } |
| if let message = sent.message { add(message) } |
| if let t = sent.turn { setTurn(t) } |
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift| index 77afa0e..cdaf79c 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Composer.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Composer.swift |
| @@ -29,7 +29,8 @@ public struct Composer: View { |
| self.attaching = attaching |
| } |
| - private var canSend: Bool { model.canSend } |
| + /// The menu panel's composer (not attaching) sends words alone. |
| + private var canSend: Bool { model.canSend(withFiles: attaching) } |
| public var body: some View { |
| VStack(alignment: .leading, spacing: 8) { |
| @@ -119,7 +120,7 @@ public struct Composer: View { |
| private func send() { |
| guard canSend else { return } |
| - Task { await model.send() } |
| + Task { await model.send(withFiles: attaching) } |
| } |
| } |
| @@ -164,10 +165,13 @@ enum ComposerReturn: Equatable { |
| /// and its editor take only text drags, so a file dragged over the field |
| /// reaches the pane's drop and inserts no path (Spike M). |
| private func focusChanged() { |
| - guard attach != nil else { return } |
| + // Every Mac composer takes only text drags: the menu panel's, which |
| + // doesn't attach, refuses a dropped file quietly rather than insert |
| + // its path (review nit 3). |
| + if focused { DispatchQueue.main.async { [weak self] in self?.narrowDrops() } } |
| + guard attach != nil else { if Self.attaching === self { Self.attaching = nil }; return } |
| if focused { |
| Self.attaching = self |
| - DispatchQueue.main.async { [weak self] in self?.narrowDrops() } |
| } else if Self.attaching === self { |
| Self.attaching = nil |
| } |
| @@ -339,7 +343,8 @@ struct ComposerAnchor: NSViewRepresentable { |
| func updateNSView(_ view: NSView, context: Context) { wire(view) } |
| private func wire(_ view: NSView) { |
| input.anchor = view; input.model = model |
| - input.attach = attaching ? { [weak model] board in |
| + // Nothing attaches while Ask doesn't take files: Paste is AppKit's. |
| + input.attach = attaching && model.canAttach ? { [weak model] board in |
| guard let model, model.canAttach else { return false } |
| return MacPasteboard.acceptAttachments(board, into: model.attachments) |
| } : nil |
| @@ -356,7 +361,7 @@ struct ComposerAnchor: UIViewRepresentable { |
| func updateUIView(_ view: UIView, context: Context) { wire(view) } |
| private func wire(_ view: UIView) { |
| input.anchor = view; input.model = model |
| - input.attach = attaching ? { [weak model] provider in |
| + input.attach = attaching && model.canAttach ? { [weak model] provider in |
| guard let model, model.canAttach else { return } |
| AttachDrop.receive([provider], into: model.attachments) |
| } : nil |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachGate.swift b/native/apple/Sources/BaseKit/Attachments/AttachGate.swift| index f8cf0ae..6365bc5 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachGate.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachGate.swift |
| @@ -34,6 +34,7 @@ import UIKit |
| } |
| func pause() { paused = true } |
| + var isPaused: Bool { paused } |
| func resume() { paused = false; admit() } |
| private func admit() { |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift| index ea26e32..8370f7c 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift |
| @@ -28,14 +28,18 @@ public actor AttachmentCache { |
| let client: any AttachmentClient |
| let now: @Sendable () -> Date |
| private var inFlight: [String: Task<URL, Error>] = [:] |
| - private var open: Set<String> = [] |
| + /// Ids open in Quick Look, counted: the same file opened twice stays |
| + /// until both previews close (review S3). |
| + private var open: [String: Int] = [:] |
| /// For tests: how many sweeps ran, and whether it was cleared. |
| private(set) var sweeps = 0 |
| private(set) var cleared = false |
| public static var defaultRoot: URL { |
| let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] |
| - return caches.appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.base", isDirectory: true) |
| + // Never Base's own folder by default: a process without a bundle id |
| + // (a test tool) must not sweep the app's cache. |
| + return caches.appendingPathComponent(Bundle.main.bundleIdentifier ?? "base-unbundled", isDirectory: true) |
| .appendingPathComponent("Attachments", isDirectory: true) |
| } |
| @@ -112,6 +116,8 @@ public actor AttachmentCache { |
| } |
| throw error |
| } |
| + // Cleared meanwhile (sign-out): nothing lands. |
| + if Task.isCancelled { try? FileManager.default.removeItem(at: part); throw CancellationError() } |
| try FileManager.default.setAttributes(Self.attributes(phone: Self.isPhone, modified: date), ofItemAtPath: part.path) |
| try FileManager.default.moveItem(at: part, to: url) |
| var values = URLResourceValues() |
| @@ -127,8 +133,10 @@ public actor AttachmentCache { |
| /// Quick Look opened or closed `id`. An expired file closed is removed. |
| public func previewing(_ id: String, open isOpen: Bool) { |
| - if isOpen { open.insert(id); return } |
| - open.remove(id) |
| + if isOpen { open[id, default: 0] += 1; return } |
| + guard let count = open[id] else { return } |
| + if count > 1 { open[id] = count - 1; return } |
| + open[id] = nil |
| let directory = folder.appendingPathComponent(id, isDirectory: true) |
| if expired(directory) { try? FileManager.default.removeItem(at: directory) } |
| } |
| @@ -143,7 +151,7 @@ public actor AttachmentCache { |
| try? manager.removeItem(at: other) |
| } |
| for directory in (try? manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? [] |
| - where !open.contains(directory.lastPathComponent) && expired(directory) { |
| + where open[directory.lastPathComponent] == nil && expired(directory) { |
| try? manager.removeItem(at: directory) |
| } |
| } |
| @@ -151,9 +159,17 @@ public actor AttachmentCache { |
| /// The account's files, all gone (sign-out, Ask disconnected). |
| public func clear() { |
| cleared = true |
| + // A download still running would land after sign-out (review nit 12). |
| + for task in inFlight.values { task.cancel() } |
| + inFlight = [:] |
| try? FileManager.default.removeItem(at: folder) |
| } |
| + /// Every account's files: nobody is signed in (review S5). |
| + public nonisolated static func removeAll(root: URL = AttachmentCache.defaultRoot) { |
| + try? FileManager.default.removeItem(at: root) |
| + } |
| + |
| private func expired(_ directory: URL) -> Bool { |
| let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] |
| guard !files.isEmpty else { return true } |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift| index b587062..9a8059c 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift |
| @@ -16,6 +16,9 @@ import Observation |
| public var file: AttachmentFile? |
| /// A line under the chip that isn't a failure: a PDF's. |
| public var note: String? |
| + /// Its upload's id once Base has it, kept when D5 marks the chip, so |
| + /// Remove and the discard still delete it (review S7). |
| + var uploadedID: String? |
| var generation = UUID() |
| var source: Source |
| public var failure: String? { if case .failed(let words) = state { return words }; return nil } |
| @@ -39,6 +42,9 @@ import Observation |
| public var sending = false |
| /// Whether Ask takes files now (`can_attach`): when not, nothing is added. |
| public var accepting = true |
| + /// An upload refused with one of Ask's states (`reconnect`, say): Ask |
| + /// reads its state again. |
| + @ObservationIgnored var onAskState: (() -> Void)? |
| @ObservationIgnored private var settling: [CheckedContinuation<Void, Never>] = [] |
| public var canRemove: Bool { !sending } |
| @@ -69,11 +75,13 @@ import Observation |
| await add(.file(url), name: name, ownedDirectory: directory) |
| } |
| - /// The uploads not sent yet, for the discard when the session ends. |
| - public var unsentIDs: [String] { readyAttachments.map(\.id) } |
| + /// The uploads not sent yet, for the discard when the session ends: |
| + /// every chip's that Base has, marked ones too. |
| + public var unsentIDs: [String] { items.compactMap(\.uploadedID) } |
| /// The app went to the background: files still queued wait (P8.5). |
| public func suspend() { gate.pause() } |
| public func resume() { gate.resume() } |
| + var suspended: Bool { gate.isPaused } |
| public var readyAttachments: [AskAttachment] { items.compactMap { if case .ready(let value) = $0.state { return value }; return nil } } |
| public func canSend(text: String) -> Bool { |
| @@ -113,15 +121,40 @@ import Observation |
| 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) } |
| + if let uploaded = item.uploadedID { delete(uploaded) } |
| + } |
| + |
| + /// Deletes an upload no chip holds, best effort. |
| + private func delete(_ uploaded: String) { |
| + let client = self.client |
| + Task { try? await client.delete(uploaded) } |
| + } |
| + |
| + /// Every chip gone, its upload deleted: D5's files after the words went |
| + /// alone. |
| + public func dropAll() { |
| + for uploaded in items.compactMap(\.uploadedID) { delete(uploaded) } |
| + clear() |
| + } |
| + |
| + /// The chips whose uploads went with a message (`ids`), and only those: |
| + /// one added while the message was sending stays (review nit 6). |
| + public func removeSent(_ ids: [String]) { |
| + let sent = Set(ids) |
| + for item in items where item.uploadedID.map(sent.contains) ?? false { |
| + uploads.removeValue(forKey: item.id)?.task.cancel(); cleanStaged(item.id) |
| } |
| + items.removeAll { $0.uploadedID.map(sent.contains) ?? false } |
| + if items.isEmpty { photos = 0 } |
| + notice = nil |
| + settle() |
| } |
| public func clear() { for upload in uploads.values { upload.task.cancel() }; uploads = [:]; items = []; for id in Array(stagedDirectories.keys) { cleanStaged(id) }; notice = nil; photos = 0; 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 } |
| + // A marked chip's upload (D5) is replaced by the new one. |
| + if let old = items[i].uploadedID { delete(old); items[i].uploadedID = nil } |
| items[i].generation = UUID(); items[i].state = .uploading(0) |
| await upload(id) |
| } |
| @@ -152,7 +185,9 @@ import Observation |
| public func mark(_ words: String) { |
| for upload in uploads.values { upload.task.cancel() } |
| uploads = [:] |
| - for i in items.indices { items[i].state = .failed(words) } |
| + // A new generation: an upload still in flight can't overwrite the |
| + // words, and if Base answers it anyway it is deleted (review S7). |
| + for i in items.indices { items[i].state = .failed(words); items[i].generation = UUID() } |
| settle() |
| } |
| /// Base's upload (P8.2, P8.3, P8.5): behind the gate, preparing and |
| @@ -189,13 +224,18 @@ import Observation |
| self.items[i].state = .uploading(fraction) |
| } |
| } |
| - guard let i = index(id, item.generation) else { return } |
| + // Removed, cleared or marked while Base answered: the |
| + // upload is nobody's, so it goes now (review S6). |
| + guard let i = index(id, item.generation) else { delete(attachment.id); return } |
| items[i].state = .ready(attachment) |
| + items[i].uploadedID = attachment.id |
| announce(BaseText.format("native.attach.attached", ["name": file.name])) |
| 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))) |
| + // Retry-After is capped, so one odd header can't hold a |
| + // place in the gate. |
| + try await sleep(max(backoff[retries], .seconds(min(refusal.retryAfter ?? 0, 30)))) |
| retries += 1 |
| try Task.checkCancellation() |
| guard let i = index(id, item.generation) else { return } |
| @@ -204,6 +244,7 @@ import Observation |
| } |
| } catch { |
| guard let i = index(id, item.generation) else { return } |
| + if case .server(_, _, let state?)? = error as? BaseAPIError, !state.isEmpty { onAskState?() } |
| let words = Self.words(error) |
| items[i].state = .failed(words) |
| announce(BaseText.format("native.attach.not_attached", ["name": item.name, "reason": words])) |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift| index 63165e7..0770b70 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift |
| @@ -108,7 +108,8 @@ public struct AttachmentFile: Sendable { |
| guard data.count <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| let types: [UTType: String] = [.png: "image/png", .jpeg: "image/jpeg", .gif: "image/gif", .webP: "image/webp"] |
| guard let media = types[type] else { throw AttachmentFailure.type } |
| - let suffix = type.preferredFilenameExtension ?? "png" |
| + // Base: ".jpg", as a converted file is named (review nit 7). |
| + let suffix = type == .jpeg ? "jpg" : (type.preferredFilenameExtension ?? "png") |
| return Self(data: data, name: (name as NSString).deletingPathExtension + "." + suffix, mediaType: media, width: width, height: height) |
| } |
| return nil |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift| index 815b867..57e66b0 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentPromises.swift |
| @@ -23,17 +23,22 @@ enum AttachmentPromises { |
| let queue = OperationQueue(); queue.maxConcurrentOperationCount = 1 |
| for promise in promises { |
| promise.receivePromisedFiles(atDestination: directory.url, options: [:], operationQueue: queue) { [directory] url, error in |
| - let result = Result<Data, Error> { |
| + // Base: staged into a directory the draft then owns and |
| + // prepared from there behind its gate, never read into |
| + // memory here (review nit 2). |
| + let result = Result<(URL, URL), Error> { |
| if let error { throw error } |
| guard url.isFileURL, |
| url.standardizedFileURL.deletingLastPathComponent() == directory.url.standardizedFileURL, |
| (try url.resourceValues(forKeys: [.isRegularFileKey])).isRegularFile == true else { throw AttachmentFailure.type } |
| - return try AttachmentFile.read(url) |
| + let owned = FileManager.default.temporaryDirectory.appendingPathComponent("base-drop-" + UUID().uuidString, isDirectory: true) |
| + do { return (try AttachmentFile.stage(url, directory: owned), owned) } |
| + catch { try? FileManager.default.removeItem(at: owned); throw error } |
| } |
| if url.standardizedFileURL.deletingLastPathComponent() == directory.url.standardizedFileURL { try? FileManager.default.removeItem(at: url) } |
| Task { @MainActor in |
| switch result { |
| - case .success(let data): await draft.add(data: data, name: url.lastPathComponent) |
| + case .success(let (staged, owned)): await draft.add(stagedURL: staged, name: url.lastPathComponent, directory: owned) |
| case .failure: draft.refuseFile() |
| } |
| } |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift| index 34b00ea..18f8399 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift |
| @@ -110,6 +110,7 @@ struct AttachmentChip: View { |
| .modifier(RetryAction(draft: draft, item: item)) |
| .focusable() |
| .onKeyPress(.delete) { draft.remove(item.id); return .handled } |
| + .onKeyPress(.deleteForward) { draft.remove(item.id); return .handled } |
| .onKeyPress(.return) { |
| guard item.failure != nil else { return .ignored } |
| Task { await draft.retry(item.id) } |
| @@ -167,7 +168,7 @@ struct AttachmentPicture: View { |
| } else { |
| Image(systemName: "doc").font(.title2).foregroundStyle(p[.haze]).accessibilityLabel(name) |
| } |
| - }.task(id: data) { |
| + }.task(id: data?.count) { |
| let bytes = data |
| let decoded = await Task.detached { bytes.flatMap { Self.thumbnail($0, side: 512) } }.value |
| guard !Task.isCancelled else { return } |
diff --git a/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift b/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift| index ea19900..8508d24 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/FileAttachment.swift |
| @@ -40,30 +40,6 @@ extension AttachmentFile { |
| completed = true |
| return target |
| } |
| - public static func prepareFile(_ source: URL, directory: URL, name: String? = nil, |
| - access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> FileAttachment { |
| - let staged = try stage(source, directory: directory, access: access) |
| - defer { try? FileManager.default.removeItem(at: staged) } |
| - func boundedData() throws -> Data { |
| - let handle = try FileHandle(forReadingFrom: staged); defer { try? handle.close() } |
| - let data = try handle.read(upToCount: AttachmentLimits.maxBytes + 1) ?? Data() |
| - guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| - return data |
| - } |
| - let filename = URL(fileURLWithPath: name ?? source.lastPathComponent).lastPathComponent |
| - let file: AttachmentFile |
| - if let image = CGImageSourceCreateWithURL(staged as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), |
| - let prepared = try prepareImage(image, name: filename, maximumBytes: AttachmentLimits.maxBytes, original: boundedData) { |
| - file = prepared |
| - } else { file = try prepare(boundedData(), name: filename) } |
| - try Task.checkCancellation() |
| - guard file.data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| - let id = UUID(), destination = directory.appendingPathComponent(UUID().uuidString) |
| - #if os(iOS) |
| - try file.data.write(to: destination, options: [.atomic, .completeFileProtection]) |
| - #else |
| - try file.data.write(to: destination, options: .atomic) |
| - #endif |
| - return FileAttachment(id: id, url: destination, name: file.name, mediaType: file.mediaType, width: file.width, height: file.height) |
| - } |
| + // Equipo's prepareFile isn't copied: Base prepares a staged file from |
| + // its URL behind the draft's gate (AttachmentFile.prepare(url:)). |
| } |
diff --git a/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift b/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift| index 90bbb25..321ad89 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift |
| @@ -28,9 +28,12 @@ enum MacPasteboard { |
| for url in urls { Task { await draft.add(url: url) } } |
| return true |
| } |
| - for type in [NSPasteboard.PasteboardType.png, .tiff] { |
| + // Base: JPEG and HEIC too, which contents(_:) counts as images |
| + // (review nit 1). |
| + let images: [(NSPasteboard.PasteboardType, String)] = [(.png, "png"), (.tiff, "tiff"), (.init("public.jpeg"), "jpg"), (.init("public.heic"), "heic")] |
| + for (type, ext) in images { |
| if let data = pasteboard.data(forType: type) { |
| - Task { await draft.add(data: data, name: type == .png ? "image.png" : "image.tiff") } |
| + Task { await draft.add(data: data, name: "image." + ext) } |
| return true |
| } |
| } |
diff --git a/native/apple/Sources/BaseKit/Attachments/QuickLook.swift b/native/apple/Sources/BaseKit/Attachments/QuickLook.swift| index c1589a7..af3c553 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/QuickLook.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/QuickLook.swift |
| @@ -19,6 +19,7 @@ struct MessageFiles: View { |
| let model: AskModel |
| @State private var gone = false |
| @State private var showing: QuickLookItem? |
| + @State private var tracker = QuickLookTracker() |
| @AccessibilityFocusState private var focus: String? |
| @Environment(\.colorScheme) private var scheme |
| @@ -66,7 +67,11 @@ struct MessageFiles: View { |
| Button(BaseText.text("ask.close"), role: .cancel) {} |
| } |
| #if os(iOS) |
| - .sheet(item: $showing, onDismiss: closed) { item in PhoneQuickLook(url: item.url).ignoresSafeArea() } |
| + // SwiftUI clears `showing` before onDismiss: the tracker keeps the |
| + // item (review S2). |
| + .sheet(item: $showing, onDismiss: { if let id = tracker.closed(cache: model.files) { focus = id } }) { item in |
| + PhoneQuickLook(url: item.url).ignoresSafeArea() |
| + } |
| #endif |
| } |
| @@ -74,31 +79,45 @@ struct MessageFiles: View { |
| guard let cache = model.files else { return } |
| let sent = message.createdAt |
| Task { |
| + // Open before it downloads, so no sweep can take it meanwhile. |
| + await cache.previewing(attachment.id, open: true) |
| do { |
| let url = try await cache.file(for: attachment, sentAt: sent) |
| - await cache.previewing(attachment.id, open: true) |
| let item = QuickLookItem(id: attachment.id, url: url) |
| + tracker.opened(item) |
| #if os(macOS) |
| - MacQuickLook.shared.show(item) { closed(item) } |
| + MacQuickLook.shared.show(item) { |
| + Task { await cache.previewing(item.id, open: false) } |
| + focus = item.id |
| + } |
| #else |
| showing = item |
| #endif |
| - } catch AttachmentCache.Failure.gone { |
| - gone = true |
| - } catch {} |
| + } catch { |
| + await cache.previewing(attachment.id, open: false) |
| + if case AttachmentCache.Failure.gone = error { gone = true } |
| + } |
| } |
| } |
| - |
| - /// Quick Look closed: an expired file goes, and focus returns. |
| - private func closed() { if let showing { closed(showing) } } |
| - private func closed(_ item: QuickLookItem) { |
| - Task { await model.files?.previewing(item.id, open: false) } |
| - focus = item.id |
| - } |
| } |
| struct QuickLookItem: Identifiable, Equatable { let id: String; let url: URL } |
| +/// The file a preview shows, kept apart from the view's state so its |
| +/// closing always reaches the cache and returns focus (review S2). |
| +@MainActor final class QuickLookTracker { |
| + private(set) var shown: QuickLookItem? |
| + func opened(_ item: QuickLookItem) { shown = item } |
| + /// The preview closed: the cache hears (an expired file goes), and the |
| + /// id comes back for focus. Nil when nothing was shown. |
| + func closed(cache: AttachmentCache?) -> String? { |
| + guard let item = shown else { return nil } |
| + shown = nil |
| + if let cache { Task { await cache.previewing(item.id, open: false) } } |
| + return item.id |
| + } |
| +} |
| + |
| /// A sent picture's thumbnail, from Base's `/preview`, kept in memory; |
| /// its name when it can't be read. |
| struct SentThumbnail: View { |
| @@ -135,9 +154,11 @@ struct SentThumbnail: View { |
| } |
| #if os(macOS) |
| -/// The Mac's Quick Look panel, for one file at a time. |
| -@MainActor final class MacQuickLook: NSObject, QLPreviewPanelDataSource, QLPreviewPanelDelegate { |
| - static let shared = MacQuickLook() |
| +/// The Mac's Quick Look panel, for one file at a time. The app delegate |
| +/// takes panel control through the responder chain and hands it here |
| +/// (review S3); each file's own close reaches the cache, counted per id. |
| +@MainActor public final class MacQuickLook: NSObject, QLPreviewPanelDataSource, QLPreviewPanelDelegate { |
| + public static let shared = MacQuickLook() |
| private var item: QuickLookItem? |
| private var onClose: (() -> Void)? |
| @@ -146,17 +167,24 @@ struct SentThumbnail: View { |
| self.item = item |
| self.onClose = onClose |
| guard let panel = QLPreviewPanel.shared() else { return } |
| - panel.dataSource = self |
| - panel.delegate = self |
| + panel.updateController() |
| + take(panel) |
| panel.reloadData() |
| panel.makeKeyAndOrderFront(nil) |
| } |
| - nonisolated func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { 1 } |
| - nonisolated func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> (any QLPreviewItem)! { |
| + /// The panel's controller (the app delegate's beginPreviewPanelControl) |
| + /// hands it here. |
| + public func take(_ panel: QLPreviewPanel) { |
| + panel.dataSource = self |
| + panel.delegate = self |
| + } |
| + |
| + nonisolated public func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { 1 } |
| + nonisolated public func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> (any QLPreviewItem)! { |
| MainActor.assumeIsolated { item?.url as NSURL? } |
| } |
| - nonisolated func windowWillClose(_ notification: Notification) { |
| + nonisolated public func windowWillClose(_ notification: Notification) { |
| MainActor.assumeIsolated { |
| onClose?() |
| onClose = nil |
diff --git a/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift b/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift| index 4781267..8876765 100644 |
| --- a/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift |
| +++ b/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift |
| @@ -19,6 +19,9 @@ import AppKit |
| /// Where a paste reads from. Tests give their own, never the person's. |
| var pasteboard: NSPasteboard = .general |
| private var observers: [NSObjectProtocol] = [] |
| + /// The item last retargeted: while it is still ours, a check costs no |
| + /// walk of the menu (review nit 4). |
| + private weak var retargeted: NSMenuItem? |
| public func install() { |
| guard observers.isEmpty else { return } |
| @@ -33,9 +36,11 @@ import AppKit |
| /// Every main-menu item still on AppKit's `paste:`, pointed here. |
| func retarget() { |
| guard let menu = NSApp.mainMenu else { return } |
| + if let item = retargeted, item.menu != nil, item.action == #selector(basePaste(_:)), item.target === self { return } |
| for item in Self.items(menu) where item.action == #selector(NSText.paste(_:)) { |
| item.action = #selector(basePaste(_:)) |
| item.target = self |
| + retargeted = item |
| } |
| } |
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift| index d2f8a1d..29fd1b9 100644 |
| --- a/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| +++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| @@ -45,10 +45,13 @@ import RastrilloApple |
| /// Where the person's Disconnect is kept, per account. |
| let defaults: UserDefaults |
| + /// The files cache's root (tests give their own). |
| + let cacheRoot: URL |
| - public init(oficina: OficinaIDModel, defaults: UserDefaults = .standard) { |
| + public init(oficina: OficinaIDModel, defaults: UserDefaults = .standard, cacheRoot: URL = AttachmentCache.defaultRoot) { |
| self.oficina = oficina |
| self.defaults = defaults |
| + self.cacheRoot = cacheRoot |
| watching = oficina.$step.sink { [weak self] step in |
| Task { @MainActor in self?.stepChanged(step) } |
| } |
| @@ -66,6 +69,11 @@ import RastrilloApple |
| if let left = account { |
| end() |
| forgetDisconnectIfGone(left.identity) |
| + } else { |
| + // Signed out with no account here (another Oficina app signed |
| + // the ID out while Base was quit, or Base was killed before it |
| + // cleared): no account's files stay (review S5). |
| + AttachmentCache.removeAll(root: cacheRoot) |
| } |
| return |
| } |
| @@ -155,7 +163,7 @@ import RastrilloApple |
| askSetup = setup |
| team = TeamModels(store: StoreModel(client: client, baseName: ""), people: PeopleModel(client: client)) |
| folds = SidebarFolds(defaults: defaults, origin: origin, identity: identity) |
| - let cache = AttachmentCache(accountKey: AccountKey.make(origin: origin, identity: identity), client: client) |
| + let cache = AttachmentCache(root: cacheRoot, accountKey: AccountKey.make(origin: origin, identity: identity), client: client) |
| files = cache |
| ask.files = cache |
| // Ask disconnected: its files go too (P9). |
| @@ -255,9 +263,13 @@ import RastrilloApple |
| public func background() { |
| settingUp?.cancel() |
| settingUp = nil |
| - // Uploads in flight carry on as background tasks; queued ones wait. |
| + // The iPhone's background: uploads in flight carry on as background |
| + // tasks; queued ones wait. The Mac calls this whenever Base isn't the |
| + // front app, and keeps running: its queue carries on (review S1). |
| // Nothing is discarded (P8.4). |
| + #if os(iOS) |
| ask?.attachments.suspend() |
| + #endif |
| ask?.pause() |
| } |
diff --git a/native/apple/Sources/BaseKit/Team/StoreModel.swift b/native/apple/Sources/BaseKit/Team/StoreModel.swift| index 8d9ec55..e82e470 100644 |
| --- a/native/apple/Sources/BaseKit/Team/StoreModel.swift |
| +++ b/native/apple/Sources/BaseKit/Team/StoreModel.swift |
| @@ -43,6 +43,9 @@ import SwiftUI |
| /// Bumped when the screen goes, so a scheduled poll from before does nothing. |
| private var generation = 0 |
| private var pollScheduled = false |
| + /// Bumped by each write: a read that started before it lands nothing |
| + /// (review nit 17). |
| + private var writes = 0 |
| /// `store`: what to show before the first read answers (the last one |
| /// seen, or a fixture). |
| @@ -79,8 +82,10 @@ import SwiftUI |
| } |
| func load() async { |
| + let started = writes |
| do { |
| let next = try await client.store() |
| + guard started == writes else { return } |
| failures = 0 |
| failed = false |
| apply(next) |
| @@ -158,6 +163,7 @@ import SwiftUI |
| guard store?.owner == true, let index = store?.rows.firstIndex(where: { $0.id == id }) else { return } |
| let before = store!.rows[index].state |
| store!.rows[index].state = .installing |
| + writes += 1 |
| notice = nil |
| work = Task { |
| do throws(BaseAPIError) { |
| @@ -186,6 +192,7 @@ import SwiftUI |
| guard let row = pendingUninstall else { return } |
| pendingUninstall = nil |
| uninstalling = row.id |
| + writes += 1 |
| notice = nil |
| let started = ContinuousClock.now |
| work = Task { |
diff --git a/native/apple/Sources/BaseKit/Team/StoreView.swift b/native/apple/Sources/BaseKit/Team/StoreView.swift| index 8e92406..58c3f98 100644 |
| --- a/native/apple/Sources/BaseKit/Team/StoreView.swift |
| +++ b/native/apple/Sources/BaseKit/Team/StoreView.swift |
| @@ -132,10 +132,14 @@ struct StoreRowActions: ViewModifier { |
| let row: StoreRow |
| let action: StoreModel.Action |
| func body(content: Content) -> some View { |
| + // Named, and the row's double-tap too (review nit 16). |
| switch action { |
| case .install: content.accessibilityAction(named: Text(BaseText.text("native.store.install"))) { model.install(row.id) } |
| + .accessibilityAction { model.install(row.id) } |
| case .tryAgain: content.accessibilityAction(named: Text(BaseText.text("native.store.try_again"))) { model.install(row.id) } |
| + .accessibilityAction { model.install(row.id) } |
| case .uninstall: content.accessibilityAction(named: Text(BaseText.text("native.store.uninstall"))) { model.requestUninstall(row.id) } |
| + .accessibilityAction { model.requestUninstall(row.id) } |
| default: content |
| } |
| } |
diff --git a/native/apple/Sources/BaseMac/BaseMacApp.swift b/native/apple/Sources/BaseMac/BaseMacApp.swift| index 0ff33dc..4cb514f 100644 |
| --- a/native/apple/Sources/BaseMac/BaseMacApp.swift |
| +++ b/native/apple/Sources/BaseMac/BaseMacApp.swift |
| @@ -4,6 +4,7 @@ import RastrilloMacUpdates |
| import AppKit |
| import BaseKit |
| import KeyboardShortcuts |
| +import Quartz |
| import RastrilloApple |
| import ServiceManagement |
| import SwiftUI |
| @@ -124,6 +125,12 @@ struct ColophonCommand: View { |
| } |
| } |
| + // Quick Look's panel asks the responder chain for a controller; the app |
| + // delegate is in it whichever window has the keyboard (review S3). |
| + override func acceptsPreviewPanelControl(_ panel: QLPreviewPanel!) -> Bool { true } |
| + override func beginPreviewPanelControl(_ panel: QLPreviewPanel!) { MacQuickLook.shared.take(panel) } |
| + override func endPreviewPanelControl(_ panel: QLPreviewPanel!) {} |
| + |
| func applicationDidBecomeActive(_ notification: Notification) { |
| Task { await session.foreground() } |
| } |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift b/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift| index 47fee97..a35ae19 100644 |
| --- a/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift |
| @@ -134,6 +134,35 @@ final class AttachmentCacheTests: XCTestCase { |
| XCTAssertFalse(FileManager.default.fileExists(atPath: old.path), "expired: gone when its preview closed") |
| } |
| + /// S3: the same file opened twice stays until both previews close. |
| + func testAFileOpenedTwiceStaysUntilBothClose() async throws { |
| + let now = Date(timeIntervalSince1970: 1_800_000_000) |
| + let c = cache(now: { now }) |
| + let old = try await c.file(for: file("at_old"), sentAt: now.addingTimeInterval(-30 * 86_400)) |
| + await c.previewing("at_old", open: true) |
| + await c.previewing("at_old", open: true) |
| + await c.previewing("at_old", open: false) |
| + await c.sweep() |
| + XCTAssertTrue(FileManager.default.fileExists(atPath: old.path), "still open once") |
| + await c.previewing("at_old", open: false) |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: old.path)) |
| + } |
| + |
| + /// S2: closing a preview reaches the cache once, and gives back the id |
| + /// for focus, however SwiftUI clears its own state first. |
| + @MainActor func testTheTrackerClosesWhatItShowed() async throws { |
| + let now = Date(timeIntervalSince1970: 1_800_000_000) |
| + let c = cache(now: { now }) |
| + let old = try await c.file(for: file("at_old"), sentAt: now.addingTimeInterval(-30 * 86_400)) |
| + await c.previewing("at_old", open: true) |
| + let tracker = QuickLookTracker() |
| + tracker.opened(QuickLookItem(id: "at_old", url: old)) |
| + XCTAssertEqual(tracker.closed(cache: c), "at_old") |
| + XCTAssertNil(tracker.closed(cache: c), "once") |
| + for _ in 0..<100 where FileManager.default.fileExists(atPath: old.path) { try await Task.sleep(for: .milliseconds(10)) } |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: old.path), "the expired file went when its preview closed") |
| + } |
| + |
| func testTheSweepRemovesOtherAccountsFolders() async throws { |
| let other = root.appendingPathComponent("ffffffffffffffffffffffffffffffff/at_9") |
| try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift b/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift| index eb78280..6930dfb 100644 |
| --- a/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentDraftTests.swift |
| @@ -18,7 +18,10 @@ import XCTest |
| private var waiting: [String: CheckedContinuation<AskAttachment, Error>] = [:] |
| var progress: [String: @Sendable (Double) -> Void] = [:] |
| + /// Base answers even an upload the app cancelled (it was already sent). |
| + var answersCancelled = false |
| func script(_ name: String, _ results: [Result<AskAttachment, Error>]) { answers[name] = results } |
| + func answerCancelled() { answersCancelled = true } |
| func failDeletes(_ error: BaseAPIError) { deleteAnswer = error } |
| func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { |
| started.append(file.name) |
| @@ -29,6 +32,7 @@ import XCTest |
| let next = queue.removeFirst(); answers[file.name] = queue |
| return try next.get() |
| } |
| + if answersCancelled { return try await withCheckedThrowingContinuation { waiting[file.name] = $0 } } |
| return try await withTaskCancellationHandler { |
| try await withCheckedThrowingContinuation { waiting[file.name] = $0 } |
| } onCancel: { Task { await self.cancel(file.name) } } |
| @@ -220,6 +224,67 @@ import XCTest |
| XCTAssertEqual(d.items.first?.failure, "Couldn’t upload. Try again.") |
| } |
| + // MARK: Fable's code review |
| + |
| + /// S6: Remove while the upload is in flight, and Base answers anyway: |
| + /// the upload it made is deleted. |
| + func testAnUploadAnsweredAfterRemoveIsDeleted() async throws { |
| + let uploads = Uploads(); await uploads.answerCancelled() |
| + let d = draft(uploads) |
| + Task { await d.add(data: text, name: "a.txt") } |
| + try await settle { await uploads.started.count == 1 } |
| + d.remove(try XCTUnwrap(d.items.first?.id)) |
| + await uploads.finish("a.txt") |
| + try await settle { await uploads.deleted == ["at_a.txt"] } |
| + } |
| + |
| + /// S7: D5's marked chips keep their uploads, so Remove and the discard |
| + /// still delete them. |
| + func testMarkedChipsKeepTheirUploads() 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.mark("Files can’t be read right now.") |
| + XCTAssertEqual(d.unsentIDs, ["at_a.txt"]) |
| + d.remove(try XCTUnwrap(d.items.first?.id)) |
| + try await settle { await uploads.deleted == ["at_a.txt"] } |
| + } |
| + |
| + /// S7: an upload in flight when D5 marks the chips can't overwrite its |
| + /// words. |
| + func testAnUploadInFlightDoesntOverwriteD5sWords() 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 } |
| + d.mark("This file has expired. Attach it again.") |
| + try await Task.sleep(for: .milliseconds(80)) |
| + XCTAssertEqual(d.items.first?.failure, "This file has expired. Attach it again.") |
| + } |
| + |
| + /// Nit 5: a Retry-After of two minutes waits thirty seconds at most. |
| + func testRetryAfterIsCapped() async throws { |
| + let uploads = Uploads() |
| + await uploads.script("a.txt", [.failure(AttachmentRefusal(code: "busy", retryAfter: 120)), .success(Uploads.uploaded("a.txt"))]) |
| + let d = draft(uploads) |
| + await d.add(data: text, name: "a.txt") |
| + XCTAssertEqual(slept, [.seconds(30)]) |
| + } |
| + |
| + /// Nit 6: only the files that went leave the composer. |
| + func testOnlyTheSentFilesLeave() async throws { |
| + let uploads = Uploads() |
| + await uploads.script("a.txt", [.success(Uploads.uploaded("a.txt"))]) |
| + await uploads.script("b.txt", [.success(Uploads.uploaded("b.txt"))]) |
| + let d = draft(uploads) |
| + await d.add(data: text, name: "a.txt") |
| + await d.add(data: text, name: "b.txt") |
| + d.removeSent(["at_a.txt"]) |
| + XCTAssertEqual(d.items.map(\.name), ["b.txt"]) |
| + let deleted = await uploads.deleted |
| + XCTAssertEqual(deleted, [], "a sent file isn't deleted") |
| + } |
| + |
| // MARK: The PDF line |
| func testAPDFSaysAskCantReadIt() async throws { |
| @@ -277,3 +342,54 @@ extension SessionTests { |
| session.end() |
| } |
| } |
| + |
| +/// Fable's code review: the session's side. |
| +extension SessionTests { |
| + /// S1: the Mac calls background() whenever Base isn't the front app; |
| + /// its upload queue carries on. |
| + func testTheMacsQueueCarriesOnWhenBaseIsntInFront() throws { |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults(), cacheRoot: FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)) |
| + session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: GatedTransport()) |
| + session.background() |
| + #if os(macOS) |
| + XCTAssertFalse(try XCTUnwrap(session.ask).attachments.suspended) |
| + #endif |
| + session.end() |
| + } |
| + |
| + /// S5: signed out with nobody's account here, no account's files stay. |
| + func testASignedOutLaunchRemovesEveryAccountsFiles() throws { |
| + let root = FileManager.default.temporaryDirectory.appendingPathComponent("SessionTests-" + UUID().uuidString) |
| + defer { try? FileManager.default.removeItem(at: root) } |
| + let left = root.appendingPathComponent("0123456789abcdef0123456789abcdef/at_old") |
| + try FileManager.default.createDirectory(at: left, withIntermediateDirectories: true) |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults(), cacheRoot: root) |
| + session.stepChanged(.welcome) |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: root.path)) |
| + } |
| +} |
| + |
| +/// S4: a composer that doesn't attach (the menu panel's) sends its words |
| +/// alone, and the window's files stay. |
| +extension AskModelTests { |
| + func testTheMenuPanelSendsWordsAloneAndLeavesTheFiles() async throws { |
| + let (m, t) = model([uploaded(), json(200, Self.sent)]) |
| + ready(m) |
| + await m.attachments.add(data: Data("hi".utf8), name: "a.txt") |
| + m.text = "Here" |
| + XCTAssertTrue(m.canSend(withFiles: false)) |
| + await m.send(withFiles: false) |
| + XCTAssertTrue(body(t.calls[1]).hasPrefix("text=Here&key="), body(t.calls[1])) |
| + XCTAssertEqual(m.attachments.readyAttachments.map(\.id), ["at_one"], "the window's chip stays") |
| + } |
| + |
| + /// S4: a failed chip in the window doesn't stop the panel's words. |
| + func testAFailedChipDoesntStopThePanelsWords() async throws { |
| + let (m, _) = 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) |
| + XCTAssertTrue(m.canSend(withFiles: false)) |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift b/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift| index 2a8a60f..56c5a5d 100644 |
| --- a/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift |
| @@ -112,6 +112,12 @@ final class AttachmentFileTests: XCTestCase { |
| XCTAssertEqual(file.width, 2560) |
| } |
| + /// Review nit 7: a JPEG sent as it is is named .jpg, as a converted one. |
| + func testAJPEGIsNamedJPG() throws { |
| + let file = try AttachmentFile.prepare(image(.jpeg, width: 100, height: 100), name: "IMG_4022.jpeg") |
| + XCTAssertEqual(file.name, "IMG_4022.jpg") |
| + } |
| + |
| func testAFileIsPreparedFromItsURL() throws { |
| let file = try AttachmentFile.prepare(url: try write(image(.heic, width: 300, height: 200), "photo.heic")) |
| XCTAssertEqual(file.convertedFrom, "HEIC") |
diff --git a/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift b/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift| index 4ee3b74..c38a653 100644 |
| --- a/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/MacAttachmentTests.swift |
| @@ -13,6 +13,7 @@ import AppKit |
| @testable import BaseKit |
| import Foundation |
| import Testing |
| +import UniformTypeIdentifiers |
| @MainActor @Suite(.serialized) struct MacAttachmentTests { |
| @Test func pastedAndDroppedImagesUseTheDraftAndGateSend() async throws { |
| @@ -62,6 +63,16 @@ extension MacAttachmentTests { |
| #expect(await server.uploads.isEmpty) |
| } |
| + /// Review nit 1: a pasteboard with only a JPEG attaches it. |
| + @Test func aJPEGAloneAttaches() async throws { |
| + let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| + board.setData(try AttachmentTests.image(.jpeg), forType: .init("public.jpeg")) |
| + let draft = AttachmentDraft(client: AttachmentServer()) |
| + #expect(MacPasteboard.acceptAttachments(board, into: draft)) |
| + for _ in 0..<100 { if !draft.readyAttachments.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) } |
| + #expect(draft.readyAttachments.count == 1) |
| + } |
| + |
| @Test func aWebURLIsNotAnAttachment() { |
| let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() } |
| board.writeObjects([URL(string: "https://example.com/photo.png")! as NSURL]) |