oficina / base Public

Attaching on the Mac: Paste, drop, the paperclip, and Base's chips

Task 17 of the native slice 2 part 1 plan, as Spike M chose (no 16A).

- AttachIntake.decide (D8, platform-neutral): an image alone, files
  alone, files whose text is only their own names, and file promises
  attach; text, even with an image beside it (Pages, Word, Excel), is text.
- MacPasteRoute: AppKit's own Edit ▸ Paste (its title and ⌘V) retargeted
  by its action, again whenever the menu is rebuilt. Only the main
  window's Ask composer (ComposerInput.attach, set by its composer alone)
  attaches; there the field gets nothing. Everywhere else, and for text,
  paste: goes down the responder chain, with menuPasting set so the rich
  paste still becomes Markdown. The context menu's Paste bypasses it
  (accepted). Installed at launch.
- Drop: the Ask pane takes file URLs and images (AttachDrop) with the
  mockup's outline and "Drop files to attach them". The field and its
  editor take only text drags, re-applied on every focus gain. Nothing is
  taken while Ask doesn't take files, nor on the Store or People panes.
- The paperclip, left of Send, only while can_attach; it opens the file
  chooser with P10's types (AttachSources.macTypes).
- Chips (Equipo's strip restyled): wrapping, up to 196 pt then
  scrolling; picture or document mark, the upload ring, the name and its
  line (size, from HEIC, Uploading…, the failure, a PDF's note), Remove
  and, once failed, Try again. Tab reaches a chip; Delete removes it;
  Return retries a failed one. VoiceOver: one element each, Remove and
  Try again as named actions, the ring's value as a percentage; the
  draft announces "{name} attached" and "{name} not attached: {reason}".
  Reduce Motion: the ring jumps.
- The menu panel's composer doesn't attach (part 1).
- AskModel takes an optional draft (fixtures); AttachmentPicture draws a
  small picture at once.

Tests: AttachIntakeTests (6); MacPasteRouteTests (5: the item kept and
retargeted; an image attaches with the field empty; rich paste is still
Markdown through the command, with an image beside the text; the menu
panel's composer pastes text even with an image; the field takes only
text drags). The existing ComposerKeyTests pass unchanged.

Snapshots: base-mac window-attach and window-drop (mockups mac-attach,
mac-drop), light and dark.

Gate: swift test -j 4 --filter 'AttachIntakeTests|MacPasteRouteTests|MacAttachment|ComposerKeyTests':
24 XCTests and 7 Swift Testing tests passed; snapshots.sh record mac
MacSnapshots (reviewed), then compare mac: passed. check-strings.py ok.

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

Summary

Task 17: attaching on the Mac
claude agent, operated by paul@keymail.dev ddff54dabea52f0d00c603fb82659bc35c769e1e parent 044ba2b
21 files changed, +713 −76
  • native/apple/Sources/BaseKit/Ask/AskModel.swift +3 −2
  • native/apple/Sources/BaseKit/Ask/AskView.swift +5 −2
  • native/apple/Sources/BaseKit/Ask/Composer.swift +83 −7
  • native/apple/Sources/BaseKit/Attachments/AttachDrop.swift +28 −0
  • native/apple/Sources/BaseKit/Attachments/AttachIntake.swift +36 −0
  • native/apple/Sources/BaseKit/Attachments/AttachSources.swift +12 −0
  • native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift +10 −2
  • native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift +133 −45
  • native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift +9 −0
  • native/apple/Sources/BaseKit/Mac/MacMainView.swift +36 −2
  • native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift +80 −0
  • native/apple/Sources/BaseKit/Resources/Localizable.xcstrings +48 −0
  • native/apple/Sources/BaseMac/BaseMacApp.swift +2 −0
  • native/apple/Tests/BaseKitTests/AttachIntakeTests.swift +39 −0
  • native/apple/Tests/BaseKitTests/MacPasteRouteTests.swift +137 −0
  • native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift +41 −16
  • native/apple/Tests/BaseSnapshots/MacSnapshots.swift +11 −0
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-light-default.png binary

CI passed — run details

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

receipt: test step 9.444s against a 60s target (the gate's other steps are not in this figure)
receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed
receipt: slow package 8.575s amadan.net/oficina/base/internal/webtest
receipt: slow package 636ms amadan.net/oficina/base/internal/issuer
receipt: slow package 632ms amadan.net/oficina/base/internal/equipo
receipt: slow package 592ms amadan.net/oficina/base/internal/operations
receipt: slow package 183ms amadan.net/oficina/base/internal/consumer
receipt: slow test 1.51s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 620ms amadan.net/oficina/base/internal/webtest TestAskUploadStalledBodyFreesItsSlot
receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
receipt: slow test 510ms amadan.net/oficina/base/internal/equipo TestUploadRefusals
=== native ===
strings: copy review's strings.json is not here (git-ignored); its comparison skipped
strings: 175 in the catalog, 172 used
worktree-lib_test: ok
diff --git a/native/apple/Sources/BaseKit/Ask/AskModel.swift b/native/apple/Sources/BaseKit/Ask/AskModel.swift
index 63d5790..d82b33d 100644
--- a/native/apple/Sources/BaseKit/Ask/AskModel.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskModel.swift
@@ -137,11 +137,12 @@ import SwiftUI
/// them).
let announce: @MainActor (String) -> Void
- public init(client: BaseClient,
+ /// `attachments`: a draft of the caller's (fixtures); else one over `client`.
+ public init(client: BaseClient, attachments: AttachmentDraft? = nil,
schedule: @escaping @MainActor (Duration, @escaping @MainActor () -> Void) -> Void = AskModel.later,
announce: @escaping @MainActor (String) -> Void = AskModel.announce) {
self.client = client
- self.attachments = AttachmentDraft(client: client)
+ self.attachments = attachments ?? AttachmentDraft(client: client, announce: announce)
self.schedule = schedule
self.announce = announce
}
diff --git a/native/apple/Sources/BaseKit/Ask/AskView.swift b/native/apple/Sources/BaseKit/Ask/AskView.swift
index f307079..4bbed2b 100644
--- a/native/apple/Sources/BaseKit/Ask/AskView.swift
+++ b/native/apple/Sources/BaseKit/Ask/AskView.swift
@@ -35,13 +35,16 @@ public struct AskView: View {
let timeZone: TimeZone?
let actions: AskActions
let focusOnAppear: Bool
+ /// The main window's Ask, which takes files (Task 17).
+ let attaching: Bool
@FocusState private var focused: Bool
@Environment(\.colorScheme) private var scheme
/// `focusOnAppear`: the field takes focus as Ask shows (the menu-bar
/// panel; never on the iPhone, where it would raise the keyboard).
- public init(model: AskModel, layout: AskLayout, timeZone: TimeZone?, actions: AskActions, focusOnAppear: Bool = false) {
+ public init(model: AskModel, layout: AskLayout, timeZone: TimeZone?, actions: AskActions, focusOnAppear: Bool = false, attaching: Bool = false) {
self.model = model; self.layout = layout; self.timeZone = timeZone; self.actions = actions; self.focusOnAppear = focusOnAppear
+ self.attaching = attaching
}
public var body: some View {
@@ -80,7 +83,7 @@ public struct AskView: View {
.font(BaseFont.body(14, relativeTo: .subheadline)).foregroundStyle(p[.haze])
.accessibilityAddTraits(.updatesFrequently)
}
- Composer(model: model, focused: $focused)
+ Composer(model: model, focused: $focused, attaching: attaching)
}
.padding(.horizontal, layout == .window ? 24 : 10)
.padding(.top, 6)
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
index ecf38e3..d3b4024 100644
--- a/native/apple/Sources/BaseKit/Ask/Composer.swift
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -18,18 +18,42 @@ public struct Composer: View {
@FocusState.Binding var focused: Bool
@Environment(\.colorScheme) private var scheme
@State private var input = ComposerInput()
+ /// The main window's composer, which takes files: its chips, the
+ /// paperclip, paste and drops (Task 17). The menu panel's doesn't.
+ let attaching: Bool
+ @State private var choosing = false
- public init(model: AskModel, focused: FocusState<Bool>.Binding) {
+ public init(model: AskModel, focused: FocusState<Bool>.Binding, attaching: Bool = false) {
self.model = model
_focused = focused
+ self.attaching = attaching
}
private var canSend: Bool { model.canSend }
public var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ if attaching, !model.attachments.items.isEmpty || model.attachments.notice != nil {
+ #if os(macOS)
+ AttachmentDraftStrip(draft: model.attachments, layout: .wrap)
+ #else
+ AttachmentDraftStrip(draft: model.attachments, layout: .line)
+ #endif
+ }
+ field
+ }
+ #if os(macOS)
+ .fileImporter(isPresented: $choosing, allowedContentTypes: AttachSources.macTypes, allowsMultipleSelection: true) { result in
+ guard case .success(let urls) = result else { return }
+ for url in urls { Task { await model.attachments.add(url: url) } }
+ }
+ #endif
+ }
+
+ private var field: some View {
let p = Palette(scheme)
let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
- HStack(alignment: .bottom, spacing: 0) {
+ return HStack(alignment: .bottom, spacing: 0) {
TextField(text: $model.text, prompt: Text(BaseText.text("ask.placeholder")).foregroundStyle(p[.placeholder]), axis: .vertical) {
Text(BaseText.text("ask.message_label"))
}
@@ -38,7 +62,7 @@ public struct Composer: View {
.foregroundStyle(p[.frost])
.lineLimit(1...7)
.focused($focused)
- .background(ComposerAnchor(input: input, model: model).allowsHitTesting(false).accessibilityHidden(true))
+ .background(ComposerAnchor(input: input, model: model, attaching: attaching).allowsHitTesting(false).accessibilityHidden(true))
.onChange(of: focused, initial: true) { _, now in input.focused = now }
// A hardware keyboard's Return (and a Mac keypad's Enter), as
// the web's keydown. On a Mac a field's own Return always
@@ -58,6 +82,18 @@ public struct Composer: View {
.padding(.vertical, 11).padding(.leading, 14).padding(.trailing, model.turn != nil || canSend ? 4 : 14)
.frame(minHeight: 44)
.accessibilityLabel(Text(BaseText.text("ask.message_label")))
+ #if os(macOS)
+ // The paperclip, left of Send, only while Ask takes files.
+ if attaching, model.canAttach {
+ Button { choosing = true } label: {
+ Image(systemName: "paperclip").font(.system(size: 15, weight: .medium)).foregroundStyle(p[.haze])
+ .frame(width: 32, height: 32).frame(width: 40, height: 44).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(Text(BaseText.text("native.attach.add")))
+ .accessibilityLabel(Text(BaseText.text("native.attach.add")))
+ }
+ #endif
if model.turn != nil {
RoundAction(icon: .stop, label: BaseText.text("ask.stop")) { Task { await model.stop() } }
.transition(.scale(scale: 0.6).combined(with: .opacity))
@@ -104,8 +140,39 @@ enum ComposerReturn: Equatable {
weak var model: AskModel?
#if os(macOS)
/// Whether the field has the keyboard (its FocusState).
- var focused = false
+ var focused = false { didSet { focusChanged() } }
weak var anchor: NSView?
+ /// The main window's composer: what attaches a pasteboard's files and
+ /// images to its draft. Nil for every other field (Task 17).
+ var attach: ((NSPasteboard) -> Bool)?
+ /// The focused composer that attaches, for the menu's Paste.
+ static weak var attaching: ComposerInput?
+ /// Set by MacPasteRoute around the `paste:` it sends: the retargeted
+ /// menu item's action is no longer `paste:`, so the rich paste below
+ /// can't recognise it by that.
+ static var menuPasting = false
+
+ /// On every focus gain, once the window's shared field editor is set up
+ /// for the field (which registers its own drag types again), the field
+ /// 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 }
+ if focused {
+ Self.attaching = self
+ DispatchQueue.main.async { [weak self] in self?.narrowDrops() }
+ } else if Self.attaching === self {
+ Self.attaching = nil
+ }
+ }
+
+ func narrowDrops() {
+ guard focused, let editor else { return }
+ for view in [editor, editor.delegate as? NSView].compactMap({ $0 }) {
+ view.unregisterDraggedTypes()
+ view.registerForDraggedTypes([.string])
+ }
+ }
/// A Mac field's editor.
var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView }
var composing: Bool { editor?.hasMarkedText() ?? false }
@@ -159,7 +226,7 @@ enum ComposerReturn: Equatable {
/// typing, an input method, dictation, drops and Undo are never a
/// Paste, and are left alone.
func richPaste(in changed: AnyObject?) {
- guard pasting, focused, !converting, let editor, changed === editor, !editor.hasMarkedText() else { return }
+ guard pasting || Self.menuPasting, focused, !converting, let editor, changed === editor, !editor.hasMarkedText() else { return }
let board = Self.pasteboard
guard let rich = board.availableType(from: [.html, .rtf]),
let plain = board.string(forType: .string), !plain.isEmpty else { return }
@@ -243,15 +310,24 @@ final class ComposerPaste: NSObject, UITextPasteDelegate {
struct ComposerAnchor: NSViewRepresentable {
let input: ComposerInput
let model: AskModel
+ let attaching: Bool
func makeNSView(context: Context) -> NSView {
- let view = NSView(); input.anchor = view; input.model = model; input.start(); return view
+ let view = NSView(); wire(view); input.start(); return view
+ }
+ 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
+ guard let model, model.canAttach else { return false }
+ return MacPasteboard.acceptAttachments(board, into: model.attachments)
+ } : nil
}
- func updateNSView(_ view: NSView, context: Context) { input.anchor = view; input.model = model }
}
#elseif os(iOS)
struct ComposerAnchor: UIViewRepresentable {
let input: ComposerInput
let model: AskModel
+ let attaching: Bool
func makeUIView(context: Context) -> UIView {
let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; input.model = model; return view
}
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachDrop.swift b/native/apple/Sources/BaseKit/Attachments/AttachDrop.swift
new file mode 100644
index 0000000..8a8cef0
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Attachments/AttachDrop.swift
@@ -0,0 +1,28 @@
+import Foundation
+import UniformTypeIdentifiers
+#if canImport(AppKit)
+import AppKit
+#endif
+
+/// Files dropped on Ask (Task 17): Finder's files by their URLs; images
+/// from other apps (a browser's, a promised photo) by their bytes.
+public enum AttachDrop {
+ public static let types: [UTType] = [.fileURL, .image]
+
+ @MainActor public static func receive(_ providers: [NSItemProvider], into draft: AttachmentDraft) {
+ for provider in providers {
+ if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {
+ _ = provider.loadObject(ofClass: URL.self) { url, _ in
+ guard let url, url.isFileURL else { return }
+ Task { @MainActor in await draft.add(url: url) }
+ }
+ } else if let type = provider.registeredTypeIdentifiers.compactMap(UTType.init).first(where: { $0.conforms(to: .image) }) {
+ let name = (provider.suggestedName ?? "image") + "." + (type.preferredFilenameExtension ?? "png")
+ _ = provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in
+ guard let data else { Task { @MainActor in draft.refuseFile() }; return }
+ Task { @MainActor in await draft.add(data: data, name: name) }
+ }
+ }
+ }
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachIntake.swift b/native/apple/Sources/BaseKit/Attachments/AttachIntake.swift
new file mode 100644
index 0000000..0c01d33
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Attachments/AttachIntake.swift
@@ -0,0 +1,36 @@
+import Foundation
+
+/// What a paste or drop holds, read without its bytes: the plain text,
+/// file URLs, whether an image is there, and file promises.
+public struct PasteboardContents: Equatable, Sendable {
+ public var text: String?
+ public var fileURLs: [URL]
+ public var hasImage: Bool
+ public var promises: Int
+ public init(text: String? = nil, fileURLs: [URL] = [], hasImage: Bool = false, promises: Int = 0) {
+ self.text = text; self.fileURLs = fileURLs; self.hasImage = hasImage; self.promises = promises
+ }
+}
+
+/// D8: whether a paste or drop attaches or is text. Files, an image alone
+/// or file promises attach. Text is text, even with an image beside it (as
+/// Pages, Word and Excel put one), unless the text is only the files' own
+/// names (as Finder's Copy puts them). Then it goes through PasteMarkdown
+/// as now.
+public enum AttachIntake {
+ public enum Item: Equatable, Sendable { case file(URL), image, promise }
+ public enum Decision: Equatable, Sendable { case attach([Item]), text }
+
+ public static func decide(_ c: PasteboardContents) -> Decision {
+ if c.promises > 0 { return .attach(Array(repeating: .promise, count: c.promises)) }
+ let text = c.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if !c.fileURLs.isEmpty {
+ let names = Set(c.fileURLs.flatMap { [$0.lastPathComponent, $0.path] })
+ let lines = text.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ if lines.allSatisfy(names.contains) { return .attach(c.fileURLs.map(Item.file)) }
+ return .text
+ }
+ if !text.isEmpty { return .text }
+ return c.hasImage ? .attach([.image]) : .text
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachSources.swift b/native/apple/Sources/BaseKit/Attachments/AttachSources.swift
new file mode 100644
index 0000000..7d49b15
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Attachments/AttachSources.swift
@@ -0,0 +1,12 @@
+import Foundation
+import UniformTypeIdentifiers
+
+/// Where files come from (P10). The logic is here, platform-neutral, so it
+/// can be tested; the views only call it.
+public enum AttachSources {
+ /// The nine types Equipo takes, and HEIC, HEIF and TIFF, which become
+ /// JPEG on the device. The Mac's file chooser offers these.
+ public static let macTypes: [UTType] = [.png, .jpeg, .webP, .gif, .pdf, .plainText,
+ UTType("net.daringfireball.markdown") ?? .plainText, .commaSeparatedText, .json,
+ .heic, .heif, .tiff]
+}
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
index b4a7ace..e95680e 100644
--- a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
+++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift
@@ -30,6 +30,9 @@ import Observation
@ObservationIgnored let gate = AttachGate()
@ObservationIgnored let background: any BackgroundWork
@ObservationIgnored let sleep: @MainActor (Duration) async throws -> Void
+ /// Says "{name} attached" and "{name} not attached: {reason}" (the
+ /// web's words) to VoiceOver.
+ @ObservationIgnored let announce: @MainActor (String) -> Void
/// Set by Ask while a message is sending: Remove waits (P8.1).
public var sending = false
/// Whether Ask takes files now (`can_attach`): when not, nothing is added.
@@ -38,8 +41,10 @@ import Observation
public var canRemove: Bool { !sending }
public init(client: any AttachmentClient, background: (any BackgroundWork)? = nil,
- sleep: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) {
+ sleep: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) },
+ announce: @escaping @MainActor (String) -> Void = AskModel.announce) {
self.client = client
+ self.announce = announce
#if os(iOS)
self.background = background ?? ApplicationBackgroundWork()
#else
@@ -169,6 +174,7 @@ import Observation
}
guard let i = index(id, item.generation) else { return }
items[i].state = .ready(attachment)
+ announce(BaseText.format("native.attach.attached", ["name": item.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.
@@ -181,7 +187,9 @@ import Observation
}
} catch {
guard let i = index(id, item.generation) else { return }
- items[i].state = .failed(Self.words(error))
+ 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/AttachmentViews.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift
index 3cd6f7f..ebc3004 100644
--- a/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift
+++ b/native/apple/Sources/BaseKit/Attachments/AttachmentViews.swift
@@ -6,59 +6,141 @@ import SwiftUI
import ImageIO
import PDFKit
-/// Shared composer attachment list. State belongs to the session's draft.
+/// The composer's files (Base's chips, mockups `mac-attach`, `phone-attach`;
+/// Equipo's AttachmentDraftStrip restyled, Task 17): each file's mark (its
+/// picture, or a document), its name and a line under it (its size, "from
+/// HEIC", Uploading… or why it didn't attach), and Remove. While a file
+/// uploads a ring round its mark fills. On the Mac the chips wrap, up to
+/// 196 pt and then scroll; on the iPhone they are one line that scrolls
+/// sideways.
public struct AttachmentDraftStrip: View {
+ public enum Layout: Sendable { case wrap, line }
+ let draft: AttachmentDraft
+ let layout: Layout
+ @State private var height: CGFloat = 0
@Environment(\.colorScheme) private var scheme
private var p: Palette { Palette(scheme) }
- let draft: AttachmentDraft
- public init(draft: AttachmentDraft) { self.draft = draft }
+ public init(draft: AttachmentDraft, layout: Layout) { self.draft = draft; self.layout = layout }
public var body: some View {
VStack(alignment: .leading, spacing: 6) {
if !draft.items.isEmpty {
- ScrollView(.horizontal) {
- HStack(alignment: .top, spacing: 12) {
- ForEach(draft.items) { item in
- VStack(alignment: .leading, spacing: 4) {
- ZStack(alignment: .topTrailing) {
- AttachmentPicture(data: item.file?.data, name: item.name)
- .frame(width: 140, height: 86).background(p[.chip])
- .clipShape(.rect(cornerRadius: 8))
- HStack(spacing: 0) {
- if item.failure != nil {
- Button { Task { await draft.retry(item.id) } } label: {
- Image(systemName: "arrow.clockwise")
- .font(.system(size: 14, weight: .semibold))
- .foregroundStyle(p[.focus])
- .padding(7).background(p[.glassBase], in: Circle())
- .frame(width: 44, height: 44).contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityLabel(BaseText.text("native.attach.retry"))
- }
- Button { draft.remove(item.id) } label: {
- Image(systemName: "xmark.circle.fill").symbolRenderingMode(.palette)
- .foregroundStyle(p[.frost], p[.glassBase]).frame(width: 44, height: 44).contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityLabel(BaseText.format("native.attach.remove", ["name": item.name]))
- }
- }
- Text(item.name).font(BaseFont.body(12, relativeTo: .caption)).lineLimit(1).truncationMode(.middle)
- switch item.state {
- case .uploading(let progress):
- ProgressView(value: progress).accessibilityLabel(BaseText.text("native.attach.uploading"))
- Text(BaseText.text("native.attach.uploading")).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.haze])
- case .failed(let words):
- Text(words).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.ember]).fixedSize(horizontal: false, vertical: true)
- case .ready: EmptyView()
- }
- }.frame(width: 140, alignment: .leading)
- }
- }.padding(.vertical, 4)
+ switch layout {
+ case .wrap:
+ ScrollView {
+ FlowLayout(spacing: 8) { chips }
+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height = $0 }
+ }
+ .frame(height: min(height, 196))
+ .scrollBounceBehavior(.basedOnSize)
+ case .line:
+ ScrollView(.horizontal) { HStack(spacing: 8) { chips } }
+ .scrollIndicators(.never)
+ }
+ }
+ if let notice = draft.notice {
+ Text(verbatim: notice).font(BaseFont.body(13, relativeTo: .footnote)).foregroundStyle(p[.frost])
+ }
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(BaseText.text("native.attach.list"))
+ }
+
+ private var chips: some View {
+ ForEach(draft.items) { item in AttachmentChip(draft: draft, item: item) }
+ }
+}
+
+/// One file in the composer. Tab reaches it; Delete removes it and Return
+/// retries a failed one. VoiceOver reads its name and line, the ring's
+/// value as a percentage (never announced as it moves), and offers Remove
+/// and, once it failed, Try again.
+struct AttachmentChip: View {
+ let draft: AttachmentDraft
+ let item: AttachmentDraft.Item
+ @Environment(\.colorScheme) private var scheme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ private var p: Palette { Palette(scheme) }
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
+ HStack(spacing: 9) {
+ ZStack {
+ AttachmentPicture(data: item.file.flatMap { $0.mediaType.hasPrefix("image/") ? $0.data : nil }, name: item.name)
+ .frame(width: 34, height: 34)
+ .clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))
+ if case .uploading(let progress) = item.state {
+ Circle().stroke(p[.rule], lineWidth: 3).frame(width: 30, height: 30)
+ Circle().trim(from: 0, to: max(0.02, progress)).stroke(p[.focus], style: StrokeStyle(lineWidth: 3, lineCap: .round))
+ .rotationEffect(.degrees(-90)).frame(width: 30, height: 30)
+ .animation(reduceMotion ? nil : .linear(duration: 0.2), value: progress)
}
- .accessibilityLabel(BaseText.text("native.attach.list"))
}
- if let notice = draft.notice { Text(notice).font(BaseFont.body(12, relativeTo: .caption)).foregroundStyle(p[.ember]) }
+ VStack(alignment: .leading, spacing: 1) {
+ Text(verbatim: item.name).font(BaseFont.body(13.5, .semibold, relativeTo: .footnote)).lineLimit(1).truncationMode(.middle)
+ Text(verbatim: line).font(BaseFont.body(12, relativeTo: .caption))
+ .foregroundStyle(item.failure != nil ? p[.frost] : p[.haze])
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .frame(maxWidth: 160, alignment: .leading)
+ if item.failure != nil {
+ Button { Task { await draft.retry(item.id) } } label: {
+ Image(systemName: "arrow.clockwise").font(.system(size: 12, weight: .semibold)).frame(width: 28, height: 28).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityHidden(true)
+ }
+ Button { draft.remove(item.id) } label: {
+ Image(systemName: "xmark").font(.system(size: 11, weight: .semibold)).frame(width: 28, height: 28).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .disabled(!draft.canRemove)
+ .accessibilityHidden(true)
+ }
+ .foregroundStyle(p[.frost])
+ .padding(.leading, 6).padding(.trailing, 4).padding(.vertical, 6)
+ .background(p[.chip], in: shape)
+ .overlay { shape.strokeBorder(item.failure != nil ? p[.ember] : p[.chipEdge], lineWidth: 1) }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(Text(verbatim: "\(item.name), \(line)"))
+ .accessibilityValue(progressValue)
+ .accessibilityAction(named: Text(BaseText.format("native.attach.remove", ["name": item.name]))) { draft.remove(item.id) }
+ .modifier(RetryAction(draft: draft, item: item))
+ .focusable()
+ .onKeyPress(.delete) { draft.remove(item.id); return .handled }
+ .onKeyPress(.return) {
+ guard item.failure != nil else { return .ignored }
+ Task { await draft.retry(item.id) }
+ return .handled
+ }
+ }
+
+ /// The line under the name: why it failed, Uploading…, a PDF's note,
+ /// or its size and what it was converted from.
+ var line: String {
+ if let failure = item.failure { return failure }
+ if case .uploading = item.state { return BaseText.text("native.attach.uploading") }
+ if let note = item.note { return note }
+ guard let file = item.file else { return "" }
+ let size = file.data.count.formatted(.byteCount(style: .file))
+ guard let from = file.convertedFrom else { return size }
+ return size + " · " + BaseText.format("native.attach.from", ["type": from])
+ }
+
+ private var progressValue: Text {
+ guard case .uploading(let progress) = item.state else { return Text(verbatim: "") }
+ return Text(progress, format: .percent.precision(.fractionLength(0)))
+ }
+}
+
+/// A failed chip's Try again, as a VoiceOver action.
+private struct RetryAction: ViewModifier {
+ let draft: AttachmentDraft
+ let item: AttachmentDraft.Item
+ func body(content: Content) -> some View {
+ if item.failure != nil {
+ content.accessibilityAction(named: Text(BaseText.text("native.attach.retry"))) { Task { await draft.retry(item.id) } }
+ } else {
+ content
}
}
}
@@ -69,6 +151,12 @@ struct AttachmentPicture: View {
let data: Data?
let name: String
@State private var image: CGImage?
+ init(data: Data?, name: String) {
+ self.data = data; self.name = name
+ // A small picture is drawn at once (no flash, and snapshots see it);
+ // a larger one off the main actor, below.
+ if let data, data.count <= 256 << 10 { _image = State(initialValue: Self.thumbnail(data, side: 512)) }
+ }
var body: some View {
Group {
if let image {
diff --git a/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift b/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift
index c01967a..90bbb25 100644
--- a/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift
+++ b/native/apple/Sources/BaseKit/Attachments/MacPasteboard.swift
@@ -6,6 +6,15 @@
import AppKit
enum MacPasteboard {
+ /// Base (Task 17): what the pasteboard holds, for AttachIntake.
+ static func contents(_ board: NSPasteboard) -> PasteboardContents {
+ let urls = (board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL]) ?? []
+ let promises = (board.readObjects(forClasses: [NSFilePromiseReceiver.self]) as? [NSFilePromiseReceiver])?.count ?? 0
+ let images: [NSPasteboard.PasteboardType] = [.png, .tiff, .init("public.jpeg"), .init("public.heic")]
+ return PasteboardContents(text: board.string(forType: .string), fileURLs: urls,
+ hasImage: board.availableType(from: images) != nil, promises: promises)
+ }
+
static func accepts(_ board: NSPasteboard) -> Bool {
board.availableType(from: [.fileURL, .png, .tiff] + NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) }) != nil
}
diff --git a/native/apple/Sources/BaseKit/Mac/MacMainView.swift b/native/apple/Sources/BaseKit/Mac/MacMainView.swift
index ca24b8b..a628519 100644
--- a/native/apple/Sources/BaseKit/Mac/MacMainView.swift
+++ b/native/apple/Sources/BaseKit/Mac/MacMainView.swift
@@ -16,13 +16,16 @@ public struct MacMainView: View {
let actions: BaseActions
@Binding var sidebarShown: Bool
@State private var pane: MacPane
+ /// Files are being dragged over Ask (mockup `mac-drop`).
+ @State private var dropping: Bool
@Environment(\.colorScheme) private var scheme
public init(me: Me?, home: HomeData?, ask: AskModel?, team: TeamModels? = nil, folds: SidebarFolds? = nil, transport: NativeTransport?,
- actions: BaseActions, sidebarShown: Binding<Bool>, pane: MacPane = .ask) {
+ actions: BaseActions, sidebarShown: Binding<Bool>, pane: MacPane = .ask, dropping: Bool = false) {
self.me = me; self.home = home; self.ask = ask; self.team = team; self.folds = folds; self.transport = transport; self.actions = actions
_sidebarShown = sidebarShown
_pane = State(initialValue: pane)
+ _dropping = State(initialValue: dropping)
}
public var body: some View {
@@ -85,7 +88,8 @@ public struct MacMainView: View {
PeopleView(model: team.people, baseName: me?.base.name ?? "", layout: .window)
default:
if let ask {
- AskView(model: ask, layout: .window, timeZone: me?.base.timeZone, actions: AskActions(setUp: actions.setUpAsk, setUpOnWeb: actions.setUpAskOnWeb))
+ AskView(model: ask, layout: .window, timeZone: me?.base.timeZone, actions: AskActions(setUp: actions.setUpAsk, setUpOnWeb: actions.setUpAskOnWeb),
+ attaching: true)
.frame(maxWidth: 760)
.frame(maxWidth: .infinity)
} else {
@@ -95,8 +99,20 @@ public struct MacMainView: View {
}
.foregroundStyle(p[.frost])
.glassSheet(cornerRadius: 18)
+ // Files dropped anywhere on Ask attach (Task 17). The field and its
+ // editor take only text drags while focused, so a file over the
+ // field lands here too, and inserts no path.
+ .overlay { if dropping { DropOutline() } }
+ .onDrop(of: AttachDrop.types, isTargeted: Binding(get: { dropping }, set: { dropping = $0 && takesFiles })) { providers in
+ guard takesFiles, let ask else { return false }
+ AttachDrop.receive(providers, into: ask.attachments)
+ return true
+ }
}
+ /// Only Ask's pane, while Ask takes files.
+ private var takesFiles: Bool { pane == .ask && (ask?.canAttach ?? false) }
+
private var title: String {
switch pane {
case .ask: "native.sidebar.ask"
@@ -272,6 +288,24 @@ struct MacSidebar: View {
}
}
+/// The outline over Ask while files are dragged over it.
+struct DropOutline: View {
+ @Environment(\.colorScheme) private var scheme
+ var body: some View {
+ let p = Palette(scheme)
+ ZStack {
+ RoundedRectangle(cornerRadius: 14, style: .continuous)
+ .strokeBorder(p[.focus], style: StrokeStyle(lineWidth: 2, dash: [7, 5]))
+ .padding(8)
+ Label { Text(BaseText.text("native.attach.drop")) } icon: { Image(systemName: "paperclip") }
+ .font(BaseFont.body(17, .semibold, relativeTo: .headline))
+ .foregroundStyle(p[.frost])
+ }
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+}
+
/// The chosen sidebar row: the hover's tint with the accent's edge.
struct SelectedRow: ViewModifier {
let selected: Bool
diff --git a/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift b/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift
new file mode 100644
index 0000000..9566c68
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Mac/MacPasteRoute.swift
@@ -0,0 +1,80 @@
+#if os(macOS)
+import AppKit
+
+/// Edit ▸ Paste on the Mac (Task 17, as Spike M chose): AppKit's own item
+/// (its localised title, ⌘V) is found by its action, `paste:`, and pointed
+/// here, again whenever the menu is rebuilt under it. In the main window's
+/// Ask composer, files and images attach (D8) and the field gets nothing;
+/// everywhere else, and for text, AppKit's `paste:` goes down the
+/// responder chain as before, flagged so the composer's rich paste still
+/// becomes Markdown.
+///
+/// Paste from the field's own context menu calls the field editor
+/// directly, so an image pasted that way does nothing (accepted, plan Task
+/// 17): the menu, ⌘V, drop and the paperclip all attach.
+@MainActor public final class MacPasteRoute: NSObject, NSMenuItemValidation {
+ public static let shared = MacPasteRoute()
+ /// The window whose composer and responder chain a paste is for.
+ var window: () -> NSWindow? = { NSApp.keyWindow }
+ /// Where a paste reads from. Tests give their own, never the person's.
+ var pasteboard: NSPasteboard = .general
+ private var observers: [NSObjectProtocol] = []
+
+ public func install() {
+ guard observers.isEmpty else { return }
+ retarget()
+ for name in [NSMenu.didAddItemNotification, NSApplication.didUpdateNotification] {
+ observers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated { self?.retarget() }
+ })
+ }
+ }
+
+ /// Every main-menu item still on AppKit's `paste:`, pointed here.
+ func retarget() {
+ guard let menu = NSApp.mainMenu else { return }
+ for item in Self.items(menu) where item.action == #selector(NSText.paste(_:)) {
+ item.action = #selector(basePaste(_:))
+ item.target = self
+ }
+ }
+
+ static func items(_ menu: NSMenu) -> [NSMenuItem] {
+ menu.items.flatMap { [$0] + ($0.submenu.map(items) ?? []) }
+ }
+
+ /// The main window's Ask composer, when it has the keyboard here.
+ private var attaching: ComposerInput? {
+ guard let input = ComposerInput.attaching, input.focused, input.attach != nil, let window = window(),
+ input.anchor?.window === window else { return nil }
+ return input
+ }
+
+ private var attaches: Bool {
+ guard attaching != nil, case .attach = AttachIntake.decide(MacPasteboard.contents(pasteboard)) else { return false }
+ return true
+ }
+
+ @objc func basePaste(_ sender: Any?) {
+ if attaches, attaching?.attach?(pasteboard) == true { return }
+ ComposerInput.menuPasting = true
+ defer { ComposerInput.menuPasting = false }
+ let responder = window()?.firstResponder
+ if pasteboard !== NSPasteboard.general, let editor = responder as? NSTextView {
+ _ = editor.readSelection(from: pasteboard)
+ return
+ }
+ let target = responder.flatMap { NSApp.target(forAction: #selector(NSText.paste(_:)), to: $0, from: sender) }
+ NSApp.sendAction(#selector(NSText.paste(_:)), to: target, from: sender)
+ }
+
+ public func validateMenuItem(_ item: NSMenuItem) -> Bool {
+ if attaches { return true }
+ // As AppKit would for paste:: the responder that would take it says.
+ guard let responder = window()?.firstResponder,
+ let target = NSApp.target(forAction: #selector(NSText.paste(_:)), to: responder, from: item) else { return false }
+ let standIn = NSMenuItem(title: item.title, action: #selector(NSText.paste(_:)), keyEquivalent: "")
+ return (target as? NSMenuItemValidation)?.validateMenuItem(standIn) ?? true
+ }
+}
+#endif
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
index 20a6aec..3d29cd5 100644
--- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
@@ -553,6 +553,18 @@
}
}
},
+ "native.attach.attached": {
+ "comment": "Base on the web's approved copy (chat.html data-w-attached). Said by VoiceOver when a file has uploaded. {name} is its name.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "{name} attached"
+ }
+ }
+ }
+ },
"native.attach.busy": {
"comment": "Base on the web's approved copy (chat.html data-w-busy). A file's chip once Base was busy after three tries.",
"extractionState": "manual",
@@ -577,6 +589,18 @@
}
}
},
+ "native.attach.drop": {
+ "comment": "Base on the web's approved copy (chat.html data-w-drop). Over the Mac's Ask while files are dragged over it.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Drop files to attach them"
+ }
+ }
+ }
+ },
"native.attach.failed": {
"comment": "Base on the web's approved copy (chat.html data-w-failed). A file's chip when its upload failed for any other reason.",
"extractionState": "manual",
@@ -601,6 +625,18 @@
}
}
},
+ "native.attach.from": {
+ "comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). A chip's line after its size, for a photo converted to JPEG on the device. {type} is HEIC, TIFF, PNG…",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "from {type}"
+ }
+ }
+ }
+ },
"native.attach.gone": {
"comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). Opening a sent file Base no longer has (a 404).",
"extractionState": "manual",
@@ -649,6 +685,18 @@
}
}
},
+ "native.attach.not_attached": {
+ "comment": "Base on the web's approved copy (chat.html data-w-not-attached). Said by VoiceOver when a file failed. {reason} is the chip's words.",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "{name} not attached: {reason}"
+ }
+ }
+ }
+ },
"native.attach.paste": {
"comment": "DRAFT 2026-11-28 (slice 2 part 1, for Luna). The iPhone's + menu in Ask: attach what's on the clipboard. Equipo's approved label.",
"extractionState": "manual",
diff --git a/native/apple/Sources/BaseMac/BaseMacApp.swift b/native/apple/Sources/BaseMac/BaseMacApp.swift
index 3a766ce..2050e26 100644
--- a/native/apple/Sources/BaseMac/BaseMacApp.swift
+++ b/native/apple/Sources/BaseMac/BaseMacApp.swift
@@ -105,6 +105,8 @@ struct ColophonCommand: View {
panel?.onShow = { state.shortcut = KeyboardShortcuts.getShortcut(for: .askBase)?.description }
KeyboardShortcuts.onKeyUp(for: .askBase) { [weak self] in self?.panel?.shortcutPressed() }
Task { await session.oficina.start() }
+ // Edit ▸ Paste attaches files in Ask's composer (Task 17).
+ MacPasteRoute.shared.install()
}
/// Open Base: the window, forward (opened again if it was closed).
diff --git a/native/apple/Tests/BaseKitTests/AttachIntakeTests.swift b/native/apple/Tests/BaseKitTests/AttachIntakeTests.swift
new file mode 100644
index 0000000..26096e4
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/AttachIntakeTests.swift
@@ -0,0 +1,39 @@
+@testable import BaseKit
+import Foundation
+import XCTest
+
+/// Task 17 (D8): what a paste or drop is, before anything reads it.
+final class AttachIntakeTests: XCTestCase {
+ let report = URL(fileURLWithPath: "/Users/paul/Desktop/Report.pdf")
+ let photo = URL(fileURLWithPath: "/Users/paul/Desktop/Shopfront.jpg")
+
+ func testAnImageAloneAttaches() {
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(hasImage: true)), .attach([.image]))
+ }
+
+ func testFilesAloneAttach() {
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(fileURLs: [report, photo])), .attach([.file(report), .file(photo)]))
+ }
+
+ /// Pages, Word and Excel put a picture of the selection beside its text.
+ func testTextWithAnImageIsText() {
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(text: "Quarterly notes", hasImage: true)), .text)
+ }
+
+ /// Finder's Copy puts the files' names beside them as text.
+ func testTextThatIsOnlyTheFilesNamesAttaches() {
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(text: "Report.pdf\nShopfront.jpg", fileURLs: [report, photo])),
+ .attach([.file(report), .file(photo)]))
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(text: report.path, fileURLs: [report])), .attach([.file(report)]))
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(text: "See the report", fileURLs: [report])), .text)
+ }
+
+ func testAFilePromiseAttaches() {
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(promises: 2)), .attach([.promise, .promise]))
+ }
+
+ func testPlainTextAndNothingAreText() {
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents(text: "hello")), .text)
+ XCTAssertEqual(AttachIntake.decide(PasteboardContents()), .text)
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/MacPasteRouteTests.swift b/native/apple/Tests/BaseKitTests/MacPasteRouteTests.swift
new file mode 100644
index 0000000..a40634f
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/MacPasteRouteTests.swift
@@ -0,0 +1,137 @@
+#if os(macOS)
+@testable import BaseKit
+import AppKit
+import SwiftUI
+import XCTest
+
+/// Task 17: the menu's Paste, as Spike M chose: AppKit's own item,
+/// retargeted. Real composers in real windows; ⌘V through a main menu with
+/// AppKit's Paste in it; a pasteboard of the test's own, never the
+/// person's.
+@MainActor final class MacPasteRouteTests: XCTestCase {
+ private var windows: [NSWindow] = []
+ private var savedMenu: NSMenu?
+ private let route = MacPasteRoute()
+ private var board: NSPasteboard!
+
+ override func setUp() {
+ _ = NSApplication.shared
+ savedMenu = NSApp.mainMenu
+ let main = NSMenu(), editItem = NSMenuItem(), edit = NSMenu(title: "Edit")
+ editItem.submenu = edit
+ main.addItem(editItem)
+ edit.addItem(withTitle: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v")
+ NSApp.mainMenu = main
+ board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)"))
+ route.pasteboard = board
+ ComposerInput.pasteboard = board
+ }
+
+ override func tearDown() {
+ windows.forEach { $0.close() }
+ NSApp.mainMenu = savedMenu
+ board.releaseGlobally()
+ ComposerInput.pasteboard = .general
+ }
+
+ private func model() -> AskModel {
+ let m = AskModel(client: BaseClient(transport: GatedTransport()) {}, schedule: { _, _ in })
+ m.applyForPreview(try! JSONDecoder().decode(AskSnapshot.self, from: Data(#"{"state":"ready","can_attach":true}"#.utf8)))
+ return m
+ }
+
+ /// A composer in its own window, with the keyboard.
+ private func composer(_ model: AskModel, attaching: Bool) throws -> NSWindow {
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 460, height: 300), styleMask: [.titled], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = NSHostingView(rootView: FocusedAttachingComposer(model: model, attaching: attaching).frame(width: 460))
+ window.makeKeyAndOrderFront(nil)
+ windows.append(window)
+ for _ in 0..<40 where !(window.firstResponder is NSTextView) { settle(0.05) }
+ XCTAssertTrue(window.firstResponder is NSTextView, "the composer never took the keyboard")
+ settle()
+ return window
+ }
+
+ private func settle(_ seconds: Double = 0.15) { RunLoop.main.run(until: Date().addingTimeInterval(seconds)) }
+
+ /// ⌘V as the keyboard sends it: the window's views, then the main menu.
+ private func commandV(_ window: NSWindow) throws {
+ route.window = { window }
+ route.retarget()
+ let event = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: 0,
+ windowNumber: window.windowNumber, context: nil, characters: "v",
+ charactersIgnoringModifiers: "v", isARepeat: false, keyCode: 9))
+ if !window.performKeyEquivalent(with: event) { XCTAssertTrue(NSApp.mainMenu?.performKeyEquivalent(with: event) ?? false, "⌘V did nothing") }
+ settle()
+ }
+
+ private func png() -> Data {
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 4, pixelsHigh: 4, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,
+ isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+ return rep.representation(using: .png, properties: [:])!
+ }
+
+ func testTheExistingPasteItemIsRetargetedAndKeepsItsTitleAndKey() throws {
+ route.retarget()
+ let item = try XCTUnwrap(NSApp.mainMenu?.items.first?.submenu?.items.first)
+ XCTAssertEqual(item.action, #selector(MacPasteRoute.basePaste(_:)))
+ XCTAssertTrue(item.target === route)
+ XCTAssertEqual(item.title, "Paste")
+ XCTAssertEqual(item.keyEquivalent, "v")
+ }
+
+ func testAnImagePastedInAskAttachesAndTheFieldGetsNothing() throws {
+ let m = model()
+ let window = try composer(m, attaching: true)
+ board.clearContents(); board.setData(png(), forType: .png)
+ try commandV(window)
+ XCTAssertEqual(m.attachments.items.count, 1)
+ XCTAssertEqual(m.text, "")
+ }
+
+ /// Text with an image beside it (Pages) is text, and a rich paste still
+ /// becomes Markdown through the retargeted item.
+ func testARichPasteThroughTheCommandIsStillMarkdown() throws {
+ let m = model()
+ let window = try composer(m, attaching: true)
+ board.clearContents()
+ board.setString("<p>The <b>flour</b> comes <i>Thursday</i></p>", forType: .html)
+ board.setString("The flour comes Thursday", forType: .string)
+ board.setData(png(), forType: .tiff)
+ try commandV(window)
+ XCTAssertEqual(m.text, "The **flour** comes *Thursday*")
+ XCTAssertTrue(m.attachments.items.isEmpty)
+ }
+
+ func testTheMenuPanelsComposerPastesTextEvenWithAnImage() throws {
+ let m = model()
+ let window = try composer(m, attaching: false)
+ board.clearContents()
+ board.setData(png(), forType: .png)
+ board.setString("panel words", forType: .string)
+ try commandV(window)
+ XCTAssertEqual(m.text, "panel words")
+ XCTAssertTrue(m.attachments.items.isEmpty, "the menu panel's composer never attaches")
+ }
+
+ /// Spike M: the field and the window's shared field editor take only
+ /// text drags while Ask's composer has the keyboard, so a file dragged
+ /// over the field reaches the pane.
+ func testTheFieldTakesOnlyTextDrags() throws {
+ let window = try composer(model(), attaching: true)
+ let editor = try XCTUnwrap(window.firstResponder as? NSTextView)
+ XCTAssertEqual(editor.registeredDraggedTypes, [.string])
+ XCTAssertEqual((editor.delegate as? NSView)?.registeredDraggedTypes, [.string])
+ }
+}
+
+private struct FocusedAttachingComposer: View {
+ let model: AskModel
+ let attaching: Bool
+ @FocusState private var focused: Bool
+ var body: some View {
+ Composer(model: model, focused: $focused, attaching: attaching).onAppear { focused = true }
+ }
+}
+#endif
diff --git a/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift b/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift
index 55dbc32..ddeeb8c 100644
--- a/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift
+++ b/native/apple/Tests/BaseSnapshots/AttachmentFixtures.swift
@@ -6,6 +6,7 @@ import BaseKit
import CoreText
import Foundation
import ImageIO
+import RastrilloTestSupport
import SwiftUI
import UniformTypeIdentifiers
@@ -40,34 +41,58 @@ import UniformTypeIdentifiers
return data as Data
}
- /// A draft as the mockups show it: Home.png uploading (42%) and
- /// Home-failed.png failed. Its uploads never finish.
- static func draft() async -> AttachmentDraft {
- let draft = AttachmentDraft(client: FixtureAttachmentClient())
- for name in ["Home.png", "Home-failed.png"] {
- Task { await draft.add(data: image, name: name) }
- while !draft.items.contains(where: { $0.name == name }) { await Task.yield() }
- }
- for _ in 0..<500 {
- if draft.items.allSatisfy({ if case .uploading(let p) = $0.state { return p > 0 }; return true }) { break }
+ /// The composer's files as mockup mac-attach shows them: Shopfront.jpg
+ /// uploaded, Loaves.jpg uploading (62%), Opening hours.pdf with its
+ /// note, Orders.csv uploaded.
+ static func mockupDraft() async -> AttachmentDraft {
+ let draft = AttachmentDraft(client: FixtureAttachmentClient(), background: NoBackgroundWork(), announce: { _ in })
+ await draft.add(data: image, name: "Shopfront.jpg")
+ Task { await draft.add(data: landscape, name: "Loaves.jpg") }
+ while !draft.items.contains(where: { if case .uploading(let p) = $0.state { return p > 0.5 }; return false }) {
try? await Task.sleep(for: .milliseconds(10))
}
+ await draft.add(data: Data("%PDF-1.7\n".utf8), name: "Opening hours.pdf")
+ await draft.add(data: Data("day,orders\n2025-12-22,61\n".utf8), name: "Orders.csv")
return draft
}
+ /// The mockups' thread, with Ask taking files, and a draft (mac-attach)
+ /// or none (mac-drop).
+ static func attachingThread(text: String = "", draft: AttachmentDraft? = nil) -> AskModel {
+ let model = AskModel(client: BaseClient(transport: ScriptedTransport()) {}, attachments: draft, schedule: { _, _ in })
+ model.applyForPreview(try! JSONDecoder().decode(AskSnapshot.self, from: Data(#"""
+ {"state":"ready","cursor":1,"status":"","turn":null,"cards":[],"messages":[
+ {"id":"m1","role":"person","text":"Can you put together a simple website for the bakery?","turn_id":"t1"},
+ {"id":"m2","role":"assistant","text":"On it. Here’s a first look, with the menu from your Sheets.","turn_id":"t1"}],
+ "jobs":[{"id":"j1","revision":1,"kind":"job","state":"asking","question":"Bakery website","result":"First look ready","options":[],"links":[]}],
+ "can_attach":true}
+ """#.utf8)))
+ model.text = text
+ return model
+ }
+
+ /// Prepared before a catalog draws (its draft fills asynchronously).
+ static var prepared: AskModel?
+ static func prepare() async {
+ prepared = attachingThread(text: "Use these on the website, and count last December’s orders by day", draft: await mockupDraft())
+ }
+
/// A sent message's files: a portrait PNG and a landscape JPEG.
nonisolated static let sent = [AskAttachment(id: "at_fixture", kind: "image", name: "Home.png", mediaType: "image/png", size: 8000, width: 360, height: 640),
- AskAttachment(id: "at_landscape", kind: "image", name: "Landscape.jpg", mediaType: "image/jpeg", size: 21_000, width: 640, height: 360)]
+ AskAttachment(id: "at_landscape", kind: "image", name: "Landscape.jpg", mediaType: "image/jpeg", size: 21_000, width: 640, height: 360)]
}
-/// Answers as Base's relay would, from the pictures above: an upload named
-/// "failed" fails, any other reports 42% and never finishes.
+/// Answers as Base's relay would: Loaves.jpg reports 62% and never
+/// finishes; anything else uploads at once.
struct FixtureAttachmentClient: AttachmentClient {
func upload(_ file: AttachmentFile, progress: @escaping @Sendable (Double) -> Void) async throws -> AskAttachment {
if file.name.contains("failed") { throw BaseAPIError.offline }
- progress(0.42)
- try await Task.sleep(for: .seconds(3600))
- return AttachmentFixtures.sent[0]
+ if file.name.hasPrefix("Loaves") {
+ progress(0.62)
+ try await Task.sleep(for: .seconds(3600))
+ }
+ return AskAttachment(id: "at_" + file.name, kind: file.mediaType.hasPrefix("image/") ? "image" : "file", name: file.name,
+ mediaType: file.mediaType, size: Int64(file.data.count), width: file.width, height: file.height)
}
func delete(_ id: String) async throws {}
func data(id: String, preview: Bool) async throws -> Data {
diff --git a/native/apple/Tests/BaseSnapshots/MacSnapshots.swift b/native/apple/Tests/BaseSnapshots/MacSnapshots.swift
index 5d44021..a3e4024 100644
--- a/native/apple/Tests/BaseSnapshots/MacSnapshots.swift
+++ b/native/apple/Tests/BaseSnapshots/MacSnapshots.swift
@@ -13,6 +13,7 @@ final class MacSnapshots: XCTestCase {
@MainActor func testMac() async throws {
try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil, "Run with native/scripts/snapshots.sh")
BaseFonts.register()
+ await AttachmentFixtures.prepare()
await assertSnapshots(of: Self.catalog)
}
@@ -37,6 +38,16 @@ final class MacSnapshots: XCTestCase {
MacMainView(me: HomeFixtures.me, home: HomeFixtures.home, ask: AskFixtures.thread(), team: TeamFixtures.team(),
folds: HomeFixtures.folded(), transport: nil, actions: .none, sidebarShown: .constant(true)).skyFrozen()
},
+ // Task 17 (mockups mac-attach, mac-drop): files in the composer,
+ // and files dragged over Ask.
+ SnapshotScreen("window-attach", mac: .fixed(width: 1280, height: 800), iphone: nil) {
+ MacMainView(me: HomeFixtures.me, home: HomeFixtures.home, ask: AttachmentFixtures.prepared, team: TeamFixtures.team(),
+ folds: HomeFixtures.folded(), transport: nil, actions: .none, sidebarShown: .constant(true)).skyFrozen()
+ },
+ SnapshotScreen("window-drop", mac: .fixed(width: 1280, height: 800), iphone: nil) {
+ MacMainView(me: HomeFixtures.me, home: HomeFixtures.home, ask: AttachmentFixtures.attachingThread(), team: TeamFixtures.team(),
+ folds: HomeFixtures.folded(), transport: nil, actions: .none, sidebarShown: .constant(true), dropping: true).skyFrozen()
+ },
SnapshotScreen("menubar", mac: .fixed(width: 410, height: 560), iphone: nil) {
MenuPanel(me: HomeFixtures.me, ask: AskFixtures.thread(), shortcut: "⌃Space", openBase: {}, actions: .none).skyFrozen()
},
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-dark-default.png
new file mode 100644
index 0000000..31c3439
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-light-default.png
new file mode 100644
index 0000000..508acb1
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-attach-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-dark-default.png
new file mode 100644
index 0000000..7bf5b19
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-light-default.png
new file mode 100644
index 0000000..a9a658c
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-mac/mac/window-drop-light-default.png differ