// The app-level half of capture, and the two things every mic now shares. // // `CaptureContext` is the composition the `[thoughts-has-no-capture-dock]` gap // said had to live at the root: the real `CaptureService`, a `PendingLinks` // keyed on the identity, and a `PendingLinkSource` answered from reads the app // already makes. Each of those answers is pinned here against a `ScriptedCore`, // and the whole chain is driven once end to end — a capture with a `#` chip, // the router filing it, the drain writing the membership — with no simulator, // no `UserDefaults` and no microphone. // // `VoiceBias` is the piece the chat bar and the thoughts dock both read, so it // is held here rather than in either surface's own suite. The card they now // share — its control decision, its growth and its scroll — is // `ComposerCardTests`. import CottonKit import XCTest @testable import CottonUI /// An intent store in memory, so a test never touches the app group's suite. private final class MemoryStore: PendingLinkStore, @unchecked Sendable { private var values: [String: Data] = [:] private let lock = NSLock() func data(_ key: String) -> Data? { lock.withLock { values[key] } } func set(_ key: String, _ value: Data?) { lock.withLock { values[key] = value } } } private enum Fixtures { /// Every key `read.thoughts` answers — the fixture is the read's own JSON, /// which is what the screens ask for their keys. static func thoughts( routedRecords: String = "null", routedKind: String = "null", routedId: String = "null", routedFacts: String = "{}", projects: String = "[]", people: String = "[]" ) -> String { """ {"thoughts":[{"id":"t1","rawText":"call the plumber","audioUrl":null,\ "capturedAt":"2026-09-11T09:00:00+05:30","routeStatus":"pending",\ "routeReason":null,"routeConfidence":null,"routedKind":\(routedKind),\ "routedId":\(routedId),"routedRecords":\(routedRecords),"routeProposal":null,\ "sweepNote":null,"sweptAt":null}],\ "routedFacts":\(routedFacts),"people":\(people),"moneyAccounts":[],\ "projects":\(projects),"collections":[],"sessionMessages":[]} """ } static let home = """ {"askedOfYou":{"rows":[],"total":0}, "projects":[{"id":"p-house","name":"The house","slug":"the-house","lastActivity":null}], "projectFactsMissing":false,"counts":{},"workspace":null} """ } @MainActor final class CaptureContextTests: XCTestCase { // ── The drain's three questions, answered from the app's own reads ──── func testAPendingCaptureHasFiledNothingYet() async { let core = ScriptedCore([CottonMethod.readThoughts: .ok(Fixtures.thoughts())]) let filed = await CorePendingLinkSource(core: core).filed("t1") XCTAssertNil(filed, "an intent must keep waiting until the router has written a record") } func testARoutedCaptureAnswersItsRecordList() async throws { let core = ScriptedCore([ CottonMethod.readThoughts: .ok( Fixtures.thoughts(routedRecords: #"[{"kind":"todo","id":"td-1"},{"kind":"note","id":"n-1"}]"#) ) ]) let answer = await CorePendingLinkSource(core: core).filed("t1") let filed = try XCTUnwrap(answer) XCTAssertEqual(filed.routedRecords.map(\.id), ["td-1", "n-1"]) XCTAssertNil(filed.routedKind) } func testAHandFiledCaptureAnswersTheOlderSinglePointer() async throws { let core = ScriptedCore([ CottonMethod.readThoughts: .ok( Fixtures.thoughts(routedKind: "\"todo\"", routedId: "\"td-9\"") ) ]) let answer = await CorePendingLinkSource(core: core).filed("t1") let filed = try XCTUnwrap(answer) XCTAssertEqual(filed.routedKind, "todo") XCTAssertEqual(filed.routedId, "td-9") } func testACaptureTheLedgerDoesNotHoldIsNotFiled() async { let core = ScriptedCore([CottonMethod.readThoughts: .ok(Fixtures.thoughts())]) let filed = await CorePendingLinkSource(core: core).filed("t-elsewhere") XCTAssertNil(filed) } func testAPersonNotesOwnPersonComesOffTheRoutedFacts() async { let core = ScriptedCore([ CottonMethod.readThoughts: .ok( Fixtures.thoughts(routedFacts: #"{"pn-1":{"dateIso":null,"personId":"per-ravi"}}"#) ) ]) let source = CorePendingLinkSource(core: core) let known = await source.ownPerson(ofPersonNote: "pn-1") XCTAssertEqual(known, .known("per-ravi")) let unknown = await source.ownPerson(ofPersonNote: "pn-2") XCTAssertEqual( unknown, .unreadable, "not knowing must never read as 'nobody' — that is how the self edge would slip through" ) } func testARefusedReadIsUnreadableNotNobody() async { let core = ScriptedCore([ CottonMethod.readThoughts: .refuse(code: "read_failed", message: "no") ]) let answer = await CorePendingLinkSource(core: core).ownPerson(ofPersonNote: "pn-1") XCTAssertEqual(answer, .unreadable) } func testAProjectsSlugComesOffTheHomeRead() async { let core = ScriptedCore([CottonMethod.readHome: .ok(Fixtures.home)]) let source = CorePendingLinkSource(core: core) let slug = await source.projectSlug("p-house") XCTAssertEqual(slug, "the-house", "`read.home` is the one read answering id AND slug") let missing = await source.projectSlug("p-gone") XCTAssertNil(missing, "a project the app cannot name keeps its intent for the next pass") } // ── The whole chain, once ───────────────────────────────────────────── func testACaptureWithAChipIsWrittenRememberedAndLinkedOnceTheRouterFiles() async throws { let core = ScriptedCore([ CottonMethod.captureCreate: .ok(#"{"id":"t1"}"#), CottonMethod.write: .ok("{}"), CottonMethod.readHome: .ok(Fixtures.home), // Filed already by the time the drain asks: a todo out of the words. CottonMethod.readThoughts: .ok( Fixtures.thoughts(routedRecords: #"[{"kind":"todo","id":"td-1"}]"#) ), ]) let context = CaptureContext( userId: "owner-1", workspaceId: "ws-1", core: core, store: MemoryStore(), report: { trouble in XCTFail("nothing should be reported: \(trouble)") } ) let created = try await context.service.capture( CaptureRequest(text: "call the plumber", projectIds: ["p-house"]), personIds: [] ) XCTAssertEqual(created.text("id"), "t1") let settled = await context.drain() XCTAssertEqual(settled, 1, "one intent, one capture, one settlement") let calls = await core.calls let writes = calls.filter { $0.method == CottonMethod.write }.map(\.requestJSON) XCTAssertTrue( writes.contains { $0.contains("update_thought") && $0.contains("the-house") }, "the THOUGHT's own membership goes through update_thought, by slug: \(writes)" ) XCTAssertTrue( writes.contains { $0.contains("link_to_project") && $0.contains("td-1") }, "the routed todo is linked to the same project: \(writes)" ) } // A destination chosen in New thought must reach the write and its Undo; // the board's database must not replace the personal default. func testCaptureDestinationScopesTheWriteAndUndo() async throws { let core = ScriptedCore([ CottonMethod.captureCreate: .ok(#"{"id":"t1"}"#), CottonMethod.write: .ok("{}") ]) let context = CaptureContext(userId: "o", workspaceId: "personal", core: core, store: MemoryStore()) { _ in } let destination = ShownDatabase() let scoped = context.scoped(to: destination) _ = try await scoped.service.capture(CaptureRequest(text: "personal first"), personIds: []) destination.id = "yoga" _ = try await scoped.service.capture(CaptureRequest(text: "chosen database"), personIds: []) try await scoped.filing.takeBack(thoughtId: "t1") let calls = await core.calls let requests = try calls.map { try JSONDecoder().decode(JSONValue.self, from: Data($0.requestJSON.utf8)) } XCTAssertNil(requests[0]["database"]) XCTAssertEqual(requests[1].text("database"), "yoga") XCTAssertEqual(requests[2].text("database"), "yoga") XCTAssertEqual(requests[2]["args"]?.text("id"), "t1") } func testTheSameIdentityIsOneContextAndADifferentOneIsAnother() { let core = ScriptedCore() let a = CaptureContext(userId: "o", workspaceId: "w", core: core, store: MemoryStore()) { _ in } XCTAssertEqual(a.userId, "o") XCTAssertEqual(a.workspaceId, "w") } // Voice-context v1 ranks manual and automatic terms in Rust. Reordering, // trimming a name, or using the manual-only editor loses that contract. func testVoiceContextPreservesRankAndSpellingButDropsBlanks() async { let core = ScriptedCore(["read.voiceContext": .ok(#"{"biasGroups":[{"tag":"screen","terms":[" Meri ","🌱 Quillby","Meri"," ","\n",42,null]}]}"#)]) let hints = await VoiceBias.hints(core: core) XCTAssertEqual(hints.terms, [" Meri ", "🌱 Quillby", "Meri"]) let calls = await core.calls XCTAssertEqual(calls.map(\.method), ["read.voiceContext"]) } // A mic must start even when the optional context cannot be read. func testAnUnreadableVoiceContextBiasesNothingAndRefusesNothing() async { let core = ScriptedCore([ "read.voiceContext": .refuse(code: "read_failed", message: "no") ]) let hints = await VoiceBias.hints(core: core) XCTAssertEqual(hints, DictationHints()) XCTAssertNil(hints.language, "the device's own language") } private func voiceContext(_ json: String) throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: Data(json.utf8)) } /// RULE: The voice context's `biasGroups` reach the recogniser group by group in the core's order with their tags, blank terms are dropped and spelling kept, and `language` is the person's — because the core ranks in Rust and a second ranking here would decide a different hundred words. func testVoiceContextGroupsKeepTheCoresOrderAndTags() throws { let grouped = VoiceBias.hints(try voiceContext(#""" {"language":"hi","biasTerms":["ignored"],"biasGroups":[ {"tag":"people","terms":["Ravi"," "," Meri "]}, {"tag":"places","terms":["Tin Factory",42,null]}, {"terms":["no tag"]} ]} """#)) XCTAssertEqual( grouped.groups, [ DictationHints.Group(tag: "people", terms: ["Ravi", " Meri "]), DictationHints.Group(tag: "places", terms: ["Tin Factory"]), ]) XCTAssertEqual(grouped.language, "hi") let bare = VoiceBias.hints(try voiceContext(#"{"biasGroups":[{"tag":"screen","terms":["Quillby",""," \n ","Meri"]}]}"#)) XCTAssertEqual(bare.groups, [DictationHints.Group(tag: "screen", terms: ["Quillby", "Meri"])]) XCTAssertNil(bare.language) } }