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(title): implement LLM-generated titles for chat sessions and fallback handling

Durganshu Mishra9111ad1487ff
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index c0531a2..e377957 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -191,12 +191,64 @@ class AgentEngine(
Log.d(TAG, "setupWorkingDir: ${dir.absolutePath}")
}
- /** Derived from the first user message; stable for the rest of the session. */
+ /** LLM-generated short title, once available; set once per session. */
+ var generatedTitle: String? = null
+ private set
+ private var titleGenerationAttempted = false
+
+ /** Falls back to the truncated first user message until [generatedTitle] is set. */
fun currentTitle(): String =
- history.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"
+ generatedTitle ?: history.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"
+
+ /**
+ * Restores title state when switching the engine to another session. Pass `null`
+ * for a fresh/untitled session so the next [saveCurrentSession] regenerates one;
+ * pass an already-generated title to avoid re-requesting it from the LLM.
+ */
+ fun restoreTitle(title: String?) {
+ generatedTitle = title
+ titleGenerationAttempted = title != null
+ }
+
+ /**
+ * Best-effort, once-per-session request for a short descriptive title based on the
+ * first user message. Silently leaves [generatedTitle] unset on failure, so
+ * [currentTitle] keeps returning the truncated-message fallback.
+ */
+ private suspend fun generateTitleIfNeeded(llm: LLMClient) {
+ if (titleGenerationAttempted) return
+ val firstUserText = history.firstOrNull { it.role == "user" }?.textContent?.trim()
+ if (firstUserText.isNullOrBlank()) return
+ titleGenerationAttempted = true
+ try {
+ val messages = listOf(
+ ChatMessage(
+ role = "system",
+ content = JsonPrimitive(
+ "You write short chat titles. Reply with a 3-6 word title summarizing " +
+ "the user's message, no quotes and no trailing punctuation. Reply with " +
+ "the title only."
+ )
+ ),
+ ChatMessage(role = "user", content = JsonPrimitive(firstUserText))
+ )
+ val titleModel = settings.subAgentModel.ifBlank { settings.model }
+ val response = llm.chat(messages = messages, temperature = 0f, modelOverride = titleModel)
+ val title = response.choices.firstOrNull()?.message?.textContent
+ ?.trim()?.trim('"', '\'', '.', ' ')?.take(60)
+ if (!title.isNullOrBlank()) {
+ generatedTitle = title
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ // Best-effort; keep the truncated-message fallback.
+ }
+ }
suspend fun saveCurrentSession() {
val id = sessionId ?: return
+ clientProvider()?.let { generateTitleIfNeeded(it) }
val title = currentTitle()
historyRepository.saveSession(
ChatSession(
@@ -209,6 +261,8 @@ class AgentEngine(
agentMode = agentModeProvider()?.name
)
)
+ // Rename the chat dir in place now that the real title is known.
+ setupWorkingDir()
}
private suspend fun checkAndCompactHistory(llm: LLMClient) {
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 90f32c0..3fa20dc 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -145,6 +145,16 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private fun viewingEngineSession(): Boolean =
_uiState.value.activeSessionId == agentEngine.sessionId
+ /**
+ * True when [ChatSession.title] is still the legacy truncated-first-message
+ * fallback rather than an LLM-generated title, so it's eligible to be
+ * (re)generated next time the session is saved.
+ */
+ private fun ChatSession.isFallbackTitle(): Boolean {
+ val fallback = messages.firstOrNull { it.role == "user" }?.textContent?.take(30)
+ return title.isBlank() || title == fallback
+ }
+
private val _uiState = MutableStateFlow(ChatUiState())
val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()
@@ -168,6 +178,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
// empty chat; past sessions remain one tap away in the drawer.
agentEngine.sessionId = java.util.UUID.randomUUID().toString()
agentEngine.tokenCount = 0
+ agentEngine.restoreTitle(null)
agentEngine.setupWorkingDir(create = false)
_uiState.update { it.copy(activeSessionId = agentEngine.sessionId) }
updateContextUsage()
@@ -389,8 +400,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
if (saved != null) {
agentEngine.history.addAll(saved.messages)
agentEngine.tokenCount = saved.tokenCount
+ agentEngine.restoreTitle(if (saved.isFallbackTitle()) null else saved.title)
} else {
agentEngine.tokenCount = 0
+ agentEngine.restoreTitle(null)
}
agentEngine.setupWorkingDir()
}
@@ -631,6 +644,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
agentEngine.history.clear()
agentEngine.sessionId = newId
agentEngine.tokenCount = 0
+ agentEngine.restoreTitle(null)
agentEngine.setupWorkingDir(create = false)
engineTranscript = emptyList()
engineAgent = defaultAgent
@@ -708,6 +722,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
agentEngine.history.addAll(session.messages)
agentEngine.sessionId = session.id
agentEngine.tokenCount = session.tokenCount
+ agentEngine.restoreTitle(if (session.isFallbackTitle()) null else session.title)
agentEngine.setupWorkingDir()
engineTranscript = session.displayMessages
engineAgent = restoredAgent