// THE DOCK, as state — the assembly's whole brain, with no view in it.//// The dock is one card — the words, then `[+] … (mic) (send)` along its bottom// edge. `+` is the DETERMINISTIC lane (you already know what you are making),// the words are the NATURAL-LANGUAGE lane (free text, live dictation, and the// typed sigil grammar). Neither `#` nor `@` is a button anywhere — they are typing// grammar, and the whole feature is `SigilTokenizer.swift` reading the token// the caret stands in. This file decides; `CaptureDock.swift` and// `CaptureComposer.swift` only draw what it says.//// ## Three deliberate differences from the TypeScript//// **1. This model DOES write, and the dock that came before did not.** There,// `CaptureDock` reported a `DockCapture` upward and each host owned the// mutation, because the mutation lived in the screen. There is no query// cache here (`CaptureService`'s own header says so), so the host-side half of// that seam has nowhere else to live: what the screen's capture handler// did — build the request, ride the plan, toast the failure — happens in// ``send()``. The VALUE the dock reported survives intact as ``DockCapture``,// built first and then handed to the write, so the shape the tests assert is// still the shape that crosses.//// **2. There is NO toast on send, and one on failure.** The receipt is the// transcript — another lane's screen, which re-reads because a row landed// (``onCaptured``). `handleCapture` had an error toast and no success toast,// and a success receipt added here would be a sentence nobody reads over a// screen that already shows the answer.//// **3. A failed send GIVES THE WORDS BACK.** The old `onError` rolled an// optimistic row out of the cache and the words were already gone from the// field. This app has no optimistic row, so the equivalent rollback is the// draft returning: a capture that did not land must not be a thought that// vanished. It is restored only while the draft is still empty — a writer who// has started the next thought wins. The draft's PICTURES come back with the// words: they are half of the thought that did not land, and a screenshot// silently dropped from a bug report is the report quietly rewritten.//// ## Pictures on a thought//// A thought carries pictures (store schema 36) — a bug report from the phone is// one thought with a screenshot. They come in through the `+` fan's Picture and// Camera rows, or from the share sheet (`ShareIntake.swift` branch 2, handed on// by the navigator), and each one is ALREADY a record by the time it is on the// draft: `capture.media` copies the bytes into the store and writes the photo// row first, and the capture only NAMES it (`CaptureRequest.attachments`). So a// picture on a draft that is never sent is simply a photo in the library, and a// picture on a capture that is refused comes back to the draft with the words.//// **Words are still required.** A capture with pictures and no words is// refused below the boundary, so ``canSend`` reads the words alone and the// arrow stays dimmed over a picture with nothing said about it.//// ## Two rules that look like details and are not//// • **The chip IS the scope.** A place's pre-attached chip is what// `placePlan` reads, so taking it off reverts the capture to ordinary// classification. A plan outliving its chip would make the chip decoration.// • **What is SHOWN is what is SENT.** A chip neither the vocabulary nor the// place can name is dropped from the strip AND from the capture. Hiding it// while still sending its id is the worst of both: no chip on screen,// nothing to take off, and the link lands anyway.importCottonKitimportFoundation// MARK: - The write seam/// What ``DockModel`` needs of the capture path, and nothing more.////// A protocol rather than the concrete ``CaptureService`` so a test drives this/// model with no `UserDefaults`, no `PendingLinks` and no core — building the/// real service means building the link store, and a dock test has no business/// knowing that a link intent is remembered at all. The one implementation is/// the real one.publicprotocolCaptureSending: Sendable {func capture(_ request: CaptureRequest, personIds: [String]) asyncthrows -> JSONValue}extensionCaptureService: CaptureSending {}// MARK: - What the dock reports/// What the dock decided a capture IS: the words, what it is linked to, and —/// where the place made it certain — where it lands.////// Kept as a value even though this model performs the write itself: it is the/// unit the dock's whole test suite asserts, and building it before the/// write means the decision and the request are two steps rather than one/// tangle.publicstructDockCapture: Sendable, Equatable {publiclet text: String/// Projects the writer attached — typed `#` picks, plus the project of the/// page they are standing on. Every one is a deliberate act, so the write/// lands them `applied_by: 'user'` without consulting the router.publiclet projectIds: [String]/// People the writer attached — typed `@` picks, plus the person of the/// page they are standing on.publiclet personIds: [String]/// A destination the PLACE made certain (a person's page → a person note),/// or nil when the capture takes its usual road — the live plan if the/// classifier produced one for these words, the server's router otherwise.publiclet plan: DockRoutePlan?/// The pictures on the draft, in the order they were put there — the/// order the thought keeps them in.publiclet pictures: [CapturedPicture]publicinit( text: String, projectIds: [String], personIds: [String], plan: DockRoutePlan?, pictures: [CapturedPicture] = [] ) {self.text = textself.projectIds = projectIdsself.personIds = personIdsself.plan = planself.pictures = pictures }}/// A chip on the pending capture, resolved to a name the strip can draw.////// `id` is the CHIP's identity (grammar + record), not the record's: a project/// and a person may share an id space by accident, and two chips colliding in a/// `ForEach` is a row that vanishes.publicstructAttachedChip: Sendable, Equatable, Identifiable {publiclet sigil: Sigilpubliclet recordId: Stringpubliclet name: Stringpublicvar id: String { "\(sigil.rawValue)\(recordId)" }/// The word in the chip's accessibility identifier — the grammar, spelled/// out for the reader. Identifier vocabulary, never user copy, so it does/// not go through `CottonStrings`.publicvar kindWord: String { sigil == .hash ? "project" : "person" }publicinit(sigil: Sigil, recordId: String, name: String) {self.sigil = sigilself.recordId = recordIdself.name = name }}/// A chip before it has been named — which grammar attached it, and to what.privatestructDockChip: Equatable {publiclet sigil: Sigillet id: String}// MARK: - The model@MainActor@ObservablepublicfinalclassDockModel {// ── Where it is standing ──────────────────────────────────────────────/// The scoping rule's whole input: the placeholder, the chip that arrives/// pre-attached, and the destination a person's page makes certain.publicprivate(set) var place: DockPlace/// The identity of the place these chips were armed for.privatevar seenPlaceKey: Stringprivatevar chips: [DockChip]// ── The draft ─────────────────────────────────────────────────────────/// The words. Read by the field; written only through ``fieldEdited(_:)``/// and the model's own paths, so dictation and the writer never race for it.publicprivate(set) var text = ""/// The screen the dock was raised over, sent with every thought so/// whoever files it knows what "this" meant; nil over Home.publicvar screen: CaptureScreen?/// The voice split: a dictated draft is offered to the send's command/// first, and one it answers true for ran as a command for the app/// ("open todos") — it is not saved. Every other draft is saved as a/// thought. The sender hands it in at the send, over what its screen/// shows then: a command kept from when the dock mounted reads a Home/// whose tools had not loaded (phone build 285, `HomeVoiceTests`).publictypealiasSpokenCommand = @MainActor (String) async -> Bool/// The draft holds dictated words.publicprivate(set) var spoken = false/// How many times a host has asked for the keyboard.////// A COUNTER, not a flag — this is the port of `CaptureDockHandle.focusComposer`,/// and the reason that had to be imperative: the capture deep link lands on/// a screen that is the root of its stack and never remounts, so a/// mount-time `autoFocus` changes nothing on the SECOND tap of the phone's/// home-screen link. A flag would have the same defect; a counter always/// changes.publicprivate(set) var focusRequests = 0/// Ask for the keyboard. Idempotent in effect and never in value.publicfunc focusComposer() { focusRequests += 1 }/// The pictures on the draft, in the order they were put there. Each is a/// record already (see the header's "Pictures on a thought"); the capture/// only names them.publicprivate(set) var pictures: [CapturedPicture] = []/// How many pictures are on their way into the store right now. A COUNT,/// because two picked in quick succession are two captures in flight, and/// a flag cleared by the first would call the second done.publicprivate(set) var picturesArriving = 0/// Where the caret stands, in CHARACTERS — the index space/// `SigilTokenizer.swift` reports its spans in, for the reason its header/// gives. A UTF-16 offset from a text view has to be converted before it/// arrives here.publicprivate(set) var caret = 0// ── Injected ──────────────────────────────────────────────────────────privatelet captures: any CaptureSendingprivatelet media: any MediaCapturingprivatelet dictation: DictationModelprivatelet vocabulary: DockVocabularyprivatelet haptics: any Hapticsprivatelet toasts: ToastCenter/// The recogniser's vocabulary bias — the person's own proper nouns. A/// closure so it is read at the tap rather than captured at construction:/// the list lands after the screen does.privatelet hints: @MainActor () async -> DictationHints/// The hints read when the screen came up (``prepareDictation()``), so/// the tap opens the microphone without waiting on a read of the core.privatevar warmHints: DictationHints?// ── What a host may listen to ─────────────────────────────────────────/// Every keystroke, so a host can classify on a pause.////// During dictation nothing is reported — partials would machine-gun the/// classifier — and the finished transcript arrives as ONE change. The/// clear on send is deliberately silent too: a host reads its plan inside/// its own send handler, and clearing first would make every send look/// stale.publicvar onTextChange: ((String) -> Void)?/// The last dictation's ending, named (the voiceTake rule). The sentence/// is already spoken by this model; this is for a host that wants the/// fact, and it reacts in its own draw (`onChange`), over what it shows/// then — a closure handed in at mount reads the host as it was mounted/// (`HomeVoiceTests`).publicprivate(set) var ending: DictationEnding?/// A dictation's ending, counted, so a second take that ends the same way/// is still a change.publicstructDictationEnding: Equatable, Sendable {publiclet outcome: DictationOutcomepubliclet take: Int }/// A capture LANDED. Not a receipt — the transcript is the receipt — but/// the signal a screen re-reads on, because a write answers with `tables`/// and the screens re-read (design P5).publicvar onCaptured: ((JSONValue) -> Void)?/// The last capture `send` wrote — its words and the projects it was aimed/// at — kept past the draft's clearing so the host's receipt can say where/// it went (`NewThoughtOverlay`). Set before the write; a write that fails/// leaves it, and `onCaptured` is the signal that it landed.publicprivate(set) var lastSent: DockCapture?/// **This takes ownership of the dictation model's unasked-ending channel.**/// One host per `DictationModel`: an interruption has exactly one place to/// land, and a second assignment would silently take the words away from the/// first.publicinit( place: DockPlace = .page, captures: any CaptureSending, media: any MediaCapturing, dictation: DictationModel, vocabulary: DockVocabulary = DockVocabulary(), haptics: any Haptics, toasts: ToastCenter, hints: @escaping @MainActor () async -> DictationHints = { DictationHints() } ) {self.place = placeself.seenPlaceKey = placeKeyOf(place)self.chips = DockModel.initialChips(place)self.captures = capturesself.media = mediaself.dictation = dictationself.vocabulary = vocabularyself.haptics = hapticsself.toasts = toastsself.hints = hints dictation.onUnasked = { [weakself] result inself?.land(result) } }// ── The place moving ──────────────────────────────────────────────────/// Standing somewhere NEW re-arms the place's own chips.////// Keyed on the IDENTITY of the place, not on the value, so a host that/// re-states the same place does not wipe chips the writer just attached —/// and idempotent for the same reason the TypeScript adjusted this DURING/// RENDER rather than in an effect: the first paint after the move must/// never show the old place's chips.////// **The SwiftUI translation.** React re-runs a component body with a new/// prop; there is no body here to re-run, so the host sets the place on the/// model where it builds the dock — which is its own render. Because this is/// idempotent, calling it from a body records no change when the place has/// not moved, and when it HAS the chips are correct before the frame is/// drawn. An `onChange`/`task` would be exactly the effect the TypeScript/// refused: one frame of the old place's chips under the new place's/// placeholder.////// It re-arms EVERYTHING, typed chips included, as the TypeScript's/// `setChips(initialChips(place))` does — a `#cotton` typed on one project/// page is not a fact about the next one.publicfunc standing(on next: DockPlace) {let key = placeKeyOf(next) place = nextguard key != seenPlaceKey else { return } seenPlaceKey = key chips = DockModel.initialChips(next) }/// The chips a place arrives with — its own project, its own person. Both/// are removable: standing somewhere is a strong signal, never a verdict.privatestaticfunc initialChips(_ place: DockPlace) -> [DockChip] { placeProjectIds(place).map { DockChip(sigil: .hash, id: $0) } + placePersonIds(place).map { DockChip(sigil: .at, id: $0) } }// ── What the pill draws ───────────────────────────────────────────────/// The pill's invitation, in the voice of the place it stands on.publicvar placeholder: String { dockPlaceholder(place) }/// What the field must SHOW: the live stream while dictating, the writer's/// own words otherwise.publicvar displayText: String { dictation.isLive ? dictation.fieldText : text }/// Dictation owns the field — it is read-only while this is true.publicvar isDictationLive: Bool { dictation.isLive }/// A session is up or coming up: the meter is lit.publicvar isListening: Bool { dictation.isListening }/// The newest meter readings, oldest first — the listening line's waveform.publicvar dictationWaveform: [Double] { dictation.waveform }/// The tapped finish is in flight — both dictation buttons are inert.publicvar isFinishing: Bool { dictation.isFinishing }/// `m:ss`, for the listening line.publicvar dictationClock: String { dictation.clock }/// The listening line's own sentence.publicvar dictationStatus: String { dictation.statusLine }/// Send is reachable — there are words to capture.////// The mic is drawn BESIDE it either way and is reachable with words in/// the field: a thought half-typed and then spoken is the common case, and/// the transcript splices onto what is already there/// (``startDictation()``'s prefix). What this decides is whether the arrow/// is live or dimmed, never whether it is drawn.publicvar canSend: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }/// The arrow is LIVE: there are words, and no picture is still on its way/// into the store.////// ``canSend`` is the words rule and is left exactly as it was — a picture/// never stands in for them. This adds the one wait a picture brings: a/// send tapped while `capture.media` is still copying would file the/// thought WITHOUT the picture the person just chose, and the picture would/// then land on the next, empty draft.publicvar isReadyToSend: Bool { canSend && picturesArriving == 0 }// ── The typed-sigil grammar ───────────────────────────────────────────/// Which vocabulary a sigil completes against — the ONE place that decides.privatefunc vocabularyFor(_ sigil: Sigil) -> [SigilCandidate] { sigil == .hash ? vocabulary.projects : vocabulary.people }/// The `#…` or `@…` token the caret is standing in.////// Read off the draft, never defaulted: a `#` fallback would file a person/// as a project the one time the two disagreed.publicvar activeToken: SigilToken? { activeSigilToken(text, caret: caret) }/// What the completion strip offers, best first. Empty for a bare `#` — a/// bare sigil is not a question, and a strip that held its space would make/// the pill jump every time somebody typed one.publicvar suggestions: [SigilCandidate] {guardlet token = activeToken, !token.query.isEmpty else { return [] }return matchCandidates( vocabularyFor(token.sigil), query: token.query, exclude: excluded(token.sigil) ) }/// Already-attached ids for one SIGIL. Excluded per sigil rather than/// wholesale: a person already attached must not silence a project/// suggestion, or the reverse.privatefunc excluded(_ sigil: Sigil) -> Set<String> {Set(chips.filter { $0.sigil == sigil }.map(\.id)) }/// The chips as the strip draws them, and as the capture carries them.////// Each is resolved against its OWN vocabulary — a chip needs a name — and/// falls back to the PLACE, which knows what it is called even when the/// host handed over no vocabulary at all (R8) or its read is still in/// flight.////// A chip with neither is DROPPED, from the strip and from the capture/// alike. An EMPTY name counts as no name: JavaScript's `name ? … : null`/// treated `""` as unnamed and Swift's optional does not, so the emptiness/// is tested here rather than left to a difference between two languages.publicvar attachedChips: [AttachedChip] { chips.compactMap { chip inlet found = vocabularyFor(chip.sigil).first { $0.id == chip.id }let name = found?.name ?? placeChipName(place, sigil: chip.sigil, id: chip.id) ?? ""guard !name.isEmpty else { returnnil }returnAttachedChip(sigil: chip.sigil, recordId: chip.id, name: name) } }// ── Typing ────────────────────────────────────────────────────────────/// The field changed. Ignored while dictation owns it — the words arriving/// then are the recogniser's, and they land through ``land(_:)``.publicfunc fieldEdited(_ next: String) {guard !dictation.isLive else { return }if next.isEmpty { spoken = false } edit(next) }/// The caret moved without the words changing — a tap, an arrow key, or the/// correction that follows a keystroke made mid-sentence.////// Clamped rather than trusted: a selection reported before a programmatic/// edit is stale by the time it is read, and an index past the text is a/// trap in Swift where it was a clamp in JavaScript.publicfunc caretMoved(to position: Int) {guard !dictation.isLive else { return } caret = max(0, min(position, text.count)) }/// The one write path for the words.////// `caret` defaults to the END of the new text, which is where typing puts/// it; the platform's own selection event follows and corrects it for a tap/// or an edit made mid-sentence.privatefunc edit(_ next: String, caret at: Int? = nil) {let previous = text text = next caret = max(0, min(at ?? next.count, next.count)) onTextChange?(next)// A space or an enter typed at a token's end commits the TOP match —// the completion you get without lifting a thumb to the strip. The// LEFTMOST suggestion is that match, so reading order and keyboard// order are the same order.guardlet closed = closedSigilToken(prev: previous, next: next) else { return }guardlet top = matchCandidates( vocabularyFor(closed.sigil), query: closed.query, exclude: excluded(closed.sigil) ).firstelse { return } attach(top, sigil: closed.sigil, in: next, span: closed) }/// Take a completion off the strip.publicfunc pick(_ candidate: SigilCandidate) {guardlet token = activeToken else { return } attach(candidate, sigil: token.sigil, in: text, span: token) }/// Attach a candidate and cut its literal `#text` / `@text` out of the words.privatefunc attach( _ candidate: SigilCandidate, sigil: Sigil,in sourceText: String, span: SigilToken? ) {if !chips.contains(where: { $0.sigil == sigil && $0.id == candidate.id }) { chips.append(DockChip(sigil: sigil, id: candidate.id)) }guardlet span else { return }// The chip REPLACES the words: leaving `#meri` in the sentence would// file the sigil into the record's own text.let cut = removeSigilToken(sourceText, token: span)// The caret lands where the token WAS, so the next token is read// against the place the writer is actually in; the default (end of// text) would read from the end of a sentence they are still in the// middle of. Re-entering `edit` with the SHORTER text closes no token,// so this cannot recurse. edit(cut.text, caret: cut.caret) }/// Take a chip off. A pre-attached one comes off exactly as a typed one/// does — and taking the PLACE's chip off reverts the capture to ordinary/// classification, because a chip must never advertise a removal that/// changes nothing.publicfunc detach(_ chip: AttachedChip) { chips.removeAll { $0.sigil == chip.sigil && $0.id == chip.recordId } }// ── The project pill ──────────────────────────────────────────────────/// The projects the thought will land in — the `#` chips, which is where/// the pill reads and writes. One list, so the pill, the strip and the/// capture's `projectIds` can never disagree ("what is shown is what is/// sent"): the write files a thought's links in the same transaction that/// lands it, so a choice here is the link, never a hint to a later sweep.publicvar aimedProjects: [AttachedChip] { attachedChips.filter { $0.sigil == .hash } }/// The pill's words: the project, the first and a count when there are/// several, and "No project" when there is none.publicvar projectPillLabel: String {let aimed = aimedProjectsguardlet first = aimed.first else { returnDockModel.noProject }return aimed.count == 1 ? first.name : "\(first.name) +\(aimed.count - 1)" }/// What the pill says when the thought is in no project.publicstaticvar noProject: String { ShellLines.line("capture", "dock.no_project") }/// The projects the pill's sheet offers — the `#` vocabulary, which is/// active projects only, with the slug each cap's enamel is assigned by.publicvar projectOptions: [ProjectsSheetOption] { vocabulary.projects.map {ProjectsSheetOption( id: $0.id, name: $0.name, status: .active, slug: vocabulary.projectSlugs[$0.id]) } }/// A cap on in the pill's sheet: the project goes on the thought. A project/// the vocabulary does not hold is not a chip anyone could see, so it is/// not attached.publicfunc aim(atProject id: String) {guardlet project = vocabulary.projects.first(where: { $0.id == id }) else { return } attach(project, sigil: .hash, in: text, span: nil) }/// A cap off in the pill's sheet — the same removal as tapping its chip.publicfunc unaim(project id: String) { chips.removeAll { $0.sigil == .hash && $0.id == id } }// ── Pictures ──────────────────────────────────────────────────────────/// Put a picture that is already in the file on the draft.////// The share sheet's hand-over comes straight here; the `+` fan comes/// through ``attach(file:mime:kind:filename:)``, which captures first./// A picture already on the draft is not put on twice — `{kind, id}` is/// unique on a thought, and the crate refuses a duplicate by name.publicfunc attach(picture: CapturedPicture) {guard !pictures.contains(where: { $0.kind == picture.kind && $0.recordId == picture.recordId })else { return } pictures.append(picture) }/// Take a picture off the draft. The RECORD stays — it is a photo in the/// library, and taking it off a thought nobody has sent yet is not a/// reason to delete a photograph.publicfunc detach(picture: CapturedPicture) { pictures.removeAll { $0.kind == picture.kind && $0.recordId == picture.recordId } }/// A file on this device, captured into the store and put on the draft.////// `capture.media` first (``MediaCapturing``), then the record goes on the/// draft — the order the boundary asks for./// The source file is the CALLER's: a staged copy is deleted by whoever/// staged it, and a file the person picked is theirs to keep.////// A refusal is SAID, in the crate's own words when it had some, and the/// draft is left as it was.publicfunc attach( file url: URL, mime: String, kind: CaptureMediaKind, filename: String? ) async { picturesArriving += 1defer { picturesArriving -= 1 }do {let landed = tryawait media.capture( file: url, mime: mime, kind: kind, filename: filename)// A row with no id is a picture no capture can name — saying so// beats a tile that would ride the send and be refused there.guard !landed.recordId.isEmpty else { toasts.show(DockModel.pictureRefused, tone: .error)return } attach( picture: CapturedPicture( kind: kind, recordId: landed.recordId, key: landed.key, posterKey: landed.posterKey)) haptics.select() } catch { toasts.show( (error as? CottonCallError)?.message ?? DockModel.pictureRefused, tone: .error ) } }/// The sentence for a picture that did not reach the draft.staticvar pictureRefused: String { ShellLines.line("capture", "dock.picture_refused") }// ── Send ──────────────────────────────────────────────────────────────/// What the dock would report for the words as they stand — the value/// `onCapture` carried, built before anything is written.////// `nil` for an empty draft: send no-ops on nothing, and there is no capture/// to describe.publicfunc pendingCapture() -> DockCapture? {let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmed.isEmpty else { returnnil }let shown = attachedChipslet personIds = shown.filter { $0.sigil == .at }.map(\.recordId)returnDockCapture( text: trimmed, projectIds: shown.filter { $0.sigil == .hash }.map(\.recordId), personIds: personIds,// The place's plan stands only while its chip does — see `placePlan`. plan: placePlan(place, text: trimmed, attachedPersonIds: personIds), pictures: pictures ) }/// Tap ↑.////// Trims, no-ops on empty, fires the press haptic, CLEARS THE FIELD, and/// only then writes: capture must feel INSTANT, so nothing on this path/// waits for the network before the pill is ready for the next thought.////// `press`, not `select` — the two map to different generators. Send is/// the most repeated control in the app; a tick where/// the phone thumps is the one place the difference is felt every day./// A scoped sender explains why its command was refused; global capture/// keeps its existing failure sentence. The draft rollback is shared.publicvar captureFailureMessage: (Error) -> String = { _ inShellLines.line("capture", "dock.capture_refused") }publicfunc send(runsSpokenCommand: SpokenCommand? = nil) async {// A picture still copying would be left behind by this send — see// ``isReadyToSend``. The arrow is dimmed then, so this is the rule the// arrow draws, held here as well for any caller that is not the arrow.guard picturesArriving == 0, let capture = pendingCapture() else { return } haptics.press()if spoken, capture.pictures.isEmpty, let runsSpokenCommand, await runsSpokenCommand(capture.text) { clearDraft()return }// Kept for the rollback below — see the header's third difference.let carried = chips lastSent = capture// The draft's life ends with the capture it described; the PLACE's own// chips come straight back, because the place has not moved. clearDraft()do {let created = tryawait captures.capture(CaptureRequest( text: capture.text,// `withUserChips`: the chips ride the PLAN as well as the// capture row — see `planJSON`. plan: capture.plan.map {DockModel.planJSON($0, userProjectIds: capture.projectIds) },// Meaningless without a plan, and the crate stores NULL// then: a sent plan is the proposal the person saw, and// the classifier reads the column, so it is set in exactly// the same breath as the plan. userEdited: capture.plan != nil, projectIds: capture.projectIds,// In the draft's order, which is the order the thought// keeps them in. attachments: capture.pictures.map(\.attachment), saidTable: screen?.table, saidRecordId: screen?.recordId ), personIds: capture.personIds )// NO SUCCESS TOAST. The receipt is the transcript; this is the// signal it re-reads on. onCaptured?(created) } catch { toasts.show(captureFailureMessage(error), tone: .error)// The words come back — but only over a draft the writer has not// already started filling, and never over a live dictation. A// picture put on the next thought counts as starting it.guard text.isEmpty, pictures.isEmpty, !dictation.isLive else { return } text = capture.text caret = capture.text.count chips = carried// The pictures with them: half of the thought that did not land. pictures = capture.pictures } }privatefunc clearDraft() { spoken = false text = "" caret = 0 chips = DockModel.initialChips(place)// The pictures belong to the capture that is leaving; each is still a// photo in the library whatever happens to it. pictures = []// Deliberately NOT reported: a host reads its plan inside its own send// handler, and clearing first would make every send look stale. The// host ends the plan's life itself, after it has used it. }/// The plan on the wire — `person_note`/// with its `personId` and `body`, at the confidence a human standing on/// the page earns, and the person's own `#` chips on every record.////// Written out here rather than through `Encodable` because `CaptureRequest`/// carries the plan as an opaque `JSONValue`: the SHAPE is the contract, and/// a synthesised encoding would rename a key the day somebody renamed a/// property.////// ## `userProjectIds` — the writer's own chips////// The dock's `#` chips go ON each planned record before sending, and that/// is the WHOLE reason a chip on a planned capture reaches the record as/// the person's own. 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`, whose own comment is/// *"this one is a person's decision and is ALWAYS `user`"* — separately/// from the classifier's `project_id`, which takes the plan's stamp/// (`:988-1000`). Send a plan without the field and the filer writes NO/// user link on the routed record at all; the membership then arrives/// minutes later from ``PendingLinks``' drain, stamped by whichever tool/// that path uses. So this is not the plan editor's — it is the reason the/// drain does not have to write the record link at all when a plan rides/// along.////// It FILLS rather than stamps in the TypeScript (`record.userProjectIds ??/// userProjectIds`, R52) — a record answered one chip at a time in the plan/// editor keeps its own list. ``DockPlannedRecord`` carries no such field,/// because the plan editor that would set it is not built here, so every/// record takes the dock's list. When the editor lands, that field is what/// grows and this line is what reads it.////// `[]` is a real answer, not a silence: "no chips on this record" is what/// lets a chip be TAKEN OFF on a re-commit, which is why the key is written/// unconditionally.////// The key is camelCase because the wire is: `PlannedRecord` is/// `#[serde(rename_all = "camelCase")]`/// (`cotton-core/src/rules/routing.rs:215-246`), which is why the server's/// own fixtures send `"userProjectIds"`.staticfunc planJSON(_ plan: DockRoutePlan, userProjectIds: [String]) -> JSONValue {let chips = JSONValue.array(userProjectIds.map(JSONValue.string))return .object(["records": .array( plan.records.map { record inswitch record.target {case .personNote(let personId, let body):return .object(["target": .object(["kind": .string("person_note"),"personId": .string(personId),"body": .string(body), ]),"confidence": .number(record.confidence),"userProjectIds": chips, ]) } } ) ]) }// ── Dictation: A TAP, NEVER A HOLD ────────────────────────────────────//// The card's control row, two states: the mic and send BOTH drawn while// the person owns the field, and ✕ / ✓ while a session is live. There is no// long-press anywhere in this assembly — the hold-to-record voice note// retired with the dictation spec, and the mic streams text as you talk./// Tap the mic.////// The prefix is the trimmed words already in the field, remembered so the/// transcript folds onto them — which is the whole of "speak into a/// half-typed thought". The mic is reachable with words in the field/// (`CaptureComposer.swift`'s header says why it did not used to be), so/// this prefix is the common case rather than the unreachable one.////// The haptic is fired HERE, before the two refusals — a tap that cannot/// start a dictation is still a tap that landed. The call site owns it:/// the model is shared with `/take`, which fires none of these, so a haptic/// inside the model would double up there.publicfunc startDictation() async { haptics.press()let prefix = text.trimmingCharacters(in: .whitespacesAndNewlines)let warm = warmHints// RULE: the tap never waits on the hints read. A tap before the// screen's warm read came back (a real-sized household reads its// hints for seconds) listens with no hints, so the microphone opens —// or the system asks for it — at once: a tap that read the core first// gave nothing for ~3 s and then the system's prompt (walker294 row// 118). The next tap is warm.iflet refusal = await dictation.start(prefix: prefix, hints: warm ?? DictationHints()) { ended(refusal) }// The names move as the person works, and the person's own model is// compiled again from their lines: the next tap's model is prepared// for the hints read now, after this one is already listening — never// for this tap's, which would leave the next tap cold whenever the// model moved (voiceline, 16 Oct 2026).await prepareDictation() }/// Warm the microphone's model for the next tap: the hints read now and/// the recogniser prepared for them. Called when the screen with the mic/// comes up and on every return to the foreground — never on the tap.publicfunc prepareDictation() async {let read = await hints() warmHints = read dictation.prepare(hints: read) }/// Tap ✓.publicfunc finishDictation() async { haptics.press() land(await dictation.finish()) }/// Tap the keyboard while listening — land what was heard, then hand the/// field to the person's thumbs (design 2026-09-13 D5). The finish is the/// same finish ✓ performs, so the words are never lost on the way to the/// keyboard; the focus request is the same counter the capture link uses.publicfunc switchToTyping() async {if dictation.isLive {await finishDictation() } focusComposer() }/// Tap ✕ — a deliberate discard, the one ending that keeps no words and/// owes no sentence.publicfunc cancelDictation() { haptics.press() dictation.cancel() ended(.dictationCancelled) }/// Land a finished dictation in the field and name its ending — the ONE/// path for a finish the person tapped and for an interruption the mic/// suffered (a call, Siri, an alarm). The words stay, whoever ended it:/// iOS's own dictation keeps what it heard, and so does this field.privatefunc land(_ result: DictationResult) {// The model keeps the prefix past the ending precisely so this can read// it after the session has gone idle.let prefix = dictation.prefixif !result.text.isEmpty { edit(VoiceTake.foldDictationSegment(prefix, result.text)) spoken = true haptics.success() } ended(result.outcome) }/// Every ending is NAMED and the app always speaks — a capture app that can/// drop a thought in silence is not a capture app. A named ending's/// sentence is an ERROR receipt; `dictated` and `dictationCancelled` have/// none, and say nothing.privatefunc ended(_ outcome: DictationOutcome) {iflet sentence = VoiceTake.dictationMessage(outcome) { toasts.show(sentence, tone: .error) } ending = DictationEnding(outcome: outcome, take: (ending?.take ?? 0) + 1) }}/// Where a thought was said: the table or record when one stands there.publicstructCaptureScreen: Equatable, Sendable {publicvar table: String?publicvar recordId: String?publicinit(table: String? = nil, recordId: String? = nil) {self.table = tableself.recordId = recordId }/// The table or record `route` stands on; neither where it stands on none.publicinit?(_ route: Route?) {guardlet route else { returnnil }switch route {case .tableList(let table, _, _, _, _, _, _): self.init(table: table)case .tableRecord(let table, let id): self.init(table: table, recordId: id)default: self.init() } }}/// Where a dictated "open todos" goes on a box with no list under it: the/// tool the core's spoken line opens (`shell.input {op: line, at: board,/// spoken}`). Nil for every other line, and when the core cannot be asked —/// those are thoughts.enumSpokenOpen { @MainActor staticfunc route(_ words: String, core: (any CottonCalling)?) async -> Route? {let ask: JSONValue = .object(["op": "line", "at": .object(["board": .object([:])]), "words": .string(words), "spoken": .bool(true)])guardlet core, let read = try? await core.callJSON(CottonMethod.shellInput, ask),let table = read["opens"]?["table"]?.stringelse { returnnil }return read["opens"]?["id"]?.string.map { .tableRecord(table: table, id: $0) } ?? BoardLayout.listRoute(forTable: table) }}/// The new-thought overlay's voice split, over what the overlay is drawn/// with now: a spoken "open …" closes it and opens the tool; false for a/// thought, which the dock keeps.@MainActorstructSpokenOpenVoice {let core: (any CottonCalling)?let navigator: Navigator?/// The overlay goes before the page opens.let close: () -> Voidfunc run(_ words: String) async -> Bool {guardlet route = awaitSpokenOpen.route(words, core: core) else {returnfalse } close() navigator?.open(route)returntrue }}