// The capture dock's composer, case for case and name for name. // // The previous tests drove a rendered component through a change-text event and // a selection change; these drive `DockModel` directly, which is the same events // by their real names — `fieldEdited` IS the change-text event, // `caretMoved(to:)` IS the platform's selection event, `pick` IS a tap on the // completion strip. // The dock's rules were never about the view, and a rule that needs a simulator // to be exercised is a rule nobody exercises. // // FOUR of the previous cases do not appear here, each for a stated reason: // // • the four `+` fan cases ("stays shut until + is pressed", "offers exactly // Todo · Event · Note · Contact · Scan", "the Todo action asks the tool for // its create sheet", "closes BEFORE it navigates"). The rows and their // destinations are `AddFanActionsTests`, and the shut-before-it-acts // ordering is `AddFanSheet.swift`'s own `dismiss()`-then-`onChoose` — both // landed before this file and re-asserting them here would be a second // copy of somebody else's guard. // // The last two cases in this file have NO original: the place moving and the // failed send. Both are properties the previous code stated in a comment and // never held — and the second is this app's own divergence (`DockModel`'s // header, difference 3), which makes it exactly the kind that must be pinned. import CottonKit import XCTest @testable import CottonUI /// The capture path, recorded. /// /// The real ``CaptureService`` needs a link store, a link source, a writer and /// a `UserDefaults` suite; a dock test has no business knowing that a link /// intent is remembered at all, which is what ``CaptureSending`` is for. actor RecordingCapture: CaptureSending { struct Refused: Error {} private(set) var requests: [(request: CaptureRequest, personIds: [String])] = [] private var failure: Error? /// A write held open, so a test can type WHILE one is in flight — the only /// way to stage the race the rollback has to lose. private var isHeld = false private var held: CheckedContinuation? func refuseEverything() { failure = Refused() } func hold() { isHeld = true } func release() { isHeld = false held?.resume() held = nil } func capture(_ request: CaptureRequest, personIds: [String]) async throws -> JSONValue { requests.append((request, personIds)) if isHeld { await withCheckedContinuation { continuation in held = continuation } } if let failure { throw failure } return .object(["id": .string("cap-\(requests.count)")]) } func sent() -> [(request: CaptureRequest, personIds: [String])] { requests } func last() -> (request: CaptureRequest, personIds: [String])? { requests.last } } /// The picture path, recorded — `capture.media` with no core, no decoder and /// no scratch directory. /// /// Each file answers the record the test names for it (`answers`), so a case /// can put several pictures on a draft and read their ORDER back off the /// capture. A file with no answer is refused, which is how a case stages a /// picture that did not make it into the store. actor RecordingMedia: MediaCapturing { struct Refused: Error {} private var answers: [String: MediaCaptured] = [:] private(set) var asked: [(file: String, kind: CaptureMediaKind)] = [] /// This file lands as that record. func answer(_ file: String, recordId: String, key: String) { answers[file] = MediaCaptured(key: key, recordId: recordId) } func capture( file url: URL, mime: String, kind: CaptureMediaKind, filename: String? ) async throws -> MediaCaptured { asked.append((url.lastPathComponent, kind)) guard let answer = answers[url.lastPathComponent] else { throw Refused() } return answer } func askedFiles() -> [String] { asked.map(\.file) } } @MainActor final class DockModelTests: XCTestCase { private var captures = RecordingCapture() private var media = RecordingMedia() private var recogniser = FakeRecogniser() private var haptics = RecordingHaptics() private var toasts = ToastCenter(scheduler: ManualToastScheduler()) override func setUp() async throws { captures = RecordingCapture() media = RecordingMedia() recogniser = FakeRecogniser() haptics = RecordingHaptics() toasts = ToastCenter(scheduler: ManualToastScheduler()) } /// The two vocabularies the TypeScript's `PROJECTS` / `PEOPLE` constants /// hold, in the same order. private func vocabulary(empty: Bool = false) -> DockVocabulary { let words = DockVocabulary() guard !empty else { return words } words.supply( projects: [ VocabularyProject(id: "pr-meri", name: "Meri", status: "active"), VocabularyProject(id: "pr-cotton", name: "Cotton", status: "active"), ], people: [ VocabularyPerson(id: "per-ravi", name: "Ravi Kumar"), VocabularyPerson(id: "per-meera", name: "Meera"), ] ) return words } private func dock( place: DockPlace = .page, vocabulary words: DockVocabulary? = nil ) -> DockModel { DockModel( place: place, captures: captures, media: media, dictation: DictationModel(recogniser: recogniser), vocabulary: words ?? vocabulary(), haptics: haptics, toasts: toasts ) } private func dictate(_ words: String, into model: DockModel) async { await model.startDictation() recogniser.emit(.started) recogniser.speak(words) recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.segment(words)) recogniser.emit(.ended) } await model.finishDictation() } /// RULE: the dock offers only a DICTATED draft to the spoken-command hook, and a draft the hook does not run is saved as a thought — a typed "open todos" is the person's thought, and a spoken line no command claims is never dropped. func testOnlyASpokenDraftIsOfferedAsACommandAndEveryOtherIsSaved() async { var offered: [String] = [] let model = dock() let command: DockModel.SpokenCommand = { words in offered.append(words) return words.lowercased().hasPrefix("open") } await dictate("open todos", into: model) await model.send(runsSpokenCommand: command) var sent = await captures.requests.map { $0.request.text } XCTAssertEqual(offered, ["open todos"]) XCTAssertEqual(sent, [], "a spoken command that ran is not saved") XCTAssertEqual(model.text, "") await dictate("Remind me to call Anvika Rathore tomorrow morning", into: model) await model.send(runsSpokenCommand: command) sent = await captures.requests.map { $0.request.text } XCTAssertEqual(sent, ["Remind me to call Anvika Rathore tomorrow morning"], "a spoken thought is saved") model.fieldEdited("open todos") await model.send(runsSpokenCommand: command) sent = await captures.requests.map { $0.request.text } XCTAssertEqual(offered.count, 2, "a typed line is never offered as a spoken command") XCTAssertEqual(sent.last, "open todos", "a typed line is saved as a thought") } // Capture reads fresh context for each session — read after a tap, for // the next one, never awaited before the microphone opens (walker294 row // 118: a cold tap waited ~3 s on the read before the system's prompt). func testCaptureMicReadsFreshContextForTheNextSession() async { let core = ScriptedCore(["read.voiceContext": .ok(#"{"biasGroups":[{"tag":"screen","terms":["Meri"]}]}"#)]) let model = DockModel( place: .page, captures: captures, media: media, dictation: DictationModel(recogniser: recogniser), vocabulary: vocabulary(), haptics: haptics, toasts: toasts, hints: { await VoiceBias.hints(core: core) }) await model.startDictation() XCTAssertEqual(recogniser.sessions.last?.terms, [], "a cold tap listens at once, with no hints") recogniser.emit(.started) recogniser.whenCancelled = { [recogniser = self.recogniser] in recogniser.emit(.ended) } model.cancelDictation() await core.answer("read.voiceContext", .ok(#"{"biasGroups":[{"tag":"screen","terms":["Quillby","Meri"]}]}"#)) await model.startDictation() XCTAssertEqual(recogniser.sessions.last?.terms, ["Meri"], "the next tap takes what the last one read") XCTAssertEqual(recogniser.sessions.count, 2) let calls = await core.calls XCTAssertEqual(calls.map(\.method), ["read.voiceContext", "read.voiceContext"]) model.cancelDictation() } private let meri = SigilCandidate(id: "pr-meri", name: "Meri") private let cotton = SigilCandidate(id: "pr-cotton", name: "Cotton") private let ravi = SigilCandidate(id: "per-ravi", name: "Ravi Kumar") private let meera = SigilCandidate(id: "per-meera", name: "Meera") /// What the last send actually asked for. private func lastSend() async -> (request: CaptureRequest, personIds: [String]) { guard let last = await captures.last() else { XCTFail("nothing was sent") return (CaptureRequest(), []) } return last } // MARK: - The two objects func testDocksPlusAndPillAndSendsTheWordsUp() async { let model = dock() model.fieldEdited(" Pay the GST ") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "Pay the GST") XCTAssertEqual(sent.request.projectIds, []) XCTAssertEqual(sent.personIds, []) XCTAssertNil(sent.request.plan) XCTAssertFalse(sent.request.userEdited) // A PRESS, not a select. The two map to different generators and the // composer's Send is a press; it is the most repeated control in the // app, so this is the one difference a person feels every day. XCTAssertEqual(haptics.events, ["press"]) } func testTheArrowGoesLiveTheMomentThereAreWordsAndDimsAgainWhenTheyGo() { let model = dock() // Empty: the arrow is dimmed. The mic is drawn either way. XCTAssertFalse(model.canSend) model.fieldEdited("call Ramesh") XCTAssertTrue(model.canSend) // …and back again when the thought is deleted. Whitespace is nothing. model.fieldEdited(" ") XCTAssertFalse(model.canSend) } // MARK: - typed # attaches a project func testOffersMatchingProjectsOnceThereAreCharactersAfterTheHash() { let model = dock() // A bare `#` is not a question — the strip stays away. model.fieldEdited("pay #") XCTAssertEqual(model.suggestions, []) model.fieldEdited("pay #c") XCTAssertEqual(model.suggestions.map(\.id), ["pr-cotton"]) } func testTurnsHashMeriIntoAChipAndStripsTheLiteralFromTheWords() async { let model = dock() model.fieldEdited("pay the bill #meri") model.pick(meri) XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-meri"]) XCTAssertFalse(model.text.contains("#meri")) await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "pay the bill") XCTAssertEqual(sent.request.projectIds, ["pr-meri"]) XCTAssertEqual(sent.personIds, []) XCTAssertNil(sent.request.plan) } func testASpaceCommitsTheTopMatchWithoutATap() { let model = dock() model.fieldEdited("#meri") model.fieldEdited("#meri ") XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-meri"]) // The separator went with the token — no double gap left behind. XCTAssertEqual(model.text, "") } func testAChipCanBeTakenOffAgainAndARemovedProjectDoesNotRideTheCapture() async { let model = dock() model.fieldEdited("#meri") model.pick(meri) guard let chip = model.attachedChips.first else { return XCTFail("no chip") } model.detach(chip) XCTAssertEqual(model.attachedChips, []) model.fieldEdited("buy dal") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "buy dal") XCTAssertEqual(sent.request.projectIds, []) } func testCarriesSeveralProjectsAtOnce() async { let model = dock() model.fieldEdited("#mer") model.pick(meri) model.fieldEdited("file it #cot") model.pick(cotton) await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "file it") XCTAssertEqual(sent.request.projectIds, ["pr-meri", "pr-cotton"]) } func testClearsTheDraftAfterASendButKeepsThePlacesOwnChips() async { let model = dock() model.fieldEdited("#mer") model.pick(meri) model.fieldEdited("pay it") await model.send() // The page pre-attaches nothing, so nothing comes back. XCTAssertEqual(model.attachedChips, []) XCTAssertEqual(model.text, "") XCTAssertFalse(model.canSend) } // MARK: - typed @ attaches a person func testTurnsAtRaviIntoAChipAndSendsThePersonId() async { let model = dock() model.fieldEdited("ask @ravi about the quote") // The caret is standing in the token — a tap, as the platform reports it. model.caretMoved(to: 9) model.pick(ravi) XCTAssertEqual(model.attachedChips.map(\.recordId), ["per-ravi"]) XCTAssertFalse(model.text.contains("@ravi")) await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "ask about the quote") XCTAssertEqual(sent.request.projectIds, []) XCTAssertEqual(sent.personIds, ["per-ravi"]) // A typed `@` on the PAGE is a link, never a destination: only a // person's page makes the plan certain. XCTAssertNil(sent.request.plan) } func testOffersPeopleForAtAndProjectsForHashNeverTheOtherVocabulary() { let model = dock() model.fieldEdited("@me") XCTAssertEqual(model.suggestions.map(\.id), ["per-meera"]) model.fieldEdited("#me") XCTAssertEqual(model.suggestions.map(\.id), ["pr-meri"]) } func testDoesNotOpenATokenInsideAnEmailAddress() { // Every address typed into a capture would otherwise become a chip. let model = dock() model.fieldEdited("mail ravi@example.com") XCTAssertNil(model.activeToken) XCTAssertEqual(model.suggestions, []) // …and not with the caret standing right after the @ either. model.caretMoved(to: 10) XCTAssertNil(model.activeToken) } func testCarriesAProjectAndAPersonOnTheSameCapture() async { let model = dock() model.fieldEdited("#mer") model.pick(meri) model.fieldEdited("call @rav") model.pick(ravi) await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "call") XCTAssertEqual(sent.request.projectIds, ["pr-meri"]) XCTAssertEqual(sent.personIds, ["per-ravi"]) } // MARK: - The scoping rule func testAProjectPagesDockArrivesWithTheProjectAttachedRemovably() async { let model = dock(place: .project(id: "pr-meri", name: "Meri")) XCTAssertTrue(model.placeholder.contains("Meri"), model.placeholder) XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-meri"]) model.fieldEdited("call the plumber") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "call the plumber") XCTAssertEqual(sent.request.projectIds, ["pr-meri"]) XCTAssertEqual(sent.personIds, []) XCTAssertNil(sent.request.plan) } func testAProjectPagesOwnChipIsStillRemovableStandingHereIsNotAVerdict() async { let model = dock(place: .project(id: "pr-meri", name: "Meri")) guard let chip = model.attachedChips.first else { return XCTFail("no chip") } model.detach(chip) XCTAssertEqual(model.attachedChips, []) model.fieldEdited("not about the project") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, []) } func testAPlainPagePreAttachesNothingAPlaceIsAScopeNotADefault() async { let model = dock() model.fieldEdited("pay it") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, []) XCTAssertEqual(sent.personIds, []) XCTAssertNil(sent.request.plan) } func testAPersonPageKeepsTheWordsAboutThemAPersonNoteAndThePersonChip() async { let model = dock(place: .person(id: "per-ravi", name: "Ravi Kumar")) XCTAssertTrue(model.placeholder.contains("Ravi Kumar"), model.placeholder) XCTAssertEqual(model.attachedChips.map(\.recordId), ["per-ravi"]) model.fieldEdited("prefers a call before 9") await model.send() let sent = await lastSend() XCTAssertEqual(sent.personIds, ["per-ravi"]) // The wire shape, spelled out: this is what `capture.create` stores on // the row, and a renamed key here is a plan the server cannot read. XCTAssertEqual( sent.request.plan, .object([ "records": .array([ .object([ "target": .object([ "kind": .string("person_note"), "personId": .string("per-ravi"), "body": .string("prefers a call before 9"), ]), "confidence": .number(1), // `withUserChips`: no chips on this record is a // STATEMENT, not a silence — it is what lets a chip be // taken off on a re-commit. "userProjectIds": .array([]), ]) ]) ]) ) // A plan the person SENT is a plan they accepted. XCTAssertTrue(sent.request.userEdited) } func testAPlanCarriesThePersonsOwnChipsOnEveryRecord() async { // `withUserChips`. The server's filer // reads `user_project_ids` PER RECORD and writes those links // `applied_by: "user"` (`cotton-server/src/routing/file_plan.rs:973-986`) // — send a plan without them and the routed record is filed with no // user link at all, and the chip arrives minutes later from the drain // under somebody else's hand. let model = dock(place: .person(id: "per-ravi", name: "Ravi Kumar")) model.fieldEdited("prefers a call before 9 #mer") model.caretMoved(to: 28) model.pick(meri) await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, ["pr-meri"]) guard case .object(let plan)? = sent.request.plan, case .array(let records)? = plan["records"], case .object(let first)? = records.first else { return XCTFail("the plan did not go out in the shape the filer reads") } XCTAssertEqual(first["userProjectIds"], .array([.string("pr-meri")])) } // MARK: - A host that passes only a place // // R8 of this chain: a host may mount the dock with a place and nothing else // and still get the place's chip and the links it earns. func testShowsAndSendsThePlacesChipWithNoVocabularyAtAll() async { let model = dock( place: .project(id: "pr-meri", name: "Meri"), vocabulary: vocabulary(empty: true) ) // The place knows its own name, so the chip is never a blank pill. XCTAssertEqual(model.attachedChips.map(\.name), ["Meri"]) model.fieldEdited("call the plumber") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, ["pr-meri"]) } // MARK: - The person page's chip is the scope func testCarriesATypedAtMeeraBesideThePagesOwnPerson() async { let model = dock(place: .person(id: "per-ravi", name: "Ravi Kumar")) model.fieldEdited("ask @mee about the quote") model.caretMoved(to: 8) model.pick(meera) await model.send() let sent = await lastSend() XCTAssertEqual(sent.personIds, ["per-ravi", "per-meera"]) } func testRevertsToOrdinaryClassificationOnceThePagesChipComesOff() async { // The chip is the scope: gone from the screen must mean gone from the // decision, or it is decoration. let model = dock(place: .person(id: "per-ravi", name: "Ravi Kumar")) guard let chip = model.attachedChips.first else { return XCTFail("no chip") } model.detach(chip) XCTAssertEqual(model.attachedChips, []) model.fieldEdited("pay the GST") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, []) XCTAssertEqual(sent.personIds, []) XCTAssertNil(sent.request.plan) XCTAssertFalse(sent.request.userEdited) } // MARK: - The caret after a chip lands // // A cut from the MIDDLE leaves the tokenizer reading from the middle. What // this pins is the draft the dock reasons over, which is what decides // whether the next keystroke opens a token. func testReadsTheNextTokenFromTheCutNotFromTheEndOfTheText() { let model = dock() // Two tokens, and the caret is standing in the FIRST one. model.fieldEdited("pay #meri #cot") model.caretMoved(to: 9) model.pick(meri) // The literal is gone and the seam healed… XCTAssertEqual(model.text, "pay #cot") // …and the draft caret sits at the cut (4), which is BEFORE `#cot`'s // sigil — so the strip is silent, exactly as it is when you have not // entered a token. XCTAssertEqual(model.caret, 4) XCTAssertNil(model.activeToken) // The discriminator: the same text with the caret at the END — which is // what a plain replace would have reported — IS inside `#cot` and does // offer Cotton. Only the caret differed. model.caretMoved(to: 8) XCTAssertEqual(model.suggestions.map(\.id), ["pr-cotton"]) } func testHealsALeadingCutToTheHeadOfTheText() { let model = dock() model.fieldEdited("#meri pay it") model.caretMoved(to: 5) model.pick(meri) XCTAssertEqual(model.text, "pay it") } // MARK: - A chip with no name is neither shown nor sent func testDropsAPlaceChipTheVocabularyAndThePlaceBothFailToName() async { // A project place naming `pr-ghost`, and a vocabulary that has never // heard of it: nothing can put a word on the chip. let model = dock(place: .project(id: "pr-ghost", name: "")) XCTAssertEqual(model.attachedChips, []) model.fieldEdited("pay the bill") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, []) XCTAssertEqual(sent.personIds, []) } func testStillSendsEveryChipItCanName() async { let model = dock() model.fieldEdited("#mer") model.pick(meri) model.fieldEdited("pay it") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, ["pr-meri"]) } // MARK: - The place moving // // No original case: the previous file stated this in a comment beside the // during-render adjustment and never held it. func testStandingSomewhereNewReArmsTheChipsAndStatingTheSamePlaceDoesNot() { let model = dock(place: .project(id: "pr-meri", name: "Meri")) model.fieldEdited("#cot") model.pick(cotton) XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-meri", "pr-cotton"]) // A host re-stating the same place must not wipe what the writer just // attached — the whole reason the adjustment is keyed on identity. model.standing(on: .project(id: "pr-meri", name: "Meri")) XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-meri", "pr-cotton"]) // Standing somewhere else re-arms EVERYTHING: a `#cotton` typed on one // project page is not a fact about the next one. model.standing(on: .project(id: "pr-cotton", name: "Cotton")) XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-cotton"]) XCTAssertTrue(model.placeholder.contains("Cotton"), model.placeholder) } // MARK: - Send's two receipts // // No TypeScript case for the second: this port's own divergence // (`DockModel`'s header, difference 3). func testASuccessfulSendSaysNothingTheTranscriptIsTheReceipt() async { let model = dock() var landed: [String] = [] model.onCaptured = { landed.append($0.text("id") ?? "") } model.fieldEdited("pay it") await model.send() XCTAssertNil(toasts.current, "a success toast is a sentence nobody reads") XCTAssertEqual(landed, ["cap-1"], "the transcript re-reads because a row landed") } func testAFailedSendSaysSoAndGivesTheWordsBack() async { await captures.refuseEverything() let model = dock(place: .project(id: "pr-meri", name: "Meri")) model.fieldEdited("call the plumber") await model.send() XCTAssertEqual(toasts.current?.tone, .error) XCTAssertFalse(toasts.current?.message.isEmpty ?? true, "a failed capture says so") // A capture that did not land must not be a thought that vanished. XCTAssertEqual(model.text, "call the plumber") XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-meri"]) } func testAFailedSendLeavesTheNextThoughtAloneTheWriterWins() async { await captures.refuseEverything() await captures.hold() let model = dock() model.fieldEdited("call the plumber") let flight = Task { await model.send() } await waitForRequests(1) // They got there first. model.fieldEdited("something else entirely") await captures.release() await flight.value XCTAssertEqual(toasts.current?.tone, .error, "a failed capture says so") XCTAssertEqual(model.text, "something else entirely") } /// Wait until the capture path has been asked `count` times. private func waitForRequests(_ count: Int) async { for _ in 0..<400 { if await captures.sent().count >= count { return } try? await Task.sleep(for: .milliseconds(5)) } XCTFail("the capture path was never asked") } // MARK: - Pictures on a thought (store schema 36) /// A file on this device, captured and put on the draft. private func picked( _ model: DockModel, _ file: String, as recordId: String, kind: CaptureMediaKind = .photo ) async { await media.answer(file, recordId: recordId, key: "ws/\(kind.rawValue)/\(recordId).jpg") await model.attach( file: URL(fileURLWithPath: "/staged/\(file)"), mime: kind == .video ? "video/mp4" : "image/jpeg", kind: kind, filename: file ) } /// **The pictures ride the capture, in the order they were put on the /// draft** — the order the thought keeps them in. Each one names the /// record `capture.media` answered, `{kind, id}` and nothing else. func testAPictureAttachedRidesTheCaptureInOrder() async { let model = dock() await picked(model, "a.jpg", as: "photo:a") await picked(model, "b.mov", as: "video:b", kind: .video) model.fieldEdited("the login screen is blank") XCTAssertEqual(model.pictures.map(\.recordId), ["photo:a", "video:b"]) await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "the login screen is blank") XCTAssertEqual( sent.request.attachments, [CaptureAttachment(kind: .photo, id: "photo:a"), CaptureAttachment(kind: .video, id: "video:b")] ) let asked = await media.askedFiles() XCTAssertEqual(asked, ["a.jpg", "b.mov"], "each picture was captured once, in order") } /// **Words are still required.** A capture with pictures and no words is /// refused below the boundary, so the dock never sends one: the arrow stays /// dimmed and a tap on it is nothing. func testASendWithPicturesAndNoWordsDoesNotSend() async { let model = dock() await picked(model, "a.jpg", as: "photo:a") XCTAssertFalse(model.canSend) XCTAssertFalse(model.isReadyToSend) XCTAssertNil(model.pendingCapture()) await model.send() let sent = await captures.sent() XCTAssertTrue(sent.isEmpty) XCTAssertEqual(model.pictures.map(\.recordId), ["photo:a"], "the picture stays on the draft") } /// A refused capture gives the pictures back WITH the words — half of the /// thought that did not land is still half of it. func testAFailedSendGivesThePicturesBack() async { await captures.refuseEverything() let model = dock() await picked(model, "a.jpg", as: "photo:a") model.fieldEdited("receipt for the plumber") await model.send() XCTAssertEqual(model.text, "receipt for the plumber") XCTAssertEqual(model.pictures.map(\.recordId), ["photo:a"]) } /// A picture put on the NEXT thought while the refused one was in flight /// counts as starting it — the rollback does not pour the old pictures /// over the new draft. func testAFailedSendDoesNotOverwriteAPictureOnTheNextThought() async { await captures.refuseEverything() await captures.hold() let model = dock() await picked(model, "a.jpg", as: "photo:a") model.fieldEdited("first") let sending = Task { await model.send() } await settledSend() model.attach(picture: CapturedPicture(kind: .photo, recordId: "photo:next", key: "k")) await captures.release() await sending.value XCTAssertEqual(model.pictures.map(\.recordId), ["photo:next"]) XCTAssertEqual(model.text, "") } /// Taking one off leaves the others, in their order — and deletes /// nothing: the record is a photo in the library. func testDetachRemovesOnePicture() async { let model = dock() await picked(model, "a.jpg", as: "photo:a") await picked(model, "b.jpg", as: "photo:b") await picked(model, "c.jpg", as: "photo:c") model.detach(picture: model.pictures[1]) XCTAssertEqual(model.pictures.map(\.recordId), ["photo:a", "photo:c"]) model.fieldEdited("two left") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.attachments.map(\.id), ["photo:a", "photo:c"]) } /// The draft's life ends with the capture it described — pictures too. func testASendClearsThePicturesWithTheWords() async { let model = dock() await picked(model, "a.jpg", as: "photo:a") model.fieldEdited("sent") await model.send() XCTAssertEqual(model.pictures, []) XCTAssertEqual(model.text, "") model.fieldEdited("the next one") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.attachments, [], "the next capture carries none of them") } /// The same record twice is one picture — `{kind, id}` is unique on a /// thought and the crate refuses a duplicate by name. func testTheSamePictureIsNotPutOnTwice() { let model = dock() let one = CapturedPicture(kind: .photo, recordId: "photo:a", key: "k") model.attach(picture: one) model.attach(picture: one) XCTAssertEqual(model.pictures, [one]) } /// A picture that did not make it into the store is SAID, and the draft /// is left as it was. func testAPictureTheStoreRefusedIsSaidAndNotAttached() async { let model = dock() await model.attach( file: URL(fileURLWithPath: "/staged/unknown.jpg"), mime: "image/jpeg", kind: .photo, filename: nil) XCTAssertEqual(model.pictures, []) XCTAssertEqual(model.picturesArriving, 0) XCTAssertEqual(toasts.current?.message, DockModel.pictureRefused) } /// Yields until the held send has reached the capture seam — it has cleared /// the draft by then. private func settledSend() async { for _ in 0..<200 { if await !captures.sent().isEmpty { return } await Task.yield() } XCTFail("the send never reached the capture seam") } // MARK: - The project pill /// RULE: The capture bar's project pill writes the thought's project links, so a project chosen on it rides capture.create's projectIds and lands with the thought, never as a hint to a later sweep. func testAPillChoiceRidesTheCapturesProjectIds() async { let model = dock() XCTAssertFalse(model.projectPillLabel.contains("Cotton"), "an emptied pill names no project") XCTAssertFalse(model.projectPillLabel.contains("Meri"), "an emptied pill names no project") XCTAssertEqual(model.projectOptions.map(\.id), ["pr-meri", "pr-cotton"]) model.aim(atProject: "pr-cotton") XCTAssertEqual(model.projectPillLabel, "Cotton") XCTAssertEqual(model.attachedChips.map(\.recordId), ["pr-cotton"]) model.fieldEdited("ship the pill") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.text, "ship the pill") XCTAssertEqual(sent.request.projectIds, ["pr-cotton"]) } func testThePillTakesAProjectOffAndCountsSeveral() async { let model = dock(place: .project(id: "pr-meri", name: "Meri")) XCTAssertEqual(model.projectPillLabel, "Meri") model.aim(atProject: "pr-cotton") XCTAssertTrue(model.projectPillLabel.contains("Meri"), "the pill names its first project") XCTAssertTrue(model.projectPillLabel.contains("1"), "the pill counts the rest") model.unaim(project: "pr-meri") XCTAssertEqual(model.projectPillLabel, "Cotton") // A project the vocabulary does not hold is no chip anyone could see. model.aim(atProject: "pr-gone") XCTAssertEqual(model.aimedProjects.map(\.recordId), ["pr-cotton"]) model.unaim(project: "pr-cotton") XCTAssertFalse(model.projectPillLabel.contains("Cotton"), "an emptied pill names no project") XCTAssertFalse(model.projectPillLabel.contains("Meri"), "an emptied pill names no project") model.fieldEdited("unfiled") await model.send() let sent = await lastSend() XCTAssertEqual(sent.request.projectIds, []) } }