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 multi-session persistence and context window compaction for chat history
Rishabh Bajpaid9a76f5de12b
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex ef08f43..6667aa7 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -7,6 +7,7 @@ import com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepositoryimport com.gotcha.llm.ChatMessage+import com.gotcha.data.ChatSessionimport com.gotcha.llm.LLMClientimport com.gotcha.llm.ToolCallimport com.gotcha.tools.ToolExecutor@@ -51,7 +52,9 @@ data class ChatUiState(val isBusy: Boolean = false,val activity: String? = null, // e.g. "Running: toggle_dark_mode…"val pendingConfirmation: PendingConfirmation? = null,- val isConfigured: Boolean = false+ val isConfigured: Boolean = false,+ val activeSessionId: String? = null,+ val contextUsagePercent: Float = 0f)class ChatViewModel(application: Application) : AndroidViewModel(application) {@@ -70,7 +73,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private var appInForeground = true/** LLM-shaped history (excludes the system prompt, which is prepended per call). */- private val llmHistory = mutableListOf<ChatMessage>()+ private var llmHistory = mutableListOf<ChatMessage>()+ private var activeSessionId: String? = null+ private var activeSessionTokenCount: Int = 0private var nextId = 0Lprivate var confirmationGate: CompletableDeferred<Boolean>? = nullprivate var agentJob: Job? = null@@ -85,11 +90,28 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {init {refreshSettings()viewModelScope.launch {- llmHistory.addAll(historyRepository.load())+ val sessions = historyRepository.listSessions()+ if (sessions.isNotEmpty()) {+ val latest = sessions.first()+ activeSessionId = latest.id+ activeSessionTokenCount = latest.tokenCount+ llmHistory.addAll(latest.messages)+ } else {+ activeSessionId = java.util.UUID.randomUUID().toString()+ activeSessionTokenCount = 0+ }+ _uiState.update { it.copy(activeSessionId = activeSessionId) }+ updateContextUsage()rebuildUiMessages()}}+ private fun updateContextUsage() {+ val limit = settings.maxContextTokens.toFloat()+ val percent = if (limit > 0) activeSessionTokenCount.toFloat() / limit else 0f+ _uiState.update { it.copy(contextUsagePercent = percent.coerceIn(0f, 1f)) }+ }+/** Re-reads settings; call after the settings screen saves. */fun refreshSettings() {settings = settingsRepository.load()@@ -120,7 +142,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {} catch (e: CancellationException) {appendUi(MessageKind.ERROR, "Agent was interrupted by the user.")} finally {- historyRepository.save(llmHistory)+ saveCurrentSession()_uiState.update { it.copy(isBusy = false, activity = null) }agentJob = null}@@ -151,12 +173,46 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {if (_uiState.value.isBusy) returnllmHistory.clear()nextId = 0- _uiState.update { it.copy(messages = emptyList()) }- viewModelScope.launch { historyRepository.clear() }+ activeSessionId = java.util.UUID.randomUUID().toString()+ activeSessionTokenCount = 0+ _uiState.update { it.copy(messages = emptyList(), activeSessionId = activeSessionId) }+ updateContextUsage()+ }++ private suspend fun saveCurrentSession() {+ val id = activeSessionId ?: return+ val title = llmHistory.firstOrNull { it.role == "user" }?.content?.take(30) ?: "New Chat"+ historyRepository.saveSession(ChatSession(id, title, System.currentTimeMillis(), llmHistory.toList(), activeSessionTokenCount))+ }++ private suspend fun checkAndCompactHistory(llm: LLMClient) {+ val threshold = (settings.maxContextTokens * 0.8).toInt()+ if (activeSessionTokenCount <= threshold) return++ _uiState.update { it.copy(activity = "Compacting history…") }+ val compactionSystem = ChatMessage(+ role = "system",+ content = "You are an advanced context compaction agent. Your task is to compress the preceding conversation history into a highly dense, structured continuation summary. You must preserve critical context, decisions, and codebase states while eliminating conversational filler and repetitive tool logs.\n\nGenerate a structured summary containing exactly the following sections:\n1. **Goal**: What is the ultimate objective of this engineering session?\n2. **Instructions & Constraints**: What specific guidelines, patterns, user preferences, or technical limitations have been established?\n3. **Discoveries & Architecture**: What have we learned about the codebase? Detail any symbol mappings, logic structures, or debugging conclusions.\n4. **Accomplished**: What changes have already been completely implemented, verified, or fixed?\n5. **Relevant Files**: Which files are currently being modified or are active in the workspace?\n\nCRITICAL: Do not lose technical specifics, user-stated constraints, or deep investigation states.\n\nContinue if you have next steps, or stop and ask for clarification if you are unsure how to proceed."+ )++ try {+ val response = llm.chat(listOf(compactionSystem) + llmHistory)+ val summary = response.choices.firstOrNull()?.message?.content+ if (!summary.isNullOrBlank()) {+ llmHistory.clear()+ llmHistory.add(ChatMessage(role = "assistant", content = summary))+ activeSessionTokenCount = response.usage?.totalTokens ?: 0+ updateContextUsage()+ // Keep the UI messages intact for the user, but history is wiped for the agent+ }+ } catch (e: Exception) {+ // If compaction fails, we just continue with normal truncated history+ }}private suspend fun runToolLoop() {val llm = client ?: return+ checkAndCompactHistory(llm)repeat(settings.maxToolRounds) { iteration ->if (iteration > 0) delay(INTER_CALL_DELAY_MS) // throttle (PRD §11.2 #7)_uiState.update { it.copy(activity = "Thinking…") }@@ -167,6 +223,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {appendUi(MessageKind.ERROR, friendlyError(e))return}++ response.usage?.totalTokens?.let {+ activeSessionTokenCount = it+ updateContextUsage()+ }val message = response.choices.firstOrNull()?.messageif (message == null) {@@ -208,7 +269,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {)result.needsPermission?.let { _permissionRequests.tryEmit(it) }}- historyRepository.save(llmHistory)+ saveCurrentSession()}appendUi(MessageKind.ERROR,@@ -286,11 +347,24 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {))- /** Keeps the prompt bounded (PRD §11.2 #6) without splitting a tool-call/result pair,- * and ensures the history begins with a user message to satisfy strict model templates. */+ /** Trims history just in case compaction failed and we strictly need to fit it without splitting tool pairs. */private fun trimmedHistory(): List<ChatMessage> {- if (llmHistory.size <= MAX_HISTORY_MESSAGES) return llmHistory- var start = llmHistory.size - MAX_HISTORY_MESSAGES+ // Fallback approximation since exact token counts of subsets are unknown+ val maxTokens = settings.maxContextTokens+ var currentTokens = 0+ var start = llmHistory.size - 1++ while (start >= 0) {+ currentTokens += (llmHistory[start].content?.length ?: 0) / 4+ if (currentTokens > maxTokens) {+ start+++ break+ }+ start--+ }++ if (start < 0) start = 0+while (start < llmHistory.size && llmHistory[start].role != "user") start++return llmHistory.subList(start, llmHistory.size)}@@ -325,7 +399,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}private companion object {- const val MAX_HISTORY_MESSAGES = 40const val INTER_CALL_DELAY_MS = 400Lconst val CONFIRM_TIMEOUT_MS = 60_000L}diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.ktindex c1300a2..9c53c8b 100644--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt@@ -8,34 +8,63 @@ import kotlinx.serialization.builtins.ListSerializerimport kotlinx.serialization.json.Jsonimport java.io.File+import kotlinx.serialization.Serializable+import java.util.UUID++@Serializable+data class ChatSession(+ val id: String,+ val title: String,+ val lastModified: Long,+ val messages: List<ChatMessage>,+ val tokenCount: Int = 0+)+/**- * Persists the single conversation (LLM-shaped messages, including tool- * calls/results) as JSON in the app sandbox so history survives restarts.+ * Persists multiple chat sessions as JSON files in a dedicated 'chats' directory.*/class ChatHistoryRepository(context: Context) {- private val file = File(context.filesDir, "chat_history.json")+ private val chatsDir = File(context.filesDir, "chats").apply { mkdirs() }private val json = Json { ignoreUnknownKeys = true }- private val serializer = ListSerializer(ChatMessage.serializer())+ private val serializer = ChatSession.serializer()++ suspend fun listSessions(): List<ChatSession> = withContext(Dispatchers.IO) {+ chatsDir.listFiles()+ ?.filter { it.extension == "json" }+ ?.mapNotNull { file ->+ try {+ val session = json.decodeFromString(serializer, file.readText())+ // Only return metadata-light clone if desired, but we just return full for now+ session+ } catch (e: Exception) {+ null+ }+ }+ ?.sortedByDescending { it.lastModified }+ ?: emptyList()+ }- suspend fun load(): List<ChatMessage> = withContext(Dispatchers.IO) {- if (!file.exists()) return@withContext emptyList()+ suspend fun loadSession(id: String): ChatSession? = withContext(Dispatchers.IO) {+ val file = File(chatsDir, "$id.json")+ if (!file.exists()) return@withContext nulltry {json.decodeFromString(serializer, file.readText())} catch (e: Exception) {- emptyList() // corrupt history is dropped rather than crashing+ null}}- suspend fun save(messages: List<ChatMessage>) = withContext(Dispatchers.IO) {+ suspend fun saveSession(session: ChatSession) = withContext(Dispatchers.IO) {try {- file.writeText(json.encodeToString(serializer, messages))+ val file = File(chatsDir, "${session.id}.json")+ file.writeText(json.encodeToString(serializer, session.copy(lastModified = System.currentTimeMillis())))} catch (_: Exception) {- // Persistence is best-effort.+ // Best-effort}}- suspend fun clear() = withContext(Dispatchers.IO) {- file.delete()+ suspend fun deleteSession(id: String) = withContext(Dispatchers.IO) {+ File(chatsDir, "$id.json").delete()}}diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 4e88193..35303ed 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -10,7 +10,8 @@ data class Settings(val baseUrl: String = DEFAULT_BASE_URL,val model: String = DEFAULT_MODEL,val confirmSensitiveActions: Boolean = true,- val maxToolRounds: Int = 30+ val maxToolRounds: Int = 30,+ val maxContextTokens: Int = 40000) {val isConfigured: Boolean get() = apiKey.isNotBlank() && baseUrl.isNotBlank()@@ -42,7 +43,8 @@ class SettingsRepository(context: Context) {?: Settings.DEFAULT_BASE_URL,model = prefs.getString(KEY_MODEL, Settings.DEFAULT_MODEL) ?: Settings.DEFAULT_MODEL,confirmSensitiveActions = prefs.getBoolean(KEY_CONFIRM_SENSITIVE, true),- maxToolRounds = prefs.getInt(KEY_MAX_TOOL_ROUNDS, 30)+ maxToolRounds = prefs.getInt(KEY_MAX_TOOL_ROUNDS, 30),+ maxContextTokens = prefs.getInt(KEY_MAX_CONTEXT_TOKENS, 40000))fun save(settings: Settings) {@@ -52,6 +54,7 @@ class SettingsRepository(context: Context) {.putString(KEY_MODEL, settings.model).putBoolean(KEY_CONFIRM_SENSITIVE, settings.confirmSensitiveActions).putInt(KEY_MAX_TOOL_ROUNDS, settings.maxToolRounds)+ .putInt(KEY_MAX_CONTEXT_TOKENS, settings.maxContextTokens).apply()}@@ -61,5 +64,6 @@ class SettingsRepository(context: Context) {const val KEY_MODEL = "model"const val KEY_CONFIRM_SENSITIVE = "confirm_sensitive"const val KEY_MAX_TOOL_ROUNDS = "max_tool_rounds"+ const val KEY_MAX_CONTEXT_TOKENS = "max_context_tokens"}}diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.ktindex 0efaa39..d2e93ce 100644--- a/app/src/main/java/com/gotcha/llm/Models.kt+++ b/app/src/main/java/com/gotcha/llm/Models.kt@@ -56,7 +56,15 @@ data class ChatRequest(@Serializabledata class ChatResponse(- val choices: List<Choice>+ val choices: List<Choice>,+ val usage: Usage? = null+)++@Serializable+data class Usage(+ @SerialName("prompt_tokens") val promptTokens: Int = 0,+ @SerialName("completion_tokens") val completionTokens: Int = 0,+ @SerialName("total_tokens") val totalTokens: Int = 0)@Serializablediff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 2d9cc6d..ed2c1e2 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -13,6 +13,7 @@ import androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Buttonimport androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedTextField@@ -62,6 +63,11 @@ fun ChatScreen(}) { padding ->Column(modifier = Modifier.fillMaxSize().padding(padding)) {+ LinearProgressIndicator(+ progress = { state.contextUsagePercent },+ modifier = Modifier.fillMaxWidth(),+ color = if (state.contextUsagePercent > 0.8f) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary+ )LazyColumn(state = listState,modifier = Modifier.weight(1f).fillMaxWidth()diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex c075b8a..288d61b 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -48,6 +48,7 @@ fun SettingsScreen(var model by remember { mutableStateOf(initial.model) }var confirmSensitive by remember { mutableStateOf(initial.confirmSensitiveActions) }var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }+ var maxContextTokens by remember { mutableStateOf(initial.maxContextTokens.toString()) }var showKey by remember { mutableStateOf(false) }var status by remember { mutableStateOf<String?>(null) }var testing by remember { mutableStateOf(false) }@@ -58,7 +59,8 @@ fun SettingsScreen(baseUrl = baseUrl.trim(),model = model.trim(),confirmSensitiveActions = confirmSensitive,- maxToolRounds = maxToolRounds.toIntOrNull()?.takeIf { it > 0 } ?: 30+ maxToolRounds = maxToolRounds.toIntOrNull()?.takeIf { it > 0 } ?: 30,+ maxContextTokens = maxContextTokens.toIntOrNull()?.takeIf { it > 0 } ?: 40000)Scaffold(@@ -113,6 +115,14 @@ fun SettingsScreen(keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),modifier = Modifier.fillMaxWidth())+ OutlinedTextField(+ value = maxContextTokens,+ onValueChange = { maxContextTokens = it },+ label = { Text("Max context tokens") },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+ modifier = Modifier.fillMaxWidth()+ )Row(modifier = Modifier.fillMaxWidth(),