package com.cottondb.messages.chat import com.cottondb.shell.core.CottonCore import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.io.File /** * The face reads the core's own answers (crates/cotton-core/src/messages/app/shapes.rs, as chat_app.rs serialises * them, camelCase): a list page with its fan, a thread page with runs, a day pill, the unread divider, an event, a * reply, reactions and an album; the composer's answer; an act's bubble. And a thread held as pages merges its newest * page asked again without drawing anything twice; New chat's people; the look from `chat.themes`. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [35], application = android.app.Application::class) class ChatAnswersTest { private val words = Words { set, key -> "$set:$key" } private fun j(text: String): JsonObject = CottonCore.json.parseToJsonElement(text).jsonObject private val list = j(""" {"filter":"all","rows":[ {"thread":"t1","name":"Asha Rao","group":false,"source":"cotton","picture":{"initials":"AR","tint":3}, "lastLine":{"text":"On my way.","mine":true,"tick":"read"},"when":"09:12","unread":0,"markedUnread":false, "pinned":true,"muted":false,"archived":false,"leading":[{"act":"unread","label":"Unread"},{"act":"unpinChat","label":"Unpin"}], "trailing":[{"act":"mute","label":"Mute"},{"act":"archive","label":"Archive"}], "hold":[{"act":"unread","label":"Mark as unread"},{"act":"unpinChat","label":"Unpin"},{"act":"mute","label":"Mute"}, {"act":"archive","label":"Archive"},{"act":"deleteChat","label":"Delete","confirm":"Delete the chat with Asha Rao?"}]}, {"thread":"t2","name":"Saturday hike","group":true,"source":"cotton","picture":{"initials":"SH","tint":5}, "lastLine":{"text":"Photo","sender":"Ravi","mark":"photo","mine":false},"when":"Yesterday","unread":4,"markedUnread":false, "pinned":false,"muted":true,"archived":false,"leading":[],"trailing":[]}, {"thread":"t3","name":"Meera Iyer","group":false,"source":"whatsapp","picture":{"initials":"MI","tint":1}, "draft":"Draft: see you","unread":0,"markedUnread":true,"pinned":false,"muted":false,"archived":false,"leading":[],"trailing":[]} ],"next":"cursor-80","counts":{"all":3,"people":2,"groups":1,"unread":2,"archived":0,"sources":{"cotton":2,"whatsapp":1}}, "fan":[{"id":"all","label":"All","count":3,"on":true},{"id":"people","label":"People","count":2,"on":false}, {"id":"account","label":"Account","on":false}], "words":{"title":"Chats","search":"Search","empty":"No chats yet."}} """) /** Cotton's own Downloads chat alone is still an empty list: it says how to begin (store pass, 24 Nov 2026). */ @Test fun downloads_alone_is_an_empty_list() { val alone = j("""{"rows":[{"thread":"downloads","kind":"downloads","name":"Downloads","group":false,"source":"cotton","leading":[],"trailing":[]}], "words":{"title":"Chats","search":"Search","empty":"No chats yet. Tap the pen to write to someone."}}""") assertEquals("No chats yet. Tap the pen to write to someone.", ChatList.of(alone, words).empty?.title) assertNull("a chat of theirs: not empty", ChatList.of(list, words).empty) } @Test fun a_list_page_reads_its_rows_fan_and_cursor() { val l = ChatList.of(list, words) assertEquals("Chats", l.title) assertEquals("Search", l.searchHint) assertEquals("chat:start.title", l.compose) assertEquals(listOf("all", "people", "account"), l.menu.map { it.id }) assertTrue(l.menu.first().current) assertNull(l.menu.last().count) assertEquals("cursor-80", l.next) assertNull(l.empty) val (asha, hike, meera) = l.rows assertEquals("t1", asha.id) assertEquals("read", asha.ticks) assertNull(asha.unread) assertEquals(listOf("unread", "unpinChat"), asha.swipeStart.map { it.id }) assertEquals(listOf("mute", "archive"), asha.swipeEnd.map { it.id }) // Held: the core's menu, in its words (FEEDBACK1 item 6: Mark as unread); Delete asks first. assertEquals(listOf("Mark as unread", "Unpin", "Mute", "Archive", "Delete"), asha.hold.map { it.label }) assertEquals("Delete the chat with Asha Rao?", asha.hold.last().confirm) assertTrue(asha.hold.last().red) assertTrue(hike.hold.isEmpty()) assertEquals("4", hike.unread) assertEquals("Ravi", hike.sender) assertEquals("photo", hike.mark) assertNull(hike.ticks) // Marked unread by hand: a badge with no number; a draft stands as the last line. assertEquals("", meera.unread) assertEquals("Draft: see you", meera.line) assertEquals("MI", meera.avatar.initials) } @Test fun an_empty_list_says_the_cores_line() { val l = ChatList.of(j("""{"filter":"unread","rows":[],"counts":{"all":0,"people":0,"groups":0,"unread":0,"archived":0,"sources":{}},"fan":[],"words":{"title":"Chats","search":"Search","empty":"Nothing unread."}}"""), words) assertEquals("Nothing unread.", l.empty?.title) } private fun bubble(id: String, mine: Boolean, head: Boolean, tail: Boolean, extra: String = "") = """{"item":"bubble","message":"$id","mine":$mine,"kind":"text","text":"words $id","head":$head,"tail":$tail,"time":"09:0${id.last()}", "pinned":false,"actions":["reply","react","copy","forward","edit","pin","select","delete"]$extra}""" private fun page(items: String, older: String? = "old-1", newer: String? = null) = j(""" {"thread":"t2","header":{"name":"Saturday hike","picture":{"initials":"SH","tint":5},"group":true,"source":"cotton","status":"4 members"}, "pinned":{"message":"m1","title":"Pinned message","line":"words m1","count":1}, "items":[$items],${older?.let { "\"older\":\"$it\"," } ?: ""}${newer?.let { "\"newer\":\"$it\"," } ?: ""}"unread":2, "jump":{"count":5,"label":"Jump to latest"}, "composer":{"thread":"t2","text":"","placeholder":"Message","button":"mic","buttonLabel":"Hold to record","attach":true,"attachLabel":"Attach", "sendEnabled":false,"dictate":true,"dictateLabel":"Speak","returnSends":false,"hardwareReturnSends":true}, "actions":{"reply":"Reply","react":"React","copy":"Copy","forward":"Forward","edit":"Edit","delete":"Delete","pin":"Pin","unpin":"Unpin", "select":"Select","copied":"Copied","emoji":["๐Ÿ‘","โค๏ธ","๐Ÿ˜‚"]}} """) private val ravi = """"sender":{"name":"Ravi Menon","picture":{"initials":"RM","tint":2},"tint":2}""" @Test fun a_thread_page_reads_runs_markers_and_kinds() { val p = ThreadPage.of(page( """{"item":"day","label":"Today"},""" + bubble("m1", false, true, false, ",$ravi") + "," + bubble("m2", false, false, true, ",$ravi,\"reactions\":[{\"emoji\":\"โค๏ธ\",\"count\":2,\"mine\":true}]") + "," + """{"item":"unread","label":"2 unread messages"},""" + """{"item":"event","message":"e1","text":"Ravi added Asha"},""" + bubble("m3", true, true, true, ""","tick":"delivered","edited":"edited","reply":{"message":"m1","sender":"Ravi Menon","line":"words m1"}, "media":[{"index":0,"kind":"photo","width":400,"height":300},{"index":1,"kind":"photo","width":300,"height":300}]"""), ), words) assertEquals("t2", p.chat) assertEquals("Saturday hike", p.header?.name) assertEquals("4 members", p.header?.status) assertEquals("words:more", p.header?.more) assertEquals("m1", p.pinned?.message) assertEquals("old-1", p.before) assertTrue(p.latest) assertEquals(5, p.jump) assertEquals("Jump to latest", p.words?.jump) assertEquals("words:back", p.words?.back) // A day pill and the divider take the id of the message under them, so keys stay put across asks. assertEquals(listOf("day:m1", "m1", "m2", "unread:e1", "e1", "m3"), p.items.map { it.id }) val (m1, m2) = p.items.filterIsInstance() assertEquals("Ravi Menon", m1.name) // Their picture rides on every message of theirs; the face draws it once, at the head of the run. assertEquals("RM", m1.avatar?.initials) assertTrue(m1.first && !m2.first) assertNull(m2.name) assertEquals("RM", m2.avatar?.initials) assertTrue(m1.gutter && m2.gutter) assertTrue(m2.reactions.single().mine) assertEquals("Ravi added Asha", (p.items[4] as Item.Event).text) val m3 = p.items.last() as Item.Message assertTrue(m3.out) assertEquals("delivered", m3.ticks) assertEquals("chat:state.delivered", m3.ticksSpoken) assertEquals("edited", m3.edited) assertEquals("m1", m3.reply?.message) assertEquals(listOf("msg:m3:0", "msg:m3:1"), m3.album?.items?.map { it.key }) assertEquals(4f / 3f, m3.album!!.items[0].ratio, 0.001f) // The composer as the thread hands it, and the long press from the bubble's own acts . assertEquals("mic", p.composer?.button) assertFalse(p.composer!!.returnSends) val menu = MessageMenu.of(m3, p.actions) assertEquals(listOf("๐Ÿ‘", "โค๏ธ", "๐Ÿ˜‚"), menu.reactions) assertEquals(listOf("reply", "copy", "forward", "edit", "pin", "select", "delete"), menu.acts.map { it.id }) assertEquals("Reply", menu.acts.first().label) assertTrue(menu.acts.last().red) } /** A WhatsApp chat that sends: Delete is the core's "Delete for everyone", beside "Delete for me", both red. */ @Test fun a_whatsapp_message_offers_delete_for_everyone_and_for_me() { val p = ThreadPage.of(page("""{"item":"bubble","message":"w1","mine":true,"kind":"text","text":"See you at six","head":true,"tail":true,"time":"09:01","pinned":false, "actions":["copy","edit","pin","delete","deleteMine","select"]}"""), words) val menu = MessageMenu.of(p.items.single() as Item.Message, com.cottondb.messages.chat.ActionWords.of(kotlinx.serialization.json.buildJsonObject { put("delete", kotlinx.serialization.json.JsonPrimitive("Delete for everyone")); put("deleteMine", kotlinx.serialization.json.JsonPrimitive("Delete for me")) })) val byId = menu.acts.associateBy { it.id } assertEquals("Delete for everyone", byId["delete"]?.label) assertEquals("Delete for me", byId["deleteMine"]?.label) assertTrue(byId["delete"]!!.red && byId["deleteMine"]!!.red) } // An agent in a chat (CONTRACT "An agent in a chat"): an agent's words are never the person's own, even on the phone // that sent them; its name and whose agent it is come with them, and TalkBack says both. @Test fun an_agents_words_say_whose_agent_it_is_and_are_never_mine() { val p = ThreadPage.of(page("""{"item":"bubble","message":"a1","mine":false,"kind":"text","text":"Fixed in the next build.","sender":{"name":"Claude","picture":{"initials":"C","tint":2},"tint":2},"agent":{"id":"mem-1","name":"Claude","line":"Your agent"},"head":true,"tail":true,"face":true,"time":"09:02","pinned":false,"actions":["reply","react"]}"""), words) val m = p.items.single() as Item.Message assertEquals(false, m.out) assertEquals("Claude", m.name) assertEquals("Your agent", m.agent) assertTrue(m.spoken, m.spoken.startsWith("Claude, Your agent, ")) } @Test fun a_deleted_message_says_the_cores_line_and_offers_nothing_to_react() { val p = ThreadPage.of(page("""{"item":"bubble","message":"d1","mine":false,"kind":"deleted","text":"This message was deleted","head":true,"tail":true,"time":"09:01","pinned":false,"actions":[]}"""), words) val d = p.items.single() as Item.Message assertEquals("This message was deleted", d.deleted) assertEquals("", d.body) assertTrue(MessageMenu.of(d, p.actions).let { it.acts.isEmpty() && it.reactions.isEmpty() }) } @Test fun a_new_chats_first_message_stays_under_the_day_the_core_answers_after_it() { // Sent into an empty chat, the bubble is held before the core's day divider exists; the newest page asked // again puts the day above it, as the core orders them. val t = ThreadState("t2", ThreadPage.of(page("", older = null), words)) t.sent(Item.of(j(bubble("m1", true, true, true)), words)) t.merge(ThreadPage.of(page("""{"item":"day","label":"Today","numeral":"21","words":"Saturday ยท November"},${bubble("m1", true, true, true)}""", older = null), words)) assertEquals(listOf("day", "m1"), t.items.map { if (it is Item.Day) "day" else it.id }) } @Test fun a_day_divider_keyed_again_is_not_drawn_twice() { // The day held under one key comes back under another once a message arrives: one day, not two. val t = ThreadState("t2", ThreadPage.of(page("""{"item":"day","id":"d-old","label":"Today","numeral":"21","words":"Saturday"},${bubble("m1", true, true, true)}""", older = null), words)) t.merge(ThreadPage.of(page("""{"item":"day","id":"d-new","label":"Today","numeral":"21","words":"Saturday"},${bubble("m0", false, true, true)},${bubble("m1", true, true, true)}""", older = null), words)) assertEquals(1, t.items.count { it is Item.Day }) assertEquals(listOf("m0", "m1"), t.items.filterIsInstance().map { it.id }) } @Test fun a_held_thread_merges_its_newest_page_asked_again() { val first = ThreadPage.of(page(bubble("m1", false, true, false) + "," + bubble("m2", false, false, true)), words) val t = ThreadState("t2", first) // A send lands at once. val sent = ActEffect.of(j("""{"ok":true,"act":"send","thread":"t2","message":"m3","bubble":${bubble("m3", true, true, true, ",\"tick\":\"sending\"")},"flush":true}"""), words) assertTrue(sent.flush) t.sent(sent.item!!) assertEquals(listOf("m1", "m2", "m3"), t.items.map { it.id }) // The engine says something changed: the newest page again, with the tick moved and a reply below. val again = ThreadPage.of(page(bubble("m1", false, true, false) + "," + bubble("m2", false, false, true) + "," + bubble("m3", true, true, true, ",\"tick\":\"read\"") + "," + bubble("m4", false, true, true)), words) assertEquals(1, t.merge(again)) assertEquals(listOf("m1", "m2", "m3", "m4"), t.items.map { it.id }) assertEquals("read", (t.items[2] as Item.Message).ticks) } @Test fun pages_above_are_held_as_a_window_with_no_item_twice() { val t = ThreadState("t2", ThreadPage.of(page(bubble("n0", false, true, true), older = "c0"), words)) for (i in 1..ThreadState.MAX_PAGES + 5) { t.older(ThreadPage.of(page(bubble("p$i", false, true, true), older = "c$i", newer = "n$i"), words)) } assertEquals(ThreadState.MAX_PAGES, t.items.size) assertFalse(t.latest) assertEquals("c${ThreadState.MAX_PAGES + 5}", t.before) assertEquals(t.items.size, t.items.map { it.id }.toSet().size) } @Test fun the_composers_answer_reads_its_strip() { val c = Compose.of(j("""{"thread":"t2","text":"fixed","placeholder":"Message","button":"send","buttonLabel":"Save","attach":false,"attachLabel":"Attach", "strip":{"kind":"edit","message":"m3","title":"Edit message","line":"words m3","cancel":"Cancel"},"sendEnabled":true,"dictate":true,"dictateLabel":"Speak","returnSends":false,"hardwareReturnSends":true}""")) assertEquals("edit", c.strip?.kind) assertEquals("m3", c.strip?.message) assertEquals("Cancel", c.strip?.cancel) assertTrue(c.sendEnabled) assertEquals("Save", c.buttonLabel) } /** New chat picks from Your people (`people.pick`) in the core's order; adding a number stays the way to someone new. */ @Test fun new_chat_reads_your_people_and_the_add_row() { val page = PickPage.of(j( """{"title":"New chat","heading":"Your people","rows":[{"number":"+15550100001","words":"Asha","initials":"A"}, {"number":"+15550100003","words":"+15550100003","detail":"Waiting for them to add you back","initials":"#"}], "add":{"words":"Add a person","hint":"Their number, starting with +"}}""", )) assertEquals("New chat", page.title) assertEquals(listOf("+15550100001", "+15550100003"), page.rows.map { it.number }) assertEquals("Waiting for them to add you back", page.rows[1].detail) assertNull(page.rows[0].detail) assertEquals("Add a person" to "Their number, starting with +", page.addWords to page.addHint) assertNull(page.none) } /** With nobody yet, or the object out of reach, the page says the core's line, the unreachable first. */ @Test fun new_chat_says_why_nobody_stands_there() { val empty = PickPage.of(j("""{"title":"New chat","heading":"Your people","rows":[],"add":{"words":"Add","hint":"+"},"empty":"No one yet."}""")) assertEquals("No one yet.", empty.none) val away = PickPage.of(j("""{"title":"New chat","heading":"Your people","rows":[],"add":{"words":"Add","hint":"+"},"unreachable":"Out of reach."}""")) assertEquals("Out of reach.", away.none) } /** The add's Go stands only for what reads as a number, as on iPhone. */ @Test fun only_a_number_is_offered_to_add() { assertTrue(PickPage.isNumber("+15550100001")) assertTrue(PickPage.isNumber(" 0555")) assertFalse(PickPage.isNumber("Asha")) assertFalse(PickPage.isNumber(" ")) } /** A voice message's bars: at most 64, each the loudest of its run, the loudest of all 1. */ @Test fun a_voice_message_folds_its_levels_into_bars() { val bars = ChatOutbox.bars((0 until 300).map { (it % 10) / 20f }) assertEquals(64, bars.size) assertEquals(1f, bars.max(), 0.001f) assertTrue(bars.all { it in 0f..1f }) assertEquals(listOf(0.5f, 1f), ChatOutbox.bars(listOf(0.1f, 0.2f))) assertTrue(ChatOutbox.bars(emptyList()).isEmpty()) val voice = ChatOutbox.voice(File("/x/v.m4a"), 4200, listOf(0.2f, 0.4f)) assertEquals("voice", voice["kind"]?.toString()?.trim('"')) assertEquals("4200", voice["durationMs"]?.toString()) } /** A received voice message opens from its own message and index; a sent picture stands from its local file. */ @Test fun a_voice_bubble_names_the_file_it_plays() { val p = ThreadPage.of(page(bubble("v1", false, true, true, ""","media":[{"index":0,"kind":"voice","length":"0:42","waveform":[0.1,0.9]}]""")), words) val v = (p.items.single() as Item.Message).voice!! assertEquals("msg:v1:0", v.key) assertEquals(42, v.seconds) assertEquals(listOf(10, 90), v.wave) assertNull(v.transcript) } /** * FEEDBACK1 item 5: a voice message's words, heard on the sender's phone and sealed like it, following it, stand * under the player and are said with it. */ @Test fun a_voice_message_carries_its_words() { val p = ThreadPage.of(page(bubble("v2", false, true, true, ""","media":[{"index":0,"kind":"voice","length":"0:05","transcript":"See you at ten"}]""")), words) val m = p.items.single() as Item.Message assertEquals("See you at ten", m.voice!!.transcript) assertTrue(m.spoken, m.spoken.contains("See you at ten")) } /** The recording handed to the recognizer: one channel at 16 kHz, whatever it was recorded at. */ @Test fun a_recording_is_heard_as_mono_at_16khz() { val stereo44 = ShortArray(44_100 * 2) { if (it % 2 == 0) 1000 else 3000 } val heard = VoiceTranscript.mono16k(stereo44, channels = 2, rate = 44_100) assertEquals(16_000, heard.size) assertTrue(heard.all { it.toInt() == 2000 }) val mono16 = shortArrayOf(1, 2, 3) assertEquals(mono16.toList(), VoiceTranscript.mono16k(mono16, channels = 1, rate = 16_000).toList()) } /** * The look from `chat.themes`, built here as chat_app.rs builds it from the kit (kits/messages/themes.json: each * appearance's tokens plus `tint.` and `name.`): every token the face reads is there, so nothing is a gap. */ @Test fun the_look_reads_every_kit_theme_with_no_gap() { val repo = generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "apps/registry.json").isFile } val kit = CottonCore.json.parseToJsonElement(File(repo, "crates/cotton-core/kits/messages/themes.json").readText()).jsonObject fun colours(theme: JsonObject, appearance: String) = kotlinx.serialization.json.buildJsonObject { theme[appearance]!!.jsonObject.forEach { (k, v) -> put(k, v) } kit["tints"]!!.jsonObject[appearance]!!.jsonArray.forEachIndexed { n, c -> put("tint.$n", c) } kit["names"]!!.jsonObject[appearance]!!.jsonArray.forEachIndexed { n, c -> put("name.$n", c) } } val themes = kit["themes"]!!.jsonArray.map { it.jsonObject } val answer = j("""{"themes":[${themes.joinToString(",") { t -> """{"id":${t["id"]},"name":"Name","on":false,"ground":${t["ground"]},"light":${colours(t, "light")},"dark":${colours(t, "dark")}}""" }}], "light":"cotton","dark":"plain", "text":{"title":"Text size","chosen":"large","options":[{"id":"small","label":"Small","scale":0.9},{"id":"standard","label":"Standard","scale":1.0},{"id":"large","label":"Large","scale":1.15}]}, "ground":{"title":"Chat background","chosen":"theme","options":[{"id":"theme","label":"As the look"},{"id":"plain","label":"Plain"},{"id":"weave","label":"Weave"}]}, "words":{"title":"Look","light":"Light","dark":"Dark","settings":"Settings"}}""") val look = ChatLook.of(answer)!! assertEquals("cotton", look.light.id) assertTrue(look.light.weave) assertEquals("plain", look.dark.id) assertTrue(look.dark.dark) assertEquals(listOf("Look", "Light", "Dark", "Settings"), listOf(look.title, look.lightLabel, look.darkLabel, look.settings)) assertEquals(1.15f, look.textScale, 0.001f) assertEquals(listOf("small", "standard", "large"), look.text.options.map { it.id }) assertEquals("theme", look.ground.chosen) assertEquals("Chat background", look.ground.title) assertEquals(themes.size, look.themes.size) for (c in look.themes) for (t in listOf(c.light, c.dark)) { assertEquals(8, t.tints.size) assertEquals(8, t.names.size) } // Every token the face reads is in each appearance (a gap would be drawn as the text colour). val read = listOf( "ground", "header", "text", "secondary", "rule", "accent", "badge_ink", "bubble_out", "ink_out", "meta_out", "bubble_in", "ink_in", "meta_in", "badge", "tick", "tick_read", "quote_bar", "pattern", "link", "pill", "pill_ink", "reaction", "reaction_ink", "danger", ) for (t in themes) for (appearance in listOf("light", "dark")) assertTrue("${t["id"]} $appearance", read.all { it in t[appearance]!!.jsonObject }) assertNull(ChatLook.of(j("""{"themes":[],"light":"plain","dark":"plain","words":{"title":"","light":"","dark":""}}"""))) assertNotNull(ChatTheme.colour("#2F6FEB80")) assertNull(ChatTheme.colour("blue")) } /** * COMMS WITHOUT MAIL (26 Nov 2026): the switch is Chats, Calls, You. Mail, Senders and Sites are Cotton Post's and * Cotton Sites'; a mail a core of before still weaves among the messages draws nothing, the messages around it stand. */ @Test fun the_switch_is_chats_calls_you_and_a_woven_mail_draws_nothing() { assertEquals(listOf(Place.Chats, Place.Calls, Place.You), shownPlaces()) val items = Item.page(listOf( j("""{"item":"day","label":"Today","numeral":"26","words":"Today"}"""), j("""{"item":"mail","email":"e1","mailThread":"m1","subject":"Invented subject","time":"09:00"}"""), j("""{"message":"msg-a","kind":"text","text":"Hello","time":"09:01"}"""), ), words) assertEquals(2, items.size) assertTrue(items[0] is Item.Day) assertEquals("the day pill takes the message under it, past the mail", "day:msg-a", items[0].id) assertEquals("msg-a", (items[1] as Item.Message).id) } }