Files in the thread, Quick Look, and the cache
Task 19 of the native slice 2 part 1 plan (spec 7.6, P9, R3).
- The person's bubble: thumbnails from /preview (a lone picture larger;
one that can't be read shows its name), then a pill per other file
(mark, name, size), then the words; files alone leave no empty line.
VoiceOver: "Image, {name}" (DRAFT) and "{name}, {size}", each a
button. FilesLine and its string are gone.
- Quick Look: the Mac's QLPreviewPanel on a click, or Space on the
focused file; the iPhone's QLPreviewController, with Share. Focus comes
back to the file when it closes. A file Base no longer has (404) says
"This file isn't available any more." (DRAFT).
- AttachmentCache (P9): Caches/<bundle>/Attachments/<accountKey>/<id>/<name>
(the bundle's own folder: the Mac app isn't sandboxed, so its Caches is
the person's, and a sweep there must touch only Base's); ids checked;
names reduced to a safe last component, at most 120 bytes on a character
boundary, with their media type's extension; 0600, out of backups,
complete protection on the iPhone; one download per id; dated by the
message (or the download); swept after 14 days, never under an open
Quick Look, and an expired file goes when its preview closes; other
accounts' folders swept; cleared when the session ends and when Ask is
disconnected. Sweeps at sign-in (launch), coming forward, the Mac's
window opening, and daily while the Mac app runs.
- PreviewCache: 64 thumbnails, 2 MiB each, on the main actor so a cached
one draws at once.
- The copied full-size preview (MessageAttachments, AttachmentPreview,
AttachmentPDF) is deleted; Quick Look replaces it.
- PrivacyInfo.xcprivacy: NSPrivacyAccessedAPICategoryFileTimestamp, C617.1.
Tests: AttachmentCacheTests (13, each P9 rule) and the session's clearing
and sweeping; AskViewTests' bubble parts and labels.
Snapshots: base-ask sent-files (mockups mac-quicklook, phone-sent), Mac
light and dark, iPhone also at AX3.
Not unit-tested: the Quick Look panel and controller themselves and the
focus return (Task 21's hand checks).
Gate: swift test -j 4 --filter 'AttachmentCacheTests|AskViewTests|SessionTests': 50
passed; build-iphone.sh simulator succeeded; snapshots record (reviewed),
compare mac and compare iphone: passed. check-strings.py ok.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Task 19: files in the thread, Quick Look and the cache
19 files changed,
+672
−148
native/PrivacyInfo.xcprivacy+10 −0native/apple/Sources/BaseKit/Ask/AskModel.swift+9 −1native/apple/Sources/BaseKit/Ask/Thread.swift+13 −25native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift+179 −0native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift+3 −102native/apple/Sources/BaseKit/Attachments/QuickLook.swift+185 −0native/apple/Sources/BaseKit/Resources/Localizable.xcstrings+12 −12native/apple/Sources/BaseKit/Session/BaseSession.swift+19 −0native/apple/Sources/BaseMac/BaseMacApp.swift+7 −0native/apple/Tests/BaseKitTests/AskViewTests.swift+13 −8native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift+204 −0native/apple/Tests/BaseSnapshots/AskSnapshots.swift+5 −0native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift+13 −0native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-ax3.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-default.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-ax3.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-default.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-dark-default.pngbinarynative/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-light-default.pngbinary
CI failed — 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 === [90m10:32PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net [90m10:32PM[0m [32mINF[0m [1m1 commits scanned.[0m [90m10:32PM[0m [32mINF[0m [1mscanned ~3144533 bytes (3.14 MB) in 259ms[0m [90m10:32PM[0m [33mWRN[0m [1mleaks found: 1[0m exit status 1 make: *** [Makefile:71: gitleaks] Error 1 amadan: step gitleaks failed: exit status 2 amadan: job failed at step gitleaks — its output is above, not at the tail of this log
diff --git a/native/PrivacyInfo.xcprivacy b/native/PrivacyInfo.xcprivacy| index 1f4ad6e..d57f6f4 100644 |
| --- a/native/PrivacyInfo.xcprivacy |
| +++ b/native/PrivacyInfo.xcprivacy |
| @@ -21,6 +21,16 @@ |
| <string>1C8F.1</string> |
| </array> |
| </dict> |
| + <dict> |
| + <!-- The files cache's sweep reads its own files' dates (slice 2, |
| + plan P9): files inside the app's container only. --> |
| + <key>NSPrivacyAccessedAPIType</key> |
| + <string>NSPrivacyAccessedAPICategoryFileTimestamp</string> |
| + <key>NSPrivacyAccessedAPITypeReasons</key> |
| + <array> |
| + <string>C617.1</string> |
| + </array> |
| + </dict> |
| </array> |
| </dict> |
| </plist> |
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift| index d82b33d..65cdb68 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift |
| @@ -87,7 +87,9 @@ import SwiftUI |
| /// When Ask's Oficina ID key wants renewing (Task 7), and where Equipo is. |
| public private(set) var renewAfter: Date? |
| /// Base says the member disconnected Ask (nil: it doesn't say). |
| - public private(set) var disconnected: Bool? |
| + public private(set) var disconnected: Bool? { |
| + didSet { if disconnected == true, oldValue != true { onDisconnected?() } } |
| + } |
| public private(set) var equipoOrigin: URL? |
| /// The composer's text. |
| public var text = "" |
| @@ -131,6 +133,12 @@ import SwiftUI |
| let client: BaseClient |
| /// The files waiting to go with the next message (slice 2). |
| public let attachments: AttachmentDraft |
| + /// The account's cache of files opened from the thread (P9). |
| + public var files: AttachmentCache? |
| + /// Sent files' thumbnails, in memory. |
| + public let previews = PreviewCache() |
| + /// Base said the member disconnected Ask: the session clears the cache. |
| + @ObservationIgnored var onDisconnected: (() -> Void)? |
| /// 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 |
diff --git a/native/apple/Sources/BaseKit/Ask/Thread.swift b/native/apple/Sources/BaseKit/Ask/Thread.swift| index 3e6f62d..8605bf4 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/Thread.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/Thread.swift |
| @@ -89,6 +89,9 @@ struct AskThread: View { |
| Bubble(person: m.isPerson, maxWidth: bubbleWidth) { |
| let parts = PersonBubble.parts(m) |
| VStack(alignment: .leading, spacing: 4) { |
| + if !m.attachments.isEmpty { |
| + MessageFiles(message: m, images: parts.images, files: parts.files, model: model).padding(.bottom, 2) |
| + } |
| // The person's own words take the web's little Markdown |
| // (PersonMarkdown); with none, they are exactly as written. |
| if !parts.showsText { |
| @@ -100,9 +103,7 @@ struct AskThread: View { |
| } else { |
| BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript) |
| } |
| - if let names = parts.names { |
| - FilesLine(names: names) |
| - } |
| + |
| } |
| } |
| case .draft(let d): |
| @@ -132,32 +133,19 @@ struct AskThread: View { |
| } |
| } |
| -/// What a person's bubble shows until the app draws files (slice 2, plan |
| -/// P9): their words, then one plain line of their files' names, so a |
| -/// message of files alone is never an empty bubble. |
| +/// What a person's bubble shows (slice 2): its files, then its words; a |
| +/// message of files alone has no empty line of words. |
| enum PersonBubble { |
| - struct Parts: Equatable { var showsText: Bool; var names: String? } |
| + struct Parts: Equatable { var showsText: Bool; var images: [AskAttachment]; var files: [AskAttachment] } |
| static func parts(_ m: AskMessage) -> Parts { |
| - let names = m.attachments.map(\.name).filter { !$0.isEmpty } |
| let hasText = !m.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| - return Parts(showsText: hasText || names.isEmpty, names: names.isEmpty ? nil : names.joined(separator: ", ")) |
| - } |
| -} |
| - |
| -/// The names line: a paperclip and the files' names, in the secondary |
| -/// ink; VoiceOver reads "Attached: …". |
| -struct FilesLine: View { |
| - let names: String |
| - @Environment(\.colorScheme) private var scheme |
| - var body: some View { |
| - HStack(alignment: .firstTextBaseline, spacing: 5) { |
| - Image(systemName: "paperclip").font(BaseFont.body(12, relativeTo: .footnote)).accessibilityHidden(true) |
| - Text(verbatim: names).font(BaseFont.body(13, relativeTo: .footnote)).fixedSize(horizontal: false, vertical: true) |
| - } |
| - .foregroundStyle(Palette(scheme)[.haze]) |
| - .accessibilityElement(children: .ignore) |
| - .accessibilityLabel(Text(BaseText.format("ask.files_line_a11y", ["names": names]))) |
| + return Parts(showsText: hasText || m.attachments.isEmpty, images: m.attachments.filter(\.isImage), files: m.attachments.filter { !$0.isImage }) |
| } |
| + /// A thumbnail's VoiceOver label. |
| + static func imageLabel(_ a: AskAttachment) -> String { BaseText.format("native.attach.image_a11y", ["name": a.name]) } |
| + /// A pill's: its name and size. |
| + static func pillLabel(_ a: AskAttachment) -> String { "\(a.name), \(size(a))" } |
| + static func size(_ a: AskAttachment) -> String { a.size.formatted(.byteCount(style: .file)) } |
| } |
| /// A line of the conversation: the person's on the right in teal, the |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift| new file mode 100644 |
| index 0000000..ea26e32 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentCache.swift |
| @@ -0,0 +1,179 @@ |
| +import Foundation |
| +import UniformTypeIdentifiers |
| + |
| +/// The files opened from the thread, kept on this device (plan P9, spec |
| +/// 7.6 and 7.9 ruling 12): |
| +/// - at `Caches/<bundle>/Attachments/<accountKey>/<attachment id>/<name>`: |
| +/// the bundle's own folder, because the Mac app isn't sandboxed and its |
| +/// Caches is the person's; `accountKey` is P5's hash, the id is checked, |
| +/// and the name is reduced to a safe last component with its media |
| +/// type's extension; |
| +/// - each file 0600, out of backups, and on the iPhone written with |
| +/// complete protection; |
| +/// - dated by its message (or its download), and swept after 14 days, |
| +/// except a file open in Quick Look, which goes when its preview closes |
| +/// if it expired meanwhile; |
| +/// - one download per id at a time; |
| +/// - another account's folder is swept away; this account's is cleared |
| +/// when the session ends or Ask is disconnected. |
| +/// Share and "Open with" hand a copy to another app, which these rules |
| +/// can't follow (spec 7.6). |
| +public actor AttachmentCache { |
| + public enum Failure: Error, Equatable { case badID, gone } |
| + |
| + public static let keep: TimeInterval = 14 * 86_400 |
| + |
| + let root: URL |
| + let accountKey: String |
| + let client: any AttachmentClient |
| + let now: @Sendable () -> Date |
| + private var inFlight: [String: Task<URL, Error>] = [:] |
| + private var open: Set<String> = [] |
| + /// 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) |
| + .appendingPathComponent("Attachments", isDirectory: true) |
| + } |
| + |
| + public init(root: URL = AttachmentCache.defaultRoot, accountKey: String, client: any AttachmentClient, |
| + now: @escaping @Sendable () -> Date = Date.init) { |
| + self.root = root; self.accountKey = accountKey; self.client = client; self.now = now |
| + } |
| + |
| + var folder: URL { root.appendingPathComponent(accountKey, isDirectory: true) } |
| + |
| + // MARK: Names |
| + |
| + /// `[A-Za-z0-9_-]{1,64}`. |
| + public static func validID(_ id: String) -> Bool { |
| + !id.isEmpty && id.utf8.count <= 64 && id.unicodeScalars.allSatisfy { CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-").contains($0) } |
| + } |
| + |
| + /// The server's name reduced to its last path component, without `/`, |
| + /// `\`, NUL, a leading `.` or `..`, at most 120 bytes on a character |
| + /// boundary, its extension the media type's (`bin` when unknown), so a |
| + /// text file named `x.command` opens as text. |
| + public static func safeName(_ name: String, mediaType: String) -> String { |
| + var last = name.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) ?? "" |
| + last = last.replacingOccurrences(of: "\u{0}", with: "") |
| + while last.hasPrefix(".") { last.removeFirst() } |
| + var stem = (last as NSString).deletingPathExtension |
| + if stem.isEmpty || stem == ".." { stem = "file" } |
| + let ext = UTType(mimeType: mediaType)?.preferredFilenameExtension ?? "bin" |
| + let room = 120 - ext.utf8.count - 1 |
| + var cut = "" |
| + for character in stem { |
| + if cut.utf8.count + String(character).utf8.count > room { break } |
| + cut.append(character) |
| + } |
| + return (cut.isEmpty ? "file" : cut) + "." + ext |
| + } |
| + |
| + /// What each file is written with. |
| + static func attributes(phone: Bool, modified: Date) -> [FileAttributeKey: Any] { |
| + var out: [FileAttributeKey: Any] = [.posixPermissions: 0o600, .modificationDate: modified] |
| + if phone { out[.protectionKey] = FileProtectionType.complete } |
| + return out |
| + } |
| + |
| + static var isPhone: Bool { |
| + #if os(iOS) |
| + true |
| + #else |
| + false |
| + #endif |
| + } |
| + |
| + // MARK: Files |
| + |
| + /// The file, from the cache or downloaded once (a second caller waits |
| + /// for the first). `sentAt` is its message's time. |
| + public func file(for attachment: AskAttachment, sentAt: Date?) async throws -> URL { |
| + guard Self.validID(attachment.id) else { throw Failure.badID } |
| + let directory = folder.appendingPathComponent(attachment.id, isDirectory: true) |
| + let url = directory.appendingPathComponent(Self.safeName(attachment.name, mediaType: attachment.mediaType)) |
| + if FileManager.default.fileExists(atPath: url.path) { return url } |
| + if let running = inFlight[attachment.id] { return try await running.value } |
| + let client = self.client, date = sentAt ?? now() |
| + let task = Task<URL, Error> { |
| + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) |
| + let part = directory.appendingPathComponent(".part-" + UUID().uuidString) |
| + do { |
| + try await client.download(id: attachment.id, to: part) |
| + } catch { |
| + try? FileManager.default.removeItem(at: part) |
| + if case .server(404, _, _)? = error as? BaseAPIError { |
| + try? FileManager.default.removeItem(at: directory) |
| + throw Failure.gone |
| + } |
| + throw error |
| + } |
| + 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() |
| + values.isExcludedFromBackup = true |
| + var excluded = url |
| + try excluded.setResourceValues(values) |
| + return url |
| + } |
| + inFlight[attachment.id] = task |
| + defer { inFlight[attachment.id] = nil } |
| + return try await task.value |
| + } |
| + |
| + /// 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) |
| + let directory = folder.appendingPathComponent(id, isDirectory: true) |
| + if expired(directory) { try? FileManager.default.removeItem(at: directory) } |
| + } |
| + |
| + /// Files past 14 days (not open in Quick Look), and other accounts' |
| + /// folders, removed. Runs at launch, on coming forward, when the Mac's |
| + /// window opens and daily while it runs. |
| + public func sweep() { |
| + sweeps += 1 |
| + let manager = FileManager.default |
| + for other in (try? manager.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? [] where other.lastPathComponent != accountKey { |
| + try? manager.removeItem(at: other) |
| + } |
| + for directory in (try? manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? [] |
| + where !open.contains(directory.lastPathComponent) && expired(directory) { |
| + try? manager.removeItem(at: directory) |
| + } |
| + } |
| + |
| + /// The account's files, all gone (sign-out, Ask disconnected). |
| + public func clear() { |
| + cleared = true |
| + try? FileManager.default.removeItem(at: folder) |
| + } |
| + |
| + private func expired(_ directory: URL) -> Bool { |
| + let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] |
| + guard !files.isEmpty else { return true } |
| + let cutoff = now().addingTimeInterval(-Self.keep) |
| + return files.allSatisfy { ((try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast) < cutoff } |
| + } |
| +} |
| + |
| +/// Thumbnails in memory (P9): 64 at most, each at most 2 MiB, the oldest |
| +/// going first. On the main actor, so a thumbnail already here draws at once. |
| +@MainActor public final class PreviewCache { |
| + let limit: Int |
| + private var data: [String: Data] = [:] |
| + private var order: [String] = [] |
| + public init(limit: Int = 64) { self.limit = limit } |
| + public var count: Int { data.count } |
| + public func get(_ id: String) -> Data? { data[id] } |
| + public func put(_ id: String, _ bytes: Data) { |
| + guard bytes.count <= BaseClient.previewMaxBytes else { return } |
| + if data.updateValue(bytes, forKey: id) == nil { order.append(id) } |
| + while order.count > limit { data[order.removeFirst()] = nil } |
| + } |
| +} |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift| index d886bc3..34b00ea 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift |
| @@ -1,10 +1,10 @@ |
| // Copied from Equipo origin/main 8bd40ed1: native/apple/Sources/EquipoKit/Attachments/AttachmentViews.swift |
| // (R5). Task 12 makes it compile: Base's palette, faces and words, and |
| -// AttachmentClient. Tasks 17 to 19 draw Base's chips and bubble; Task 19 |
| -// deletes the full-size preview, which Quick Look replaces. |
| +// AttachmentClient. Task 17 restyled the strip as Base's chips; Task 19 |
| +// deleted the full-size preview (MessageAttachments, AttachmentPreview), |
| +// which Quick Look replaces. |
| import SwiftUI |
| import ImageIO |
| -import PDFKit |
| /// The composer's files (Base's chips, mockups `mac-attach`, `phone-attach`; |
| /// Equipo's AttachmentDraftStrip restyled, Task 17): each file's mark (its |
| @@ -179,102 +179,3 @@ struct AttachmentPicture: View { |
| return CGImageSourceCreateThumbnailAtIndex(source, 0, [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: side] as CFDictionary) |
| } |
| } |
| - |
| -/// Sent thumbnails use authenticated API reads, never bare remote-image URLs. |
| -public struct MessageAttachments: View { |
| - let attachments: [AskAttachment] |
| - let client: any AttachmentClient |
| - @State private var selected: AskAttachment? |
| - public init(_ attachments: [AskAttachment], client: any AttachmentClient) { |
| - self.attachments = attachments; self.client = client |
| - } |
| - public var body: some View { |
| - LazyVGrid(columns: [GridItem(.adaptive(minimum: 120, maximum: 180), alignment: .leading)], alignment: .leading, spacing: 8) { |
| - ForEach(attachments) { file in |
| - Button { selected = file } label: { SentAttachmentTile(file: file, client: client) } |
| - .buttonStyle(.plain).accessibilityLabel(file.name) |
| - } |
| - } |
| - #if os(iOS) |
| - .fullScreenCover(item: $selected) { AttachmentPreview(file: $0, client: client) } |
| - #else |
| - .sheet(item: $selected) { AttachmentPreview(file: $0, client: client).frame(minWidth: 600, minHeight: 500) } |
| - #endif |
| - } |
| -} |
| - |
| -private struct SentAttachmentTile: View { |
| - @Environment(\.colorScheme) private var scheme |
| - private var p: Palette { Palette(scheme) } |
| - let file: AskAttachment |
| - let client: any AttachmentClient |
| - @State private var data: Data? |
| - var body: some View { |
| - VStack(alignment: .leading, spacing: 4) { |
| - AttachmentPicture(data: data, name: file.name).frame(height: 100).frame(maxWidth: .infinity) |
| - .background(p[.chip]).clipShape(.rect(cornerRadius: 8)) |
| - Text(file.name).font(BaseFont.body(12, relativeTo: .caption)).lineLimit(1).truncationMode(.middle).frame(maxWidth: .infinity, alignment: .leading) |
| - } |
| - .task(id: file.id) { |
| - if file.kind == "image" { data = try? await client.data(id: file.id, preview: true) } |
| - } |
| - } |
| -} |
| - |
| -private struct AttachmentPreview: View { |
| - @Environment(\.colorScheme) private var scheme |
| - private var p: Palette { Palette(scheme) } |
| - let file: AskAttachment |
| - let client: any AttachmentClient |
| - @Environment(\.dismiss) private var dismiss |
| - @State private var data: Data? |
| - @State private var failure = false |
| - @State private var image: CGImage? |
| - var body: some View { |
| - NavigationStack { |
| - Group { |
| - if let data { |
| - if let image { |
| - ScrollView([.horizontal, .vertical]) { |
| - Image(decorative: image, scale: 1).resizable().scaledToFit() |
| - .containerRelativeFrame(.horizontal).accessibilityLabel(file.name) |
| - } |
| - } else if file.mediaType == "application/pdf" { AttachmentPDF(data: data) } |
| - else { ScrollView { Text(String(decoding: data, as: UTF8.self)).font(.system(.body, design: .monospaced)).textSelection(.enabled).padding() } } |
| - } else if failure { |
| - VStack { |
| - Text(BaseText.text("native.attach.gone")) |
| - Button(BaseText.text("native.attach.retry")) { Task { await load() } } |
| - } |
| - } else { ProgressView().accessibilityLabel(file.name) } |
| - } |
| - .frame(maxWidth: .infinity, maxHeight: .infinity) |
| - .background(p[.menuBase]).navigationTitle(file.name) |
| - .toolbar { ToolbarItem(placement: .confirmationAction) { Button(BaseText.text("ask.close")) { dismiss() } } } |
| - }.task { await load() } |
| - } |
| - private func load() async { |
| - failure = false |
| - do { |
| - let bytes = try await client.data(id: file.id, preview: false) |
| - let decoded = await Task.detached { AttachmentPicture.thumbnail(bytes, side: 4096) }.value |
| - guard !Task.isCancelled else { return } |
| - image = decoded; data = bytes |
| - } |
| - catch { failure = true } |
| - } |
| -} |
| - |
| -#if os(iOS) |
| -private struct AttachmentPDF: UIViewRepresentable { |
| - let data: Data |
| - func makeUIView(context: Context) -> PDFView { let view = PDFView(); view.autoScales = true; view.document = PDFDocument(data: data); return view } |
| - func updateUIView(_ view: PDFView, context: Context) {} |
| -} |
| -#else |
| -private struct AttachmentPDF: NSViewRepresentable { |
| - let data: Data |
| - func makeNSView(context: Context) -> PDFView { let view = PDFView(); view.autoScales = true; view.document = PDFDocument(data: data); return view } |
| - func updateNSView(_ view: PDFView, context: Context) {} |
| -} |
| -#endif |
diff --git a/native/apple/Sources/BaseKit/Attachments/QuickLook.swift b/native/apple/Sources/BaseKit/Attachments/QuickLook.swift| new file mode 100644 |
| index 0000000..c1589a7 |
| --- /dev/null |
| +++ b/native/apple/Sources/BaseKit/Attachments/QuickLook.swift |
| @@ -0,0 +1,185 @@ |
| +import SwiftUI |
| +#if os(macOS) |
| +import AppKit |
| +import Quartz |
| +#elseif os(iOS) |
| +import QuickLook |
| +import UIKit |
| +#endif |
| + |
| +/// A sent message's files (mockups `mac-quicklook`, `phone-sent`): its |
| +/// pictures' thumbnails (from `/preview`), a lone one larger, then a pill |
| +/// for each other file (its mark, name and size). Each opens in Quick Look |
| +/// (the Mac's panel; the iPhone's QLPreviewController, with Share), from |
| +/// the account's cache; focus comes back to it when Quick Look closes. |
| +struct MessageFiles: View { |
| + let message: AskMessage |
| + let images: [AskAttachment] |
| + let files: [AskAttachment] |
| + let model: AskModel |
| + @State private var gone = false |
| + @State private var showing: QuickLookItem? |
| + @AccessibilityFocusState private var focus: String? |
| + @Environment(\.colorScheme) private var scheme |
| + |
| + var body: some View { |
| + let p = Palette(scheme) |
| + VStack(alignment: .leading, spacing: 6) { |
| + if !images.isEmpty { |
| + HStack(spacing: 6) { |
| + ForEach(images) { image in |
| + let side: CGFloat = images.count == 1 ? 220 : 110 |
| + Button { open(image) } label: { |
| + SentThumbnail(attachment: image, model: model) |
| + .frame(width: side, height: images.count == 1 ? min(220, side * CGFloat(max(image.height, 1)) / CGFloat(max(image.width, 1))) : side) |
| + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) |
| + } |
| + .buttonStyle(.plain) |
| + .accessibilityLabel(Text(verbatim: PersonBubble.imageLabel(image))) |
| + .accessibilityFocused($focus, equals: image.id) |
| + #if os(macOS) |
| + .onKeyPress(.space) { open(image); return .handled } |
| + #endif |
| + } |
| + } |
| + } |
| + ForEach(files) { file in |
| + Button { open(file) } label: { |
| + HStack(spacing: 7) { |
| + Image(systemName: "doc").font(.system(size: 13, weight: .medium)) |
| + Text(verbatim: file.name).font(BaseFont.body(13.5, .semibold, relativeTo: .footnote)).lineLimit(1).truncationMode(.middle) |
| + Text(verbatim: PersonBubble.size(file)).font(BaseFont.body(12.5, relativeTo: .caption)).foregroundStyle(p[.haze]) |
| + } |
| + .padding(.horizontal, 10).frame(minHeight: 32) |
| + .background(p[.chip], in: RoundedRectangle(cornerRadius: 8, style: .continuous)) |
| + .overlay { RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(p[.chipEdge], lineWidth: 1) } |
| + } |
| + .buttonStyle(.plain) |
| + .accessibilityLabel(Text(verbatim: PersonBubble.pillLabel(file))) |
| + .accessibilityFocused($focus, equals: file.id) |
| + #if os(macOS) |
| + .onKeyPress(.space) { open(file); return .handled } |
| + #endif |
| + } |
| + } |
| + .alert(Text(BaseText.text("native.attach.gone")), isPresented: $gone) { |
| + Button(BaseText.text("ask.close"), role: .cancel) {} |
| + } |
| + #if os(iOS) |
| + .sheet(item: $showing, onDismiss: closed) { item in PhoneQuickLook(url: item.url).ignoresSafeArea() } |
| + #endif |
| + } |
| + |
| + private func open(_ attachment: AskAttachment) { |
| + guard let cache = model.files else { return } |
| + let sent = message.createdAt |
| + Task { |
| + 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) |
| + #if os(macOS) |
| + MacQuickLook.shared.show(item) { closed(item) } |
| + #else |
| + showing = item |
| + #endif |
| + } catch AttachmentCache.Failure.gone { |
| + gone = true |
| + } catch {} |
| + } |
| + } |
| + |
| + /// 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 } |
| + |
| +/// A sent picture's thumbnail, from Base's `/preview`, kept in memory; |
| +/// its name when it can't be read. |
| +struct SentThumbnail: View { |
| + let attachment: AskAttachment |
| + let model: AskModel |
| + @State private var data: Data? |
| + @State private var failed = false |
| + @Environment(\.colorScheme) private var scheme |
| + init(attachment: AskAttachment, model: AskModel) { |
| + self.attachment = attachment; self.model = model |
| + _data = State(initialValue: model.previews.get(attachment.id)) |
| + } |
| + var body: some View { |
| + let p = Palette(scheme) |
| + ZStack { |
| + p[.chip] |
| + if let data { |
| + AttachmentPicture(data: data, name: attachment.name).aspectRatio(contentMode: .fill) |
| + } else if failed { |
| + Text(verbatim: attachment.name).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.haze]).padding(6) |
| + } |
| + } |
| + .task(id: attachment.id) { |
| + if let cached = model.previews.get(attachment.id) { data = cached; return } |
| + do { |
| + let bytes = try await model.attachments.client.data(id: attachment.id, preview: true) |
| + model.previews.put(attachment.id, bytes) |
| + data = bytes |
| + } catch { |
| + failed = true |
| + } |
| + } |
| + } |
| +} |
| + |
| +#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() |
| + private var item: QuickLookItem? |
| + private var onClose: (() -> Void)? |
| + |
| + func show(_ item: QuickLookItem, onClose: @escaping () -> Void) { |
| + self.onClose?() |
| + self.item = item |
| + self.onClose = onClose |
| + guard let panel = QLPreviewPanel.shared() else { return } |
| + panel.dataSource = self |
| + panel.delegate = self |
| + panel.reloadData() |
| + panel.makeKeyAndOrderFront(nil) |
| + } |
| + |
| + nonisolated func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { 1 } |
| + nonisolated func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> (any QLPreviewItem)! { |
| + MainActor.assumeIsolated { item?.url as NSURL? } |
| + } |
| + nonisolated func windowWillClose(_ notification: Notification) { |
| + MainActor.assumeIsolated { |
| + onClose?() |
| + onClose = nil |
| + item = nil |
| + } |
| + } |
| +} |
| +#elseif os(iOS) |
| +/// The iPhone's Quick Look, with Share. |
| +struct PhoneQuickLook: UIViewControllerRepresentable { |
| + let url: URL |
| + func makeUIViewController(context: Context) -> UINavigationController { |
| + let controller = QLPreviewController() |
| + controller.dataSource = context.coordinator |
| + return UINavigationController(rootViewController: controller) |
| + } |
| + func updateUIViewController(_ controller: UINavigationController, context: Context) {} |
| + func makeCoordinator() -> Coordinator { Coordinator(url: url) } |
| + final class Coordinator: NSObject, QLPreviewControllerDataSource { |
| + let url: URL |
| + init(url: URL) { self.url = url } |
| + func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 } |
| + func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> any QLPreviewItem { url as NSURL } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings| index 1f5f114..2921341 100644 |
| --- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings |
| @@ -109,18 +109,6 @@ |
| } |
| } |
| }, |
| - "ask.files_line_a11y": { |
| - "comment": "Copy review 13 (pending). VoiceOver's reading of the line of a person's files' names under their words, until the app draws files (slice 2). {names} is the names, comma-separated.", |
| - "extractionState": "manual", |
| - "localizations": { |
| - "en": { |
| - "stringUnit": { |
| - "state": "translated", |
| - "value": "Attached: {names}" |
| - } |
| - } |
| - } |
| - }, |
| "ask.jump": { |
| "comment": "Base on the web's approved copy. Floats at the conversation's foot when the person has scrolled up and something new arrives (chat.html).", |
| "extractionState": "manual", |
| @@ -661,6 +649,18 @@ |
| } |
| } |
| }, |
| + "native.attach.image_a11y": { |
| + "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). VoiceOver: a picture's thumbnail in a sent message. A button: it opens the picture in Quick Look.", |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Image, {name}" |
| + } |
| + } |
| + } |
| + }, |
| "native.attach.limit": { |
| "comment": "Base on the web's approved copy (chat.html data-w-limit). A file's chip when 20 uploads already wait unsent.", |
| "extractionState": "manual", |
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift| index 4147fbf..d2f8a1d 100644 |
| --- a/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| +++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift |
| @@ -36,6 +36,8 @@ import RastrilloApple |
| public private(set) var team: TeamModels? |
| /// The sidebar's folds, for this account on this device (P5). |
| public private(set) var folds: SidebarFolds? |
| + /// The files opened from the thread, for this account (P9). |
| + public private(set) var files: AttachmentCache? |
| @ObservationIgnored public private(set) var askSetup: AskSetup? |
| @ObservationIgnored private var transport: SwappableTransport? |
| @@ -153,6 +155,14 @@ 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) |
| + files = cache |
| + ask.files = cache |
| + // Ask disconnected: its files go too (P9). |
| + ask.onDisconnected = { Task { await cache.clear() } } |
| + // At launch (a sign-in is the start of a session): other accounts' |
| + // folders and expired files go. |
| + sweepFiles() |
| refreshing = Task { await self.refresh() } |
| } |
| @@ -175,6 +185,8 @@ import RastrilloApple |
| team?.end() |
| team = nil |
| folds = nil |
| + if let files { Task { await files.clear() } } |
| + files = nil |
| ask = nil; askSetup = nil; client = nil; transport = nil; account = nil |
| signedIn = nil; me = nil; home = nil |
| } |
| @@ -226,8 +238,15 @@ import RastrilloApple |
| } |
| /// The app came forward. |
| + /// Expired files and other accounts' go: at launch, on coming forward, |
| + /// when the Mac's window opens and daily while it runs (P9). |
| + public func sweepFiles() { |
| + if let files { Task { await files.sweep() } } |
| + } |
| + |
| public func foreground() async { |
| ask?.attachments.resume() |
| + if let files { await files.sweep() } |
| await oficina.renewIfNeeded() |
| await refresh() |
| } |
diff --git a/native/apple/Sources/BaseMac/BaseMacApp.swift b/native/apple/Sources/BaseMac/BaseMacApp.swift| index 2050e26..0ff33dc 100644 |
| --- a/native/apple/Sources/BaseMac/BaseMacApp.swift |
| +++ b/native/apple/Sources/BaseMac/BaseMacApp.swift |
| @@ -107,7 +107,12 @@ struct ColophonCommand: View { |
| Task { await session.oficina.start() } |
| // Edit ▸ Paste attaches files in Ask's composer (Task 17). |
| MacPasteRoute.shared.install() |
| + // The files cache's daily sweep while the app runs (P9). |
| + sweeping = Timer.scheduledTimer(withTimeInterval: 86_400, repeats: true) { [weak self] _ in |
| + MainActor.assumeIsolated { self?.session.sweepFiles() } |
| + } |
| } |
| + private var sweeping: Timer? |
| /// Open Base: the window, forward (opened again if it was closed). |
| func showMain() { |
| @@ -152,6 +157,8 @@ struct MacRoot: View { |
| } |
| .ignoresSafeArea() |
| .frame(minWidth: 860, minHeight: 560) |
| + // The window opened: the files cache sweeps (P9). |
| + .onAppear { session.sweepFiles() } |
| .baseAppearance(session.me?.appearance ?? .system) |
| .onChange(of: phase) { _, now in if now != .active { session.background() } } |
| } |
diff --git a/native/apple/Tests/BaseKitTests/AskViewTests.swift b/native/apple/Tests/BaseKitTests/AskViewTests.swift| index 17cd0a2..b0f309d 100644 |
| --- a/native/apple/Tests/BaseKitTests/AskViewTests.swift |
| +++ b/native/apple/Tests/BaseKitTests/AskViewTests.swift |
| @@ -147,13 +147,18 @@ extension AskViewTests { |
| /// A person's bubble with files and words shows the words, then the |
| /// names line; with files alone, only the names; with words alone, no |
| /// line (plan P9). |
| - func testThePersonsBubbleNamesItsFiles() { |
| - let files = [AskAttachment(id: "at_abcdefgh12", kind: "image", name: "shot.png"), AskAttachment(id: "at_abcdefgh13", name: "q3.csv")] |
| - XCTAssertEqual(PersonBubble.parts(AskMessage(id: "m", role: "person", text: "Look", attachments: files)), |
| - .init(showsText: true, names: "shot.png, q3.csv")) |
| - XCTAssertEqual(PersonBubble.parts(AskMessage(id: "m", role: "person", text: " ", attachments: files)), |
| - .init(showsText: false, names: "shot.png, q3.csv")) |
| - XCTAssertEqual(PersonBubble.parts(AskMessage(id: "m", role: "person", text: "Look")), .init(showsText: true, names: nil)) |
| - XCTAssertEqual(BaseText.format("ask.files_line_a11y", ["names": "shot.png, q3.csv"]), "Attached: shot.png, q3.csv") |
| + /// Task 19: thumbnails, then pills, then the words; files alone leave |
| + /// no empty line. A thumbnail is "Image, {name}"; a pill its name and |
| + /// size. |
| + func testThePersonsBubbleShowsItsFiles() { |
| + let shot = AskAttachment(id: "at_abcdefgh12", kind: "image", name: "shot.png", mediaType: "image/png", size: 1_800_000) |
| + let csv = AskAttachment(id: "at_abcdefgh13", name: "q3.csv", mediaType: "text/csv", size: 14_000) |
| + XCTAssertEqual(PersonBubble.parts(AskMessage(id: "m", role: "person", text: "Look", attachments: [csv, shot])), |
| + .init(showsText: true, images: [shot], files: [csv])) |
| + XCTAssertEqual(PersonBubble.parts(AskMessage(id: "m", role: "person", text: " ", attachments: [shot])), |
| + .init(showsText: false, images: [shot], files: [])) |
| + XCTAssertEqual(PersonBubble.parts(AskMessage(id: "m", role: "person", text: "Look")), .init(showsText: true, images: [], files: [])) |
| + XCTAssertEqual(PersonBubble.imageLabel(shot), "Image, shot.png") |
| + XCTAssertEqual(PersonBubble.pillLabel(csv), "q3.csv, \(Int64(14_000).formatted(.byteCount(style: .file)))") |
| } |
| } |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift b/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift| new file mode 100644 |
| index 0000000..09f1354 |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentCacheTests.swift |
| @@ -0,0 +1,204 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import XCTest |
| + |
| +/// Task 19 (plan P9): the cache of files opened from the thread. |
| +final class AttachmentCacheTests: XCTestCase { |
| + var root: URL! |
| + let key = "a1b2c3d4e5f60718293a4b5c6d7e8f90" |
| + |
| + override func setUpWithError() throws { |
| + root = FileManager.default.temporaryDirectory.appendingPathComponent("AttachmentCacheTests-" + UUID().uuidString) |
| + } |
| + override func tearDownWithError() throws { try? FileManager.default.removeItem(at: root) } |
| + |
| + /// A client whose downloads count, and can be held. |
| + actor Downloads: AttachmentClient { |
| + var count = 0 |
| + var hold: CheckedContinuation<Void, Never>? |
| + var holding = false |
| + var missing = false |
| + func holdNext() { holding = true } |
| + func release() { hold?.resume(); hold = nil } |
| + func gone() { missing = true } |
| + func download(id: String, to destination: URL) async throws { |
| + count += 1 |
| + if missing { throw BaseAPIError.server(status: 404, code: nil, state: nil) } |
| + if holding { holding = false; await withCheckedContinuation { hold = $0 } } |
| + try Data("bytes of \(id)".utf8).write(to: destination, options: .withoutOverwriting) |
| + } |
| + func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment { throw BaseAPIError.offline } |
| + func delete(_ id: String) async throws {} |
| + func data(id: String, preview: Bool) async throws -> Data { Data() } |
| + } |
| + |
| + func cache(_ client: Downloads = Downloads(), now: @escaping @Sendable () -> Date = Date.init) -> AttachmentCache { |
| + AttachmentCache(root: root, accountKey: key, client: client, now: now) |
| + } |
| + func file(_ id: String = "at_1", _ name: String = "Report.pdf", _ type: String = "application/pdf") -> AskAttachment { |
| + AskAttachment(id: id, kind: "file", name: name, mediaType: type) |
| + } |
| + |
| + func testTheFileGoesUnderTheAccountAndID() async throws { |
| + let url = try await cache().file(for: file(), sentAt: nil) |
| + XCTAssertEqual(url.path, root.appendingPathComponent("\(key)/at_1/Report.pdf").path) |
| + XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), "bytes of at_1") |
| + } |
| + |
| + func testNamesAreReducedToALastComponentWithTheirTypesExtension() { |
| + XCTAssertEqual(AttachmentCache.safeName("../x.command", mediaType: "text/plain"), "x.txt") |
| + XCTAssertEqual(AttachmentCache.safeName("a/b\\c.png", mediaType: "image/png"), "c.png") |
| + XCTAssertEqual(AttachmentCache.safeName(".hidden.html", mediaType: "text/plain"), "hidden.txt") |
| + XCTAssertEqual(AttachmentCache.safeName("..", mediaType: "text/csv"), "file.csv") |
| + XCTAssertEqual(AttachmentCache.safeName("na\u{0}me.pdf", mediaType: "application/pdf"), "name.pdf") |
| + XCTAssertEqual(AttachmentCache.safeName("thing", mediaType: "application/x-unknown"), "thing.bin") |
| + let long = String(repeating: "é", count: 100) + ".txt" |
| + let cut = AttachmentCache.safeName(long, mediaType: "text/plain") |
| + XCTAssertLessThanOrEqual(cut.utf8.count, 120) |
| + XCTAssertTrue(cut.hasSuffix(".txt")) |
| + XCTAssertNotNil(cut.data(using: .utf8), "cut on a character boundary") |
| + } |
| + |
| + func testIDsAreChecked() async { |
| + XCTAssertTrue(AttachmentCache.validID("at_AZaz09-_")) |
| + for bad in ["", "../at", "at/1", String(repeating: "a", count: 65), "at 1"] { |
| + XCTAssertFalse(AttachmentCache.validID(bad), bad) |
| + } |
| + do { _ = try await cache().file(for: file("../etc"), sentAt: nil); XCTFail("a bad id was taken") } catch {} |
| + } |
| + |
| + func testFilesAreOwnersOnlyAndOutOfBackups() async throws { |
| + let url = try await cache().file(for: file(), sentAt: nil) |
| + let attributes = try FileManager.default.attributesOfItem(atPath: url.path) |
| + XCTAssertEqual(attributes[.posixPermissions] as? Int, 0o600) |
| + XCTAssertEqual(try url.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup, true) |
| + } |
| + |
| + /// On the iPhone each file is written with complete protection. |
| + func testTheIPhonesFilesAreProtectedComplete() { |
| + let date = Date(timeIntervalSince1970: 1_800_000_000) |
| + let phone = AttachmentCache.attributes(phone: true, modified: date) |
| + XCTAssertEqual(phone[.protectionKey] as? FileProtectionType, .complete) |
| + XCTAssertEqual(phone[.posixPermissions] as? Int, 0o600) |
| + XCTAssertEqual(phone[.modificationDate] as? Date, date) |
| + XCTAssertNil(AttachmentCache.attributes(phone: false, modified: date)[.protectionKey]) |
| + } |
| + |
| + func testOneDownloadPerID() async throws { |
| + let client = Downloads(); await client.holdNext() |
| + let c = cache(client), report = file() |
| + async let first = c.file(for: report, sentAt: nil) |
| + try await Task.sleep(for: .milliseconds(50)) |
| + async let second = c.file(for: report, sentAt: nil) |
| + try await Task.sleep(for: .milliseconds(50)) |
| + await client.release() |
| + let (a, b) = try await (first, second) |
| + XCTAssertEqual(a, b) |
| + let count = await client.count |
| + XCTAssertEqual(count, 1) |
| + _ = try await c.file(for: file(), sentAt: nil) |
| + let again = await client.count |
| + XCTAssertEqual(again, 1, "a file already here isn't downloaded again") |
| + } |
| + |
| + func testTheFileIsDatedByItsMessageOrItsDownload() async throws { |
| + let sent = Date(timeIntervalSince1970: 1_790_000_000) |
| + let now = Date(timeIntervalSince1970: 1_800_000_000) |
| + let c = cache(now: { now }) |
| + let a = try await c.file(for: file("at_a"), sentAt: sent) |
| + let b = try await c.file(for: file("at_b"), sentAt: nil) |
| + XCTAssertEqual(try a.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, sent) |
| + XCTAssertEqual(try b.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, now) |
| + } |
| + |
| + func testTheSweepRemovesWhatIsOlderThanFourteenDays() 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(-15 * 86_400)) |
| + let fresh = try await c.file(for: file("at_new"), sentAt: now.addingTimeInterval(-13 * 86_400)) |
| + await c.sweep() |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: old.deletingLastPathComponent().path)) |
| + XCTAssertTrue(FileManager.default.fileExists(atPath: fresh.path)) |
| + } |
| + |
| + /// R3: never under an open Quick Look; an expired one goes when it closes. |
| + func testTheSweepSkipsAFileOpenInQuickLookAndRemovesItWhenItCloses() 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.sweep() |
| + XCTAssertTrue(FileManager.default.fileExists(atPath: old.path), "open in Quick Look") |
| + await c.previewing("at_old", open: false) |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: old.path), "expired: gone when its preview closed") |
| + } |
| + |
| + func testTheSweepRemovesOtherAccountsFolders() async throws { |
| + let other = root.appendingPathComponent("ffffffffffffffffffffffffffffffff/at_9") |
| + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) |
| + let c = cache() |
| + let mine = try await c.file(for: file(), sentAt: nil) |
| + await c.sweep() |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: other.deletingLastPathComponent().path)) |
| + XCTAssertTrue(FileManager.default.fileExists(atPath: mine.path)) |
| + } |
| + |
| + func testClearingRemovesTheAccountsFolder() async throws { |
| + let c = cache() |
| + let url = try await c.file(for: file(), sentAt: nil) |
| + await c.clear() |
| + XCTAssertFalse(FileManager.default.fileExists(atPath: url.deletingLastPathComponent().deletingLastPathComponent().path)) |
| + } |
| + |
| + func testAFileBaseNoLongerHasIsGone() async throws { |
| + let client = Downloads(); await client.gone() |
| + do { _ = try await cache(client).file(for: file(), sentAt: nil); XCTFail("no error") } |
| + catch { XCTAssertEqual(error as? AttachmentCache.Failure, .gone) } |
| + } |
| + |
| + @MainActor func testPreviewsAreKeptSixtyFourAtATime() { |
| + let previews = PreviewCache(limit: 64) |
| + for n in 0..<70 { previews.put("at_\(n)", Data(repeating: 1, count: 10)) } |
| + XCTAssertNil(previews.get("at_0"), "the oldest went") |
| + XCTAssertNotNil(previews.get("at_69")) |
| + XCTAssertEqual(previews.count, 64) |
| + previews.put("big", Data(repeating: 1, count: (2 << 20) + 1)) |
| + XCTAssertNil(previews.get("big"), "over 2 MiB is never kept") |
| + } |
| +} |
| + |
| +/// P9: when the session clears and sweeps the cache. |
| +extension SessionTests { |
| + func testTheCacheIsClearedWhenTheSessionEndsAndSweptComingForward() async throws { |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| + let t = gated("alice", "Alice's", "Hello Alice") |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { t.release(path) } |
| + session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: t) |
| + let cache = try XCTUnwrap(session.files) |
| + var sweeps = 0 |
| + for _ in 0..<100 where sweeps == 0 { try await Task.sleep(for: .milliseconds(10)); sweeps = await cache.sweeps } |
| + XCTAssertEqual(sweeps, 1, "at launch (sign-in)") |
| + await session.foreground() |
| + let after = await cache.sweeps |
| + XCTAssertEqual(after, 2, "on coming forward") |
| + session.end() |
| + XCTAssertNil(session.files) |
| + var cleared = false |
| + for _ in 0..<100 where !cleared { try await Task.sleep(for: .milliseconds(10)); cleared = await cache.cleared } |
| + XCTAssertTrue(cleared) |
| + } |
| + |
| + func testDisconnectingAskClearsTheCache() async throws { |
| + let session = BaseSession(oficina: memoryOficina(), defaults: freshDefaults()) |
| + let t = gated("alice", "Alice's", "Hello Alice") |
| + t.answer("/ask/state", #"{"state":"ready","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"disconnected":true}"#) |
| + for path in ["/api/v1/me", "/api/v1/home", "/ask/state"] { t.release(path) } |
| + session.begin(identity: "id-alice", origin: URL(string: "https://alice.example")!, transport: t) |
| + let cache = try XCTUnwrap(session.files) |
| + await session.refreshing?.value |
| + var cleared = false |
| + for _ in 0..<100 where !cleared { try await Task.sleep(for: .milliseconds(10)); cleared = await cache.cleared } |
| + XCTAssertTrue(cleared, "Ask disconnected: its files go") |
| + session.end() |
| + } |
| +} |
diff --git a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift| index 365d5f2..d56a355 100644 |
| --- a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift |
| +++ b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift |
| @@ -23,6 +23,11 @@ final class AskSnapshots: XCTestCase { |
| SnapshotScreen("thread", mac: .fixed(width: 1000, height: 720), iphone: .fixed(width: 402, height: 874)) { |
| AskFrame { AskView(model: AskFixtures.thread(), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) } |
| }, |
| + // Task 19 (mockups mac-quicklook, phone-sent): the person's |
| + // message with its pictures and a file, opened in Quick Look. |
| + SnapshotScreen("sent-files", mac: .fixed(width: 1000, height: 720), iphone: .fixed(width: 402, height: 874)) { |
| + AskFrame { AskView(model: AttachmentFixtures.sentThread(), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) } |
| + }, |
| SnapshotScreen("job-view", mac: .width(320), iphone: .width(402)) { |
| JobView(job: AskFixtures.job, timeZone: AskFixtures.zone, close: {}, now: SnapshotSettings.now) |
| }, |
diff --git a/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift b/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift| index f9388d6..a88222e 100644 |
| --- a/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift |
| +++ b/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift |
| @@ -95,6 +95,19 @@ import UniformTypeIdentifiers |
| return data as Data |
| } |
| + /// Mockups mac-quicklook and phone-sent: the person's message with two |
| + /// pictures and a CSV, its thumbnails already in memory. |
| + static func sentThread() -> AskModel { |
| + let model = attachingThread(draft: AttachmentDraft(client: FixtureAttachmentClient(), background: NoBackgroundWork(), announce: { _ in })) |
| + let csv = AskAttachment(id: "at_orders", kind: "file", name: "Orders.csv", mediaType: "text/csv", size: 14_000) |
| + model.apply(.message(AskMessage(id: "m5", role: "person", |
| + text: "Use these on the website: the shopfront for the top of the page, the loaves for the menu. And can you count last December’s orders by day?", |
| + turnID: "t5", attachments: sent + [csv]))) |
| + model.previews.put("at_fixture", image) |
| + model.previews.put("at_landscape", landscape) |
| + return model |
| + } |
| + |
| static var prepared: AskModel? |
| static var preparedPhone: AskModel? |
| static func prepare() async { |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-ax3.png| new file mode 100644 |
| index 0000000..9667d9c |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-ax3.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-default.png| new file mode 100644 |
| index 0000000..775e742 |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-dark-default.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-ax3.png| new file mode 100644 |
| index 0000000..0fe4efd |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-ax3.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-default.png| new file mode 100644 |
| index 0000000..7a388a7 |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/sent-files-light-default.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-dark-default.png| new file mode 100644 |
| index 0000000..12f1e5b |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-dark-default.png differ |
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-light-default.png| new file mode 100644 |
| index 0000000..b49c18a |
| Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/sent-files-light-default.png differ |