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.

feat: implement message editing and revert functionality with history truncation logic and UI support

Rishabh Bajpaifc17c6e756d7
diff --git a/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt b/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt
index 9d7889a..6f88bce 100644
--- a/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt
+++ b/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt
@@ -1,10 +1,16 @@
package com.gotcha
+import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.hasText
+import androidx.compose.ui.test.isEnabled
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
+import androidx.compose.ui.test.performTouchInput
+import androidx.compose.ui.test.longClick
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -12,6 +18,7 @@ import com.gotcha.testutil.MOCK_REPLY_OK
import com.gotcha.testutil.MockLlm
import com.gotcha.testutil.TestSeed
import org.junit.After
+import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -32,6 +39,37 @@ class ChatRoundTripTest {
mockLlm.shutdown()
}
+ /**
+ * Type [text], then wait until the send button is actually enabled before
+ * clicking. The send button only appears once the composer has text, and it
+ * stays disabled while a run is in flight — so this helper inherently waits
+ * for the previous run to finish before sending the next message.
+ */
+ private fun sendText(text: String) {
+ composeRule.onNodeWithTag("chat_input").performTextInput(text)
+ composeRule.waitUntil(timeoutMillis = 15_000) {
+ composeRule.onAllNodes(hasTestTag("send_button") and isEnabled())
+ .fetchSemanticsNodes().isNotEmpty()
+ }
+ composeRule.onNodeWithTag("send_button").performClick()
+ }
+
+ private fun waitForReply() {
+ composeRule.waitUntil(timeoutMillis = 15_000) {
+ composeRule.onAllNodes(hasText(MOCK_REPLY_OK, substring = true))
+ .fetchSemanticsNodes().isNotEmpty()
+ }
+ }
+
+ /** Consumes and returns the request bodies recorded since [previousCount]. */
+ private fun drainSince(previousCount: Int): List<String> {
+ val bodies = mutableListOf<String>()
+ while (mockLlm.server.requestCount > previousCount) {
+ mockLlm.server.takeRequest()?.let { bodies.add(it.body.readUtf8()) }
+ }
+ return bodies
+ }
+
@Test
fun sendingPrompt_showsMockReply() {
mockLlm.start()
@@ -41,16 +79,111 @@ class ChatRoundTripTest {
scenario = ActivityScenario.launch(MainActivity::class.java)
composeRule.waitForIdle()
- composeRule.onNodeWithTag("chat_input").performTextInput("hello")
- composeRule.onNodeWithTag("send_button").performClick()
+ sendText("hello")
- composeRule.waitUntil(timeoutMillis = 15_000) {
- composeRule.onAllNodes(hasText(MOCK_REPLY_OK, substring = true))
- .fetchSemanticsNodes().isNotEmpty()
- }
+ waitForReply()
val request = mockLlm.server.takeRequest()
assertTrue(request.path?.endsWith("/chat/completions") == true)
assertTrue(request.body.readUtf8().contains("test-model"))
}
+
+ @Test
+ fun editMessage_truncatesHistoryAndRegenerates() {
+ mockLlm.start()
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedConfigured(context, baseUrl = mockLlm.baseUrl, model = "test-model")
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ sendText("first prompt")
+ waitForReply()
+ sendText("second prompt")
+ waitForReply()
+ // run2's request + the run1 title-generation request must both have landed
+ // and the final run cleaned up before we snapshot, so the edit's
+ // regeneration is the only new request.
+ composeRule.waitUntil(timeoutMillis = 15_000) { mockLlm.server.requestCount >= 3 }
+ composeRule.waitForIdle()
+ val since = mockLlm.server.requestCount
+
+ composeRule.onNode(hasText("first prompt")).performTouchInput { longClick() }
+ composeRule.waitForIdle()
+ composeRule.onNodeWithText("Edit message").performClick()
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("chat_input").performTextClearance()
+ composeRule.onNodeWithTag("chat_input").performTextInput("EDITED first")
+ // Wait for the previous run to finish (the send button stays disabled
+ // while busy) so the edit isn't dropped by the busy guard.
+ composeRule.waitUntil(timeoutMillis = 15_000) {
+ composeRule.onAllNodes(hasTestTag("send_button") and isEnabled())
+ .fetchSemanticsNodes().isNotEmpty()
+ }
+ composeRule.onNodeWithTag("send_button").performClick()
+
+ composeRule.waitUntil(timeoutMillis = 15_000) { mockLlm.server.requestCount > since }
+
+ val bodies = drainSince(since)
+ assertTrue(
+ "regeneration request must contain the edited prompt",
+ bodies.any { it.contains("EDITED first") }
+ )
+ assertFalse(
+ "dropped turn must not be sent to the LLM",
+ bodies.any { it.contains("second prompt") }
+ )
+ assertFalse(
+ "old prompt must not be sent to the LLM",
+ bodies.any { it.contains("first prompt") }
+ )
+ }
+
+ @Test
+ fun revertToMessage_deletesSubsequentMessages() {
+ mockLlm.start()
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedConfigured(context, baseUrl = mockLlm.baseUrl, model = "test-model")
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ sendText("first prompt")
+ waitForReply()
+ sendText("second prompt")
+ waitForReply()
+ composeRule.waitUntil(timeoutMillis = 15_000) { mockLlm.server.requestCount >= 3 }
+ composeRule.waitForIdle()
+ val since = mockLlm.server.requestCount
+
+ composeRule.onNode(hasText("first prompt")).performTouchInput { longClick() }
+ composeRule.waitForIdle()
+ composeRule.onNodeWithText("Revert to this message").performClick()
+ composeRule.waitForIdle()
+ composeRule.onNodeWithText("Revert").performClick()
+ composeRule.waitForIdle()
+
+ assertTrue(
+ "reverted bubble must disappear from the transcript",
+ composeRule.onAllNodes(hasText("second prompt")).fetchSemanticsNodes().isEmpty()
+ )
+
+ sendText("third prompt")
+ composeRule.waitUntil(timeoutMillis = 15_000) { mockLlm.server.requestCount > since }
+
+ val bodies = drainSince(since)
+ assertTrue(
+ "continuing after revert must send the new prompt",
+ bodies.any { it.contains("third prompt") }
+ )
+ assertTrue(
+ "the reverted-to turn must be preserved",
+ bodies.any { it.contains("first prompt") }
+ )
+ assertFalse(
+ "the dropped turn must never be sent again",
+ bodies.any { it.contains("second prompt") }
+ )
+ }
}
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 26f898a..29173ae 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -769,7 +769,11 @@ class MainActivity : ComponentActivity() {
},
onCreateShareCard = {
sharePoster.open(chatViewModel.activeSessionRunSummaries())
- }
+ },
+ onEditMessage = { id, text, imageBase64 ->
+ chatViewModel.editMessage(id, text, imageBase64)
+ },
+ onRevertMessage = { id -> chatViewModel.revertTo(id) }
)
}
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatHistoryEdit.kt b/app/src/main/java/com/gotcha/agent/ChatHistoryEdit.kt
new file mode 100644
index 0000000..4c18257
--- /dev/null
+++ b/app/src/main/java/com/gotcha/agent/ChatHistoryEdit.kt
@@ -0,0 +1,64 @@
+package com.gotcha.agent
+
+import com.gotcha.llm.ChatMessage
+
+/**
+ * Pure helpers that map between the on-screen transcript ([UiMessage] bubbles)
+ * and the LLM-shaped [AgentEngine.history] for the Edit / Revert message
+ * features.
+ *
+ * The two lists do not map 1:1: a single user turn expands in [history] into
+ * many messages — the prompt, assistant tool-call rounds, `tool` results, and
+ * *injected* vision `user` messages for screenshots and read image files. So
+ * truncation is always computed on **real user prompts** only, using the same
+ * heuristics `rebuildUiMessagesFrom` applies when reconstructing a transcript.
+ */
+
+/**
+ * True when [msg] is a genuine user prompt rather than an injected screen or
+ * image observation. The markers mirror the screen-observation heuristics the
+ * transcript rebuild applies to `user` messages, plus the image-file injection
+ * prefix used by `AgentEngine.handleImageResult`.
+ */
+internal fun isRealUserPrompt(msg: ChatMessage): Boolean {
+ if (msg.role != "user") return false
+ val t = msg.textContent
+ return !(
+ t.startsWith("[Screen State]") ||
+ t.startsWith("Screen text:") ||
+ t.contains("── UI Elements ──") ||
+ t.startsWith("The assistant read an image file:")
+ )
+}
+
+/**
+ * Indices into [history] of the real user prompts, in order. These correlate
+ * 1:1 with the `USER` bubbles in the transcript, since the only `USER` bubbles
+ * ever emitted come from `ChatViewModel.sendMessage`/`editMessage`.
+ */
+internal fun userTurnStarts(history: List<ChatMessage>): List<Int> =
+ history.indices.filter { isRealUserPrompt(history[it]) }
+
+/**
+ * Truncates [history] to the [turnIndex]-th real user turn.
+ *
+ * - [dropTurn] = true (edit): the target prompt is removed so its turn is
+ * replaced by the edited text and a fresh reply.
+ * - [dropTurn] = false (revert): the target prompt becomes the last message.
+ *
+ * Turn tails (tool rounds, sub-agent results, injected observations) are
+ * removed together with their prompt because truncation is by the **next** real
+ * prompt's start. Returns the original list when [turnIndex] is out of range.
+ */
+internal fun truncateHistoryAtTurn(
+ history: List<ChatMessage>,
+ turnIndex: Int,
+ dropTurn: Boolean
+): List<ChatMessage> {
+ val start = userTurnStarts(history).getOrNull(turnIndex) ?: return history
+ // Materialise an independent copy: the callers swap this result into the live
+ // history (clear() + addAll), and a subList view would go stale — and throw a
+ // ConcurrentModificationException — the moment the backing list is cleared.
+ val kept = history.subList(0, start).toList()
+ return if (dropTurn) kept else kept + history[start]
+}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 01c1a66..16eb141 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -385,13 +385,22 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")
return
}
- currentRunIsVoice = isVoiceInput || lastInputWasVoice
- lastInputWasVoice = false
val msg = if (imageBase64 != null) {
visionUserMessage(trimmed, imageBase64, "jpeg")
} else {
ChatMessage(role = "user", content = JsonPrimitive(trimmed))
}
+ launchUserRun(msg, imageBase64, isVoiceInput)
+ }
+
+ /**
+ * Appends [msg] to the viewed session's LLM history, shows the USER bubble,
+ * and starts an agent run. Shared by [sendMessage] and [editMessage], so both
+ * paths go through the same busy-marking, run, and NonCancellable cleanup.
+ */
+ private fun launchUserRun(msg: ChatMessage, imageBase64: String?, isVoiceInput: Boolean) {
+ currentRunIsVoice = isVoiceInput || lastInputWasVoice
+ lastInputWasVoice = false
val viewedId = _uiState.value.activeSessionId
agentJob = viewModelScope.launch {
// Ensure the engine is bound to the session being viewed. After a
@@ -402,39 +411,144 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
agentEngine.history += msg
appendEngineUi(MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" }, imageBase64)
- val runningId = agentEngine.sessionId
- val runningTitle = engineTranscript.firstOrNull { it.kind == MessageKind.USER }
- ?.text?.take(30) ?: "New Chat"
+ val runningId = agentEngine.sessionId ?: return@launch
+ executeRun(engineAgent, runningId)
+ }
+ }
+
+ /** Busy-marking + agent run + NonCancellable cleanup, from the old sendMessage body. */
+ private suspend fun executeRun(agent: AgentMode, runningId: String) {
+ val runningTitle = engineTranscript.firstOrNull { it.kind == MessageKind.USER }
+ ?.text?.take(30) ?: "New Chat"
+ _uiState.update {
+ it.copy(
+ isBusy = true,
+ runningSessionId = runningId,
+ runningSessionTitle = runningTitle
+ )
+ }
+ runHadError = false
+ try {
+ agentEngine.run(agent)
+ } catch (_: CancellationException) {
+ appendEngineUi(MessageKind.ERROR, "Agent was interrupted by the user.")
+ } finally {
+ withContext(NonCancellable) {
+ currentRunIsVoice = false
+ lastInputWasVoice = false
+ agentEngine.saveCurrentSession()
+ _uiState.update {
+ it.copy(
+ isBusy = false,
+ runningSessionId = null,
+ runningSessionTitle = null,
+ activity = if (viewingEngineSession()) null else it.activity,
+ subAgentRunning = if (viewingEngineSession()) null else it.subAgentRunning,
+ subAgentCurrentAction = if (viewingEngineSession()) null else it.subAgentCurrentAction
+ )
+ }
+ agentJob = null
+ }
+ }
+ }
+
+ /**
+ * Replaces the user message [targetId] with [newText], keeping the original
+ * image attachment unless a new one was picked. The target's whole turn and
+ * everything after it are dropped from both the LLM history and the on-screen
+ * transcript, then the agent re-runs immediately so a fresh reply is
+ * generated from the edited history.
+ */
+ fun editMessage(targetId: Long, newText: String, imageBase64: String?) {
+ val trimmed = newText.trim()
+ if (trimmed.isEmpty() && imageBase64 == null) return
+ if (_uiState.value.isBusy || _uiState.value.runningSessionId != null) return
+ if (client == null) {
+ appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")
+ return
+ }
+ currentRunIsVoice = false
+ lastInputWasVoice = false
+ val viewedId = _uiState.value.activeSessionId
+ agentJob = viewModelScope.launch {
+ bindEngineToViewedSession(viewedId)
+ val transcript = engineTranscript
+ val target = transcript.firstOrNull { it.id == targetId && it.kind == MessageKind.USER }
+ ?: return@launch
+ val k = transcript.takeWhile { it.id != targetId }.count { it.kind == MessageKind.USER }
+ // History/transcript desync guard (e.g. after compaction the transcript
+ // is reset), so a stale target id bails without partial truncation.
+ if (k >= userTurnStarts(agentEngine.history).size) return@launch
+ val kept = truncateHistoryAtTurn(agentEngine.history, k, dropTurn = true)
+ agentEngine.history.clear()
+ agentEngine.history.addAll(kept)
+ engineTranscript = transcript.take(transcript.indexOf(target))
+ _uiState.update {
+ it.copy(
+ messages = engineTranscript,
+ activity = null,
+ subAgentRunning = null,
+ subAgentCurrentAction = null
+ )
+ }
+ // Never promote undone work on the share card.
+ agentEngine.restoreRunSummaries(emptyList())
+ val editImage = imageBase64 ?: target.imageBase64
+ val msg = if (editImage != null) {
+ visionUserMessage(trimmed, editImage, "jpeg")
+ } else {
+ ChatMessage(role = "user", content = JsonPrimitive(trimmed))
+ }
+ agentEngine.history += msg
+ appendEngineUi(MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" }, editImage)
+ executeRun(engineAgent, agentEngine.sessionId ?: return@launch)
+ }
+ }
+
+ /**
+ * Truncates the conversation so the user message [targetId] becomes the last
+ * message: its own replies and everything after are dropped from both the LLM
+ * history and the on-screen transcript, letting the user continue from a
+ * clean state. No LLM call, so it works even without a configured API key.
+ */
+ fun revertTo(targetId: Long) {
+ if (_uiState.value.isBusy || _uiState.value.runningSessionId != null) return
+ val viewedId = _uiState.value.activeSessionId
+ viewModelScope.launch {
+ bindEngineToViewedSession(viewedId)
+ val transcript = engineTranscript
+ val target = transcript.firstOrNull { it.id == targetId && it.kind == MessageKind.USER }
+ ?: return@launch
+ val k = transcript.takeWhile { it.id != targetId }.count { it.kind == MessageKind.USER }
+ // History/transcript desync guard (e.g. after compaction the transcript
+ // is reset), so a stale target id bails without partial truncation.
+ if (k >= userTurnStarts(agentEngine.history).size) return@launch
+ val kept = truncateHistoryAtTurn(agentEngine.history, k, dropTurn = false)
+ agentEngine.history.clear()
+ agentEngine.history.addAll(kept)
+ engineTranscript = transcript.take(transcript.indexOf(target) + 1)
_uiState.update {
it.copy(
- isBusy = true,
- runningSessionId = runningId,
- runningSessionTitle = runningTitle
+ messages = engineTranscript,
+ activity = null,
+ subAgentRunning = null,
+ subAgentCurrentAction = null
)
}
- runHadError = false
- try {
- agentEngine.run(engineAgent)
- } catch (_: CancellationException) {
- appendEngineUi(MessageKind.ERROR, "Agent was interrupted by the user.")
- } finally {
- withContext(NonCancellable) {
- currentRunIsVoice = false
- lastInputWasVoice = false
- agentEngine.saveCurrentSession()
- _uiState.update {
- it.copy(
- isBusy = false,
- runningSessionId = null,
- runningSessionTitle = null,
- activity = if (viewingEngineSession()) null else it.activity,
- subAgentRunning = if (viewingEngineSession()) null else it.subAgentRunning,
- subAgentCurrentAction = if (viewingEngineSession()) null else it.subAgentCurrentAction
- )
- }
- agentJob = null
- }
+ // Re-derive the context readout from the truncated history, matching
+ // the engine's own estimate units so the meter doesn't lie after revert.
+ val tokens = kept.sumOf { it.textContent.length / 4 } + AgentEngine.PROMPT_OVERHEAD_TOKENS
+ agentEngine.tokenCount = tokens
+ applyContextUsage(tokens)
+ // Keep the drawer's live overlay in sync so the reverted session's
+ // row doesn't keep showing the pre-truncation count.
+ agentEngine.sessionId?.let { sid ->
+ _liveTokenBySession.update { it + (sid to tokens) }
}
+ // Never promote undone work on the share card.
+ agentEngine.restoreRunSummaries(emptyList())
+ agentEngine.saveCurrentSession()
+ refreshSessions()
}
}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index c446b5d..98a4542 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -29,6 +29,7 @@ import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.automirrored.rounded.VolumeOff
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Share
@@ -104,7 +105,9 @@ fun ChatScreen(
onStopRecording: ((String) -> Unit) -> Unit = {},
onExportChat: () -> Unit = {},
onReturnToRunning: () -> Unit = {},
- onCreateShareCard: () -> Unit = {}
+ onCreateShareCard: () -> Unit = {},
+ onEditMessage: (Long, String, String?) -> Unit = { _, _, _ -> },
+ onRevertMessage: (Long) -> Unit = { _ -> }
) {
val skin = LocalSkin.current
val isHome = state.messages.isEmpty()
@@ -116,6 +119,10 @@ fun ChatScreen(
var inputWasVoice by rememberSaveable { mutableStateOf(false) }
var pendingImageUri by rememberSaveable { mutableStateOf<Uri?>(null) }
var pendingImageBase64 by rememberSaveable { mutableStateOf<String?>(null) }
+ // Id of the user message being edited (composer pre-filled until sent/cancelled).
+ var editingMessageId by rememberSaveable { mutableStateOf<Long?>(null) }
+ // Id of the user message pending a revert confirmation.
+ var pendingRevertId by remember { mutableStateOf<Long?>(null) }
val listState = rememberLazyListState()
// Everything already in the transcript when this chat opened is history, and
@@ -293,7 +300,17 @@ fun ChatScreen(
message = message,
onSpeak = onSpeak,
isSpeaking = state.isSpeaking,
- onStopSpeaking = onStopSpeaking
+ onStopSpeaking = onStopSpeaking,
+ onEdit = { target ->
+ editingMessageId = target.id
+ // "(image attached)" is the display placeholder for an
+ // image-only prompt; leave the composer empty for those.
+ input = if (target.text == "(image attached)") "" else target.text
+ inputWasVoice = false
+ pendingImageUri = null
+ pendingImageBase64 = target.imageBase64
+ },
+ onRevert = { target -> pendingRevertId = target.id }
)
}
}
@@ -470,6 +487,49 @@ fun ChatScreen(
}
}
+ // "Editing message" banner above the composer while an edit is armed.
+ val editingTarget = editingMessageId?.let { id -> state.messages.firstOrNull { it.id == id } }
+ if (editingTarget != null) {
+ Surface(
+ color = MaterialTheme.colorScheme.secondaryContainer,
+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
+ shape = RoundedCornerShape(skin.cornerSmall),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 4.dp)
+ ) {
+ Row(
+ modifier = Modifier.padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Icon(
+ Icons.Default.Edit,
+ contentDescription = null,
+ modifier = Modifier.size(16.dp)
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(
+ "Editing message — sending will rewrite the conversation from here",
+ style = MaterialTheme.typography.bodySmall,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f)
+ )
+ TextButton(
+ onClick = {
+ editingMessageId = null
+ pendingImageUri = null
+ pendingImageBase64 = null
+ input = ""
+ inputWasVoice = false
+ }
+ ) {
+ Text("Cancel")
+ }
+ }
+ }
+ }
+
// One pill rather than a docked row: it floats clear of the bottom
// edge, and the send button is the only saturated fill on the screen.
Surface(
@@ -577,7 +637,7 @@ fun ChatScreen(
CircularProgressIndicator(modifier = Modifier.size(20.dp))
}
}
- input.isBlank() && pendingImageBase64 == null -> {
+ input.isBlank() && pendingImageBase64 == null && editingMessageId == null -> {
IconButton(
onClick = onStartListening,
modifier = Modifier.size(40.dp),
@@ -589,7 +649,13 @@ fun ChatScreen(
else -> {
IconButton(
onClick = {
- onSend(input, pendingImageBase64, inputWasVoice)
+ val editTarget = editingMessageId
+ if (editTarget != null) {
+ onEditMessage(editTarget, input, pendingImageBase64)
+ } else {
+ onSend(input, pendingImageBase64, inputWasVoice)
+ }
+ editingMessageId = null
input = ""
inputWasVoice = false
pendingImageUri = null
@@ -659,6 +725,33 @@ fun ChatScreen(
confirmButton = { TextButton(onClick = { onAnswer(null) }) { Text("Skip") } }
)
}
+
+ val pendingRevert = pendingRevertId?.let { id -> state.messages.firstOrNull { it.id == id } }
+ if (pendingRevert != null) {
+ SkinAlertDialog(
+ onDismissRequest = { pendingRevertId = null },
+ title = { Text("Revert to this message?") },
+ text = {
+ Text(
+ "This will delete all messages after this one, " +
+ "then let you continue the conversation from here.",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ },
+ confirmButton = {
+ Button(
+ onClick = {
+ val id = pendingRevert.id
+ pendingRevertId = null
+ onRevertMessage(id)
+ }
+ ) { Text("Revert") }
+ },
+ dismissButton = {
+ TextButton(onClick = { pendingRevertId = null }) { Text("Cancel") }
+ }
+ )
+ }
}
/**
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
index e182ca6..67f9a54 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -65,7 +65,9 @@ fun MessageBubble(
message: UiMessage,
onSpeak: (String) -> Unit = {},
isSpeaking: Boolean = false,
- onStopSpeaking: () -> Unit = {}
+ onStopSpeaking: () -> Unit = {},
+ onEdit: (UiMessage) -> Unit = {},
+ onRevert: (UiMessage) -> Unit = {}
) {
val context = LocalContext.current
val isUser = message.kind == MessageKind.USER
@@ -268,6 +270,22 @@ fun MessageBubble(
expanded = showMenu,
onDismissRequest = { showMenu = false }
) {
+ if (isUser) {
+ DropdownMenuItem(
+ text = { Text("Edit message") },
+ onClick = {
+ showMenu = false
+ onEdit(message)
+ }
+ )
+ DropdownMenuItem(
+ text = { Text("Revert to this message") },
+ onClick = {
+ showMenu = false
+ onRevert(message)
+ }
+ )
+ }
DropdownMenuItem(
text = { Text("Copy as text") },
onClick = {
diff --git a/app/src/test/java/com/gotcha/agent/ChatHistoryEditTest.kt b/app/src/test/java/com/gotcha/agent/ChatHistoryEditTest.kt
new file mode 100644
index 0000000..d329357
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ChatHistoryEditTest.kt
@@ -0,0 +1,192 @@
+package com.gotcha.agent
+
+import com.gotcha.llm.ChatMessage
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Coverage for the pure history-truncation helpers backing the Edit / Revert
+ * message features. These mirror the screen-observation heuristics the
+ * transcript rebuild applies, so injected vision messages never count as user
+ * turns and are always dropped together with their parent turn.
+ */
+class ChatHistoryEditTest {
+
+ private fun msg(role: String, text: String) = ChatMessage(
+ role = role,
+ content = JsonPrimitive(text)
+ )
+
+ // ---- isRealUserPrompt ----
+
+ @Test
+ fun `real prompts are detected`() {
+ assertTrue(isRealUserPrompt(msg("user", "What is in this image?")))
+ assertTrue(isRealUserPrompt(msg("user", "Send a text to mom")))
+ }
+
+ @Test
+ fun `non user roles are rejected`() {
+ assertFalse(isRealUserPrompt(msg("assistant", "Sure thing.")))
+ assertFalse(isRealUserPrompt(msg("tool", "result: ok")))
+ assertFalse(isRealUserPrompt(msg("system", "behave")))
+ }
+
+ @Test
+ fun `injected screen and image observations are rejected`() {
+ assertFalse(isRealUserPrompt(msg("user", "[Screen State]")))
+ assertFalse(isRealUserPrompt(msg("user", "Screen text: Hello")))
+ assertFalse(isRealUserPrompt(msg("user", "x\n── UI Elements ──\nfoo")))
+ assertFalse(isRealUserPrompt(msg("user", "The assistant read an image file: shot.png")))
+ }
+
+ // ---- userTurnStarts ----
+
+ @Test
+ fun `turn starts point only at real prompts`() {
+ val history = listOf(
+ msg("user", "First question"),
+ msg("assistant", "Working…"),
+ msg("tool", "result: 1"),
+ msg("user", "[Screen State]"), // injected during a run
+ msg("user", "Second question"),
+ msg("assistant", "Done."),
+ msg("user", "The assistant read an image file: a.png") // injected
+ )
+
+ assertEquals(listOf(0, 4), userTurnStarts(history))
+ }
+
+ @Test
+ fun `empty history has no turns`() {
+ assertTrue(userTurnStarts(emptyList()).isEmpty())
+ }
+
+ // ---- truncateHistoryAtTurn, revert (dropTurn = false) ----
+
+ @Test
+ fun `revert keeps history up to and including the target prompt`() {
+ val history = listOf(
+ msg("user", "A"),
+ msg("assistant", "reply A"),
+ msg("tool", "r1"),
+ msg("user", "B"),
+ msg("user", "[Screen State]"),
+ msg("assistant", "reply B"),
+ msg("user", "C"),
+ msg("assistant", "reply C")
+ )
+
+ val kept = truncateHistoryAtTurn(history, 1, dropTurn = false)
+
+ assertEquals(listOf("A", "reply A", "r1", "B"), kept.map { it.textContent })
+ }
+
+ @Test
+ fun `revert on the first prompt keeps just that prompt`() {
+ val history = listOf(
+ msg("user", "A"),
+ msg("assistant", "reply A"),
+ msg("user", "B")
+ )
+
+ assertEquals(
+ listOf("A"),
+ truncateHistoryAtTurn(history, 0, dropTurn = false).map { it.textContent }
+ )
+ }
+
+ // ---- truncateHistoryAtTurn, edit (dropTurn = true) ----
+
+ @Test
+ fun `edit on the first turn drops the whole turn`() {
+ val history = listOf(
+ msg("user", "A"),
+ msg("assistant", "reply A"),
+ msg("tool", "r1"),
+ msg("user", "B"),
+ msg("user", "[Screen State]"),
+ msg("assistant", "reply B")
+ )
+
+ assertTrue(truncateHistoryAtTurn(history, 0, dropTurn = true).isEmpty())
+ }
+
+ @Test
+ fun `edit keeps earlier turns and drops the target turn`() {
+ val history = listOf(
+ msg("user", "A"),
+ msg("assistant", "reply A"),
+ msg("user", "B"),
+ msg("assistant", "reply B")
+ )
+
+ val kept = truncateHistoryAtTurn(history, 1, dropTurn = true)
+
+ assertEquals(listOf("A", "reply A"), kept.map { it.textContent })
+ }
+
+ @Test
+ fun `edit drops injected observations after the target prompt`() {
+ val history = listOf(
+ msg("user", "A"),
+ msg("assistant", "reply A"),
+ msg("tool", "r1"),
+ msg("user", "B"),
+ msg("user", "[Screen State]"), // injected during B's run
+ msg("assistant", "reply B")
+ )
+
+ val kept = truncateHistoryAtTurn(history, 1, dropTurn = true)
+
+ assertEquals(listOf("A", "reply A", "r1"), kept.map { it.textContent })
+ }
+
+ // ---- out of range / empty ----
+
+ @Test
+ fun `out of range turn returns the original list`() {
+ val history = listOf(msg("user", "A"), msg("assistant", "reply"))
+
+ assertSame(history, truncateHistoryAtTurn(history, 5, dropTurn = true))
+ assertSame(history, truncateHistoryAtTurn(history, -1, dropTurn = false))
+ }
+
+ @Test
+ fun `empty history returns empty`() {
+ assertTrue(truncateHistoryAtTurn(emptyList(), 0, dropTurn = false).isEmpty())
+ assertTrue(truncateHistoryAtTurn(emptyList(), 0, dropTurn = true).isEmpty())
+ }
+
+ /**
+ * Regression for the production clear() + addAll() swap in
+ * [ChatViewModel.editMessage]/[revertTo]: the truncated result must be a
+ * detached copy, not a live subList view, or clearing the backing history
+ * before addAll would throw a ConcurrentModificationException.
+ */
+ @Test
+ fun `truncated result survives clearing the source history`() {
+ val history = mutableListOf(
+ msg("user", "A"),
+ msg("assistant", "reply A"),
+ msg("user", "B"),
+ msg("assistant", "reply B")
+ )
+
+ val edited = truncateHistoryAtTurn(history, 1, dropTurn = true)
+ history.clear()
+ history.addAll(edited)
+ assertEquals(listOf("A", "reply A"), history.map { it.textContent })
+
+ history.add(msg("user", "B"))
+ history.add(msg("assistant", "reply B"))
+ val reverted = truncateHistoryAtTurn(history, 0, dropTurn = false)
+ history.clear()
+ history.addAll(reverted)
+ assertEquals(listOf("A"), history.map { it.textContent })
+ }
+}
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.kt
new file mode 100644
index 0000000..089cd7e
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelEditRevertTest.kt
@@ -0,0 +1,113 @@
+package com.gotcha.agent
+
+import android.app.Application
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.ChatHistoryRepository
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowLooper
+
+/**
+ * Behavioural contract for the Edit / Revert message gates in [ChatViewModel].
+ *
+ * Like [ChatViewModelContextUsageTest], this exercises only the synchronous
+ * entry points: `viewModelScope.launch` posts continuations back to Main after
+ * a real `Dispatchers.IO` suspension, which is not observable from this JUnit
+ * tier. The feature's synchronous guards — busy, another chat running, blank
+ * input — are exactly what belongs here; the truncation math itself is covered
+ * by the pure [ChatHistoryEditTest].
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class ChatViewModelEditRevertTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private lateinit var settingsRepository: SettingsRepository
+ private lateinit var historyRepository: ChatHistoryRepository
+ private lateinit var viewModel: ChatViewModel
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ settingsRepository = SettingsRepository(application)
+ historyRepository = ChatHistoryRepository(application, "edit-revert-test-chats")
+ settingsRepository.save(Settings(apiKey = "test-key"))
+ viewModel = ChatViewModel(application)
+ // Drain the init coroutine so the baseline state is settled.
+ ShadowLooper.idleMainLooper()
+ }
+
+ @After
+ fun tearDown() {
+ runBlocking {
+ historyRepository.deleteSession("session-A")
+ historyRepository.deleteSession("session-other")
+ }
+ }
+
+ /** Force the busy / running gate on so the synchronous guards are exercised. */
+ private fun setRunning(isBusy: Boolean, runningSessionId: String?) {
+ val stateField = ChatViewModel::class.java.getDeclaredField("_uiState")
+ .apply { isAccessible = true }
+
+ @Suppress("UNCHECKED_CAST")
+ val flow = stateField.get(viewModel) as kotlinx.coroutines.flow.MutableStateFlow<ChatUiState>
+ flow.value = flow.value.copy(isBusy = isBusy, runningSessionId = runningSessionId)
+ }
+
+ @Test
+ fun `editMessage is a no-op while a run is busy`() {
+ setRunning(isBusy = true, runningSessionId = "session-A")
+ val before = viewModel.uiState.value
+
+ viewModel.editMessage(targetId = 1L, newText = "Edited", imageBase64 = null)
+ ShadowLooper.idleMainLooper()
+
+ assertEquals(before.messages, viewModel.uiState.value.messages)
+ assertEquals(before.isBusy, viewModel.uiState.value.isBusy)
+ }
+
+ @Test
+ fun `editMessage is a no-op while another chat runs`() {
+ setRunning(isBusy = false, runningSessionId = "session-other")
+ val before = viewModel.uiState.value
+
+ viewModel.editMessage(targetId = 1L, newText = "Edited", imageBase64 = null)
+ ShadowLooper.idleMainLooper()
+
+ assertEquals(before.messages, viewModel.uiState.value.messages)
+ assertFalse(viewModel.uiState.value.isBusy)
+ }
+
+ @Test
+ fun `revertTo is a no-op while a run is busy`() {
+ setRunning(isBusy = true, runningSessionId = "session-A")
+ val before = viewModel.uiState.value
+
+ viewModel.revertTo(targetId = 1L)
+ ShadowLooper.idleMainLooper()
+
+ assertEquals(before.messages, viewModel.uiState.value.messages)
+ assertEquals(before.isBusy, viewModel.uiState.value.isBusy)
+ }
+
+ @Test
+ fun `editMessage is a no-op when the input is blank and no image is attached`() {
+ val before = viewModel.uiState.value
+
+ viewModel.editMessage(targetId = 1L, newText = " ", imageBase64 = null)
+ ShadowLooper.idleMainLooper()
+
+ assertEquals(before.messages, viewModel.uiState.value.messages)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt b/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt
index f7984c3..28d343d 100644
--- a/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt
+++ b/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt
@@ -1,6 +1,9 @@
package com.gotcha.data
+import com.gotcha.agent.truncateHistoryAtTurn
+import com.gotcha.llm.ChatMessage
import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.JsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -62,4 +65,27 @@ class ChatHistoryRepositoryTest {
assertFalse(File(dir, "gone.json").exists())
assertTrue(repo.listSessions().isEmpty())
}
+
+ /**
+ * Round-trip for the Edit / Revert truncation path: save a multi-turn
+ * session, truncate its history with [com.gotcha.agent.truncateHistoryAtTurn],
+ * save again, and assert only the kept messages survive a reload.
+ */
+ @Test
+ fun `truncated history round-trips through save and load`() = runBlocking {
+ val repo = ChatHistoryRepository(tmp.newFolder("chats"))
+ val messages = listOf(
+ ChatMessage(role = "user", content = JsonPrimitive("A")),
+ ChatMessage(role = "assistant", content = JsonPrimitive("reply A")),
+ ChatMessage(role = "user", content = JsonPrimitive("B")),
+ ChatMessage(role = "assistant", content = JsonPrimitive("reply B"))
+ )
+ repo.saveSession(session("trunc").copy(messages = messages))
+
+ val kept = truncateHistoryAtTurn(messages, 0, dropTurn = false)
+ repo.saveSession(session("trunc").copy(messages = kept))
+
+ val loaded = repo.loadSession("trunc")
+ assertEquals(listOf("A"), loaded!!.messages.map { it.textContent })
+ }
}