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 persistent chat state, reasoning UI support, and assistive ball navigation integration.

Rishabh Bajpaiaf471ae34ae8
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index e0fe1a0..72fe24d 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -94,6 +94,7 @@
<activity
android:name=".MainActivity"
android:exported="true"
+ android:launchMode="singleTask"
android:theme="@style/Theme.Gotcha">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 6220f34..18a52d2 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -65,6 +65,9 @@ class MainActivity : ComponentActivity() {
/** Set when launched from the assistive ball's "Open Chat" option. */
private var openChatRequested by mutableStateOf(false)
+ /** Set when brought to front by the assistive ball (Operator-origin chats). */
+ private var openedFromBall by mutableStateOf(false)
+
/** In-app theme override, applied immediately when changed in Settings. */
private var themeMode by mutableStateOf(ThemeMode.SYSTEM)
@@ -101,6 +104,7 @@ class MainActivity : ComponentActivity() {
settingsRepository = SettingsRepository(this)
samosaAuthManager = SamosaAuthManager(applicationContext, settingsRepository)
openChatRequested = intent?.getBooleanExtra(EXTRA_OPEN_CHAT, false) == true
+ openedFromBall = intent?.getBooleanExtra(EXTRA_FROM_ASSISTIVE_BALL, false) == true
// Phase 7: tools report special-access markers; open Settings deep-links.
// Runtime permissions are no longer requested here — they are pre-configured
@@ -236,6 +240,9 @@ class MainActivity : ComponentActivity() {
if (intent.getBooleanExtra(EXTRA_OPEN_CHAT, false)) {
openChatRequested = true
}
+ if (intent.getBooleanExtra(EXTRA_FROM_ASSISTIVE_BALL, false)) {
+ openedFromBall = true
+ }
}
override fun onStart() {
@@ -324,6 +331,16 @@ class MainActivity : ComponentActivity() {
}
}
+ // Opened via the assistive ball: return to any running chat, or default a
+ // fresh chat to Operator (ball-initiated chats are Operator by design).
+ LaunchedEffect(openedFromBall) {
+ if (openedFromBall) {
+ currentRoute = Route.HOME
+ chatViewModel.onOpenedFromAssistiveBall()
+ openedFromBall = false
+ }
+ }
+
ModalNavigationDrawer(
drawerState = drawerState,
gesturesEnabled = currentRoute == Route.HOME || drawerState.isOpen,
@@ -345,7 +362,9 @@ class MainActivity : ComponentActivity() {
onOpenSettings = {
scope.launch { drawerState.close() }
currentRoute = Route.SETTINGS
- }
+ },
+ maxContextTokens = state.maxContextTokens,
+ activeTokenCount = state.tokenCount
)
}
) {
@@ -448,10 +467,14 @@ class MainActivity : ComponentActivity() {
},
onPickImage = { uri -> chatViewModel.loadImageBase64(uri) },
onSwitchAgent = chatViewModel::switchAgent,
+ onSetAgent = chatViewModel::setAgent,
onSpeak = chatViewModel::speak,
onStartListening = chatViewModel::startListening,
onStopRecording = chatViewModel::stopRecording,
- onExportChat = chatViewModel::exportChat
+ onExportChat = chatViewModel::exportChat,
+ onReturnToRunning = {
+ state.runningSessionId?.let { chatViewModel.openSession(it) }
+ }
)
}
}
@@ -484,6 +507,9 @@ class MainActivity : ComponentActivity() {
/** Intent extra: when true, launch straight into the chat screen. */
const val EXTRA_OPEN_CHAT = "com.gotcha.OPEN_CHAT"
+ /** Intent extra: brought to front by the assistive ball (Operator-origin). */
+ const val EXTRA_FROM_ASSISTIVE_BALL = "com.gotcha.FROM_ASSISTIVE_BALL"
+
/** SharedPreferences key to track first-launch permission setup. */
const val KEY_FIRST_LAUNCH_DONE = "first_launch_setup_done"
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 38c01ad..78ecb3f 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -54,7 +54,11 @@ class AgentEngine(
private val historyRepository: ChatHistoryRepository,
private val settingsProvider: () -> Settings,
private val clientProvider: () -> LLMClient?,
- private val workingDirRoot: String = "/storage/emulated/0/Gotcha/chats"
+ private val workingDirRoot: String = "/storage/emulated/0/Gotcha/chats",
+ /** Supplies the current on-screen transcript to persist alongside history. */
+ private val displayMessagesProvider: () -> List<UiMessage> = { emptyList() },
+ /** Supplies the active agent mode to persist so it survives restarts. */
+ private val agentModeProvider: () -> AgentMode? = { null }
) {
/** LLM-shaped history (excludes the system prompt, which is prepended per call). */
@@ -176,7 +180,15 @@ class AgentEngine(
val id = sessionId ?: return
val title = history.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"
historyRepository.saveSession(
- ChatSession(id, title, System.currentTimeMillis(), history.toList(), tokenCount)
+ ChatSession(
+ id = id,
+ title = title,
+ lastModified = System.currentTimeMillis(),
+ messages = history.toList(),
+ tokenCount = tokenCount,
+ displayMessages = displayMessagesProvider(),
+ agentMode = agentModeProvider()?.name
+ )
)
}
@@ -250,6 +262,9 @@ class AgentEngine(
val newTokensApprox = (summary.length / 4) + ((preserveLast?.textContent?.length ?: 0) / 4)
tokenCount = newTokensApprox
events.onTokenCount(newTokensApprox)
+ // Drop the pre-compaction on-screen transcript, then show the
+ // compaction summary as the first bubble of the fresh transcript.
+ events.onHistoryReset()
// Show the compacted message in the chat UI as an assistant message
events.onUi(MessageKind.ASSISTANT, "[System: History Compacted]\n$summary")
} else if (preserveLast != null) {
@@ -323,16 +338,35 @@ class AgentEngine(
val toolCalls = message.toolCalls.orEmpty()
if (toolCalls.isEmpty()) {
- val content = message.textContent.ifEmpty { "(no reply)" }
- history += ChatMessage(role = "assistant", content = JsonPrimitive(content))
- events.onUi(MessageKind.ASSISTANT, content)
- events.onAssistantReply(content)
+ val content = message.textContent
+ // Preserve the real (possibly empty) content and carry any reasoning
+ // through so the UI can render a reasoning-only bubble without the
+ // placeholder "(no reply)" text.
+ history += ChatMessage(
+ role = "assistant",
+ content = JsonPrimitive(content),
+ reasoningContent = message.reasoningContent
+ )
+ if (content.isNotEmpty() || !message.reasoningContent.isNullOrBlank()) {
+ events.onUi(
+ MessageKind.ASSISTANT,
+ content,
+ reasoningContent = message.reasoningContent
+ )
+ }
+ if (content.isNotEmpty()) {
+ events.onAssistantReply(content)
+ }
return
}
history += message
- if (message.hasText) {
- events.onUi(MessageKind.ASSISTANT, message.textContent)
+ if (message.hasText || !message.reasoningContent.isNullOrBlank()) {
+ events.onUi(
+ MessageKind.ASSISTANT,
+ message.textContent,
+ reasoningContent = message.reasoningContent
+ )
}
val decision = requestConfirmation(toolCalls)
diff --git a/app/src/main/java/com/gotcha/agent/AgentEvents.kt b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
index 29d6fe3..762adb7 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEvents.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEvents.kt
@@ -1,5 +1,8 @@
package com.gotcha.agent
+import kotlinx.serialization.Serializable
+
+@Serializable
enum class MessageKind { USER, ASSISTANT, TOOL, ERROR, SUBAGENT }
/** A batch of tool calls waiting for the user's confirm/deny (Phase 7). */
@@ -46,6 +49,14 @@ interface AgentEvents {
/** Special-access marker ("special:*") the host should surface/request. */
fun onPermissionRequest(marker: String)
+ /**
+ * History was just compacted: the host should drop its on-screen transcript
+ * so pre-compaction bubbles are no longer shown. The compaction summary is
+ * delivered immediately afterward via [onUi]. Default no-op for hosts that
+ * don't render a persistent transcript.
+ */
+ fun onHistoryReset() {}
+
/** Ask the user the agent's question; returns "" when unanswered. */
suspend fun awaitQuestionAnswer(question: PendingQuestion): String
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 6d6a9ac..d3bc073 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -38,6 +38,7 @@ import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
import java.io.ByteArrayOutputStream
data class UiMessage(
val id: Long,
val kind: MessageKind,
@@ -64,8 +65,14 @@ data class ChatUiState(
val pendingQuestion: PendingQuestion? = null,
val isConfigured: Boolean = false,
val activeSessionId: String? = null,
- val activeAgent: AgentMode = AgentMode.OPERATOR,
+ val activeAgent: AgentMode = AgentMode.MONITOR,
+ /** 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. */
+ val runningSessionTitle: String? = null,
val contextUsagePercent: Float = 0f,
+ val tokenCount: Int = 0,
+ val maxContextTokens: Int = 0,
val isListening: Boolean = false,
val isRecording: Boolean = false,
val ttsModels: List<AudioModel> = emptyList(),
@@ -74,7 +81,7 @@ data class ChatUiState(
// In-app chat host: session/UI state, dialogs, and TTS/STT wiring. The agent
// loop itself lives in AgentEngine and reports back through AgentEvents.
-@Suppress("TooManyFunctions")
+@Suppress("TooManyFunctions", "LargeClass")
class ChatViewModel(application: Application) : AndroidViewModel(application), AgentEvents {
private val settingsRepository = SettingsRepository(application)
@@ -107,7 +114,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
events = this,
historyRepository = historyRepository,
settingsProvider = { settings },
- clientProvider = { client }
+ clientProvider = { client },
+ // Persist the ENGINE session's own data, never the viewed session's —
+ // the user may be browsing another chat while this run continues.
+ displayMessagesProvider = { engineTranscript },
+ agentModeProvider = { engineAgent }
)
private var nextId = 0L
@@ -115,6 +126,24 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private var questionGate: CompletableDeferred<String>? = null
private var agentJob: Job? = null
+ /**
+ * Live on-screen transcript of the session currently bound to [agentEngine]
+ * (the one that runs). Kept separate from [_uiState].messages so the user
+ * can browse to another chat while a run continues in the background without
+ * the engine's output overwriting — or being overwritten by — the viewed chat.
+ */
+ private var engineTranscript: List<UiMessage> = emptyList()
+
+ /** Monotonic UiMessage id for engine bubbles while browsing a different chat. */
+ private var engineNextId: Long = 1_000_000_000L
+
+ /** Agent mode of the session currently bound to [agentEngine]. */
+ private var engineAgent: AgentMode = AgentMode.MONITOR
+
+ /** True when the session the user is viewing is the one bound to the engine. */
+ private fun viewingEngineSession(): Boolean =
+ _uiState.value.activeSessionId == agentEngine.sessionId
+
private val _uiState = MutableStateFlow(ChatUiState())
val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()
@@ -153,15 +182,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
subAgentSteps: List<String>,
reasoningContent: String?
) {
- appendUi(kind, text, imageBase64, subAgentSteps, reasoningContent)
+ appendEngineUi(kind, text, imageBase64, subAgentSteps, reasoningContent)
}
override fun onActivity(activity: String?) {
- _uiState.update { it.copy(activity = activity) }
+ if (viewingEngineSession()) {
+ _uiState.update { it.copy(activity = activity) }
+ }
}
override fun onTokenCount(totalTokens: Int) {
- updateContextUsage()
+ if (viewingEngineSession()) updateContextUsage()
+ // Keep the running-session token count fresh in the drawer regardless.
+ refreshSessions()
}
override fun onAssistantReply(text: String) {
@@ -174,13 +207,24 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
override fun onSubAgentUpdate(running: String?, currentAction: String?) {
- _uiState.update { it.copy(subAgentRunning = running, subAgentCurrentAction = currentAction) }
+ if (viewingEngineSession()) {
+ _uiState.update { it.copy(subAgentRunning = running, subAgentCurrentAction = currentAction) }
+ }
}
override fun onPermissionRequest(marker: String) {
_permissionRequests.tryEmit(marker)
}
+ /** Compaction dropped the LLM history; clear the engine transcript to match. */
+ override fun onHistoryReset() {
+ engineTranscript = emptyList()
+ if (viewingEngineSession()) {
+ nextId = 0
+ _uiState.update { it.copy(messages = emptyList()) }
+ }
+ }
+
override suspend fun awaitQuestionAnswer(question: PendingQuestion): String {
val gate = CompletableDeferred<String>()
questionGate = gate
@@ -209,10 +253,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
// ---- Settings / models ----
- private fun updateContextUsage() {
+ private fun updateContextUsage() = applyContextUsage(agentEngine.tokenCount)
+
+ /** Sets the context readout for an explicit token count (viewed session). */
+ private fun applyContextUsage(tokens: Int) {
val limit = settings.maxContextTokens.toFloat()
- val percent = if (limit > 0) agentEngine.tokenCount.toFloat() / limit else 0f
- _uiState.update { it.copy(contextUsagePercent = percent.coerceIn(0f, 1f)) }
+ val percent = if (limit > 0) tokens.toFloat() / limit else 0f
+ _uiState.update {
+ it.copy(
+ contextUsagePercent = percent.coerceIn(0f, 1f),
+ tokenCount = tokens,
+ maxContextTokens = settings.maxContextTokens
+ )
+ }
}
/** Re-reads settings; call after the settings screen saves. */
@@ -233,6 +286,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
ttsEngine.configureApi(settings.ttsApiBaseUrl, settings.effectiveApiKey)
sttEngine.configureApi(settings.sttApiBaseUrl, settings.effectiveApiKey)
_uiState.update { it.copy(isConfigured = settings.isConfigured) }
+ updateContextUsage()
}
/**
@@ -263,7 +317,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
fun sendMessage(text: String, imageBase64: String? = null) {
val trimmed = text.trim()
if (trimmed.isEmpty() && imageBase64 == null) return
- if (_uiState.value.isBusy) return
+ // One agent runs at a time. Block sending while any run is in flight —
+ // the user can browse other chats but must let the current run finish.
+ 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
@@ -273,19 +329,42 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
} else {
ChatMessage(role = "user", content = JsonPrimitive(trimmed))
}
- agentEngine.history += msg
- appendUi(MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" }, imageBase64)
+ val viewedId = _uiState.value.activeSessionId
agentJob = viewModelScope.launch {
- _uiState.update { it.copy(isBusy = true) }
+ // Ensure the engine is bound to the session being viewed. After a
+ // previous run finished while the user browsed elsewhere, the engine
+ // may still point at that older session — reload the viewed one.
+ bindEngineToViewedSession(viewedId)
+
+ 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"
+ _uiState.update {
+ it.copy(
+ isBusy = true,
+ runningSessionId = runningId,
+ runningSessionTitle = runningTitle
+ )
+ }
try {
- agentEngine.run(_uiState.value.activeAgent)
+ agentEngine.run(engineAgent)
} catch (_: CancellationException) {
- appendUi(MessageKind.ERROR, "Agent was interrupted by the user.")
+ appendEngineUi(MessageKind.ERROR, "Agent was interrupted by the user.")
} finally {
withContext(NonCancellable) {
agentEngine.saveCurrentSession()
_uiState.update {
- it.copy(isBusy = false, activity = null, subAgentRunning = null, subAgentCurrentAction = null)
+ 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
}
@@ -293,6 +372,29 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
+ /**
+ * Point [agentEngine] at [viewedId] (the session being viewed) so a run
+ * 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.
+ */
+ private suspend fun bindEngineToViewedSession(viewedId: String?) {
+ if (viewedId != null && agentEngine.sessionId != viewedId) {
+ val saved = historyRepository.loadSession(viewedId)
+ agentEngine.history.clear()
+ agentEngine.sessionId = viewedId
+ if (saved != null) {
+ agentEngine.history.addAll(saved.messages)
+ agentEngine.tokenCount = saved.tokenCount
+ } else {
+ agentEngine.tokenCount = 0
+ }
+ agentEngine.setupWorkingDir()
+ }
+ engineTranscript = _uiState.value.messages
+ engineAgent = _uiState.value.activeAgent
+ }
+
/** Load an image from a content:// URI, downscale, and return base64. */
fun loadImageBase64(uri: Uri, maxDimension: Int = 1024): String? {
return try {
@@ -441,6 +543,23 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
+ /**
+ * The app was brought to the front by the assistive ball. One agent runs at
+ * a time, so:
+ * - If a run is active, return to that running chat (never start a new one).
+ * - Else if the current chat is empty (home), default it to Operator, since
+ * ball-initiated chats are Operator by design.
+ * - Else leave the populated chat being viewed as-is.
+ */
+ fun onOpenedFromAssistiveBall() {
+ val running = _uiState.value.runningSessionId
+ when {
+ running != null -> openSession(running)
+ _uiState.value.messages.isEmpty() -> setAgent(AgentMode.OPERATOR)
+ else -> { /* keep the current chat */ }
+ }
+ }
+
/** Switch between Monitor (read-only) and Operator (full) agent mode mid-conversation. */
fun switchAgent() {
val current = _uiState.value.activeAgent
@@ -463,24 +582,57 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
AgentMode.OPERATOR ->
"Switched to Operator mode — the agent can now make changes to your device."
}
- agentEngine.history += ChatMessage(role = "system", content = JsonPrimitive(llmMsg))
+ // Only inject into the LLM history when the viewed chat is the engine's;
+ // otherwise the mode is applied at the next send (run(engineAgent)).
+ if (viewingEngineSession()) {
+ agentEngine.history += ChatMessage(role = "system", content = JsonPrimitive(llmMsg))
+ engineAgent = next
+ }
appendUi(MessageKind.ASSISTANT, uiMsg)
}
+ /**
+ * Set the agent mode directly, without injecting a mid-conversation system
+ * message. Used by the home-screen selector before the first message is sent.
+ */
+ fun setAgent(mode: AgentMode) {
+ if (_uiState.value.activeAgent == mode) return
+ _uiState.update { it.copy(activeAgent = mode) }
+ }
+
override fun onCleared() {
confirmationOverlay.dismiss()
super.onCleared()
}
- fun clearChat() {
- if (_uiState.value.isBusy) return
- agentEngine.history.clear()
+ /**
+ * Start a fresh chat. [defaultAgent] sets the starting mode: Monitor when
+ * created from the app UI, Operator when created from the assistive ball.
+ *
+ * If a run is in progress in another session, this is a VIEW-ONLY switch to a
+ * new blank chat — the engine stays bound to the running session. The engine
+ * is only re-pointed at the new blank chat when nothing is running.
+ */
+ fun clearChat(defaultAgent: AgentMode = AgentMode.MONITOR) {
+ val newId = java.util.UUID.randomUUID().toString()
+ val runInProgress = _uiState.value.runningSessionId != null
nextId = 0
- agentEngine.sessionId = java.util.UUID.randomUUID().toString()
- agentEngine.tokenCount = 0
- agentEngine.setupWorkingDir()
- _uiState.update { it.copy(messages = emptyList(), activeSessionId = agentEngine.sessionId) }
- updateContextUsage()
+ if (!runInProgress) {
+ agentEngine.history.clear()
+ agentEngine.sessionId = newId
+ agentEngine.tokenCount = 0
+ agentEngine.setupWorkingDir()
+ engineTranscript = emptyList()
+ engineAgent = defaultAgent
+ }
+ _uiState.update {
+ it.copy(
+ messages = emptyList(),
+ activeSessionId = newId,
+ activeAgent = defaultAgent
+ )
+ }
+ applyContextUsage(0)
}
fun refreshSessions() {
@@ -490,23 +642,70 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
fun openSession(id: String?) {
- if (_uiState.value.isBusy) return
viewModelScope.launch {
if (id == null) {
clearChat()
+ return@launch
+ }
+ // Re-viewing the running session: just show its live engine transcript.
+ if (id == agentEngine.sessionId && _uiState.value.runningSessionId == id) {
+ nextId = (engineTranscript.maxOfOrNull { it.id }?.plus(1)) ?: 0
+ _uiState.update {
+ it.copy(
+ activeSessionId = id,
+ activeAgent = engineAgent,
+ messages = engineTranscript
+ )
+ }
+ applyContextUsage(agentEngine.tokenCount)
+ return@launch
+ }
+ val session = historyRepository.loadSession(id) ?: return@launch
+ val restoredAgent = session.agentMode
+ ?.let { runCatching { AgentMode.valueOf(it) }.getOrNull() }
+ ?: AgentMode.MONITOR
+ val runInProgress = _uiState.value.runningSessionId != null
+ // Only rebind the engine when idle. While a run is active this is a
+ // view-only switch so the running session is never disturbed.
+ if (!runInProgress) {
+ agentEngine.history.clear()
+ agentEngine.history.addAll(session.messages)
+ agentEngine.sessionId = session.id
+ agentEngine.tokenCount = session.tokenCount
+ agentEngine.setupWorkingDir()
+ engineTranscript = session.displayMessages
+ engineAgent = restoredAgent
+ }
+ // Restore the verbatim on-screen transcript so what's shown on reopen
+ // matches exactly what was shown live. Fall back to a lossy rebuild
+ // only for legacy sessions saved before display messages existed.
+ if (session.displayMessages.isNotEmpty()) {
+ nextId = (session.displayMessages.maxOf { it.id } + 1)
+ _uiState.update {
+ it.copy(
+ activeSessionId = session.id,
+ activeAgent = restoredAgent,
+ messages = session.displayMessages,
+ // Clear engine-scoped transient UI for the viewed (non-running) chat.
+ activity = null,
+ subAgentRunning = null,
+ subAgentCurrentAction = null
+ )
+ }
+ applyContextUsage(session.tokenCount)
} else {
- val session = historyRepository.loadSession(id)
- if (session != null) {
- agentEngine.history.clear()
- agentEngine.history.addAll(session.messages)
- agentEngine.sessionId = session.id
- agentEngine.tokenCount = session.tokenCount
- nextId = 0
- agentEngine.setupWorkingDir()
- _uiState.update { it.copy(activeSessionId = session.id) }
- updateContextUsage()
- rebuildUiMessages()
+ nextId = 0
+ _uiState.update {
+ it.copy(
+ activeSessionId = session.id,
+ activeAgent = restoredAgent,
+ activity = null,
+ subAgentRunning = null,
+ subAgentCurrentAction = null
+ )
}
+ applyContextUsage(session.tokenCount)
+ rebuildUiMessagesFrom(session.messages)
}
}
}
@@ -537,8 +736,30 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
- private fun rebuildUiMessages() {
- val rebuilt = agentEngine.history.mapNotNull { msg ->
+ /**
+ * Append a bubble authored by the ENGINE (agent output). Always records it on
+ * [engineTranscript] so the running session's transcript stays complete even
+ * while the user browses another chat; mirrors into the visible [_uiState]
+ * only when that running session is the one being viewed.
+ */
+ private fun appendEngineUi(
+ kind: MessageKind,
+ text: String,
+ imageBase64: String? = null,
+ subAgentSteps: List<String> = emptyList(),
+ reasoningContent: String? = null
+ ) {
+ val viewing = viewingEngineSession()
+ val id = if (viewing) nextId++ else engineNextId++
+ val message = UiMessage(id, kind, text, imageBase64, subAgentSteps, subAgentCollapsed = true, reasoningContent)
+ engineTranscript = engineTranscript + message
+ if (viewing) {
+ _uiState.update { it.copy(messages = it.messages + message) }
+ }
+ }
+
+ private fun rebuildUiMessagesFrom(source: List<ChatMessage>) {
+ val rebuilt = source.mapNotNull { msg ->
val text = msg.textContent
when {
msg.role == "user" && (text.startsWith("[Screen State]") || text.startsWith("Screen text:")) -> {
@@ -554,7 +775,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
msg.role == "assistant" && text.isNotBlank() ->
UiMessage(nextId++, MessageKind.ASSISTANT, text, reasoningContent = msg.reasoningContent)
msg.role == "assistant" && !msg.reasoningContent.isNullOrBlank() ->
- UiMessage(nextId++, MessageKind.ASSISTANT, "(no reply)", reasoningContent = msg.reasoningContent)
+ UiMessage(nextId++, MessageKind.ASSISTANT, "", reasoningContent = msg.reasoningContent)
msg.role == "tool" && text.startsWith("SUBAGENT_STEPS:") -> {
val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
val rest = if (descEnd > 0) {
diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
index fafe5cf..4b222f6 100644
--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
@@ -1,6 +1,7 @@
package com.gotcha.data
import android.content.Context
+import com.gotcha.agent.UiMessage
import com.gotcha.llm.ChatMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -14,7 +15,16 @@ data class ChatSession(
val title: String,
val lastModified: Long,
val messages: List<ChatMessage>,
- val tokenCount: Int = 0
+ val tokenCount: Int = 0,
+ /**
+ * The verbatim on-screen transcript for this session. Persisted separately
+ * from [messages] (the LLM-shaped history) so reopening a chat restores
+ * exactly what was shown live, without lossy reconstruction. Reset on
+ * history compaction so pre-compaction bubbles are intentionally dropped.
+ */
+ val displayMessages: List<UiMessage> = emptyList(),
+ /** Persisted agent mode ("MONITOR"/"OPERATOR") so it survives app restarts. */
+ val agentMode: String? = null
)
/**
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 94cfb3e..266daad 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -81,6 +81,7 @@ class AssistiveBallService : Service() {
onOpenApp = {
val intent = Intent(this@AssistiveBallService, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ .putExtra(MainActivity.EXTRA_FROM_ASSISTIVE_BALL, true)
startActivity(intent)
}
onTakeScreenshot = { takeScreenshot() }
diff --git a/app/src/main/java/com/gotcha/ui/AppDrawer.kt b/app/src/main/java/com/gotcha/ui/AppDrawer.kt
index 897dcb5..6f5827e 100644
--- a/app/src/main/java/com/gotcha/ui/AppDrawer.kt
+++ b/app/src/main/java/com/gotcha/ui/AppDrawer.kt
@@ -41,7 +41,9 @@ fun AppDrawerContent(
onNewChat: () -> Unit,
onSessionClick: (String) -> Unit,
onDeleteSession: (String) -> Unit,
- onOpenSettings: () -> Unit
+ onOpenSettings: () -> Unit,
+ maxContextTokens: Int = 0,
+ activeTokenCount: Int = 0
) {
var sessionToDelete by remember { mutableStateOf<String?>(null) }
@@ -68,13 +70,24 @@ fun AppDrawerContent(
)
LazyColumn(modifier = Modifier.weight(1f)) {
items(sessions, key = { it.id }) { session ->
+ val tokens = if (session.id == activeSessionId) activeTokenCount else session.tokenCount
+ val usage = formatContextUsage(tokens, maxContextTokens)
NavigationDrawerItem(
label = {
- Text(
- session.title,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis
- )
+ Column {
+ Text(
+ session.title,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ if (usage != null) {
+ Text(
+ usage,
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
},
selected = session.id == activeSessionId,
onClick = { onSessionClick(session.id) },
@@ -128,3 +141,19 @@ fun AppDrawerContent(
)
}
}
+
+/**
+ * Formats a per-chat context readout like "12,345 / 70,000 tokens (18%)".
+ * Returns null when there's nothing meaningful to show yet.
+ */
+private fun formatContextUsage(tokens: Int, maxContextTokens: Int): String? {
+ if (tokens <= 0) return null
+ fun grouped(n: Int): String = "%,d".format(n)
+ return if (maxContextTokens > 0) {
+ val percent = (tokens.toFloat() / maxContextTokens * 100f)
+ .coerceIn(0f, 100f).toInt()
+ "${grouped(tokens)} / ${grouped(maxContextTokens)} tokens ($percent%)"
+ } else {
+ "${grouped(tokens)} tokens"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 01892ef..92b8954 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -4,6 +4,7 @@ import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -35,6 +36,7 @@ import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
@@ -82,12 +84,18 @@ fun ChatScreen(
onToggleAssistiveBall: (Boolean) -> Unit = {},
onPickImage: (Uri) -> String?,
onSwitchAgent: () -> Unit,
+ onSetAgent: (AgentMode) -> Unit = {},
onSpeak: (String) -> Unit = {},
onStartListening: () -> Unit = {},
onStopRecording: () -> Unit = {},
- onExportChat: () -> Unit = {}
+ onExportChat: () -> Unit = {},
+ onReturnToRunning: () -> Unit = {}
) {
val isHome = state.messages.isEmpty()
+ // A run is active in a DIFFERENT chat than the one being viewed: sending here
+ // is blocked (one agent at a time), and a banner offers a jump back.
+ val otherChatRunning = state.runningSessionId != null &&
+ state.runningSessionId != state.activeSessionId
var input by rememberSaveable { mutableStateOf("") }
var pendingImageUri by rememberSaveable { mutableStateOf<Uri?>(null) }
var pendingImageBase64 by rememberSaveable { mutableStateOf<String?>(null) }
@@ -197,6 +205,11 @@ fun ChatScreen(
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
+ Spacer(modifier = Modifier.height(24.dp))
+ AgentModeSelector(
+ selected = state.activeAgent,
+ onSelect = onSetAgent
+ )
}
} else {
LazyColumn(
@@ -261,6 +274,33 @@ fun ChatScreen(
}
}
+ // "Agent working in another chat" banner — tap to jump back to it.
+ if (otherChatRunning) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 4.dp)
+ .clip(RoundedCornerShape(8.dp))
+ .background(MaterialTheme.colorScheme.secondaryContainer)
+ .clickable { onReturnToRunning() }
+ .padding(horizontal = 12.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ CircularProgressIndicator(
+ modifier = Modifier.size(16.dp),
+ color = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(
+ "⚡ Agent working in “${state.runningSessionTitle ?: "another chat"}” — tap to return",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+
// Image attachment preview
if (pendingImageBase64 != null) {
Box(
@@ -301,7 +341,7 @@ fun ChatScreen(
) {
IconButton(
onClick = { imagePickerLauncher.launch("image/*") },
- enabled = !state.isBusy && state.isConfigured
+ enabled = !state.isBusy && state.isConfigured && !otherChatRunning
) {
Text("+", style = MaterialTheme.typography.titleLarge)
}
@@ -310,8 +350,10 @@ fun ChatScreen(
onValueChange = { input = it },
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(24.dp),
- placeholder = { Text("Let's Go") },
- enabled = !state.isBusy && state.isConfigured,
+ placeholder = {
+ Text(if (otherChatRunning) "Finish the running chat first…" else "Let's Go")
+ },
+ enabled = !state.isBusy && state.isConfigured && !otherChatRunning,
maxLines = 6,
singleLine = false
)
@@ -356,7 +398,7 @@ fun ChatScreen(
IconButton(
onClick = onStartListening,
modifier = Modifier.size(40.dp),
- enabled = state.isConfigured
+ enabled = state.isConfigured && !otherChatRunning
) {
Icon(Icons.Default.Mic, contentDescription = "Voice input")
}
@@ -370,7 +412,8 @@ fun ChatScreen(
pendingImageBase64 = null
},
modifier = Modifier.size(40.dp),
- enabled = state.isConfigured && (input.isNotBlank() || pendingImageBase64 != null)
+ enabled = state.isConfigured && !otherChatRunning &&
+ (input.isNotBlank() || pendingImageBase64 != null)
) {
Icon(Icons.Default.Send, contentDescription = "Send")
}
@@ -432,3 +475,60 @@ fun ChatScreen(
)
}
}
+
+/**
+ * Home-screen segmented control to choose the agent before the first message.
+ * Monitor = read-only, Operator = full device control.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+private fun AgentModeSelector(
+ selected: AgentMode,
+ onSelect: (AgentMode) -> Unit
+) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ "Agent",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ FilterChip(
+ selected = selected == AgentMode.MONITOR,
+ onClick = { onSelect(AgentMode.MONITOR) },
+ leadingIcon = {
+ Icon(
+ Icons.Outlined.Visibility,
+ contentDescription = null,
+ modifier = Modifier.size(18.dp)
+ )
+ },
+ label = { Text("Monitor") }
+ )
+ FilterChip(
+ selected = selected == AgentMode.OPERATOR,
+ onClick = { onSelect(AgentMode.OPERATOR) },
+ leadingIcon = {
+ Icon(
+ Icons.Filled.TouchApp,
+ contentDescription = null,
+ modifier = Modifier.size(18.dp)
+ )
+ },
+ label = { Text("Operator") }
+ )
+ }
+ Spacer(modifier = Modifier.height(6.dp))
+ Text(
+ if (selected == AgentMode.MONITOR) {
+ "Read-only — observes but cannot change your device."
+ } else {
+ "Full control — can make changes to your device."
+ },
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+}