// The share sheet's two halves.//// **The reader intake had no test at all before the rewrite** — 217 lines, five// branches, four classification rules and a precedence that three separate// comments in it explain, and nothing executable holding any of it. That was the// largest hole in this lane, so these are this app's own tests rather than a// translation of somebody else's.//// Everything is driven through `ScriptedCore`, which records every call — so// each case asserts what was ASKED as well as where the app was sent. That// matters most in the precedence cases: a share that lands on `/photos` because// the pictures branch claimed it and a share that lands on `/photos` because the// documents branch failed and fell back look identical from the route alone.//// Fixtures are synthetic throughout: `example.com`, "Priya Example", and paths// under a made-up inbox directory.importCottonMailboximport XCTest// `@testable` for `shareFileExtension` alone: the extension rule is an// INTERNAL detail of the five-branch precedence — nothing outside// `ShareIntake.swift` should be branching on a file's suffix — and the// alternative to testing it directly is inferring it from the branch it// feeds, which is a worse test of a rule the port carried line for line.@testable importCottonKit@testable importCottonUI// MARK: - Doubles/// A mailbox that lives in memory, and hands its raw JSON back.////// The raw text is what one case needs: the append is a read-modify-write over/// `[Any]` precisely so an entry this binary does not understand survives, and/// only the bytes can prove it did.privatefinalclassFakeShareStorage: ShareMailboxStorage, @unchecked Sendable {privatelet lock = NSLock()privatevar values: [String: String] = [:]init(_ seed: String? = nil) {iflet seed { values[ShareChannel.mailboxKey] = seed } }func text(_ key: String) -> String? { lock.lock()defer { lock.unlock() }return values[key] }func set(_ key: String, _ value: String?) { lock.lock()defer { lock.unlock() }iflet value { values[key] = value } else { values.removeValue(forKey: key) } }var raw: String? { text(ShareChannel.mailboxKey) }}/// The extension's copies, without a container.privatefinalclassFakeInboxFiles: ShareInboxFiles, @unchecked Sendable {privatelet lock = NSLock()privatevar present: Set<String>/// What the sniff would read off each path. A path with no entry answers/// `nil`, which is what an unreadable file does.privatevar heads: [String: String]private(set) var discarded: [String] = []/// Which paths were READ. The `.txt` branch is the only one allowed to/// look inside a file, and one case asserts the other four do not.private(set) var headsRead: [String] = []/// Where a staged copy was moved to, in order.private(set) var renames: [String] = []init(present: Set<String>, heads: [String: String] = [:]) {self.present = presentself.heads = heads }func head(_ path: String) -> String? { lock.lock()defer { lock.unlock() } headsRead.append(path)return heads[path] }func exists(_ path: String) -> Bool { lock.lock()defer { lock.unlock() }return present.contains(path) }func discard(_ path: String) { lock.lock()defer { lock.unlock() } present.remove(path) discarded.append(path) }/// The rename the meetings branch uses to give a staged copy the extension/// its declared type implies. It MOVES: the old path stops existing and the/// new one starts, which is what the disk does and what the discard/// assertions then read.func renamed(_ path: String, extension ext: String) -> String? { lock.lock()defer { lock.unlock() }guard present.contains(path) else { returnnil }let base = path.contains(".") ? String(path[path.startIndex..<path.lastIndex(of: ".")!]) : pathlet moved = "\(base).\(ext)" present.remove(path) present.insert(moved) renames.append(moved)return moved }}/// The books' shelf, without a core or a file: what it was asked to shelve/// and import, and the book row it answers.privatefinalclassFakeShelf: BookShelving, @unchecked Sendable {privatelet lock = NSLock()privatevar shelvedNow: [(path: String, format: CottonMailbox.BookFormat, fileName: String?)] = []privatevar importedNow: [String] = []let answer: Stringlet refuses: Boolinit(answer: String = "book-1", refuses: Bool = false) {self.answer = answerself.refuses = refuses }var shelved: [(path: String, format: CottonMailbox.BookFormat, fileName: String?)] { lock.lock()defer { lock.unlock() }return shelvedNow }var imported: [String] { lock.lock()defer { lock.unlock() }return importedNow }func shelve(_ url: URL, format: CottonMailbox.BookFormat, fileName: String?, into book: String?) asyncthrows -> String {let path = url.path(percentEncoded: false) lock.withLock { shelvedNow.append((path, format, fileName)) }if refuses { throwBookFileTrouble.notAPDF }return answer }func importGoodreads(_ text: String) asyncthrows -> String? { lock.withLock { importedNow.append(text) }if refuses { throwBookFileTrouble.notAPDF }return"book-first" }}/// Where the drain sent the app, and what it reported on the way.privatefinalclassRecorder: @unchecked Sendable {privatelet lock = NSLock()private(set) var landings: [ShareLanding] = []private(set) var troubles: [ShareIntakeTrouble] = []private(set) var told: [String] = []func land(_ landing: ShareLanding) { lock.lock()defer { lock.unlock() } landings.append(landing) }func trouble(_ trouble: ShareIntakeTrouble) { lock.lock()defer { lock.unlock() } troubles.append(trouble) }func tell(_ said: String) { lock.lock()defer { lock.unlock() } told.append(said) }var routes: [Route] { landings.map(\.route) }}// MARK: - Fixturesprivatelet inbox = "/share-inbox"privatefunc fileEntry( _ name: String, mime: String? = nil, text: String? = nil, id: String = UUID().uuidString) -> ShareEntry {ShareEntry( id: id, at: "2026-09-10T09:00:00Z", kind: ShareKind.file.rawValue, text: text, path: "\(inbox)/\(id)", fileName: name, mimeType: mime )}privatefunc linkEntry(_ url: String, title: String? = nil) -> ShareEntry {ShareEntry( id: UUID().uuidString, at: "2026-09-10T09:00:00Z", kind: ShareKind.url.rawValue, url: url, title: title )}privatefunc proseEntry(_ text: String) -> ShareEntry {ShareEntry( id: UUID().uuidString, at: "2026-09-10T09:00:00Z", kind: ShareKind.text.rawValue, text: text )}/// A core for the drain. Every share asks it whether it is a download; a case/// about what follows does not count that question, and a case about it/// scripts it.privatefunc shareCore(_ replies: [String: ScriptedCore.Reply] = [:]) -> ScriptedCore {ScriptedCore( replies.merging([CottonMethod.shareFetchLinks: .ok(#"{"fetch":[]}"#)]) { script, _ in script }, quiet: replies[CottonMethod.shareFetchLinks] == nil ? [CottonMethod.shareFetchLinks] : [] )}/// The whole rig: a mailbox holding these shares, a core answering this script,/// and every copy present on disk unless a case says otherwise.privatefunc rig( _ entries: [ShareEntry], replies: [String: ScriptedCore.Reply] = [:], missing: Set<String> = [], heads: [String: String] = [:], shelf: ShareShelf = ShareShelf(pdfIsBook: false), books: FakeShelf = FakeShelf()) -> (ShareIntake, ScriptedCore, Recorder, FakeShareStorage, FakeInboxFiles) {let storage = FakeShareStorage()let mailbox = ShareMailbox(storage: storage)for entry in entries { mailbox.append(entry) }let present = Set(entries.compactMap(\.path)).subtracting(missing)let files = FakeInboxFiles(present: present, heads: heads)let core = shareCore(replies)let recorder = Recorder()let intake = ShareIntake( core: core, shelf: shelf, books: books, mailbox: mailbox, files: files, navigate: { [recorder] landing in recorder.land(landing) }, report: { [recorder] trouble in recorder.trouble(trouble) }, tell: { [recorder] said in recorder.tell(said) } )return (intake, core, recorder, storage, files)}privatelet captureAnswers: [String: ScriptedCore.Reply] = [CottonMethod.captureMedia: .ok(#"{"key":"ws/photo/abc.jpg","recordId":"photo:abc"}"#)]/// The core answering a document's `capture.media`: the record it minted.privatelet documentAnswers: [String: ScriptedCore.Reply] = [CottonMethod.captureMedia: .ok(#"{"key":"ws/documents/doc-1/original.pdf","recordId":"doc-1"}"#)]privatelet pageAnswers: [String: ScriptedCore.Reply] = [CottonMethod.pageSave: .ok(#"{"id":"page-1"}"#)]/// The crate answering `meetings.create`. The route is the crate's own — the/// app never spells a meeting's path itself (design P6) — and this is exactly/// what `phone/meetings.rs` writes, `key` included, so the decode is held to a/// real answer rather than to the two fields the app happens to read.privatelet meetingAnswers: [String: ScriptedCore.Reply] = [CottonMethod.meetingsCreate: .ok( #"{"id":"11111111-2222-4333-8444-555555555555","route":"/meetings/meeting/11111111-2222-4333-8444-555555555555","key":"ws-1/meetings/11111111-2222-4333-8444-555555555555/full.m4a"}"# )]privatelet createdMeeting = Route.meetingsMeeting(id: "11111111-2222-4333-8444-555555555555")/// What the drain put on the wire for a meeting, decoded rather than grepped —/// the same rule `AskedCapture` states next door.privatestructAskedMeeting: Decodable {let path: Stringlet source: Stringlet title: String?let mime: String?}/// What the drain actually put on the wire, DECODED rather than grepped.////// A substring check over the request would be a check on Foundation's escaping/// as much as on the app — `JSONEncoder` writes `\/` for a slash and/// `JSONSerialization` does not, and a test that pins one of them fails for a/// reason that has nothing to do with sharing.privatestructAskedCapture: Decodable {let path: Stringlet mime: Stringlet kind: Stringlet filename: String?}privatestructAskedPage: Decodable {let url: String?let text: String?let title: String?}extension XCTestCase {fileprivatefunc asked<T: Decodable>( _ calls: [ScriptedCore.Recorded], _ index: Int = 0, as type: T.Type = T.self ) throws -> T {let call = try XCTUnwrap(calls.dropFirst(index).first)returntry JSONDecoder().decode(T.self, from: Data(call.requestJSON.utf8)) }}// MARK: - The precedencefinalclassShareIntakePrecedenceTests: XCTestCase {/// A zip share can also carry a text label the URL extractor would happily/// misread, which is why branch 1 runs first.func testAChatExportOutranksTheLinkInTheTextBesideIt() async {let entry = fileEntry("chat-export.zip", mime: "application/zip", text: "here it is https://example.com/a" )let (intake, core, recorder, _, _) = rig([entry], replies: pageAnswers)await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(recorder.routes, [.messagesImport]) XCTAssertEqual(recorder.landings.first?.staged?.name, "chat-export.zip") XCTAssertEqual( called, [],"the zip branch writes no row — it stages and hands the file to the import screen" ) }/// **An mp4 with no declared type is a VIDEO**, even though the recordings/// map reads `.mp4` as `audio/mp4`. Branch 2 above branch 3 settles it.func testAClipIsAPictureShareAndNotARecording() asyncthrows {let (intake, core, recorder, _, files) = rig( [fileEntry("clip.mp4")], replies: captureAnswers )await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.captureMedia])// Straight into Videos, on the film it just wrote — no composer. XCTAssertEqual(recorder.routes, [.tableRecord(table: "media", id: "photo:abc")])let request: AskedCapture = try asked(calls) XCTAssertEqual(request.kind, "video") XCTAssertEqual(request.mime, "video/mp4") XCTAssertEqual(request.filename, "clip.mp4") XCTAssertEqual( files.discarded.count, 1,"the bytes are in the store now, so the extension's copy has done its job" ) }/// The other half of the same rule: a share that SAYS `audio/mp4` is/// believed, and an audio-only mp4 stays a recording — which is now a/// meeting rather than a reported drop.func testADeclaredAudioMp4IsBelievedAndTakesTheRecordingsBranch() asyncthrows {let (intake, core, recorder, _, _) = rig( [fileEntry("note.mp4", mime: "audio/mp4")], replies: meetingAnswers)await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.meetingsCreate]) XCTAssertEqual(recorder.routes, [createdMeeting]) XCTAssertEqual(recorder.troubles, [])let request: AskedMeeting = try asked(calls) XCTAssertEqual(request.mime, "audio/mp4") }/// The papers rule still admits `image/*` for the vault's own picker, so a/// jpeg matches branch 2 AND branch 4. The/// earlier branch takes it, and the row is written at once.func testAPictureThatTheDocumentsRuleWouldAlsoClaimTakesPhotos() async {let (intake, core, recorder, _, _) = rig( [fileEntry("receipt.jpg", mime: "image/jpeg")], replies: captureAnswers )await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.captureMedia]) XCTAssertEqual(recorder.routes, [.tableRecord(table: "media", id: "photo:abc")]) }/// **A shared picture goes straight into Photos, on the record/// `capture.media` just wrote** — no composer and no message box in/// between (the owner, 23 Oct 2026). The bytes are the store's now, so the/// extension's copy is gone.func testASharedPictureOpensItsPhotoWithNoComposer() asyncthrows {let (intake, _, recorder, _, files) = rig( [fileEntry("screenshot.png", mime: "image/png")], replies: captureAnswers )await intake.drain() XCTAssertEqual(recorder.landings.count, 1)let landing = try XCTUnwrap(recorder.landings.first) XCTAssertEqual(landing.route, .tableRecord(table: "media", id: "photo:abc"), "on the library's deck at its card") XCTAssertNotEqual(landing.route, .capture, "no composer between the share and the photo") XCTAssertNil(landing.staged, "a filed picture is not a staged file") XCTAssertEqual(recorder.troubles, []) XCTAssertEqual(files.discarded.count, 1) }/// A shared clip goes straight onto the library's deck, at its card.func testASharedClipOpensItsVideoWithNoComposer() async {let (intake, _, recorder, _, _) = rig( [fileEntry("clip.mov", mime: "video/quicktime")], replies: [CottonMethod.captureMedia: .ok(#"{"key":"ws/video/abc.mov","recordId":"video:abc"}"#)] )await intake.drain() XCTAssertEqual(recorder.routes, [.tableRecord(table: "media", id: "video:abc")]) XCTAssertEqual(recorder.troubles, []) }/// An answer with no record id is a picture no capture can name, so the/// landing is the library it was always written into — never a composer/// promising a picture it cannot hold.func testAPictureAnsweredWithNoRecordLandsOnTheLibrary() async {let (intake, _, recorder, _, _) = rig( [fileEntry("receipt.jpg", mime: "image/jpeg")], replies: [CottonMethod.captureMedia: .ok(#"{"key":"ws/photo/abc.jpg"}"#)] )await intake.drain() XCTAssertEqual(recorder.routes, [.photos(show: nil)]) }/// **A paper is filed at once and its page opens** (lane door, 22 Oct/// 2026). It used to land on `/documents/import` carrying the staged file,/// and that screen never took it — the share was lost and its copy leaked.func testAPaperIsFiledAsADocumentAndItsPageOpens() asyncthrows {let (intake, core, recorder, _, files) = rig( [fileEntry("statement.pdf", mime: "application/pdf")], replies: documentAnswers )await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.captureMedia]) XCTAssertEqual(recorder.routes, [.documentsDocument(id: "doc-1")]) XCTAssertNil(recorder.landings.first?.staged, "a filed document is not a staged file")let request: AskedCapture = try asked(calls) XCTAssertEqual(request.kind, "document") XCTAssertEqual(request.mime, "application/pdf") XCTAssertEqual(request.filename, "statement.pdf") XCTAssertEqual(files.discarded.count, 1, "the bytes are in the store now") XCTAssertEqual(recorder.troubles, []) }/// A core that names no record still kept the file: the landing is the/// list it was filed into.func testADocumentAnsweredWithNoRecordLandsOnTheList() async {let (intake, _, recorder, _, _) = rig( [fileEntry("statement.pdf", mime: "application/pdf")], replies: [CottonMethod.captureMedia: .ok(#"{"key":"ws/documents/x/original.pdf"}"#)] )await intake.drain() XCTAssertEqual(recorder.routes, [.documents(status: nil)]) }/// A first refusal keeps the bytes and puts the entry back for one more/// drain, and the person is told in the core's own words.func testARefusedDocumentKeepsTheCopyOnceAndSaysSo() async {let (intake, _, recorder, storage, files) = rig( [fileEntry("scan.pdf", mime: "application/pdf")], replies: [CottonMethod.captureMedia: .refuse( code: "too_large", message: "this document is over the ceiling") ] )await intake.drain() XCTAssertEqual(recorder.routes, [.documents(status: nil)]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/document-add"]) XCTAssertEqual(recorder.troubles.first?.say, "this document is over the ceiling") XCTAssertEqual(files.discarded, [], "bytes nobody else is holding stay, once")let waiting = ShareMailbox(storage: storage).drain() XCTAssertEqual(waiting.count, 1, "put back for one more try on the next foreground") XCTAssertEqual(waiting.first?.attempt, 1) }/// A second refusal reports and lets the copy go.func testASecondDocumentRefusalReportsAndDiscards() async {var entry = fileEntry("scan.pdf", mime: "application/pdf") entry.attempt = 1let (intake, _, recorder, storage, files) = rig( [entry], replies: [CottonMethod.captureMedia: .refuse( code: "too_large", message: "this document is over the ceiling") ] )await intake.drain() XCTAssertEqual(files.discarded, [entry.path ?? ""]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/document-add"]) XCTAssertNotNil(recorder.troubles.first?.say, "the person is told, both times") XCTAssertEqual(ShareMailbox(storage: storage).drain(), [], "nothing is put back twice") }/// **The branch the owner asked for back**: share a voice note into Cotton/// and it becomes a meeting, which is what it meant before the phone lost/// its producer on 2026-09-14.////// The copy is discarded because the crate has the bytes; the title is the/// file's own stem, because a voice note is called something and that beats/// the day the crate would otherwise stamp.func testARecordingBecomesAMeetingAndTheCopyIsDiscarded() asyncthrows {let (intake, core, recorder, _, files) = rig( [fileEntry("voice-note.m4a")], replies: meetingAnswers)await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.meetingsCreate]) XCTAssertEqual( recorder.routes, [createdMeeting],"the route is the CRATE's — the app never spells a meeting's path itself" )let request: AskedMeeting = try asked(calls) XCTAssertEqual(request.source, "import") XCTAssertEqual(request.title, "voice-note") XCTAssertEqual(request.mime, "audio/mp4", "an .m4a is AAC in an MPEG-4 file") XCTAssertEqual(files.discarded.count, 1, "the bytes are in the store now") }/// **A WhatsApp voice note**, which is the recording this owner shares in/// most often: `.opus` in an Ogg container, with no declared type at all./// Before this lane `.opus` was in no extension list, so it fell past every/// branch and was filed as a page while its copy leaked in the app group.func testAWhatsAppVoiceNoteIsARecordingAndNotAPage() asyncthrows {let (intake, core, recorder, _, files) = rig( [fileEntry("PTT-20260915-WA0007.opus")], replies: meetingAnswers)await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.meetingsCreate]) XCTAssertEqual(recorder.routes, [createdMeeting])let request: AskedMeeting = try asked(calls) XCTAssertEqual( request.mime, "audio/ogg","the crate writes an Opus object at `full.opus` with the Ogg type it really is" ) XCTAssertEqual(files.discarded.count, 1) }/// A share whose NAME says nothing and whose type says everything.////// The crate reads the container off the path, which is right — a key is a/// name and it has to match its bytes — so the staged copy is renamed to/// match its declared type BEFORE the path is handed over. Passing on a/// path this phone knows is unreadable would be relaying a refusal it could/// have prevented.func testAVoiceMemoWithNoExtensionIsRenamedBeforeItIsSent() asyncthrows {let (intake, core, recorder, _, files) = rig( [fileEntry("memo", mime: "audio/x-m4a")], replies: meetingAnswers)await intake.drain()let calls = await core.callslet request: AskedMeeting = try asked(calls) XCTAssertTrue(request.path.hasSuffix(".m4a"), "sent as \(request.path)") XCTAssertEqual(files.renames.count, 1) XCTAssertEqual(recorder.routes, [createdMeeting]) XCTAssertEqual( files.discarded, files.renames,""" the path DISCARDED is the one that was sent: discarding the old name \ would leave the real file behind for ever """ ) }/// A refusal keeps the bytes ONCE. The sharing app has already let go of/// the original, so these are bytes nobody else is holding — and they are/// not deleted on this app's opinion that a call failed. **They are also/// not kept for ever**: the entry goes back in the mailbox for one more/// drain, and the person is told.func testARefusedMeetingKeepsTheCopyOnceAndSaysSo() async {let (intake, _, recorder, storage, files) = rig( [fileEntry("voice-note.m4a")], replies: [CottonMethod.meetingsCreate: .refuse( code: "too_large", message: "this recording is over the ceiling") ] )await intake.drain() XCTAssertEqual(recorder.routes, [.meetings(importing: false)]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/audio-import"]) XCTAssertEqual(files.discarded, [], "bytes nobody else is holding stay") XCTAssertEqual( recorder.troubles.first?.say, "this recording is over the ceiling","the crate's own sentence reaches the person, not just the log" )let waiting = ShareMailbox(storage: storage).drain() XCTAssertEqual(waiting.count, 1, "put back for one more try on the next foreground") XCTAssertEqual(waiting.first?.attempt, 1) }/// **"Keep on failure" must not mean "leak for ever."** A second drain that/// fails the same way reports with the reason and discards: bytes two/// drains could not file are bytes this app is keeping against a failure it/// has already had twice. The walk of 15 Sep 2026 found `.opus` and `.mp3`/// files in the app group with nothing left that knew they were there.func testASecondFailureReportsAndDiscards() async {var entry = fileEntry("voice-note.m4a") entry.attempt = 1let (intake, _, recorder, storage, files) = rig( [entry], replies: [CottonMethod.meetingsCreate: .refuse( code: "too_large", message: "this recording is over the ceiling") ] )await intake.drain()// The path DISCARDED is the one that was SENT: this share names no// container, so the staged copy was renamed before the crate saw it,// and discarding the old name would leave the real file behind. XCTAssertEqual(files.discarded, files.renames, "the copy goes, by its current name") XCTAssertEqual(files.discarded.count, 1) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/audio-import"]) XCTAssertNotNil(recorder.troubles.first?.say, "the person is told, both times") XCTAssertEqual(ShareMailbox(storage: storage).drain(), [],"nothing is put back a second time") }/// A recording whose staged copy is not there. The same posture as every/// other branch: report, and land where the person would have gone by hand.func testARecordingWithNoBytesLandsOnTheListAndIsReported() async {let entry = fileEntry("voice-note.m4a")let (intake, core, recorder, _, _) = rig([entry], missing: [entry.path ?? ""])await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [], "nothing is asked for a file that is not there") XCTAssertEqual(recorder.routes, [.meetings(importing: false)]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/audio-import"]) XCTAssertNotNil(recorder.troubles.first?.say, "the person shared something; say so") }// ── Any file at all ───────────────────────────────────────────────────/// **A file no rule used to claim is kept, not discarded.** It was/// reported by its extension and thrown away; a person who shared a file/// into their own database meant to keep it, and the core takes any type/// as a document under `application/octet-stream`.func testAFileNoRuleNamesIsKeptAsADocument() asyncthrows {let (intake, core, recorder, _, files) = rig([fileEntry("backup.7z")], replies: documentAnswers)await intake.drain()let calls = await core.callslet request: AskedCapture = try asked(calls) XCTAssertEqual(request.kind, "document") XCTAssertEqual(request.mime, "application/octet-stream") XCTAssertEqual(recorder.routes, [.documentsDocument(id: "doc-1")]) XCTAssertEqual(recorder.troubles, []) XCTAssertEqual(files.discarded.count, 1, "the store has the bytes") }/// A declared type the core does not take is never sent: a refusal there/// would be a file the person shared and lost.func testATypeTheCoreRefusesIsSentAsBytes() asyncthrows {let (intake, core, _, _, _) = rig( [fileEntry("blob", mime: "application/x-made-up")], replies: documentAnswers)await intake.drain()let calls = await core.callslet request: AskedCapture = try asked(calls) XCTAssertEqual(request.mime, "application/octet-stream") }/// The address beside a file is still a fact, and is still saved. The two/// halves are independent and neither swallows the other.func testAnAddressBesideAFileIsStillSaved() async {let entry = fileEntry("backup.7z", text: "and here it is https://example.com/a")var replies = documentAnswers replies.merge(pageAnswers) { one, _ in one }let (intake, core, recorder, _, _) = rig([entry], replies: replies)await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.captureMedia, CottonMethod.pageSave]) XCTAssertEqual(recorder.routes, [.documentsDocument(id: "doc-1")], "the file's landing stands") XCTAssertEqual(recorder.troubles, []) }}// MARK: - BooksfinalclassShareIntakeBookTests: XCTestCase {privatelet books = ShareShelf(pdfIsBook: true)/// An EPUB is a book in every app: shelved (read from the file and kept as/// a book row) ahead of the documents, and the app opens the book.func testAnEpubIsShelvedAsABookInEveryApp() async {for shelf in [ShareShelf(pdfIsBook: false), books] {let shelfDouble = FakeShelf()let entry = fileEntry("The Lantern Orchard.epub")let (intake, core, recorder, _, files) = rig([entry], shelf: shelf, books: shelfDouble)await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [], "the shelf, not a document's capture") XCTAssertEqual(shelfDouble.shelved.map(\.format), [.epub]) XCTAssertEqual(shelfDouble.shelved.first?.fileName, "The Lantern Orchard.epub") XCTAssertEqual(recorder.routes, [.tableRecord(table: "book", id: "book-1")]) XCTAssertEqual(files.discarded, [entry.path!]) } }/// The branch order: in Cotton Books a PDF is a book, ahead of the/// document branch; in Cotton it stays a document.func testAPdfIsABookInCottonBooksAndADocumentInCotton() async {let shelf = FakeShelf()let (intake, core, recorder, _, _) = rig([fileEntry("statement.pdf", mime: "application/pdf")], shelf: books, books: shelf)await intake.drain()let none = await core.methodsCalled() XCTAssertEqual(none, []) XCTAssertEqual(shelf.shelved.map(\.format), [.pdf]) XCTAssertEqual(recorder.routes, [.tableRecord(table: "book", id: "book-1")])let cottons = FakeShelf()let (cotton, core2, landed, _, _) = rig( [fileEntry("statement.pdf", mime: "application/pdf")], replies: documentAnswers, books: cottons)await cotton.drain()let called = await core2.methodsCalled() XCTAssertEqual(called, [CottonMethod.captureMedia]) XCTAssertTrue(cottons.shelved.isEmpty) XCTAssertEqual(landed.routes, [.documentsDocument(id: "doc-1")]) }/// A Goodreads export is told by its first line and handed whole to the/// object; a CSV that is not one is a document.func testAGoodreadsExportIsHandedToTheObject() asyncthrows {let csv = "Book Id,Title,Author,Author l-f\n1,Invented Title,Invented Author,\"Author, Invented\"\n"let entry = fileEntry("goodreads_library_export.csv", mime: "text/csv")let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)tryFileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: directory) }let real = directory.appendingPathComponent("export.csv")tryData(csv.utf8).write(to: real)var onDisk = entry onDisk.path = real.path(percentEncoded: false)let shelf = FakeShelf()let (intake, _, recorder, _, files) = rig([onDisk], heads: [onDisk.path!: csv], shelf: books, books: shelf)await intake.drain() XCTAssertEqual(shelf.imported, [csv])// The library lands on the deck at its first book, as the first of// many (Books' All), never on the list page over the deck. XCTAssertEqual(recorder.landings, [ShareLanding(route: .tableRecord(table: "book", id: "book-first"), many: true)]) XCTAssertEqual(recorder.told, [ShellLines.line("boot", "books.goodreads_sent")]) XCTAssertEqual(files.discarded, [onDisk.path!])let budget = fileEntry("budget.csv", mime: "text/csv")let other = FakeShelf()let (plain, core, landed, _, _) = rig([budget], replies: documentAnswers, heads: [budget.path!: "Date,Amount\n"], shelf: books, books: other)await plain.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.captureMedia]) XCTAssertTrue(other.imported.isEmpty) XCTAssertEqual(landed.routes, [.documentsDocument(id: "doc-1")]) }/// Several books shared or chosen at once land once, at the first, as the/// first of many: not on whichever came in last.func testSeveralBooksLandOnceAtTheFirst() async {let shelf = FakeShelf()let (intake, _, recorder, _, _) = rig([fileEntry("one.epub"), fileEntry("two.epub")], shelf: books, books: shelf)await intake.drain() XCTAssertEqual(shelf.shelved.count, 2) XCTAssertEqual(recorder.landings, [ShareLanding(route: .tableRecord(table: "book", id: "book-1"), many: true)]) }/// RULE: one intake's landings: two or more records of one table land once at the first, as many; a lone record, records of two tables and every other landing stand as they came.func testLandingsOfOneIntake() {let one = ShareLanding(route: .tableRecord(table: "book", id: "a"))let two = ShareLanding(route: .tableRecord(table: "book", id: "b"))let list = ShareLanding(route: ShareKnock.bookList) XCTAssertEqual(ShareLanding.landed([one]), [one]) XCTAssertEqual(ShareLanding.landed([one, two]), [ShareLanding(route: one.route, many: true)]) XCTAssertEqual(ShareLanding.landed([list, one, two]), [list, ShareLanding(route: one.route, many: true)])let photo = ShareLanding(route: .tableRecord(table: "photo", id: "p")) XCTAssertEqual(ShareLanding.landed([one, photo]), [one, photo]) XCTAssertEqual(ShareLanding.landed([]), []) }/// A book the shelf refuses is kept for one more drain, then reported and/// discarded, and the app lands on the books.func testARefusedBookIsKeptOnceThenDiscarded() async {let shelf = FakeShelf(refuses: true)let (intake, _, recorder, _, files) = rig([fileEntry("broken.epub")], shelf: books, books: shelf)await intake.drain() XCTAssertEqual(recorder.routes, [ShareKnock.bookList]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/book-add"]) XCTAssertTrue(files.discarded.isEmpty, "kept for one more try")await intake.drain() XCTAssertEqual(files.discarded.count, 1, "the second refusal discards") XCTAssertEqual(recorder.troubles.last?.say, ShellLines.line("boot", "books.refused")) }}// MARK: - A Cotton packageprivatelet packageAnswers: [String: ScriptedCore.Reply] = [CottonMethod.packageImport: .ok( #"{"created":{"cotton_todos":2},"changed":{"cotton_people":1},"unchanged":{},"refused":[],"mediaWritten":1}"#)]finalclassShareIntakePackageTests: XCTestCase {/// **A package outranks the chat branch**, which takes any zip: it is/// imported at once by its path, the copy goes, and the person is told/// what came in. Nothing navigates — the records are across tables.func testAPackageIsImportedAndThePersonIsTold() asyncthrows {let entry = fileEntry("cotton-2026-10-22.cottonpkg", mime: "application/zip")let (intake, core, recorder, _, files) = rig([entry], replies: packageAnswers)await intake.drain()let calls = await core.calls XCTAssertEqual(calls.map(\.method), [CottonMethod.packageImport]) XCTAssertTrue(calls[0].requestJSON.contains(#""args""#)) XCTAssertEqual(recorder.routes, [], "a package opens no one screen") XCTAssertEqual(recorder.told.count, 1) XCTAssertTrue(recorder.told[0].contains("3"), "two made and one changed: \(recorder.told)") XCTAssertEqual(files.discarded, [entry.path ?? ""]) XCTAssertEqual(recorder.troubles, []) }/// The name decides, whatever the staged copy is called.func testAPackageIsKnownByItsExtension() { XCTAssertTrue(isPackageShare(SharedFile(path: "/a/x", fileName: "cotton-2026-10-22.cottonpkg"))) XCTAssertTrue(isPackageShare(SharedFile(path: "/a/1234.cottonpkg"))) XCTAssertFalse(isPackageShare(SharedFile(path: "/a/chat.zip"))) }/// A refusal keeps the bytes once, in the core's own words.func testARefusedPackageKeepsTheCopyOnceAndSaysSo() async {let entry = fileEntry("cotton.cottonpkg")let (intake, _, recorder, storage, files) = rig( [entry], replies: [CottonMethod.packageImport: .refuse(code: "bad_request", message: "this is not a Cotton package")] )await intake.drain() XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/package-import"]) XCTAssertEqual(recorder.troubles.first?.say, "this is not a Cotton package") XCTAssertEqual(files.discarded, []) XCTAssertEqual(ShareMailbox(storage: storage).drain().count, 1, "put back for one more try") XCTAssertEqual(recorder.told, []) }/// Records the core would not write are said, beside what came in.func testWhatAnImportRefusedIsSaid() {let done = PackageImported( created: ["cotton_todos": 1], changed: [:], unchanged: [:], refused: [.init(table: "cotton_todos", id: "t-9", reason: "a newer copy is here")], mediaWritten: 0)let said = ShareIntake.receipt(done) XCTAssertTrue(said.contains("1"), said) XCTAssertNotEqual(said, ShareIntake.receipt(PackageImported(created: ["cotton_todos": 1], changed: [:], unchanged: [:], refused: [], mediaWritten: 0))) }}// MARK: - Settings › Bring infinalclassShareIntakeBringInTests: XCTestCase {/// Files chosen in Settings › Bring in go through the SAME branches as a/// share — and never through the mailbox, so a share waiting there for/// its one retry keeps waiting for a later foreground.func testEntriesHandedInAreFiledWithoutTouchingTheMailbox() asyncthrows {let waiting = fileEntry("voice-note.m4a")let picked = [fileEntry("statement.pdf", mime: "application/pdf"), fileEntry("backup.7z")]let storage = FakeShareStorage()let mailbox = ShareMailbox(storage: storage) mailbox.append(waiting)let core = shareCore(documentAnswers)let recorder = Recorder()let intake = ShareIntake( core: core, shelf: ShareShelf(pdfIsBook: false), mailbox: mailbox, files: FakeInboxFiles(present: Set(picked.compactMap(\.path))), navigate: { [recorder] landing in recorder.land(landing) }, report: { [recorder] trouble in recorder.trouble(trouble) }, tell: { [recorder] said in recorder.tell(said) } )await intake.intake(picked)let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.captureMedia, CottonMethod.captureMedia]) XCTAssertEqual(recorder.routes, [.documentsDocument(id: "doc-1"), .documentsDocument(id: "doc-1")]) XCTAssertEqual(ShareMailbox(storage: storage).drain().map(\.id), [waiting.id], "the mailbox is untouched") }/// A chosen or opened file is copied into the inbox under a fresh name/// that keeps its extension, and the entry keeps the person's name for it.func testAFileIsStagedLikeAShare() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent("stage-\(UUID().uuidString)")defer { try? FileManager.default.removeItem(at: root) }tryFileManager.default.createDirectory(at: root, withIntermediateDirectories: true)let source = root.appendingPathComponent("cotton-2026-10-22.cottonpkg")tryData("PK".utf8).write(to: source)let staged = stageForIntake([source], at: "2026-10-22T09:00:00Z", into: root.appendingPathComponent("inbox"))let entry = try XCTUnwrap(staged.first) XCTAssertEqual(entry.kind, ShareKind.file.rawValue) XCTAssertEqual(entry.fileName, "cotton-2026-10-22.cottonpkg") XCTAssertTrue(entry.path?.hasSuffix(".cottonpkg") ?? false) XCTAssertTrue(FileManager.default.fileExists(atPath: entry.path ?? ""), "the copy is made") XCTAssertTrue(PackageOpen.isPackage(source)) XCTAssertFalse(PackageOpen.isPackage(URL(string: "rigby:///todos")!), "a route is not a package") XCTAssertEqual(stageForIntake([source], at: "", into: nil), [], "no app group is no channel") }/// The declared type the Files pick sends is the share extension's rule:/// a MIME type when the type has one, an abstract UTI for a picture, a/// clip or a recording that has none, and nothing for a file the type says/// nothing about.func testAPickedFileIsTypedAsAShareIs() { XCTAssertEqual(shareDeclaredType(forType: "com.adobe.pdf"), "application/pdf") XCTAssertEqual(shareDeclaredType(forType: "public.jpeg"), "image/jpeg") XCTAssertNil(shareDeclaredType(forType: "public.data")) XCTAssertNil(shareDeclaredType(forType: "not.a.type")) }}// MARK: - The failure posturefinalclassShareIntakeFailureTests: XCTestCase {/// A failed stage "leaves the user exactly where a non-share entry starts:/// the import screen's own picker", and the/// drop is still worth a report.func testAMissingFileStillLandsOnTheBareImportScreen() async {let entry = fileEntry("chat-export.zip", mime: "application/zip")let (intake, core, recorder, _, _) = rig([entry], missing: [entry.path ?? ""])await intake.drain() XCTAssertEqual(recorder.routes, [.messagesImport]) XCTAssertNil( recorder.landings.first?.staged,"there are no bytes to hand over — the screen opens its own picker" )let called = await core.methodsCalled() XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/zip-stage"]) XCTAssertEqual(called, []) }/// "The same posture": land where the person would have gone by hand, and/// report the drop. `/photos` and not `/videos`, even for a clip, because/// that is the line the previous app wrote.func testACaptureRefusalStillLandsOnPhotos() async {let (intake, _, recorder, _, files) = rig( [fileEntry("clip.mp4")], replies: [CottonMethod.captureMedia: .refuse( code: "too_large", message: "this video is over the ceiling" ) ] )await intake.drain() XCTAssertEqual(recorder.routes, [.photos(show: nil)]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/picture-add"]) XCTAssertEqual( files.discarded, [],"a capture that did not land is bytes nobody else is holding — they stay" ) }/// The same posture again, for a paper whose bytes are not there: nothing/// is asked of the core, nothing is put back (there is nothing to retry/// with), and the person lands on the documents list, told.func testAMissingPaperLandsOnTheDocumentsList() async {let paper = fileEntry("statement.pdf", mime: "application/pdf")let (intake, core, recorder, storage, _) = rig([paper], missing: [paper.path ?? ""])await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, []) XCTAssertEqual(recorder.routes, [.documents(status: nil)]) XCTAssertEqual(recorder.troubles.map(\.route), ["reader-intake/document-add"]) XCTAssertEqual(ShareMailbox(storage: storage).drain(), []) }/// "The intent must never survive to re-fire this effect forever". The/// whole list is taken before the first branch/// runs, so a share whose branch failed is not offered again on the next/// foreground.func testTheMailboxIsEmptyEvenWhenEveryBranchFailed() async {let zip = fileEntry("chat-export.zip", mime: "application/zip")let (intake, _, _, storage, _) = rig( [zip, proseEntry("https://example.com/a")], replies: [CottonMethod.pageSave: .refuse(code: "write_refused", message: "not connected") ], missing: [zip.path ?? ""] )await intake.drain() XCTAssertNil(storage.raw, "the mailbox key is removed, not emptied and left behind")let second = Recorder()let again = ShareIntake( core: shareCore(), shelf: ShareShelf(pdfIsBook: false), mailbox: ShareMailbox(storage: storage), files: FakeInboxFiles(present: []), navigate: { [second] landing in second.land(landing) }, report: { [second] trouble in second.trouble(trouble) }, tell: { [second] said in second.tell(said) } )await again.drain() XCTAssertEqual(second.routes, [], "a second foreground finds nothing waiting") }}// MARK: - The linksfinalclassShareIntakeDownloadTests: XCTestCase {/// RULE: what is a download is the core's to say. The/// shell hands over the share as it came and opens the row it is told.func testACoreDownloadOpensOnItsRowAndIsNeverAPage() asyncthrows {let (intake, core, recorder, _, _) = rig( [linkEntry("https://example.com/watch", title: "A film")], replies: [CottonMethod.shareFetchLinks: .ok(#"{"fetch":["fetch-1"]}"#)] )await intake.drain()let calls = await core.calls XCTAssertEqual(calls.map(\.method), [CottonMethod.shareFetchLinks])let sent = try XCTUnwrap(calls.first?.requestJSON) XCTAssertTrue(sent.contains("https:\\/\\/example.com\\/watch") || sent.contains("https://example.com/watch"), sent) XCTAssertTrue(sent.contains("A film"), sent) XCTAssertEqual(recorder.landings, [ShareLanding(route: .tableRecord(table: "fetch", id: "fetch-1"))]) }/// A refusal says the act's own words and lands nothing: a magnet kept as/// a page would be a page nobody can read.func testARefusedDownloadSaysSoAndSavesNoPage() asyncthrows {let words = "Sign in to fetch links on your Mac"let (intake, core, recorder, _, _) = rig( [linkEntry("magnet:?xt=urn:btih:abc")], replies: [CottonMethod.shareFetchLinks: .refuse(code: "sign_in_first", message: words)] )await intake.drain()let called = await core.calls.map(\.method) XCTAssertEqual(called, [CottonMethod.shareFetchLinks]) XCTAssertTrue(recorder.landings.isEmpty) XCTAssertEqual(recorder.troubles.first?.say, words) }}finalclassShareIntakePagesTests: XCTestCase {/// Every URL in the prose becomes its own page, "exactly as Knock made/// every one its own tab".////// **ONE call carrying the whole text, and the crate makes the rows.**/// `page.save` extracts every URL itself (`validate_pages`,/// `phone/page.rs:83-105`) and answers `{ids}`; a Swift loop would need a/// second URL regex up here, and two spellings of "what counts as a URL" is/// two spellings of one page, which is two rows in the reading pile. So the/// assertion is that the app asked ONCE and handed over the prose intact —/// the one-row-per-URL half is the crate's, and its own tests hold it.func testProseWithSeveralLinksIsOneSaveCarryingTheWholeText() asyncthrows {let prose = "read these two https://example.com/alpha and https://example.com/beta"let (intake, core, _, _, _) = rig( [proseEntry(prose)], replies: [CottonMethod.pageSave: .ok(#"{"ids":["page-1","page-2"]}"#)] )await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.pageSave])let request: AskedPage = try asked(calls) XCTAssertEqual(request.text, prose, "the prose goes over whole — the crate extracts") XCTAssertNil(request.url, "`page.save` refuses `url` and `text` together, by name") }/// **A link-only share closes on its card** — the `page` record, which/// the fan brings on the Web pages tile as it brings a shared book; several/// links stand at the first of them, `many` — since the sheet opened the/// app for it (the owner, 23 Oct 2026). Before this the link opened the/// reader's page over a `page` table no tool shipped: "This app cannot/// show these records". A refused save still lands on the pages list.func testALinkShareClosesOnItsCard() async {let (one, _, onePage, _, _) = rig([linkEntry("https://example.com/alpha")], replies: pageAnswers)await one.drain() XCTAssertEqual(onePage.landings, [ShareLanding(route: .tableRecord(table: "page", id: "page-1"))])let (several, _, list, _, _) = rig( [proseEntry("https://example.com/alpha https://example.com/beta")], replies: [CottonMethod.pageSave: .ok(#"{"ids":["page-1","page-2"]}"#)])await several.drain() XCTAssertEqual(list.landings, [ShareLanding(route: .tableRecord(table: "page", id: "page-1"), many: true)])let (refused, _, stillLands, _, _) = rig( [linkEntry("https://example.com/alpha")], replies: [CottonMethod.pageSave: .refuse(code: "write_refused", message: "not connected")])await refused.drain() XCTAssertEqual(stillLands.routes, [.reader]) }/// Two shares are two saves — which is the "one save per URL" shape the/// mailbox can actually produce, since each share is its own entry.func testTwoLinkSharesAreTwoSaves() asyncthrows {let (intake, core, _, _, _) = rig( [linkEntry("https://example.com/alpha"), linkEntry("https://example.com/beta")], replies: pageAnswers )await intake.drain()let called = await core.methodsCalled()let calls = await core.calls XCTAssertEqual(called, [CottonMethod.pageSave, CottonMethod.pageSave])let first: AskedPage = try asked(calls, 0)let second: AskedPage = try asked(calls, 1) XCTAssertEqual(first.url, "https://example.com/alpha") XCTAssertEqual(second.url, "https://example.com/beta") }/// `webUrl ?? text` (`:213`) — a page share carries both, and the address is/// the fact.func testTheAddressWinsOverTheProseWhenBothArrived() asyncthrows {var entry = linkEntry("https://example.com/alpha") entry.text = "look at this https://example.com/somewhere-else"let (intake, core, _, _, _) = rig([entry], replies: pageAnswers)await intake.drain()let calls = await core.callslet request: AskedPage = try asked(calls) XCTAssertEqual(request.url, "https://example.com/alpha") XCTAssertNil(request.text, "`webUrl ?? text` — the address is the fact") }/// The title the sharing app gave the link is the card's title; a title/// that is only the address again, or blank, is no title.func testALinkKeepsTheTitleTheSharingAppGaveIt() asyncthrows {let (intake, core, _, _, _) = rig( [linkEntry("https://example.com/alpha", title: " Alpha, a page "), linkEntry("https://example.com/beta", title: "https://example.com/beta"), linkEntry("https://example.com/gamma", title: " ")], replies: pageAnswers )await intake.drain()let calls = await core.callslet titled: AskedPage = try asked(calls, 0)let addressed: AskedPage = try asked(calls, 1)let blank: AskedPage = try asked(calls, 2) XCTAssertEqual(titled.title, "Alpha, a page") XCTAssertNil(addressed.title) XCTAssertNil(blank.title) }func testAShareCarryingNeitherAnAddressNorProseAsksNothing() async {let (intake, core, recorder, _, _) = rig([proseEntry(" ")])await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, []) XCTAssertEqual(recorder.routes, []) }}// MARK: - The mailbox itselffinalclassShareMailboxTests: XCTestCase {/// The rule the raw read-modify-write exists for: an entry a/// newer extension wrote still belongs to the app that will drain it, so/// nothing is re-encoded from a decoded struct.func testAnAppendKeepsAFieldThisBuildDoesNotUnderstand() {let seeded = """ [{"id":"one","at":"2026-09-10T08:00:00Z","kind":"url",\ "url":"https://example.com/a","attempt":0,"sharedBy":"a field this build has never heard of"}] """let storage = FakeShareStorage(seeded)let mailbox = ShareMailbox(storage: storage) mailbox.append(linkEntry("https://example.com/beta"))let raw = storage.raw ?? "" XCTAssertTrue( raw.contains("a field this build has never heard of"),"re-encoding a decoded struct silently drops a newer build's data: \(raw)" ) XCTAssertTrue(raw.contains("beta"), raw) XCTAssertEqual(mailbox.drain().count, 2, "and both entries are still readable") }/// It APPENDS. The plugin's single slot lost the first of two quick shares,/// and that is the bug this channel stops reproducing.func testASecondShareDoesNotOverwriteTheFirst() {let storage = FakeShareStorage()let mailbox = ShareMailbox(storage: storage) mailbox.append(linkEntry("https://example.com/alpha")) mailbox.append(linkEntry("https://example.com/beta")) XCTAssertEqual(mailbox.drain().compactMap(\.url), ["https://example.com/alpha", "https://example.com/beta", ]) }/// One unreadable entry is not worth the whole list.func testAnUnreadableEntryIsDroppedRatherThanTakingTheListWithIt() {let storage = FakeShareStorage( #"["not an object",{"id":"two","at":"2026-09-10T08:00:00Z","kind":"url","url":"https://example.com/a","attempt":0}]"# ) XCTAssertEqual(ShareMailbox(storage: storage).drain().map(\.id), ["two"]) }func testDrainingAnEmptyMailboxIsNotAnError() { XCTAssertEqual(ShareMailbox(storage: FakeShareStorage()).drain(), []) }}// MARK: - The classification rules, as pure functionsfinalclassShareFileKindTests: XCTestCase {func testAProvidersExtensionlessNameKeepsTheStagedMoviesType() {for (ext, mime) in [("mov", "video/quicktime"), ("mp4", "video/mp4"), ("m4v", "video/mp4")] {let file = SharedFile(path: "/inbox/staged.\(ext)", fileName: "Shared clip", mimeType: "application/octet-stream") XCTAssertEqual(shareFileKind(file), .video) XCTAssertEqual(pictureContentType(file), mime) } XCTAssertEqual(pictureContentType(SharedFile(path: "/inbox/staged.m4v", mimeType: "video/x-m4v")), "video/mp4") }/// The declared-type table, case for case.func testTheDeclaredTypeWinsWhereItDeclaresSomething() { XCTAssertEqual(shareFileKind(SharedFile(path: "/a/x", mimeType: "video/mp4")), .video) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/x", mimeType: "audio/mpeg")), .audio) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/x", mimeType: "image/png")), .photo) XCTAssertEqual( shareFileKind(SharedFile(path: "/a/x", mimeType: "application/pdf")), .document ) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/x", mimeType: "public.movie")), .video) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/x", mimeType: "public.image")), .photo) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/x", mimeType: "public.audio")), .audio) }/// A type that says nothing is the same as saying nothing at all, and the/// extension answers instead.func testAnUndeclaredTypeFallsThroughToTheExtension() {for said in ["", "application/octet-stream", "public.data", "*/*"] { XCTAssertEqual( shareFileKind(SharedFile(path: "/a/photo.heic", mimeType: said)), .photo, said ) } XCTAssertEqual(shareFileKind(SharedFile(path: "/a/clip.mov")), .video) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/memo.wav")), .audio) XCTAssertEqual(shareFileKind(SharedFile(path: "/a/sheet.xlsx")), .document) }func testTheNameWinsOverThePathWhenTheShareGaveOne() { XCTAssertEqual( shareFileKind(SharedFile(path: "/a/1B2C3D", fileName: "clip.mov")), .video ) }func testTheExtensionRule() { XCTAssertEqual(shareFileExtension("a/b/report.PDF"), "pdf") XCTAssertEqual(shareFileExtension("no-extension"), "") XCTAssertEqual(shareFileExtension(".hidden"), "") XCTAssertEqual(shareFileExtension("trailing."), "") }func testTheZipRule() { XCTAssertTrue(isZipShare(SharedFile(path: "/a/chat.zip"))) XCTAssertTrue(isZipShare(SharedFile(path: "/a/x", mimeType: "application/zip"))) XCTAssertTrue( isZipShare(SharedFile(path: "/a/x", mimeType: "application/x-zip-compressed")) ) XCTAssertFalse(isZipShare(SharedFile(path: "/a/statement.pdf"))) }/// Branch 4's type is always one the core's document list carries: the/// share's own when the core takes it, the extension's next, and bytes/// otherwise.func testADocumentIsFiledUnderATypeTheCoreTakes() { XCTAssertEqual(documentContentType(SharedFile(path: "/a/x", mimeType: "application/pdf")), "application/pdf") XCTAssertEqual(documentContentType(SharedFile(path: "/a/notes.txt")), "text/plain") XCTAssertEqual(documentContentType(SharedFile(path: "/a/sheet.XLSX")), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") XCTAssertEqual(documentContentType(SharedFile(path: "/a/x", mimeType: "text/csv")), "text/csv") XCTAssertEqual(documentContentType(SharedFile(path: "/a/talk.key", mimeType: "application/x-iwork-keynote-sffkey")), "application/octet-stream") XCTAssertEqual(documentContentType(SharedFile(path: "/a/no-name")), "application/octet-stream") }/// The recordings list SUBTRACTS what the pictures claim rather than/// restating the rule.func testTheRecordingsRuleSubtractsWhatThePicturesClaim() { XCTAssertFalse(isAudioShare(SharedFile(path: "/a/clip.mp4"))) XCTAssertTrue(isAudioShare(SharedFile(path: "/a/note.mp4", mimeType: "audio/mp4"))) XCTAssertTrue(isAudioShare(SharedFile(path: "/a/memo.m4a"))) }/// Every container `MeetingAudioFormats` offers is one the share sheet/// claims — the two lists are ONE list, subtracted rather than retyped, and/// the `.opus` that used to be in neither is the reason.func testEveryContainerTheProducerOffersIsAlsoARecordingShare() {for container inMeetingAudioFormats.extensions where container != "mp4" { XCTAssertTrue( isAudioShare(SharedFile(path: "/a/note.\(container)")),".\(container) is a meeting container the share sheet does not claim" ) }// `mp4` is the one both families claim, and the ordinary share is a// clip — so it is a recording only when the share SAYS so. XCTAssertTrue(isAudioShare(SharedFile(path: "/a/note.mp4", mimeType: "audio/mp4"))) }/// Never `application/octet-stream` for a picture.func testTheContentTypeAPictureIsStoredUnder() { XCTAssertEqual(pictureContentType(SharedFile(path: "/a/clip.mp4")), "video/mp4") XCTAssertEqual(pictureContentType(SharedFile(path: "/a/clip.mov")), "video/quicktime") XCTAssertEqual(pictureContentType(SharedFile(path: "/a/x.heif")), "image/heic") XCTAssertEqual(pictureContentType(SharedFile(path: "/a/x.png")), "image/png") XCTAssertEqual( pictureContentType(SharedFile(path: "/a/x", mimeType: "public.movie")), "video/mp4" ) XCTAssertEqual(pictureContentType(SharedFile(path: "/a/unnamed")), "image/jpeg") }}// MARK: - A chat export that is a .txt/// **A `_chat.txt` is a chat, not a paper.** WhatsApp's share sheet offers/// "Without media", which hands over the transcript on its own — and until this/// lane that file matched `supportedDocumentExtensions` and was filed in the/// reading pile, where no import could reach it.////// Three rules answer it, in cost order: a zip is free, the name is free, and/// only a `.txt` whose name says nothing costs a read of its first bytes. Every/// name and transcript below is invented.finalclassChatExportTextShareTests: XCTestCase {/// The first line of an export, in the two dialects the adapter parses.privatelet iosTranscript = """ \u{200E}[26/07/2025, 10:12:45\u{202F}AM] Alpaca One: Messages are end-to-end encrypted. \u{200E}[26/07/2025, 10:13:02\u{202F}AM] Nilgiri Two: On my way """privatelet androidTranscript = """ 26/07/2025, 10:12 - Messages are end-to-end encrypted. 26/07/2025, 10:13 - Nilgiri Two: On my way """// ── the name ──────────────────────────────────────────────────────────func testTheThreeNamesWhatsAppGivesAnExport() { XCTAssertTrue(isChatExportName(SharedFile(path: "/a/_chat.txt"))) XCTAssertTrue( isChatExportName(SharedFile(path: "/a/x", fileName: "WhatsApp Chat - Alpaca One.txt")) ) XCTAssertTrue( isChatExportName(SharedFile(path: "/a/x", fileName: "WhatsApp Chat with Alpaca One.txt") ) )// The staging prefix a share sheet writes in front of the name. XCTAssertTrue( isChatExportName(SharedFile(path: "/a/x", fileName: "1757000000000-WhatsApp Chat - Trek.txt") ) ) }func testANoteIsNotAnExportHoweverItIsNamed() { XCTAssertFalse(isChatExportName(SharedFile(path: "/a/notes.txt"))) XCTAssertFalse(isChatExportName(SharedFile(path: "/a/chat.txt")))// The right name, the wrong kind of file: this rule is about `.txt`. XCTAssertFalse( isChatExportName(SharedFile(path: "/a/x", fileName: "WhatsApp Chat - Alpaca One.pdf")) ) }// ── the sniff ─────────────────────────────────────────────────────────func testTheFirstLineOfEitherDialectReadsAsATranscript() { XCTAssertTrue(looksLikeChatExport(iosTranscript)) XCTAssertTrue(looksLikeChatExport(androidTranscript))// A 24-hour phone writes no AM/PM, and iOS writes the seconds. XCTAssertTrue(looksLikeChatExport("[26/07/2025, 22:12:45] Alpaca One: Late"))// An American export, which the crate decides the date order of. XCTAssertTrue(looksLikeChatExport("[7/26/25, 10:12:45 PM] Alpaca One: Late"))// An em-dash phone. XCTAssertTrue(looksLikeChatExport("26.07.2025, 10:12 \u{2014} Alpaca One: Hello")) }func testOrdinaryProseIsNotATranscript() { XCTAssertFalse(looksLikeChatExport("Dear Nilgiri,\nhere are the notes from Tuesday.")) XCTAssertFalse(looksLikeChatExport("")) XCTAssertFalse(looksLikeChatExport("\n\n"))// A date with nothing after it is a diary heading, not a header. XCTAssertFalse(looksLikeChatExport("26/07/2025\nbought milk"))// **The FIRST line decides.** A dated line further down a file is not// an export, or every log and every diary would be somebody's chat. XCTAssertFalse( looksLikeChatExport("Notes from the trek\n[26/07/2025, 10:12:45 AM] Alpaca One: Hi") ) }// ── the three composed ────────────────────────────────────────────────func testTheNameAnswersWithoutReadingTheFile() {var read = 0 XCTAssertTrue( isChatExportShare(SharedFile(path: "/a/x", fileName: "_chat.txt")) { read += 1returnnil } ) XCTAssertEqual(read, 0, "a name that says it is an export costs no read") }func testAZipIsAnExportWithoutReadingItEither() {var read = 0 XCTAssertTrue( isChatExportShare(SharedFile(path: "/a/chat.zip")) { read += 1returnnil } ) XCTAssertEqual(read, 0) }func testANamelessTextFileIsDecidedByItsFirstLine() { XCTAssertTrue(isChatExportShare(SharedFile(path: "/a/x.txt")) { self.iosTranscript }) XCTAssertFalse(isChatExportShare(SharedFile(path: "/a/x.txt")) { "a shopping list" })// Unreadable is not an export: a guess there would file somebody's// paper as a chat. XCTAssertFalse(isChatExportShare(SharedFile(path: "/a/x.txt")) { nil }) }func testAPdfIsNeverSniffed() {var read = 0 XCTAssertFalse( isChatExportShare(SharedFile(path: "/a/statement.pdf", mimeType: "application/pdf")) { read += 1returnnil } ) XCTAssertEqual(read, 0, "only a `.txt` is ever looked inside") }// ── through the drain ─────────────────────────────────────────────────func testATextExportTakesTheChatBranchAndCarriesItsFile() async {let entry = fileEntry("WhatsApp Chat - Alpaca One.txt", mime: "text/plain")let (intake, core, recorder, _, _) = rig([entry])await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(recorder.routes, [.messagesImport]) XCTAssertEqual(recorder.landings.first?.staged?.name, "WhatsApp Chat - Alpaca One.txt") XCTAssertEqual(called, [], "the chat branch writes no row — it stages and hands over") }func testATextFileNamedNothingIsSniffedAndTakesTheChatBranch() async {let entry = fileEntry("export.txt", mime: "text/plain")let (intake, _, recorder, _, files) = rig( [entry], heads: [entry.path ?? "": iosTranscript] )await intake.drain() XCTAssertEqual(recorder.routes, [.messagesImport]) XCTAssertEqual(files.headsRead, [entry.path ?? ""], "the one branch that may read a file") }func testAnOrdinaryNoteIsStillAPaper() asyncthrows {let entry = fileEntry("notes.txt", mime: "text/plain")let (intake, core, recorder, _, _) = rig( [entry], replies: documentAnswers, heads: [entry.path ?? "": "buy milk"])await intake.drain()let calls = await core.callslet request: AskedCapture = try asked(calls) XCTAssertEqual(request.kind, "document") XCTAssertEqual(request.mime, "text/plain") XCTAssertEqual(recorder.routes, [.documentsDocument(id: "doc-1")]) }func testAPictureIsNeverReadOffTheDisk() async {let (intake, _, _, _, files) = rig( [fileEntry("receipt.jpg", mime: "image/jpeg")], replies: captureAnswers )await intake.drain() XCTAssertEqual(files.headsRead, [], "four of the five branches never open a file") }}// MARK: - The share extension's own two rules/// `CottonMailbox/ShareHandover.swift` — the rules that USED to live inside the/// extension target, where nothing executable could hold them.@MainActorfinalclassShareHandoverTests: XCTestCase {// ── which type a provider's file is staged under, and HOW ─────────────/// A concrete type with bytes wins, so a declared `audio/mp4` survives to/// the classification that keeps an audio-only mp4 out of the picture grid/// — and it is loaded as a file REPRESENTATION, which for a concrete type/// really is a file.func testAConcreteDataTypeIsPreferredOverAFileURL() { XCTAssertEqual( shareFileSource( registered: ["public.file-url", "public.mpeg-4-audio"], suggestedName: "note.mp4" ), .representation(identifier: "public.mpeg-4-audio") ) }/// **The case root cause C of the 15 Sep 2026 walk turned on.** A file URL/// answers when nothing concrete was registered — and it says `url`, so the/// extension asks for the URL and copies the file THAT names./// `loadFileRepresentation` under `public.file-url` hands back a property/// list holding a `file://` string, 261 bytes with no extension, which the/// drain then rejects while the real export is never read at all.func testAFileURLAnswersWhenNothingConcreteWasRegistered() { XCTAssertEqual( shareFileSource(registered: ["public.file-url"], suggestedName: "chat.zip"), .url(identifier: "public.file-url") ) XCTAssertEqual( shareFileSource(registered: ["public.file-url"], suggestedName: "sample.xyz"), .url(identifier: "public.file-url"),"a type this phone has no UTI for is still a FILE, not a property list" ) }/// **The case a `_chat.txt` used to fall through.** Every text type/// conforms to `public.data`, so the first pass excludes them to keep a/// selected paragraph out of the file branch — and a text FILE that/// registered nothing else was staged as prose and saved as a reading-pile/// page. A provider made from a file carries a `suggestedName`; a selection/// does not, and that is the whole difference.func testATextFileIsStagedAsAFileAndASelectionIsNot() { XCTAssertEqual( shareFileSource(registered: ["public.plain-text"], suggestedName: "_chat.txt"), .representation(identifier: "public.plain-text") ) XCTAssertNil( shareFileSource(registered: ["public.plain-text"], suggestedName: nil),"a highlighted paragraph is not a file" ) XCTAssertNil( shareFileSource( registered: ["public.plain-text"], suggestedName: "no-extension" ) ) }func testALinkCarriesNoFileAtAll() { XCTAssertNil(shareFileSource(registered: ["public.url"], suggestedName: nil)) }// ── the copy ──────────────────────────────────────────────────────────/// **A staged `.txt` keeps its extension AND its bytes.** The drain's four/// classification rules read the extension when a share declares no type,/// so a copy that lost it is a file the drain calls "no extension" and/// discards — which is what a `_chat.txt` shared out of WhatsApp did, all/// the way to the failed import the walk of 15 Sep 2026 recorded.func testAStagedCopyKeepsTheExtensionAndTheBytes() throws {let root = FileManager.default.temporaryDirectory .appendingPathComponent("share-staging-\(UUID().uuidString)")defer { try? FileManager.default.removeItem(at: root) }let source = root.appendingPathComponent("WhatsApp Chat - Alpaca One.txt")tryFileManager.default.createDirectory(at: root, withIntermediateDirectories: true)let transcript = "[26/07/2025, 10:12:45 AM] Alpaca One: Hi\n"tryData(transcript.utf8).write(to: source)let inbox = root.appendingPathComponent("share-inbox")let staged = try stageSharedFile(from: source, into: inbox, id: "abc") XCTAssertEqual(URL(fileURLWithPath: staged).lastPathComponent, "abc.txt") XCTAssertEqual(tryString(contentsOf: URL(fileURLWithPath: staged), encoding: .utf8), transcript,"the export's own bytes, not a property list holding its address" )// And a file with no extension at all keeps having none — the copy adds// nothing it was not given.let bare = root.appendingPathComponent("voicenote")tryData("x".utf8).write(to: bare)let second = try stageSharedFile(from: bare, into: inbox, id: "def") XCTAssertEqual(URL(fileURLWithPath: second).lastPathComponent, "def") }/// The name the sharing app gave, which is the only hint the import has/// about whose chat this is — kept as a LEAF, never as a path.func testASharedNameIsKeptAsALeafOrNotAtAll() { XCTAssertEqual( shareSanitisedFileName("/var/mobile/Containers/…/WhatsApp Chat - Alpaca One.zip"),"WhatsApp Chat - Alpaca One.zip" ) XCTAssertEqual(shareSanitisedFileName(" _chat.txt "), "_chat.txt") XCTAssertEqual(shareSanitisedFileName("note\u{0000}s.txt"), "notes.txt")for nothing in [nil, "", " ", ".", "..", "some/dir/"] { XCTAssertNil(shareSanitisedFileName(nothing), "\(String(describing: nothing))") } }// ── the knock ─────────────────────────────────────────────────────────func testTheKnockIsTheImportRouteUnderOurOwnScheme() throws {let url = try XCTUnwrap(ShareKnock.url(.chatExport, shareId: "entry-1")) XCTAssertEqual(url.absoluteString, "\(CottonURLScheme.name):///messages/import?share=entry-1") XCTAssertEqual(Route.deepLink(url), .messagesImport) XCTAssertTrue(ShareOpen.isShareArrival(url)) }/// Only the extension's own URL drains. A notification's link into the same/// screen, or one typed by hand, is an ordinary deep link.func testAnOrdinaryLinkIntoTheImportScreenIsNotAKnock() throws { XCTAssertFalse(ShareOpen.isShareArrival(try XCTUnwrap(URL(string: "\(CottonURLScheme.name):///messages/import"))) ) XCTAssertFalse(ShareOpen.isShareArrival(try XCTUnwrap(URL(string: "\(CottonURLScheme.name):///messages"))) ) XCTAssertFalse(ShareOpen.isShareArrival(try XCTUnwrap(URL(string: "https://example.com/messages/import?share=x")) ) ) }// ── what the extension does with it ───────────────────────────────────/// An opener that records what it was asked to open.privatefunc makeOpener( head: String? = nil,open: @escaping (URL) -> Bool ) -> (ShareOpener, Asked) {let asked = Asked()return (ShareOpener(open: { url in asked.urls.append(url)returnopen(url) }, head: { _ in head }, shelf: ShareShelf(pdfIsBook: false) ), asked ) }privatefinalclassAsked {var urls: [URL] = [] }/// The URL a knock carries, unwrapped where a test can say why it failed.privatefunc knock(_ id: String) throws -> URL {try XCTUnwrap(ShareKnock.url(.chatExport, shareId: id)) }func testAChatExportOpensCotton() asyncthrows {let (opener, asked) = makeOpener { _ intrue }let entry = ShareEntry( id: "e1", at: "2026-09-15T09:00:00Z", kind: ShareKind.file.rawValue, path: "/share-inbox/e1.zip", fileName: "WhatsApp Chat - Alpaca One.zip" )let outcome = await opener.arrived(entry) XCTAssertEqual(outcome, .opened(try knock("e1"))) XCTAssertEqual(asked.urls.count, 1) }/// **A picture and a link knock too** (the owner, 23 Oct 2026: when the/// sheet closes the app opens, for every kind of shared item). Each knocks/// at the screen its branch lands on.func testAPictureAndALinkOpenCottonToo() asyncthrows {let (opener, asked) = makeOpener { _ intrue }let picture = ShareEntry( id: "e2", at: "2026-09-15T09:00:00Z", kind: ShareKind.file.rawValue, path: "/share-inbox/e2.jpg", fileName: "receipt.jpg", mimeType: "image/jpeg" )let link = ShareEntry( id: "e3", at: "2026-09-15T09:00:00Z", kind: ShareKind.url.rawValue, url: "https://example.com/a" )let forPicture = await opener.arrived(picture)let forLink = await opener.arrived(link) XCTAssertEqual(forPicture, .opened(try XCTUnwrap(ShareKnock.url(.picture, shareId: "e2")))) XCTAssertEqual(forLink, .opened(try XCTUnwrap(ShareKnock.url(.link, shareId: "e3")))) XCTAssertEqual(asked.urls.map(Route.deepLink), [.photos(show: nil), .reader]) }/// A `.txt` with a name that says nothing is decided by its first line/// here too — the same rule the drain runs, over the copy just staged.func testATextExportIsSniffedBeforeItKnocks() asyncthrows {let entry = ShareEntry( id: "e4", at: "2026-09-15T09:00:00Z", kind: ShareKind.file.rawValue, path: "/share-inbox/e4.txt", fileName: "export.txt", mimeType: "text/plain" )let (transcript, _) = makeOpener(head: "[26/07/2025, 10:12:45 AM] Alpaca One: Hi") { _ intrue }let (prose, _) = makeOpener(head: "buy milk") { _ intrue }let forTranscript = await transcript.arrived(entry)let forProse = await prose.arrived(entry) XCTAssertEqual(forTranscript, .opened(try knock("e4"))) XCTAssertEqual( forProse, .opened(try XCTUnwrap(ShareKnock.url(.document, shareId: "e4"))),"a .txt that is not an export is a document, and knocks at the documents") }/// **A host that will not open a URL is not a lost share.** The bytes are/// copied and the entry is written before the knock, so the next foreground/// drains it — which is exactly the behaviour this seam replaced, kept as/// the floor under it.func testAHostThatWillNotOpenLeavesTheMailboxToDoItsJob() asyncthrows {let (opener, asked) = makeOpener { _ infalse }let entry = ShareEntry( id: "e5", at: "2026-09-15T09:00:00Z", kind: ShareKind.file.rawValue, path: "/share-inbox/e5.zip", fileName: "chat.zip" )let outcome = await opener.arrived(entry) XCTAssertEqual(outcome, .couldNotOpen(try knock("e5"))) XCTAssertNotEqual( outcome, .opened(try knock("e5")),"a false answer is NOT an opened one — root cause B was exactly this lie" ) XCTAssertEqual(asked.urls.count, 1) }}// MARK: - The opener, held against the extension's own source/// `App/ShareExtension/ShareViewController.swift` is an app-extension target:/// it is in no test bundle, so the only executable hold on it is a read.////// **Root cause B of the 15 Sep 2026 walk lived exactly here.** The responder/// walk sent the DEPRECATED one-argument `openURL:` and returned `true` without/// looking at anything; iOS 26 refuses that call — *"BUG IN CLIENT OF UIKIT …/// Force returning false (NO)"* — so every share reported itself opened and/// nothing came forward. A unit test cannot reach the responder chain; what it/// can do is refuse the shape that lied.@MainActorfinalclassShareExtensionOpenerSourceTests: XCTestCase {privatestaticlet lane = "the iPhone app's share extension target"privatestaticlet path = "apps/cotton/App/ShareExtension/ShareViewController.swift"}// MARK: - The knock, and the drain it owes/// `Boot/ShareArrivals.swift`. The URL is not navigation: it is a reason to/// drain, owed until the gate says a file is open.@MainActorfinalclassShareArrivalsTests: XCTestCase {func testNothingIsOwedUntilAKnockLands() {let arrivals = ShareArrivals() XCTAssertFalse(arrivals.isOwed) XCTAssertFalse(arrivals.takeOwedDrain()) }func testAKnockIsPaidExactlyOnce() {let arrivals = ShareArrivals() arrivals.arrived() XCTAssertTrue(arrivals.isOwed) XCTAssertTrue(arrivals.takeOwedDrain(), "the gate is ready: drain now") XCTAssertFalse( arrivals.takeOwedDrain(), "and never twice — one drain takes the whole mailbox") }/// Two shares in a row before the gate resolves are ONE drain, which is/// right: `ShareMailbox.drain` removes the whole list.func testTwoKnocksBeforeTheGateAreOneDrain() {let arrivals = ShareArrivals() arrivals.arrived() arrivals.arrived() XCTAssertTrue(arrivals.takeOwedDrain()) XCTAssertFalse(arrivals.takeOwedDrain()) }// ── One drain per foreground ──────────────────────────────────────────/// **The bug this rule exists for.** The knock's drain and the `.active`/// drain both ran on one arrival, so a refused share was put back for one/// more try and had that try spent in the same second, with nothing having/// changed in between (the walk of 15 Sep 2026: "kept for one more try"/// then "not imported twice, discarded", back to back).func testAnArrivalAndTheForegroundEdgeInOneActivationDrainOnce() {let arrivals = ShareArrivals() arrivals.arrived() XCTAssertTrue(arrivals.takeOwedDrain(), "the knock drains") XCTAssertFalse(arrivals.takeDrain(), "and the `.active` edge behind it does not") XCTAssertTrue(arrivals.hasDrained) }/// And the other order, because iOS does not order `onOpenURL` against the/// `.active` edge — which is why the count moves when the app LEAVES.func testTheForegroundEdgeAndAnArrivalBehindItAlsoDrainOnce() {let arrivals = ShareArrivals() XCTAssertTrue(arrivals.takeDrain(), "the foreground drains") arrivals.arrived() XCTAssertFalse(arrivals.takeOwedDrain(), "and the knock behind it does not drain again") }/// The retry happens on a genuinely later foreground.func testALaterForegroundDrainsAgain() {let arrivals = ShareArrivals() XCTAssertTrue(arrivals.takeDrain()) XCTAssertFalse(arrivals.takeDrain()) arrivals.wentAway() XCTAssertFalse(arrivals.hasDrained) XCTAssertTrue(arrivals.takeDrain(), "a new foreground, a new drain") XCTAssertFalse(arrivals.takeDrain()) }/// A knock that lands while the app is away is still owed when it comes/// back — the foreground it belongs to is the new one.func testAKnockTakenWhileAwayIsPaidOnTheNextForeground() {let arrivals = ShareArrivals() XCTAssertTrue(arrivals.takeDrain(), "the cold launch drains") arrivals.wentAway() arrivals.arrived() XCTAssertTrue(arrivals.takeOwedDrain()) XCTAssertFalse(arrivals.takeDrain()) }}// MARK: - The boundary, held against the cratefinalclassShareBoundaryContractTests: XCTestCase {/// The path belongs to the RUST FFI lane. `SourceSweep.mustRead` implements/// AGENTS.md's three by-path rules: the read fails LOUDLY when it finds/// nothing, the owning lane is named here, and the path is grepped/// repo-wide before it moves.privatestaticlet lane = "Rust FFI (the phone's method table)"/// Both answer shapes, because `page.save` has two.func testTheSavedPagesAnswerReadsBothOfItsShapes() throws {let one = try JSONDecoder().decode(PagesSaved.self, from: Data(#"{"id":"p1"}"#.utf8)) XCTAssertEqual(one.ids, ["p1"])let many = try JSONDecoder().decode(PagesSaved.self, from: Data(#"{"ids":["p1","p2"]}"#.utf8) ) XCTAssertEqual(many.ids, ["p1", "p2"]) }}// MARK: - The document types are the core's/// Branch 4 names a type before the bytes are copied, and the core refuses one/// off its document list — so the app's list IS the core's, read out of/// `cotton-rules/src/media.rs` (the one upload table the core and the Worker/// both read) and held equal here. A type the core adds/// or drops reddens this rather than turning a share into a lost file.finalclassShareDocumentTypesTests: XCTestCase {func testTheAppsDocumentTypesAreTheCoresList() throws {let source = trySourceSweep.mustRead("crates/cotton-rules/src/media.rs", ownedBy: "the Rust rules (what the server signs an upload for)")let start = try XCTUnwrap(source.range(of: "const DOCUMENT_TYPES: &[&str] = &["), "DOCUMENT_TYPES moved")let rest = source[start.upperBound...]let end = try XCTUnwrap(rest.range(of: "];"))let body = rest[..<end.lowerBound] .split(separator: "\n") .map { $0.trimmingCharacters(in: .whitespaces) } .filter { !$0.hasPrefix("//") } .joined(separator: "\n")let pattern = try NSRegularExpression(pattern: #""([^"]+)""#)let range = NSRange(body.startIndex..., in: body)let core = Set( pattern.matches(in: body, range: range).compactMap { match inRange(match.range(at: 1), in: body).map { String(body[$0]) } }) XCTAssertFalse(core.isEmpty, "read no types out of DOCUMENT_TYPES") XCTAssertEqual(documentContentTypes, core) }}// MARK: - Films/// What the drain put on the wire for films, decoded.privatestructAskedFilms: Decodable {structFilm: Decodable { let path: String; let sourcePath: String }let films: [Film]let onlyFilms: Bool}finalclassShareIntakeFilmTests: XCTestCase {privatelet cinemas = ShareShelf.of(flavour: ShareShelf.cinemasFlavour)privatelet cotton = ShareShelf.of(flavour: ShareShelf.cottonFlavour)privatestaticfunc capture(_ outcome: String, table: String = "film", id: String = "film-1") -> [String: ScriptedCore.Reply] { [CottonMethod.filmsCapture: .ok(#"{"films":[{"sourcePath":"x","outcome":"\#(outcome)","id":"\#(id)","table":"\#(table)","title":"SyntheticTestPattern","line":"SyntheticTestPatternisinCinemas."}],"said":"SyntheticTestPatternisinCinemas."}"#)] }privatefunc asked(_ core: ScriptedCore) asyncthrows -> AskedFilms {let calls = await core.callslet call = try XCTUnwrap(calls.first { $0.method == CottonMethod.filmsCapture })returntry JSONDecoder().decode(AskedFilms.self, from: Data(call.requestJSON.utf8)) }/// RULE (Cinemas, 5 Nov 2026): in Cotton Cinemas every video is a film — an MKV no camera writes and an MP4 alike — handed to the films' intake by the name it came in as, every one kept, and the app lands on what came in.func testEveryVideoIsAFilmInCottonCinemas() asyncthrows {for name in ["The Long Night (2019).mkv", "Synthetic Test Pattern (2021).mp4"] {let entry = fileEntry(name, mime: name.hasSuffix(".mp4") ? "video/mp4" : nil)let (intake, core, recorder, _, files) = rig([entry], replies: Self.capture("added"), shelf: cinemas)await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.filmsCapture], name)let films = tryawait asked(core) XCTAssertEqual(films.films.map(\.sourcePath), [name]) XCTAssertEqual(films.films.map(\.path), [entry.path!]) XCTAssertFalse(films.onlyFilms, "Cinemas keeps every film, short or long") XCTAssertEqual(recorder.routes, [.tableRecord(table: "film", id: "film-1")]) XCTAssertEqual(recorder.told, ["Synthetic Test Pattern is in Cinemas."]) XCTAssertEqual(files.discarded, [entry.path!]) } }/// RULE (Cinemas gaps, 5 Nov 2026): a film door's folder (Plus › Add a folder) is read where it stands and copied once, by the core into the store: its files are asked of the films' intake by their own paths, named under the folder, never staged into the share inbox, never discarded, and the app lands on what came in.func testAFilmDoorsFolderIsCopiedOnceFromWhereItStands() asyncthrows {let picked = FileManager.default.temporaryDirectory.appendingPathComponent("door-\(UUID().uuidString)/Kestrel Point", isDirectory: true)let season = picked.appendingPathComponent("Season 1", isDirectory: true)tryFileManager.default.createDirectory(at: season, withIntermediateDirectories: true)let episode = season.appendingPathComponent("Kestrel Point S01E01.mp4")tryData("invented episode bytes".utf8).write(to: episode)defer { try? FileManager.default.removeItem(at: picked.deletingLastPathComponent()) }let (intake, core, recorder, _, files) = rig([], replies: Self.capture("added", table: "film_episode", id: "episode-1"), shelf: cinemas)await intake.films(inPlace: [picked])let films = tryawait asked(core) XCTAssertEqual(films.films.map { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() }, [episode.resolvingSymlinksInPath()],"read where it stands, never a staged copy") XCTAssertEqual(films.films.map(\.sourcePath), ["Kestrel Point/Season 1/Kestrel Point S01E01.mp4"]) XCTAssertFalse(films.onlyFilms) XCTAssertTrue(files.discarded.isEmpty, "the person's own file is never discarded") XCTAssertTrue(FileManager.default.fileExists(atPath: episode.path)) XCTAssertEqual(recorder.routes, [.tableRecord(table: "film_episode", id: "episode-1")]) }/// RULE (Cinemas, 5 Nov 2026): in Cotton a clip's container is asked of the films' intake with onlyFilms, and what it says is no film goes on to Photos as it always did — never the reverse; a film lands on its record and Photos never sees it.func testInCottonAClipGoesOnToPhotosAndAFilmStays() asyncthrows {let clip = fileEntry("IMG_0042.mp4", mime: "video/mp4")var replies = Self.capture("not_film") replies.merge(captureAnswers) { $1 }let (intake, core, recorder, _, _) = rig([clip], replies: replies, shelf: cotton)await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.filmsCapture, CottonMethod.captureMedia])let onlyFilms = tryawait asked(core).onlyFilms XCTAssertTrue(onlyFilms) XCTAssertEqual(recorder.routes.count, 1) XCTAssertNotEqual(recorder.routes.first, .tableRecord(table: "film", id: "film-1"))let long = fileEntry("Home Movie 1998.mp4", mime: "video/mp4")let (film, core2, landed, _, _) = rig([long], replies: Self.capture("added", id: "film-2"), shelf: cotton)await film.drain()let filmCalls = await core2.methodsCalled() XCTAssertEqual(filmCalls, [CottonMethod.filmsCapture]) XCTAssertEqual(landed.routes, [.tableRecord(table: "film", id: "film-2")]) }/// RULE (Bandcamp into Music, 7 Nov 2026): in Cotton Music a ZIP whose songs make one album knocks as songs and comes in as that album — `music.zip` streams it out, then ONE `music.capture` carries each song's entry, the ZIP's cover where a song has none, and the ZIP's name, shop, day bought and booklet — and the app opens the album.func testInMusicAnAlbumZipComesInAsItsAlbum() asyncthrows {let music = ShareShelf.of(flavour: ShareShelf.musicFlavour)let zip = fileEntry("Ana Lume - Blue Hour.zip", mime: "application/zip")let replies: [String: ScriptedCore.Reply] = [CottonMethod.musicZip: .ok(#"{"songs":[{"entry":"AnaLume - BlueHour - 01Dawn.flac","path":"/nowhere/01Dawn.flac","sourcePath":"AnaLume - BlueHour/AnaLume - BlueHour - 01Dawn.flac"}],"coverPath":"/nowhere/cover.jpg","bookletPath":"/nowhere/booklet.pdf","storeUrl":"https://analume.bandcamp.com/album/blue-hour","storeId":"bandcamp:analume/blue-hour","boughtOn":"2026-11-07"}"#),CottonMethod.musicCapture: .ok(#"{"songs":[{"sourcePath":"AnaLume - BlueHour/AnaLume - BlueHour - 01Dawn.flac","outcome":"added","id":"song-1","title":"Dawn","line":"Dawn came in."}],"said":"AnaLume - BlueHour.zip came inasBlueHour.","album":"album-1"}"#), ] XCTAssertEqual(ShareKnock.kind(try XCTUnwrap(SharedFile(zip)), shelf: music, head: { nil }), .song)let (intake, core, landed, _, _) = rig([zip], replies: replies, shelf: music)await intake.drain()let calls = await core.calls XCTAssertEqual(calls.map(\.method), [CottonMethod.musicZip, CottonMethod.musicCapture])structOpened: Decodable { let path: String; let name: String; let into: String }let opened = try JSONDecoder().decode(Opened.self, from: Data(calls[0].requestJSON.utf8)) XCTAssertEqual([opened.path, opened.name], [try XCTUnwrap(zip.path), "Ana Lume - Blue Hour.zip"]) XCTAssertFalse(opened.into.isEmpty)structAsked: Decodable {structSong: Decodable { let entry: String?; let coverPath: String? }structZip: Decodable { let name: String; let boughtOn: String?; let storeUrl: String?; let storeId: String?; let bookletPath: String? }let songs: [Song]let zip: Zip? }let asked = try JSONDecoder().decode(Asked.self, from: Data(calls[1].requestJSON.utf8)) XCTAssertEqual(asked.songs.map(\.entry), ["Ana Lume - Blue Hour - 01 Dawn.flac"]) XCTAssertEqual(asked.songs.first?.coverPath, "/nowhere/cover.jpg", "a song with no picture of its own takes the ZIP's cover")let sent = try XCTUnwrap(asked.zip) XCTAssertEqual([sent.name, sent.boughtOn, sent.storeUrl, sent.storeId, sent.bookletPath], ["Ana Lume - Blue Hour.zip", "2026-11-07", "https://analume.bandcamp.com/album/blue-hour", "bandcamp:analume/blue-hour", "/nowhere/booklet.pdf"]) XCTAssertEqual(landed.routes, [.tableRecord(table: "music_album", id: "album-1")]) XCTAssertEqual(landed.told, ["Ana Lume - Blue Hour.zip came in as Blue Hour."]) }/// RULE (Bandcamp into Music, 7 Nov 2026): a ZIP holding no song is no album and goes on to the branch a ZIP always took; a ZIP that is not one album is said; in Cotton a ZIP is never asked of the music intake.func testAZipThatIsNoAlbumIsWhatItWas() async {let music = ShareShelf.of(flavour: ShareShelf.musicFlavour)let (none, core, landed, _, _) = rig([fileEntry("Photos.zip")], replies: [CottonMethod.musicZip: .ok(#"{"refused":"no_songs","line":"Photos.zip holds no songs."}"#)], shelf: music)await none.drain()let noneCalls = await core.methodsCalled() XCTAssertEqual(noneCalls, [CottonMethod.musicZip]) XCTAssertEqual(landed.routes, [.messagesImport])let (two, _, said, _, _) = rig([fileEntry("Two.zip")], replies: [CottonMethod.musicZip: .ok(#"{"refused":"folders","line":"Two.zip holds songs in more than one folder, so it is not one album."}"#)], shelf: music)await two.drain() XCTAssertEqual(said.told, ["Two.zip holds songs in more than one folder, so it is not one album."]) XCTAssertEqual(said.routes, [ShareKnock.songList])let (chat, cottonCore, chatLanded, _, _) = rig([fileEntry("WhatsApp Chat - Ana.zip")], shelf: cotton)await chat.drain()let cottonCalls = await cottonCore.methodsCalled() XCTAssertEqual(cottonCalls, []) XCTAssertEqual(chatLanded.routes, [.messagesImport]) XCTAssertEqual(ShareKnock.kind(SharedFile(path: "/x", fileName: "a.zip"), shelf: cotton, head: { nil }), .chatExport) }/// RULE: in Cotton an MKV is a film whatever its length and knocks as one; a `.ts` or a `.webm` stays what it was, and in Cotton Music a video never reaches the films' intake.func testWhatKnocksAsAFilmWhere() async {let mkv = SharedFile(path: "/share-inbox/a.mkv", fileName: "The Long Night (2019).mkv", mimeType: nil) XCTAssertEqual(ShareKnock.kind(mkv, shelf: cotton, head: { nil }), .film) XCTAssertEqual(ShareKnock.kind(mkv, shelf: cinemas, head: { nil }), .film)let mp4 = SharedFile(path: "/share-inbox/b.mp4", fileName: "IMG_0042.mp4", mimeType: "video/mp4") XCTAssertEqual(ShareKnock.kind(mp4, shelf: cotton, head: { nil }), .picture) XCTAssertEqual(ShareKnock.kind(mp4, shelf: cinemas, head: { nil }), .film) XCTAssertEqual(ShareKnock.route(.film), ShareKnock.filmList)let ts = SharedFile(path: "/share-inbox/c.ts", fileName: "theme.ts", mimeType: nil) XCTAssertFalse(mayBeFilmShare(ts)) XCTAssertTrue(mayBeFilmShare(mp4)) XCTAssertTrue(mayBeFilmShare(mkv))let music = ShareShelf.of(flavour: ShareShelf.musicFlavour)let (intake, core, _, _, _) = rig([fileEntry("IMG_0042.mp4", mime: "video/mp4")], replies: captureAnswers, shelf: music)await intake.drain()let called = await core.methodsCalled() XCTAssertEqual(called, [CottonMethod.captureMedia]) }}// MARK: - A podcast subscription list/// A core answering `import_opml` from a queue, one answer a run.private actor QueuedCore: CottonCalling {privatevar answers: [String]private(set) var asked: [String] = []init(_ answers: [String]) { self.answers = answers }func callRaw(_ method: String, requestJSON: String) throws -> String {if method == CottonMethod.shareFetchLinks { return #"{"ok":true,"data":{"fetch":[]}}"# } asked.append(requestJSON)return #"{"ok":true,"data":\#(answers.removeFirst())}"# }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}func close() {}}finalclassShareIntakeOpmlTests: XCTestCase {privatelet opml = """ <?xml version="1.0" encoding="UTF-8"?> <opml version="2.0"><head><title>Invented</title></head><body> <outline type="rss" text="One" xmlUrl="https://example.com/one.xml"/> </body></opml> """/// The file on disk, as the share extension or a door stages it.privatefunc staged(_ name: String, _ text: String, mime: String? = nil) throws -> (ShareEntry, URL) {let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)tryFileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)let real = directory.appendingPathComponent(name)tryData(text.utf8).write(to: real)var entry = fileEntry(name, mime: mime) entry.path = real.path(percentEncoded: false)return (entry, directory) }/// RULE (7 Nov 2026): an OPML file is handed WHOLE to the object's/// `import_opml` as its text, its words are said as the object says them,/// and the app stands on the first new show among the shows.func testAnOpmlFileIsHandedToTheObjectAsText() asyncthrows {let (entry, directory) = try staged("subscriptions.opml", opml)defer { try? FileManager.default.removeItem(at: directory) }let said = "1 added, 0 already here"let (intake, core, recorder, _, files) = rig( [entry], replies: [CottonMethod.objectAct: .ok(#"{"added":1,"already":0,"failed":[],"more":0,"podcasts":["podcast-1"],"said":"\#(said)"}"#)])await intake.drain()let calls = await core.calls XCTAssertEqual(calls.map(\.method), [CottonMethod.objectAct])structAsked: Decodable { let act: String; let args: [String: String] }let request: Asked = try asked(calls) XCTAssertEqual(request.act, PodcastActs.importOpml) XCTAssertEqual(request.args, ["file": opml]) XCTAssertEqual(recorder.told, [said]) XCTAssertEqual(recorder.landings, [ShareLanding(route: .tableRecord(table: "podcast", id: "podcast-1"), many: true)]) XCTAssertEqual(files.discarded, [entry.path!]) }/// A list of nothing new lands on the shows' list; a refusal (a phone not/// signed in) is said in the core's own words, never the shell's.func testNothingNewLandsOnTheListAndARefusalIsTheCores() asyncthrows {let (entry, directory) = try staged("subscriptions.opml", opml)defer { try? FileManager.default.removeItem(at: directory) }let (intake, _, recorder, _, _) = rig( [entry], replies: [CottonMethod.objectAct: .ok(#"{"added":0,"already":1,"failed":[],"more":0,"podcasts":[],"said":"0 added, 1 already here"}"#)])await intake.drain() XCTAssertEqual(recorder.routes, [ShareKnock.podcastList])let (refused, refusedDirectory) = try staged("subscriptions.opml", opml)defer { try? FileManager.default.removeItem(at: refusedDirectory) }let words = "Sign in first: this asks your backup."let (signedOut, _, told, _, _) = rig([refused], replies: [CottonMethod.objectAct: .refuse(code: "sign_in_first", message: words)])await signedOut.drain() XCTAssertEqual(told.troubles.map(\.say), [words]) XCTAssertEqual(told.routes, [ShareKnock.podcastList]) }/// A plain `.xml` is a subscription list only when its root is `<opml`/// (Reeder and Overcast claim `.opml` under types of their own); any/// other XML stays a document.func testAnXmlFileIsOpmlByItsRoot() {let xml = SharedFile(path: "/share-inbox/a.xml", fileName: "Overcast.xml", mimeType: "text/xml") XCTAssertTrue(isOpmlShare(xml, head: { opml })) XCTAssertFalse(isOpmlShare(xml, head: { #"<?xml version="1.0"?><rss version="2.0"></rss>"# })) XCTAssertTrue(isOpmlShare(SharedFile(path: "/share-inbox/b", fileName: "list.opml"), head: { nil })) XCTAssertFalse(isOpmlShare(SharedFile(path: "/share-inbox/c", fileName: "notes.txt"), head: { opml })) }/// RULE: a list past one run's hundred is asked again while a run brings/// shows in, each run's words said; a run that brings none in stops it.func testAListPastOneRunIsAskedAgainWhileItBringsShowsIn() asyncthrows {let core = QueuedCore([ #"{"added":100,"already":0,"failed":[],"more":30,"podcasts":["p-1"],"said":"100 added"}"#, #"{"added":30,"already":100,"failed":[],"more":0,"podcasts":["p-101"],"said":"30 added"}"#, ])var said: [String] = []let runs = tryawaitPodcastSubscriptions(core: core).bring(opml) { said.append($0) } XCTAssertEqual(runs.map(\.added), [100, 30]) XCTAssertEqual(said, ["100 added", "30 added"])let stuck = QueuedCore([#"{"added":0,"already":0,"failed":[],"more":30,"podcasts":[],"said":"0 added"}"#])let once = tryawaitPodcastSubscriptions(core: stuck).bring(opml) { _ in } XCTAssertEqual(once.count, 1) }}// MARK: - A folder of booksfinalclassShareIntakeBookFolderTests: XCTestCase {/// A synthetic Calibre tree, staged as a door stages a folder.privatefunc tree() throws -> (ShareEntry, URL) {let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)let folder = directory.appendingPathComponent("Calibre Library")for name in ["Invented Author/Invented Title (1)/metadata.opf", "Invented Author/Invented Title (1)/cover.jpg","Invented Author/Invented Title (1)/Invented Title - Invented Author.epub", ".DS_Store"] {let file = folder.appendingPathComponent(name)tryFileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)tryData("synthetic".utf8).write(to: file) }var entry = fileEntry("Calibre Library") entry.path = folder.path(percentEncoded: false)return (entry, directory) }privatestructAsked: Decodable {structFile: Decodable { let path: String; let name: String }let files: [File] }/// RULE (7 Nov 2026): Books' Add a folder hands every file of the tree to/// `books.folder`, named below the folder; the core's words are said with/// each refused book's why, and the app stands on All at the first book.func testAFolderOfBooksIsHandedWholeToTheCore() asyncthrows {let (entry, directory) = try tree()defer { try? FileManager.default.removeItem(at: directory) }let answer = #"{"books":[{"id":"book-1","title":"InventedTitle","outcome":"already"},{"id":null,"title":"Other","outcome":"refused","why":"Unreadable."}],"skipped":[],"words":"Added0 books. 1 book was here already. 1 book could not be added."}"#let (intake, core, recorder, _, files) = rig([entry], replies: [CottonMethod.booksFolder: .ok(answer)])await intake.intake([entry], foldersAreBooks: true)let calls = await core.calls XCTAssertEqual(calls.map(\.method), [CottonMethod.booksFolder])let request: Asked = try asked(calls) XCTAssertEqual(request.files.map(\.name), ["Invented Author/Invented Title (1)/cover.jpg","Invented Author/Invented Title (1)/Invented Title - Invented Author.epub","Invented Author/Invented Title (1)/metadata.opf", ]) XCTAssertTrue(request.files.allSatisfy { FileManager.default.fileExists(atPath: $0.path) }) XCTAssertEqual(recorder.told, ["Added 0 books. 1 book was here already. 1 book could not be added.\nOther: Unreadable."]) XCTAssertEqual(recorder.landings, [ShareLanding(route: .tableRecord(table: "book", id: "book-1"), many: true)]) XCTAssertEqual(files.discarded, [entry.path!]) }/// A folder with no book is refused in the core's words; in Cotton a/// folder shared in stays songs, and in Cotton Books it is books.func testAnEmptyFolderIsRefusedInTheCoresWords() asyncthrows {let (entry, directory) = try tree()defer { try? FileManager.default.removeItem(at: directory) }let words = "This folder holds no EPUB or PDF that could be read."let (intake, _, recorder, _, _) = rig([entry], replies: [CottonMethod.booksFolder: .refuse(code: "refused", message: words)], shelf: ShareShelf(pdfIsBook: true))await intake.drain() XCTAssertEqual(recorder.troubles.map(\.say), [words]) XCTAssertEqual(recorder.routes, [ShareKnock.bookList]) }}