Skip to content

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.

test: cover the seeder's partial write and the view-only persona handoff

Durganshud60e61d745c6
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index b461d35..e54e100 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -726,8 +726,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
* operates on it. Only called from [sendMessage], which is gated on nothing
* else running, so re-pointing the engine here is safe. Reloads the session's
* LLM history from disk when the engine had drifted to another session.
+ *
+ * `internal` rather than private so the handoff can be tested directly: it is
+ * where a persona picked while another chat was running finally reaches the
+ * engine, and [sendMessage] itself can't be driven from a JVM test.
*/
- private suspend fun bindEngineToViewedSession(viewedId: String?) {
+ internal suspend fun bindEngineToViewedSession(viewedId: String?) {
if (viewedId != null && agentEngine.sessionId != viewedId) {
val saved = historyRepository.loadSession(viewedId)
agentEngine.history.clear()
diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
index 7e5efeb..c7b4b37 100644
--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
@@ -95,8 +95,10 @@ class ChatHistoryRepository internal constructor(private val chatsDir: File) {
* 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.
+ *
+ * Returns true when the write succeeded. Best-effort by design: most callers
+ * ignore it, and [SampleChatSeeder] is the one that doesn't.
*/
- /** Returns true when the write succeeded. Best-effort by design: most callers ignore it. */
suspend fun saveSession(session: ChatSession, touch: Boolean = true): Boolean = withContext(Dispatchers.IO) {
try {
val file = File(chatsDir, "${session.id}.json")
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.kt
index f39f188..9020f93 100644
--- a/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.kt
@@ -62,9 +62,26 @@ class ChatViewModelPersonaTest {
}
/** The engine is private; its persona is what the system prompt is built from. */
- private fun enginePersonaId(): String? {
+ private fun engine(): AgentEngine {
val field = ChatViewModel::class.java.getDeclaredField("agentEngine").apply { isAccessible = true }
- return (field.get(viewModel) as AgentEngine).sessionPersonaId
+ return field.get(viewModel) as AgentEngine
+ }
+
+ private fun enginePersonaId(): String? = engine().sessionPersonaId
+
+ /** Which session the engine is bound to — the one a persona would apply to. */
+ private fun enginePersonaOwner(): String? = engine().sessionId
+
+ /**
+ * Mark [id] as the session with a run in flight (null once it finishes). The
+ * real path runs an agent loop over the network, which this tier can't drive.
+ */
+ private fun seedRunningSession(id: String?) {
+ val stateField = ChatViewModel::class.java.getDeclaredField("_uiState").apply { isAccessible = true }
+
+ @Suppress("UNCHECKED_CAST")
+ val flow = stateField.get(viewModel) as MutableStateFlow<ChatUiState>
+ flow.value = flow.value.copy(runningSessionId = id)
}
private fun seedMessages(messages: List<UiMessage>) {
@@ -129,6 +146,43 @@ class ChatViewModelPersonaTest {
assertNull(enginePersonaId())
}
+ /**
+ * The view-only transition: a run is in flight in another chat, so the engine
+ * stays bound to that one and must not pick up a persona chosen on the blank
+ * chat the user browsed to. The persona waits in UI state and reaches the
+ * engine only when the viewed chat becomes the engine's, at send time.
+ */
+ @Test
+ fun `a persona picked while another chat runs never touches the running one`() {
+ val runningId = requireNotNull(viewModel.uiState.value.activeSessionId)
+ seedRunningSession(runningId)
+ // Browse to a new blank chat; the engine stays on the running session.
+ viewModel.clearChat()
+ assertEquals(runningId, enginePersonaOwner())
+
+ viewModel.setPersona(requireNotNull(personaById("doctor")))
+
+ assertEquals("doctor", viewModel.uiState.value.activePersonaId)
+ assertNull("the running chat's prompt must not gain a persona", enginePersonaId())
+ }
+
+ @Test
+ fun `the persona reaches the engine when the viewed chat becomes the engine's`() = runBlocking {
+ val runningId = requireNotNull(viewModel.uiState.value.activeSessionId)
+ seedRunningSession(runningId)
+ viewModel.clearChat()
+ viewModel.setPersona(requireNotNull(personaById("chef")))
+ val viewedId = requireNotNull(viewModel.uiState.value.activeSessionId)
+
+ // The run finishes and the user sends their first message here: sendMessage
+ // binds the engine to the viewed session before running it.
+ seedRunningSession(null)
+ viewModel.bindEngineToViewedSession(viewedId)
+
+ assertEquals(viewedId, enginePersonaOwner())
+ assertEquals("chef", enginePersonaId())
+ }
+
@Test
fun `a saved session carries its persona back`() = runBlocking {
historyRepository.saveSession(
diff --git a/app/src/test/java/com/gotcha/data/SampleChatSeederTest.kt b/app/src/test/java/com/gotcha/data/SampleChatSeederTest.kt
index fc58870..a55cb66 100644
--- a/app/src/test/java/com/gotcha/data/SampleChatSeederTest.kt
+++ b/app/src/test/java/com/gotcha/data/SampleChatSeederTest.kt
@@ -80,6 +80,37 @@ class SampleChatSeederTest {
assertTrue(repo.listSessions().isEmpty())
}
+ /**
+ * The half-written case, which is the one that can strand an install without
+ * samples forever: if a failed attempt left the first sample behind, the next
+ * launch's "is the list empty?" check would see it and skip retrying.
+ *
+ * The failure is made real rather than mocked — a directory sitting where the
+ * second sample's file belongs makes that one write throw, and only that one.
+ */
+ @Test
+ fun `a partial write leaves nothing behind and retries on the next launch`() = runBlocking {
+ val dir = tmp.newFolder()
+ val repo = ChatHistoryRepository(dir)
+ val blocker = java.io.File(dir, "${SampleChats.SCREEN_QA_ID}.json").apply { mkdirs() }
+
+ assertFalse(SampleChatSeeder.seedIfNeeded(repo, prefs))
+ assertTrue(
+ "the sample that did write must be cleaned up, or the retry never runs",
+ repo.listSessions().isEmpty()
+ )
+ assertFalse(
+ "the flag must stay unset so the next launch tries again",
+ prefs.getBoolean(SampleChatSeeder.SEEDED_KEY, false)
+ )
+
+ // Next launch, with whatever blocked the write gone.
+ assertTrue(blocker.delete())
+ assertTrue(SampleChatSeeder.seedIfNeeded(repo, prefs))
+ assertEquals(SampleChats.all().map { it.id }.toSet(), repo.listSessions().map { it.id }.toSet())
+ assertTrue(prefs.getBoolean(SampleChatSeeder.SEEDED_KEY, false))
+ }
+
@Test
fun `an upgrading user with chats is never seeded`() = runBlocking {
val repo = repo()