package com.cottondb.messages.warm import android.app.Application import androidx.activity.ComponentActivity import androidx.compose.foundation.lazy.LazyListState import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.onAllNodesWithTag import com.cottondb.messages.chat.ChatList import com.cottondb.messages.chat.ChatRow import com.cottondb.messages.chat.DownloadOpen import com.cottondb.messages.chat.DownloadsModel import com.cottondb.messages.chat.Opening import com.cottondb.messages.chat.Words import com.cottondb.shell.Shared import com.cottondb.shell.core.CottonCore import com.cottondb.shell.str import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * The Downloads chat on Android (DLCHAT; assets/design/chat/CONTRACT.md "The Downloads chat"), drawn from answers * shaped as the core's `chat.list`, `chat.downloads` and `chat.downloads.send` give them. Every link and name is invented. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [35], application = Application::class) class DownloadsChatTest { @get:Rule val compose = createAndroidComposeRule() private fun json(text: String): JsonObject = CottonCore.json.parseToJsonElement(text).jsonObject private val words = Words { set, key -> "$set:$key" } private val downloadsRow = """{"thread":"downloads","kind":"downloads","name":"Downloads","group":false,"source":"cotton", "picture":{"initials":"","tint":0,"mark":"downloads"},"lastLine":{"text":"Done: river-walk-talk.mp4","mine":false},"when":"9:41", "unread":0,"markedUnread":false,"pinned":false,"muted":false,"archived":false,"sendable":false, "leading":[],"trailing":[{"act":"mute","label":"Mute"}],"hold":[{"act":"mute","label":"Mute"}]}""" private val personRow = """{"thread":"t1","name":"Asha Menon","group":false,"source":"cotton","picture":{"initials":"AM","tint":1}, "lastLine":{"text":"Are we still on for Sunday?","mine":false},"when":"9:48","unread":0,"markedUnread":false,"pinned":false,"muted":false, "archived":false,"leading":[],"trailing":[]}""" private fun line(state: String, name: String, text: String, extra: String = "") = """{"state":"$state","name":"$name","text":"$text","row":"x"$extra}""" private fun item(fetch: String, link: String, line: String, day: Boolean = false) = """{"fetch":"$fetch","link":{"text":"https://$link","shown":"$link","at":"2026-11-22T04:11:00.000Z","time":"9:41"},"cotton":{"at":"2026-11-22T04:12:00.000Z","time":"9:42","line":$line}${if (day) ""","day":{"date":"22","words":"Sunday · November"}""" else ""}}""" private val page = """{"thread":"downloads","kind":"downloads","title":"Downloads","by":"Cotton, on this phone", "picture":{"initials":"","tint":0,"mark":"downloads"},"about":"Only you are in this chat.","placeholder":"Paste or share a link","muted":false, "hold":[{"act":"mute","label":"Mute"}],"items":[ ${item("f-done", "example.com/talks/river-walk-talk.mp4", line("done", "river-walk-talk.mp4", "Done · 412 MB · opens in Cinemas", ""","act":{"act":"open","label":"Open"},"unopened":{"text":"Done · saved to Files · no app here opens it","act":{"act":"show","label":"Show"}}"""), day = true)}, ${item("f-failed", "example.org/files/recipes-2019.zip", line("failed", "recipes-2019.zip", "Failed · the site didn't answer", ""","act":{"act":"retry","label":"Retry"}"""))}, ${item("f-on", "example.net/albums/quiet-hours.flac", line("progress", "quiet-hours.flac", "40%", ""","percent":40"""))}, ${item("f-new", "example.com/books/garden-notes.epub", line("queued", "garden-notes.epub", "Queued · waiting for your Mac"))} ]}""" /** A core that answers the Downloads chat's methods and records what it was asked. */ private class Core(val page: () -> String, val send: (String) -> String) { val asked = mutableListOf>() suspend fun ask(method: String, request: JsonObject): JsonObject { asked += method to request val text = when (method) { "chat.downloads" -> page() "chat.downloads.send" -> send(request.str("text").orEmpty()) else -> """{"item":null}""" } return CottonCore.json.parseToJsonElement(text).jsonObject } } private fun model(core: Core) = DownloadsModel(core::ask, CoroutineScope(SupervisorJob() + Dispatchers.Main)) /** RULE (DLCHAT): the list holds the Downloads chat as Cotton's: its mark where a person's initials stand, the newest download's line, Mute its only swipe; a tap opens it as its kind says. */ @Test fun the_list_draws_the_downloads_chat_as_cottons_and_a_tap_opens_it() { val list = ChatList.of(json("""{"words":{"title":"Chats","search":"Search"},"filters":[],"rows":[$personRow,$downloadsRow]}"""), words) val row = list.rows.single { it.id == "downloads" } assertEquals("downloads", row.kind) assertEquals("downloads", row.avatar.mark) assertEquals(listOf("mute"), (row.swipeStart + row.swipeEnd).map { it.id }) var opened: ChatRow? = null compose.setContent { WarmTheme(night = false) { ChatsPlace(list, LazyListState(), "", ChatsWords("New chat", "You", "Muted", "Pinned", "Unread", "More"), {}, {}, { opened = it }, { _, _ -> }, {}, {}, {}) } } compose.onNodeWithTag("chat-row-downloads").assertIsDisplayed() assertEquals("Cotton's mark in the Downloads row alone", 1, compose.onAllNodesWithTag("cotton-mark", useUnmergedTree = true).fetchSemanticsNodes().size) compose.onNodeWithText("Done: river-walk-talk.mp4").assertIsDisplayed() compose.onNodeWithTag("chat-row-downloads").performClick() assertEquals("downloads", opened?.id) } /** RULE: each download is the person's link and ONE line from Cotton: the file's name, its state, a bar while it comes, and Open or Retry at its end; a failed Retry asks the core's retry. */ @Test fun each_download_is_its_link_and_one_line_from_cotton() { val core = Core(page = { page }, send = { """{"fetch":[]}""" }) val dl = model(core) val acts = mutableListOf>() compose.setContent { WarmTheme(night = false) { DownloadsChat(dl, DownloadsWords("Back", "Send"), onBack = {}, onAct = { item, act -> acts += item.fetch to act; if (act == "retry") dl.retry(item.fetch) }, onHold = {}) } } dl.refresh() compose.waitForIdle() compose.onNodeWithText("Cotton, on this phone").assertIsDisplayed() // The chat opens at its newest; the oldest is scrolled to. compose.onNodeWithTag("downloads-items").performScrollToNode(hasTestTag("downloads-link-f-done")) compose.onNodeWithTag("downloads-link-f-done", useUnmergedTree = true).assertExists() compose.onNodeWithTag("downloads-state-f-done", useUnmergedTree = true).assertTextEquals("Done · 412 MB · opens in Cinemas") compose.onNodeWithTag("downloads-items").performScrollToNode(hasTestTag("downloads-line-f-new")) compose.onNodeWithTag("downloads-name-f-new", useUnmergedTree = true).assertTextEquals("garden-notes.epub") compose.onNodeWithTag("downloads-state-f-new", useUnmergedTree = true).assertTextEquals("Queued · waiting for your Mac") compose.onNodeWithTag("downloads-bar-f-on", useUnmergedTree = true).assertExists() compose.onNodeWithTag("downloads-items").performScrollToNode(hasTestTag("downloads-line-f-done")) compose.onNodeWithTag("downloads-act-open-f-done").assertExists() compose.onNodeWithTag("downloads-items").performScrollToNode(hasTestTag("downloads-act-retry-f-failed")) compose.onNodeWithTag("downloads-act-retry-f-failed").performClick() compose.waitForIdle() assertEquals(listOf("f-failed" to "retry"), acts) assertTrue(core.asked.any { (m, r) -> m == "chat.downloads.act" && r.str("act") == "retry" && r.str("fetch") == "f-failed" }) // Where nothing on this phone opened it: the core's words for that, and Show. dl.unopened = setOf("f-done") compose.waitForIdle() compose.onNodeWithTag("downloads-items").performScrollToNode(hasTestTag("downloads-line-f-done")) compose.onNodeWithTag("downloads-state-f-done", useUnmergedTree = true).assertTextEquals("Done · saved to Files · no app here opens it") compose.onNodeWithTag("downloads-act-show-f-done").assertExists() } /** RULE: a link written goes to the core's send and stands at once as its item; words with no link stand with Cotton's one line under them. */ @Test fun a_link_sent_stands_queued_and_words_without_one_are_answered() { var held = """{"title":"Downloads","by":"Cotton, on this phone","placeholder":"Paste or share a link","items":[]}""" val core = Core(page = { held }, send = { text -> if (text.contains("https://")) """{"fetch":["f-1"],"items":[${item("f-1", "files.example/a.pdf", line("queued", "a.pdf", "Queued"))}]}""" else """{"fetch":[],"said":"Send a link here and Cotton will download it."}""" }) val dl = model(core) compose.setContent { WarmTheme(night = false) { DownloadsChat(dl, DownloadsWords("Back", "Send"), onBack = {}, onAct = { _, _ -> }, onHold = {}) } } dl.refresh() compose.waitForIdle() compose.onNodeWithContentDescription("Paste or share a link").assertExists() compose.onNodeWithTag("downloads-field").performTextInput("can you get me that film?") compose.onNodeWithTag("downloads-send").performClick() compose.waitForIdle() compose.onNodeWithText("Send a link here and Cotton will download it.").assertIsDisplayed() compose.onNodeWithText("can you get me that film?").assertExists() compose.onNodeWithTag("downloads-field").performTextInput("https://files.example/a.pdf") compose.onNodeWithTag("downloads-send").performClick() compose.waitForIdle() compose.onNodeWithTag("downloads-state-f-1", useUnmergedTree = true).assertTextEquals("Queued") assertEquals("https://files.example/a.pdf", core.asked.last { it.first == "chat.downloads.send" }.second.str("text")) } /** RULE: Open goes to the Cotton app that plays it when one on the phone answers its link, else the file in the phone's viewer, else the core's words. */ @Test fun open_tries_the_app_then_the_file() { val both = DownloadOpen(listOf("photos" to "cottonphotos://lists/photo/p1"), "a.jpg", "ws/photos/a.jpg") assertEquals(Opening.App("cottonphotos://lists/photo/p1"), Opening.of(both) { true }) assertEquals(Opening.Viewer("ws/photos/a.jpg"), Opening.of(both) { false }) assertEquals(Opening.Save, Opening.of(DownloadOpen(listOf("cinemas" to "cottoncinemas://lists/film/f1"), "f.mkv", null)) { false }) } /** RULE: a share given to Comms' Downloads target says so to the core (`to: downloads`); a plain share says nothing of it. */ @Test fun a_share_to_the_downloads_target_says_where_it_goes() { assertEquals("downloads", Shared(text = "https://files.example/a.pdf", to = "downloads").request().str("to")) assertEquals(null, Shared(text = "https://files.example/a.pdf").request().str("to")) val manifest = java.io.File("src/messages/AndroidManifest.xml").readText() assertTrue("the alias is Comms' share target", manifest.contains("com.cottondb.messages.DownloadsShare") && manifest.contains("""android:name="com.cottondb.share.to" android:value="downloads"""")) assertTrue("it takes links and .torrent files", manifest.contains("application/x-bittorrent")) assertTrue("Open can ask whether Cinemas is here", manifest.contains("cottoncinemas")) } /** RULE: a download told by the core (`chat.notices`' downloads) is read as one notice: the chat's title, the file and its state. */ @Test fun a_download_notice_is_read_from_the_cores_answer() { val notices = com.cottondb.messages.Notices.of(json("""{"notices":[],"missed":[],"downloads":[{"fetch":"f-done","key":"downloads:f-done","thread":"downloads","title":"Downloads","name":"river-walk-talk.mp4","text":"Done · 412 MB","state":"done","at":"2026-11-22T04:12:00.000Z"}]}""")) val told = notices.downloads.single() assertEquals("f-done", told.fetch) assertEquals("river-walk-talk.mp4 · Done · 412 MB", told.body) assertEquals(java.time.Instant.parse("2026-11-22T04:12:00.000Z").toEpochMilli(), told.at) } }