Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(chat): seed two sample chats into an empty chat list
Durganshuad3e18a2f850
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex efea6de..fa8f779 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,17 @@ All notable changes to Gotcha are documented here.## [Unreleased]### Added+- **Two sample chats on a fresh install.** The chat list opened on nothing at+ all, so the one thing a first-time user couldn't find out was what Gotcha is+ for. A new install now starts with two short transcripts that show it: a+ device action with a follow-up in **Operator** (turn Wi-Fi on, then the+ Bluetooth screen the agent opens because Android won't let it flip that switch+ itself) and a question about the screen in **Monitor**. They are ordinary+ chats — open them, carry them on, or delete them — and both the drawer row and+ a line above the transcript say they're samples, so a demonstration is never+ mistaken for something you said. Seeding happens once per install and only+ into an empty list: upgrading keeps the chats you have, and deleting the+ samples is final.- **The assistant can now answer questions about Gotcha itself.** There was atool for the company behind the app (`about_samosa_ai`) but none for the app,so "what can you do?" and "which setting do I change to read replies aloud?"diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex c4c7561..faaad9c 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -72,6 +72,13 @@ class AgentEngine(var sessionId: String? = nullvar tokenCount: Int = 0+ /**+ * True while the bound session is one of the chats seeded on first run.+ * Carried through every save so a sample the user carries on with stays+ * labelled as one — its opening exchange is still not something they said.+ */+ var sessionIsSample: Boolean = false+/*** Stable key for the provider's server-side prompt KV cache* (`prompt_cache_key` / `X-Session-Id`), independent of [sessionId] which@@ -304,7 +311,8 @@ class AgentEngine(tokenCount = tokenCount,displayMessages = displayMessagesProvider(),agentMode = agentModeProvider()?.name,- runSummaries = runSummaries.toList()+ runSummaries = runSummaries.toList(),+ isSample = sessionIsSample))// Rename the chat dir in place now that the real title is known.diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex ab954b0..272386a 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -104,6 +104,12 @@ data class ChatUiState(val isConfigured: Boolean = false,val activeSessionId: String? = null,val activeAgent: AgentMode = AgentMode.MONITOR,+ /**+ * True while the open chat is one of the samples seeded on first run, so the+ * transcript can say so above the first bubble. Nothing else depends on it:+ * a sample is continued, renamed and deleted like any other chat.+ */+ val viewingSample: Boolean = false,/** Id of the session with an in-progress run, or null when nothing is running. */val runningSessionId: String? = null,/** Title of the running session, for the "return to running chat" banner. */@@ -272,6 +278,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A_uiState.update { it.copy(activeSessionId = agentEngine.sessionId) }updateContextUsage()migrateChatDirsIfNeeded()+ com.gotcha.data.SampleChatSeeder.seedIfNeeded(historyRepository, settingsRepository.prefs)refreshSessions()}}@@ -1107,6 +1114,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A// and saveCurrentSession() would persist the stale list into the// new chat file.agentEngine.restoreRunSummaries(emptyList())+ agentEngine.sessionIsSample = falseagentEngine.setupWorkingDir(create = false)engineTranscript = emptyList()engineAgent = defaultAgent@@ -1115,7 +1123,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(messages = emptyList(),activeSessionId = newId,- activeAgent = defaultAgent+ activeAgent = defaultAgent,+ viewingSample = false)}applyContextUsage(0)@@ -1177,7 +1186,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(activeSessionId = id,activeAgent = engineAgent,- messages = engineTranscript+ messages = engineTranscript,+ viewingSample = _sessions.value.firstOrNull { s -> s.id == id }?.isSample == true)}applyContextUsage(agentEngine.tokenCount)@@ -1197,6 +1207,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AagentEngine.tokenCount = session.tokenCountagentEngine.restoreTitle(if (session.isFallbackTitle()) null else session.title)agentEngine.restoreRunSummaries(session.runSummaries)+ agentEngine.sessionIsSample = session.isSampleagentEngine.setupWorkingDir()engineTranscript = session.displayMessagesengineAgent = restoredAgent@@ -1210,6 +1221,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(activeSessionId = session.id,activeAgent = restoredAgent,+ viewingSample = session.isSample,messages = session.displayMessages,// Clear engine-scoped transient UI for the viewed (non-running) chat.activity = null,@@ -1224,6 +1236,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(activeSessionId = session.id,activeAgent = restoredAgent,+ viewingSample = session.isSample,activity = null,subAgentRunning = null,subAgentCurrentAction = nulldiff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.ktindex 5490ca0..8831c55 100644--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt@@ -29,7 +29,15 @@ data class ChatSession(* Structured records of completed runs (the "share your moment" raw data),* newest last. Bounded at capture time so this can't grow unbounded.*/- val runSummaries: List<RunSummary> = emptyList()+ val runSummaries: List<RunSummary> = emptyList(),+ /**+ * True for the chats seeded on first run to demonstrate what Gotcha can be+ * asked for. Marked in the drawer and above the transcript so a sample is+ * never mistaken for something the user said, but otherwise an ordinary+ * session: openable, continuable and deletable. Defaulted so every chat+ * written before samples existed decodes as a real one.+ */+ val isSample: Boolean = false)/**@@ -74,10 +82,18 @@ class ChatHistoryRepository internal constructor(private val chatsDir: File) {}}- suspend fun saveSession(session: ChatSession) = withContext(Dispatchers.IO) {+ /**+ * Writes [session], stamping it as modified now. Pass [touch] = false to keep+ * the session's own [ChatSession.lastModified] — seeded sample chats carry+ * crafted timestamps that decide their order in the drawer, and a save-time+ * stamp would collapse them all into the same millisecond.+ */+ suspend fun saveSession(session: ChatSession, touch: Boolean = true) = withContext(Dispatchers.IO) {try {val file = File(chatsDir, "${session.id}.json")- file.writeText(json.encodeToString(serializer, session.copy(lastModified = System.currentTimeMillis())))+ val toWrite =+ if (touch) session.copy(lastModified = System.currentTimeMillis()) else session+ file.writeText(json.encodeToString(serializer, toWrite))} catch (_: Exception) {// Best-effort}diff --git a/app/src/main/java/com/gotcha/data/SampleChatSeeder.kt b/app/src/main/java/com/gotcha/data/SampleChatSeeder.ktnew file mode 100644index 0000000..ff65cf1--- /dev/null+++ b/app/src/main/java/com/gotcha/data/SampleChatSeeder.kt@@ -0,0 +1,40 @@+package com.gotcha.data++import android.content.SharedPreferences+import android.util.Log++/**+ * Puts [SampleChats] on disk the first time Gotcha runs with an empty chat list.+ *+ * Seeding happens at most once per install, and only into a list that has+ * nothing in it: an existing user upgrading into this version keeps the chat+ * list they had, and a user who deletes the samples never sees them come back.+ * Both of those are the same rule — the flag is written whether or not anything+ * was actually seeded, so "have we done this?" is answered once and for all.+ */+internal object SampleChatSeeder {++ const val SEEDED_KEY = "seeded_sample_chats_v1"++ /**+ * Returns true when samples were written. Best-effort: a failure here must+ * not stop the app from opening, so it is logged and the flag left unset,+ * which lets the next launch try again against a still-empty list.+ */+ suspend fun seedIfNeeded(repository: ChatHistoryRepository, prefs: SharedPreferences): Boolean {+ if (prefs.getBoolean(SEEDED_KEY, false)) return false+ return try {+ val seed = repository.listSessions().isEmpty()+ if (seed) {+ // touch = false: the crafted timestamps are what order the two+ // samples in the drawer, and a save-time stamp would flatten them.+ SampleChats.all().forEach { repository.saveSession(it, touch = false) }+ }+ prefs.edit().putBoolean(SEEDED_KEY, true).apply()+ seed+ } catch (e: Exception) {+ Log.w("Gotcha", "seedIfNeeded: failed to seed sample chats", e)+ false+ }+ }+}diff --git a/app/src/main/java/com/gotcha/data/SampleChats.kt b/app/src/main/java/com/gotcha/data/SampleChats.ktnew file mode 100644index 0000000..af1b1cb--- /dev/null+++ b/app/src/main/java/com/gotcha/data/SampleChats.kt@@ -0,0 +1,120 @@+package com.gotcha.data++import com.gotcha.agent.MessageKind+import com.gotcha.agent.UiMessage+import com.gotcha.llm.ChatMessage+import kotlinx.serialization.json.JsonPrimitive++/**+ * The chats seeded into an empty chat list on first run.+ *+ * A fresh install opened on nothing at all, so the one thing a first-time user+ * could not find out was what Gotcha is for. These two transcripts answer that+ * by showing it: a device action with a follow-up (Operator) and a question+ * about the screen (Monitor) — the two halves of the agent selector.+ *+ * They are ordinary sessions, not a special screen: openable, continuable and+ * deletable like any other, and marked [ChatSession.isSample] so the drawer and+ * the transcript header can say where they came from.+ */+internal object SampleChats {++ /** Stable ids: re-seeding can only ever overwrite these, never fork copies. */+ const val DEVICE_ACTION_ID = "sample-device-action"+ const val SCREEN_QA_ID = "sample-screen-qa"++ /**+ * Both samples, oldest first, timestamped just before [now] so the first+ * chat the user actually starts sorts above them in the drawer.+ */+ fun all(now: Long = System.currentTimeMillis()): List<ChatSession> = listOf(+ deviceAction(now - TWO_MINUTES),+ screenQa(now - ONE_MINUTE)+ )++ /**+ * Operator: the agent drives the device. The follow-up is the honest half of+ * the story — Android does not let an app flip Bluetooth, so the agent opens+ * the screen and hands over, which is worth seeing before it happens for real.+ */+ private fun deviceAction(lastModified: Long): ChatSession {+ val exchanges = listOf(+ "Turn on Wi-Fi" to "Wi-Fi is on.",+ "Now turn Bluetooth off" to+ "I've opened the Bluetooth screen for you. Android doesn't let an app flip " ++ "that switch itself, so tap it there and it's done."+ )+ return sample(+ id = DEVICE_ACTION_ID,+ title = "Turn on Wi-Fi",+ agentMode = "OPERATOR",+ lastModified = lastModified,+ exchanges = exchanges,+ display = listOf(+ ui(0, MessageKind.USER, exchanges[0].first),+ ui(1, MessageKind.TOOL, "toggle_wifi: Wi-Fi turned on (was off, now on)."),+ ui(2, MessageKind.ASSISTANT, exchanges[0].second),+ ui(3, MessageKind.USER, exchanges[1].first),+ ui(4, MessageKind.TOOL, "open_setting: Opened Bluetooth."),+ ui(5, MessageKind.ASSISTANT, exchanges[1].second)+ )+ )+ }++ /** Monitor: nothing is changed, the agent only looks and answers. */+ private fun screenQa(lastModified: Long): ChatSession {+ val exchanges = listOf(+ "What's on my screen?" to+ "You're on a flight booking page — a Berlin → Lisbon search for 14 March, " ++ "with the cheapest fare at the top at €89 and a Continue button under it. " ++ "Ask me to compare the options or read out any part of it."+ )+ return sample(+ id = SCREEN_QA_ID,+ title = "What's on my screen?",+ agentMode = "MONITOR",+ lastModified = lastModified,+ exchanges = exchanges,+ display = listOf(+ ui(0, MessageKind.USER, exchanges[0].first),+ ui(1, MessageKind.TOOL, "read_screen: Read the screen (31 elements)."),+ ui(2, MessageKind.ASSISTANT, exchanges[0].second)+ )+ )+ }++ /**+ * The on-screen transcript ([display]) carries the tool bubbles, because+ * that is what a real run looks like. The LLM-shaped history carries only+ * the user/assistant text of [exchanges] — a fabricated `tool_calls` entry+ * with no matching id would make the provider reject the very first request+ * if the user carried the sample on, and the text alone is enough context+ * for them to do so.+ */+ private fun sample(+ id: String,+ title: String,+ agentMode: String,+ lastModified: Long,+ exchanges: List<Pair<String, String>>,+ display: List<UiMessage>+ ) = ChatSession(+ id = id,+ title = title,+ lastModified = lastModified,+ messages = exchanges.flatMap { (user, assistant) ->+ listOf(+ ChatMessage(role = "user", content = JsonPrimitive(user)),+ ChatMessage(role = "assistant", content = JsonPrimitive(assistant))+ )+ },+ displayMessages = display,+ agentMode = agentMode,+ isSample = true+ )++ private fun ui(id: Long, kind: MessageKind, text: String) = UiMessage(id, kind, text)++ private const val ONE_MINUTE = 60_000L+ private const val TWO_MINUTES = 120_000L+}diff --git a/app/src/main/java/com/gotcha/ui/AppDrawer.kt b/app/src/main/java/com/gotcha/ui/AppDrawer.ktindex 0122ab1..48f41d1 100644--- a/app/src/main/java/com/gotcha/ui/AppDrawer.kt+++ b/app/src/main/java/com/gotcha/ui/AppDrawer.kt@@ -124,6 +124,17 @@ fun AppDrawerContent(maxLines = 1,overflow = TextOverflow.Ellipsis)+ // The one thing that distinguishes a seeded chat+ // from one the user held: said on the row rather+ // than only inside, so the list itself is honest.+ if (session.isSample) {+ Text(+ "Sample chat",+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.primary,+ maxLines = 1+ )+ }if (usage != null) {// Tabular figures: this counter ticks while a// reply streams, and proportional digits makediff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 3a5361c..723e6cb 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -349,6 +349,9 @@ fun ChatScreen(state = listState,modifier = Modifier.weight(1f).fillMaxWidth().testTag("message_list")) {+ if (state.viewingSample) {+ item(key = "sample_notice") { SampleChatNotice() }+ }items(state.messages, key = { it.id }) { message ->// Only what arrives after the chat is open animates, and// each id only ever animates once — `add` is false the@@ -1034,3 +1037,29 @@ private fun AgentModeOption(}}}++/**+ * Sits above the first bubble of a chat seeded on first run. The transcript is+ * written in the user's voice, so without this line it would read as something+ * they said and Gotcha did — the notice is what keeps a demonstration from+ * passing itself off as history.+ */+@Composable+private fun SampleChatNotice() {+ Surface(+ color = MaterialTheme.colorScheme.primary.copy(alpha = 0.10f),+ contentColor = MaterialTheme.colorScheme.onSurfaceVariant,+ shape = RoundedCornerShape(12.dp),+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 8.dp)+ .testTag("sample_chat_notice")+ ) {+ Text(+ "Sample chat — this one ships with Gotcha to show what it can do. " ++ "Carry it on, or delete it from the drawer.",+ style = MaterialTheme.typography.labelMedium,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+}diff --git a/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt b/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.ktindex 28d343d..5f215c7 100644--- a/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt+++ b/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt@@ -53,6 +53,31 @@ class ChatHistoryRepositoryTest {assertNull(chatsRepo.loadSession("call-1"))}+ @Test+ fun `the sample marking survives a round-trip and defaults to false`() = runBlocking {+ val dir = tmp.newFolder("chats")+ val repo = ChatHistoryRepository(dir)+ repo.saveSession(session("seeded").copy(isSample = true))+ assertTrue(repo.loadSession("seeded")!!.isSample)+ assertFalse(repo.loadSession("seeded")!!.title.isBlank())++ // A chat written before samples existed has no such field at all.+ File(dir, "legacy.json").writeText(+ """{"id":"legacy","title":"Old","lastModified":0,"messages":[]}"""+ )+ assertFalse(repo.loadSession("legacy")!!.isSample)+ }++ @Test+ fun `saving without touch keeps the session's own timestamp`() = runBlocking {+ val repo = ChatHistoryRepository(tmp.newFolder("chats"))+ repo.saveSession(session("kept").copy(lastModified = 4_200L), touch = false)+ assertEquals(4_200L, repo.loadSession("kept")!!.lastModified)++ repo.saveSession(session("stamped").copy(lastModified = 4_200L))+ assertTrue(repo.loadSession("stamped")!!.lastModified > 4_200L)+ }+@Testfun `deleteSession removes the backing file`() = runBlocking {val dir = tmp.newFolder("calls")diff --git a/app/src/test/java/com/gotcha/data/SampleChatSeederTest.kt b/app/src/test/java/com/gotcha/data/SampleChatSeederTest.ktnew file mode 100644index 0000000..fc58870--- /dev/null+++ b/app/src/test/java/com/gotcha/data/SampleChatSeederTest.kt@@ -0,0 +1,98 @@+package com.gotcha.data++import android.content.Context+import android.content.SharedPreferences+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Seeding is a one-shot, and the cases that matter are the ones where it must+ * NOT happen: an upgrading user with chats of their own, and a user who deleted+ * the samples and does not want them back.+ *+ * Robolectric is here only for [SharedPreferences]; the repository uses its+ * internal File constructor against a temporary folder.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SampleChatSeederTest {++ @get:Rule+ val tmp = TemporaryFolder()++ private lateinit var prefs: SharedPreferences++ @Before+ fun setup() {+ prefs = ApplicationProvider.getApplicationContext<Context>()+ .getSharedPreferences("sample_chat_seeder_test", Context.MODE_PRIVATE)+ prefs.edit().clear().commit()+ }++ private fun repo() = ChatHistoryRepository(tmp.newFolder())++ @Test+ fun `seeds the samples into an empty chat list`() = runBlocking {+ val repo = repo()+ assertTrue(SampleChatSeeder.seedIfNeeded(repo, prefs))+ val seeded = repo.listSessions()+ assertEquals(SampleChats.all().map { it.id }.toSet(), seeded.map { it.id }.toSet())+ assertTrue(seeded.all { it.isSample })+ assertTrue(prefs.getBoolean(SampleChatSeeder.SEEDED_KEY, false))+ }++ @Test+ fun `seeded samples keep their crafted order`() = runBlocking {+ val repo = repo()+ SampleChatSeeder.seedIfNeeded(repo, prefs)+ // listSessions sorts newest first, so the drawer shows the screen Q&A+ // above the device action — the save must not have restamped both.+ assertEquals(+ listOf(SampleChats.SCREEN_QA_ID, SampleChats.DEVICE_ACTION_ID),+ repo.listSessions().map { it.id }+ )+ }++ @Test+ fun `a second run seeds nothing`() = runBlocking {+ val repo = repo()+ SampleChatSeeder.seedIfNeeded(repo, prefs)+ assertFalse(SampleChatSeeder.seedIfNeeded(repo, prefs))+ assertEquals(SampleChats.all().size, repo.listSessions().size)+ }++ @Test+ fun `deleted samples do not come back`() = runBlocking {+ val repo = repo()+ SampleChatSeeder.seedIfNeeded(repo, prefs)+ repo.listSessions().forEach { repo.deleteSession(it.id) }+ assertFalse(SampleChatSeeder.seedIfNeeded(repo, prefs))+ assertTrue(repo.listSessions().isEmpty())+ }++ @Test+ fun `an upgrading user with chats is never seeded`() = runBlocking {+ val repo = repo()+ repo.saveSession(+ ChatSession(id = "mine", title = "My chat", lastModified = 0L, messages = emptyList())+ )+ assertFalse(SampleChatSeeder.seedIfNeeded(repo, prefs))+ assertEquals(listOf("mine"), repo.listSessions().map { it.id })+ // The flag is still written, so emptying the list later does not+ // suddenly turn an established install into a fresh one.+ assertTrue(prefs.getBoolean(SampleChatSeeder.SEEDED_KEY, false))+ repo.deleteSession("mine")+ assertFalse(SampleChatSeeder.seedIfNeeded(repo, prefs))+ assertTrue(repo.listSessions().isEmpty())+ }+}diff --git a/app/src/test/java/com/gotcha/data/SampleChatsTest.kt b/app/src/test/java/com/gotcha/data/SampleChatsTest.ktnew file mode 100644index 0000000..fc74cd6--- /dev/null+++ b/app/src/test/java/com/gotcha/data/SampleChatsTest.kt@@ -0,0 +1,134 @@+package com.gotcha.data++import com.gotcha.agent.MessageKind+import com.gotcha.tools.AgentMode+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * [SampleChats] is hand-written content that the app persists and then replays+ * as if it were a real transcript. These are the invariants that replay relies+ * on — most importantly that continuing a sample sends a history the provider+ * will accept.+ */+class SampleChatsTest {++ private val samples = SampleChats.all(now = 1_000_000L)++ @Test+ fun `ships one or two samples with stable unique ids`() {+ assertTrue("Expected 1-2 samples, got ${samples.size}", samples.size in 1..2)+ assertEquals(samples.size, samples.map { it.id }.distinct().size)+ assertEquals(+ listOf(SampleChats.DEVICE_ACTION_ID, SampleChats.SCREEN_QA_ID).sorted(),+ samples.map { it.id }.sorted()+ )+ }++ @Test+ fun `every sample is marked as one and has a title`() {+ samples.forEach { sample ->+ assertTrue("Unmarked sample: ${sample.id}", sample.isSample)+ assertTrue("Blank title in ${sample.id}", sample.title.isNotBlank())+ }+ }++ @Test+ fun `samples are dated before now so a real chat sorts above them`() {+ val now = 1_000_000L+ SampleChats.all(now).forEach { sample ->+ assertTrue("${sample.id} is not in the past", sample.lastModified < now)+ }+ // And they are ordered relative to each other, so the drawer can't shuffle.+ assertEquals(+ SampleChats.all(now).map { it.lastModified }.distinct().size,+ samples.size+ )+ }++ @Test+ fun `each sample shows a short exchange, opened by the user`() {+ samples.forEach { sample ->+ assertTrue("${sample.id} has no transcript", sample.displayMessages.isNotEmpty())+ assertEquals(+ "${sample.id} must open with the user",+ MessageKind.USER,+ sample.displayMessages.first().kind+ )+ assertEquals(+ "${sample.id} must end with the assistant",+ MessageKind.ASSISTANT,+ sample.displayMessages.last().kind+ )+ val userTurns = sample.displayMessages.count { it.kind == MessageKind.USER }+ assertTrue("${sample.id} shows $userTurns exchanges, expected 1-2", userTurns in 1..2)+ assertTrue(+ "${sample.id} has a blank bubble",+ sample.displayMessages.all { it.text.isNotBlank() }+ )+ }+ }++ @Test+ fun `display message ids are unique and ordered`() {+ // The transcript is restored verbatim and keyed by id in the LazyColumn,+ // and ChatViewModel resumes numbering from the maximum.+ samples.forEach { sample ->+ val ids = sample.displayMessages.map { it.id }+ assertEquals("Duplicate ids in ${sample.id}", ids.size, ids.distinct().size)+ assertEquals("Unordered ids in ${sample.id}", ids.sorted(), ids)+ }+ }++ @Test+ fun `history is plain alternating text with no orphan tool calls`() {+ samples.forEach { sample ->+ val roles = sample.messages.map { it.role }+ assertEquals(+ "${sample.id} must alternate user/assistant",+ List(roles.size) { if (it % 2 == 0) "user" else "assistant" },+ roles+ )+ sample.messages.forEach { message ->+ assertTrue("Empty history message in ${sample.id}", message.hasText)+ // A fabricated tool call has no result to match it, and the+ // provider rejects the whole request if the user carries on.+ assertNull("Fabricated tool_calls in ${sample.id}", message.toolCalls)+ assertNull("Fabricated tool_call_id in ${sample.id}", message.toolCallId)+ }+ }+ }++ @Test+ fun `history matches what the transcript shows the user saying`() {+ samples.forEach { sample ->+ assertEquals(+ "${sample.id}: history and transcript disagree",+ sample.displayMessages.filter { it.kind == MessageKind.USER }.map { it.text },+ sample.messages.filter { it.role == "user" }.map { it.textContent }+ )+ }+ }++ @Test+ fun `agent mode is a real mode and both modes are demonstrated`() {+ val modes = samples.map { sample ->+ val raw = requireNotNull(sample.agentMode) { "${sample.id} has no agent mode" }+ AgentMode.valueOf(raw)+ }+ assertEquals("Samples should show both halves of the selector", 2, modes.distinct().size)+ }++ @Test+ fun `samples start with a clean slate`() {+ // Seeded chats were never run, so there is nothing to count or share:+ // a non-zero token count would show a context readout in the drawer for+ // a conversation that never cost anything.+ samples.forEach { sample ->+ assertEquals(0, sample.tokenCount)+ assertTrue(sample.runSummaries.isEmpty())+ }+ }+}