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.

Search chats by title and message text in the drawer

Rishabh Bajpaief33b1719a1b
diff --git a/app/src/main/java/com/gotcha/data/ChatSearch.kt b/app/src/main/java/com/gotcha/data/ChatSearch.kt
new file mode 100644
index 0000000..b570dfe
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/ChatSearch.kt
@@ -0,0 +1,97 @@
+package com.gotcha.data
+
+/** One chat the drawer search found: its title matched, or its text did. */
+data class ChatSearchHit(
+ val sessionId: String,
+ /** The matching line of chat text, or null when only the title matched. */
+ val snippet: String? = null
+)
+
+/**
+ * The drawer's chat search: matches a query against each chat's title and the
+ * text of its transcript. Pure and in memory, because the drawer already holds
+ * every session it lists.
+ *
+ * Results keep the drawer's own newest-first order, so a familiar chat stays
+ * where the user expects it while a query narrows the list.
+ */
+object ChatSearch {
+
+ /** Characters of context kept either side of a match. */
+ private const val SNIPPET_RADIUS = 48
+
+ /** Longest snippet shown; longer matches are cut with an ellipsis. */
+ private const val SNIPPET_MAX = 120
+
+ /** [sessions] whose title or text contains [query], in the order given. */
+ fun search(sessions: List<ChatSession>, query: String): List<ChatSearchHit> {
+ val needle = query.trim()
+ if (needle.isEmpty()) return emptyList()
+ return sessions.mapNotNull { session ->
+ // A title match does not hide a text match: the row still shows the
+ // line, which is what tells the user why this chat is here.
+ val snippet = snippetIn(session, needle)
+ if (snippet != null || session.title.contains(needle, ignoreCase = true)) {
+ ChatSearchHit(session.id, snippet)
+ } else {
+ null
+ }
+ }
+ }
+
+ /**
+ * The first line of [session]'s text containing [needle], shortened with
+ * context around the match, or null when nothing matches.
+ */
+ fun snippetIn(session: ChatSession, needle: String): String? {
+ for (text in sessionTexts(session)) {
+ val at = text.indexOf(needle, ignoreCase = true)
+ if (at >= 0) return shorten(text, at, needle.length)
+ }
+ return null
+ }
+
+ /**
+ * What a chat can be found by: its visible transcript, or the LLM-shaped
+ * history for chats saved before transcripts were kept. Blank lines are
+ * skipped so a match never lands on whitespace.
+ */
+ private fun sessionTexts(session: ChatSession): Sequence<String> = sequence {
+ if (session.displayMessages.isNotEmpty()) {
+ session.displayMessages.forEach { message ->
+ if (message.text.isNotBlank()) yield(message.text)
+ }
+ } else {
+ session.messages.forEach { message ->
+ val text = message.textContent
+ if (text.isNotBlank()) yield(text)
+ }
+ }
+ }
+
+ private fun shorten(text: String, matchAt: Int, matchLength: Int): String {
+ val start = charBoundary(text, (matchAt - SNIPPET_RADIUS).coerceAtLeast(0))
+ val end = charBoundary(text, (matchAt + matchLength + SNIPPET_RADIUS).coerceAtMost(text.length))
+ val cut = text.substring(start, end).replace(WHITESPACE, " ").trim()
+ val shortened = if (cut.length > SNIPPET_MAX) cut.take(charBoundary(cut, SNIPPET_MAX)).trimEnd() + "…" else cut
+ return when {
+ start > 0 && end < text.length -> "…$shortened…"
+ start > 0 -> "…$shortened"
+ end < text.length -> "$shortened…"
+ else -> shortened
+ }
+ }
+
+ /**
+ * [index] moved off the middle of a surrogate pair: cutting a pair in half
+ * would render as a replacement character in the snippet.
+ */
+ private fun charBoundary(text: String, index: Int): Int = when {
+ index <= 0 || index >= text.length -> index
+ text[index - 1].isHighSurrogate() && text[index].isLowSurrogate() -> index - 1
+ else -> index
+ }
+
+ /** Newlines and the Unicode spaces that `\s` does not always cover. */
+ private val WHITESPACE = Regex("[\\s\\u00A0\\u2007\\u202F]+")
+}
diff --git a/app/src/main/java/com/gotcha/ui/AppDrawer.kt b/app/src/main/java/com/gotcha/ui/AppDrawer.kt
index 666779f..a27d1a0 100644
--- a/app/src/main/java/com/gotcha/ui/AppDrawer.kt
+++ b/app/src/main/java/com/gotcha/ui/AppDrawer.kt
@@ -1,8 +1,10 @@
package com.gotcha.ui
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
@@ -10,8 +12,10 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.Schedule
+import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material3.Button
@@ -24,21 +28,27 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
+import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.gotcha.R
import com.gotcha.agent.ChatTitle
+import com.gotcha.data.ChatSearch
+import com.gotcha.data.ChatSearchHit
import com.gotcha.data.ChatSession
import com.gotcha.i18n.stringLookup
import com.gotcha.ui.theme.GotchaMono
@@ -46,6 +56,9 @@ import com.gotcha.ui.theme.LocalSkin
import com.gotcha.ui.theme.SkinAlertDialog
import com.gotcha.ui.tour.TourAnchor
import com.gotcha.ui.tour.tourAnchor
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.withContext
@Composable
fun AppDrawerContent(
@@ -69,6 +82,8 @@ fun AppDrawerContent(
liveTokenBySession: Map<String, Int> = emptyMap()
) {
var sessionToDelete by remember { mutableStateOf<String?>(null) }
+ // The drawer's search: empty shows every chat, as before.
+ var query by remember { mutableStateOf("") }
// The drawer covers the app rather than floating in it, so it gets a ground
// of its own. Stated explicitly rather than left to DrawerDefaults, because
@@ -103,23 +118,87 @@ fun AppDrawerContent(
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(horizontal = 28.dp, vertical = 20.dp)
)
- NavigationDrawerItem(
- label = { Text(stringResource(R.string.drawer_new_chat)) },
- icon = { Icon(Icons.Default.Add, contentDescription = null) },
- selected = false,
- onClick = onNewChat,
- colors = itemColors,
- modifier = itemModifier
- )
+ // Search and new chat share one row: the field takes the width, the
+ // button costs a tap target. Sending "New Chat" as a full row left
+ // the list a line shorter for no gain.
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ ChatSearchField(
+ query = query,
+ onQueryChange = { query = it },
+ modifier = Modifier.weight(1f)
+ )
+ IconButton(
+ onClick = {
+ // A search belongs to the list it narrowed: leaving it
+ // behind would greet the next open with a filtered list.
+ query = ""
+ onNewChat()
+ },
+ modifier = Modifier.testTag("drawer_new_chat")
+ ) {
+ Icon(
+ Icons.Default.Add,
+ contentDescription = stringResource(R.string.drawer_new_chat)
+ )
+ }
+ }
HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
+ val searching = query.isNotBlank()
+ // Searching stays off the main thread: every chat's transcript is
+ // scanned, and a long history must not make typing stutter. The
+ // short delay coalesces keystrokes; "empty" is applied at once,
+ // because clearing the field should restore the list immediately.
+ var hits by remember { mutableStateOf<List<ChatSearchHit>>(emptyList()) }
+ var searchPending by remember { mutableStateOf(false) }
+ LaunchedEffect(query, sessions) {
+ if (query.isBlank()) {
+ hits = emptyList()
+ searchPending = false
+ } else {
+ searchPending = true
+ delay(SEARCH_DEBOUNCE_MS)
+ hits = withContext(Dispatchers.Default) { ChatSearch.search(sessions, query) }
+ searchPending = false
+ }
+ }
+ // One list either way: matching chats with their snippet, or all of
+ // them. Kept in the drawer's own order.
+ val rows = when {
+ !searching -> sessions.map { it to null }
+ else -> {
+ val snippets = hits.associate { it.sessionId to it.snippet }
+ sessions.filter { it.id in snippets }.map { it to snippets[it.id] }
+ }
+ }
Text(
- stringResource(R.string.drawer_recent_chats),
+ if (searching) {
+ stringResource(R.string.drawer_search_results, rows.size)
+ } else {
+ stringResource(R.string.drawer_recent_chats)
+ },
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 28.dp, vertical = 4.dp)
)
LazyColumn(modifier = Modifier.weight(1f)) {
- items(sessions, key = { it.id }) { session ->
+ // Only once the search has run: until then the previous results
+ // are still on screen, and "no chats match" would be a lie.
+ if (searching && rows.isEmpty() && !searchPending) {
+ item {
+ Text(
+ stringResource(R.string.drawer_search_no_results, query.trim()),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier
+ .padding(horizontal = 28.dp, vertical = 12.dp)
+ .testTag("drawer_search_no_results")
+ )
+ }
+ }
+ items(rows, key = { it.first.id }) { (session, snippet) ->
val tokens = liveTokenBySession[session.id]
?: (if (session.id == activeSessionId) activeTokenCount else session.tokenCount)
val usage = formatContextUsage(tokens, maxContextTokens)
@@ -131,6 +210,18 @@ fun AppDrawerContent(
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
+ // Why this chat matched, when the title didn't:
+ // the line of chat text holding the query.
+ if (snippet != null) {
+ Text(
+ snippet,
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.testTag("drawer_search_snippet")
+ )
+ }
// The one thing that distinguishes a seeded chat
// from one the user held: said on the row rather
// than only inside, so the list itself is honest.
@@ -158,7 +249,10 @@ fun AppDrawerContent(
}
},
selected = session.id == activeSessionId,
- onClick = { onSessionClick(session.id) },
+ onClick = {
+ query = ""
+ onSessionClick(session.id)
+ },
badge = {
IconButton(onClick = { sessionToDelete = session.id }) {
Icon(
@@ -230,6 +324,42 @@ fun AppDrawerContent(
}
}
+/** How long typing must settle before the drawer searches, in milliseconds. */
+private const val SEARCH_DEBOUNCE_MS = 120L
+
+/**
+ * The drawer's chat search field: one line, always visible above the list, so
+ * a chat can be found by its title or by anything said in it.
+ */
+@Composable
+private fun ChatSearchField(query: String, onQueryChange: (String) -> Unit, modifier: Modifier = Modifier) {
+ OutlinedTextField(
+ value = query,
+ onValueChange = onQueryChange,
+ modifier = modifier.testTag("drawer_search"),
+ singleLine = true,
+ textStyle = MaterialTheme.typography.bodyMedium,
+ placeholder = {
+ Text(
+ stringResource(R.string.drawer_search_placeholder),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ },
+ leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
+ trailingIcon = {
+ if (query.isNotEmpty()) {
+ IconButton(onClick = { onQueryChange("") }) {
+ Icon(
+ Icons.Default.Close,
+ contentDescription = stringResource(R.string.drawer_search_clear)
+ )
+ }
+ }
+ }
+ )
+}
+
/**
* Formats a per-chat context readout like "12,345 / 70,000 tokens (18%)".
* Returns null when there's nothing meaningful to show yet.
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 09df0c2..14db598 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">Alle aktiven Connectors sind aktuell.</string>
<string name="connectors_imap_saved">Gespeichert. Die Zugangsdaten werden bei der ersten Nutzung geprüft.</string>
<string name="drawer_new_chat">Neuer Chat</string>
+ <string name="drawer_search_placeholder">Chats durchsuchen</string>
+ <string name="drawer_search_clear">Suche löschen</string>
+ <string name="drawer_search_results">Ergebnisse (%1$d)</string>
+ <string name="drawer_search_no_results">Keine Chats passen zu „%1$s“.</string>
<string name="drawer_import_chats">Chats importieren</string>
<string name="drawer_back_up_all_chats">Alle Chats sichern</string>
<string name="drawer_connectors">Connectors</string>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 3367710..65c681d 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">Todos los conectores activos están al día.</string>
<string name="connectors_imap_saved">Guardado. Las credenciales se comprueban la primera vez que se usan.</string>
<string name="drawer_new_chat">Nuevo chat</string>
+ <string name="drawer_search_placeholder">Buscar chats</string>
+ <string name="drawer_search_clear">Borrar búsqueda</string>
+ <string name="drawer_search_results">Resultados (%1$d)</string>
+ <string name="drawer_search_no_results">Ningún chat coincide con «%1$s».</string>
<string name="drawer_import_chats">Importar chats</string>
<string name="drawer_back_up_all_chats">Copia de seguridad de todos los chats</string>
<string name="drawer_connectors">Conectores</string>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index c6963c6..3fba5f2 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">Tous les connecteurs actifs sont à jour.</string>
<string name="connectors_imap_saved">Enregistré. Les identifiants sont vérifiés à la première utilisation.</string>
<string name="drawer_new_chat">Nouvelle discussion</string>
+ <string name="drawer_search_placeholder">Rechercher des chats</string>
+ <string name="drawer_search_clear">Effacer la recherche</string>
+ <string name="drawer_search_results">Résultats (%1$d)</string>
+ <string name="drawer_search_no_results">Aucun chat ne correspond à « %1$s ».</string>
<string name="drawer_import_chats">Importer des discussions</string>
<string name="drawer_back_up_all_chats">Sauvegarder toutes les discussions</string>
<string name="drawer_connectors">Connecteurs</string>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 5589f1e..45644b7 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">सभी सक्रिय कनेक्टर अप-टू-डेट हैं।</string>
<string name="connectors_imap_saved">सहेजा गया। पहली बार इस्तेमाल पर क्रेडेंशियल जाँचे जाते हैं।</string>
<string name="drawer_new_chat">नई चैट</string>
+ <string name="drawer_search_placeholder">चैट खोजें</string>
+ <string name="drawer_search_clear">खोज साफ़ करें</string>
+ <string name="drawer_search_results">परिणाम (%1$d)</string>
+ <string name="drawer_search_no_results">“%1$s” से कोई चैट नहीं मिली।</string>
<string name="drawer_import_chats">चैट इंपोर्ट करें</string>
<string name="drawer_back_up_all_chats">सभी चैट का बैकअप लें</string>
<string name="drawer_connectors">कनेक्टर</string>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index e832233..4570556 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">Tutti i connettori attivi sono aggiornati.</string>
<string name="connectors_imap_saved">Salvato. Le credenziali vengono verificate al primo utilizzo.</string>
<string name="drawer_new_chat">Nuova chat</string>
+ <string name="drawer_search_placeholder">Cerca chat</string>
+ <string name="drawer_search_clear">Cancella ricerca</string>
+ <string name="drawer_search_results">Risultati (%1$d)</string>
+ <string name="drawer_search_no_results">Nessuna chat corrisponde a «%1$s».</string>
<string name="drawer_import_chats">Importa chat</string>
<string name="drawer_back_up_all_chats">Backup di tutte le chat</string>
<string name="drawer_connectors">Connettori</string>
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index f8d4c32..e55d935 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">有効なコネクタはすべて最新です。</string>
<string name="connectors_imap_saved">保存しました。認証情報は初回使用時に確認されます。</string>
<string name="drawer_new_chat">新しいチャット</string>
+ <string name="drawer_search_placeholder">チャットを検索</string>
+ <string name="drawer_search_clear">検索をクリア</string>
+ <string name="drawer_search_results">結果(%1$d件)</string>
+ <string name="drawer_search_no_results">「%1$s」に一致するチャットはありません。</string>
<string name="drawer_import_chats">チャットをインポート</string>
<string name="drawer_back_up_all_chats">すべてのチャットをバックアップ</string>
<string name="drawer_connectors">コネクタ</string>
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index f9f74d4..e1e258e 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">Todos os conectores ativos estão atualizados.</string>
<string name="connectors_imap_saved">Salvo. As credenciais são verificadas no primeiro uso.</string>
<string name="drawer_new_chat">Novo chat</string>
+ <string name="drawer_search_placeholder">Pesquisar conversas</string>
+ <string name="drawer_search_clear">Limpar pesquisa</string>
+ <string name="drawer_search_results">Resultados (%1$d)</string>
+ <string name="drawer_search_no_results">Nenhuma conversa corresponde a “%1$s”.</string>
<string name="drawer_import_chats">Importar chats</string>
<string name="drawer_back_up_all_chats">Fazer backup de todos os chats</string>
<string name="drawer_connectors">Conectores</string>
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index d04ada7..fb4585c 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -584,6 +584,10 @@
<string name="connectors_all_up_to_date">所有已启用的连接器都是最新的。</string>
<string name="connectors_imap_saved">已保存。凭据会在首次使用时验证。</string>
<string name="drawer_new_chat">新对话</string>
+ <string name="drawer_search_placeholder">搜索聊天</string>
+ <string name="drawer_search_clear">清除搜索</string>
+ <string name="drawer_search_results">结果(%1$d)</string>
+ <string name="drawer_search_no_results">没有与“%1$s”匹配的聊天。</string>
<string name="drawer_import_chats">导入对话</string>
<string name="drawer_back_up_all_chats">备份所有对话</string>
<string name="drawer_connectors">连接器</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 4eef222..2fa060c 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -760,6 +760,10 @@
<!-- AppDrawer -->
<string name="drawer_new_chat">New Chat</string>
+ <string name="drawer_search_placeholder">Search chats</string>
+ <string name="drawer_search_clear">Clear search</string>
+ <string name="drawer_search_results">Results (%1$d)</string>
+ <string name="drawer_search_no_results">No chats match “%1$s”.</string>
<!-- Import/backup moved to Settings ▸ Chats; the strings stay because the
settings rows reuse them, so no locale churn. -->
<string name="drawer_import_chats">Import chats</string>
diff --git a/app/src/test/java/com/gotcha/data/ChatSearchTest.kt b/app/src/test/java/com/gotcha/data/ChatSearchTest.kt
new file mode 100644
index 0000000..e109355
--- /dev/null
+++ b/app/src/test/java/com/gotcha/data/ChatSearchTest.kt
@@ -0,0 +1,155 @@
+package com.gotcha.data
+
+import com.gotcha.agent.MessageKind
+import com.gotcha.agent.UiMessage
+import com.gotcha.llm.ChatMessage
+import kotlinx.serialization.json.JsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The drawer's chat search: titles first, then the text of the chat itself. */
+class ChatSearchTest {
+
+ private fun chat(
+ id: String,
+ title: String,
+ vararg said: String
+ ) = ChatSession(
+ id = id,
+ title = title,
+ lastModified = 0L,
+ messages = emptyList(),
+ displayMessages = said.mapIndexed { index, text ->
+ UiMessage(id = index.toLong(), kind = MessageKind.USER, text = text)
+ }
+ )
+
+ @Test
+ fun `an empty query matches nothing, so the drawer shows every chat`() {
+ val sessions = listOf(chat("a", "Groceries", "milk"))
+ assertTrue(ChatSearch.search(sessions, "").isEmpty())
+ assertTrue(ChatSearch.search(sessions, " ").isEmpty())
+ }
+
+ @Test
+ fun `a title match returns the chat with no snippet`() {
+ val sessions = listOf(chat("a", "Groceries", "milk"))
+ val hits = ChatSearch.search(sessions, "groc")
+
+ assertEquals(1, hits.size)
+ assertEquals("a", hits.single().sessionId)
+ assertNull("the title already says why it matched", hits.single().snippet)
+ }
+
+ @Test
+ fun `a match inside the chat returns the line it was said in`() {
+ val sessions = listOf(
+ chat("a", "Trip", "Paris in May", "then Berlin in June"),
+ chat("b", "Work", "send the report")
+ )
+ val hit = ChatSearch.search(sessions, "berlin").single()
+
+ assertEquals("a", hit.sessionId)
+ assertTrue("snippet should hold the match: ${hit.snippet}", hit.snippet!!.contains("Berlin"))
+ }
+
+ @Test
+ fun `matching ignores case`() {
+ val sessions = listOf(chat("a", "Trip", "Paris in May"))
+ assertEquals(1, ChatSearch.search(sessions, "PARIS").size)
+ assertEquals(1, ChatSearch.search(sessions, "paris").size)
+ }
+
+ @Test
+ fun `no match returns nothing`() {
+ assertTrue(ChatSearch.search(listOf(chat("a", "Trip", "Paris")), "zebra").isEmpty())
+ }
+
+ @Test
+ fun `chats keep the order they were given`() {
+ val sessions = listOf(chat("new", "Trip", "Paris"), chat("old", "Travel", "Paris"))
+ // Both match on text, neither on title: the drawer order is kept.
+ assertEquals(listOf("new", "old"), ChatSearch.search(sessions, "paris").map { it.sessionId })
+ // Only the first matches on title.
+ assertEquals(listOf("new"), ChatSearch.search(sessions, "trip").map { it.sessionId })
+ }
+
+ @Test
+ fun `a chat saved before transcripts were kept is searched by its history`() {
+ val legacy = ChatSession(
+ id = "legacy",
+ title = "Old chat",
+ lastModified = 0L,
+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("the old words"))),
+ displayMessages = emptyList()
+ )
+ val hit = ChatSearch.search(listOf(legacy), "old words").single()
+ assertEquals("legacy", hit.sessionId)
+ assertTrue(hit.snippet!!.contains("old words"))
+ }
+
+ @Test
+ fun `a snippet never splits a surrogate pair`() {
+ // Emoji-dense text: the context slice and the 120-character cut both
+ // land mid-pair without the boundary guard.
+ val text = "😀".repeat(300) + " needle " + "😀".repeat(300)
+ val snippet = ChatSearch.search(listOf(chat("a", "Emoji", text)), "needle").single().snippet!!
+ assertTrue(snippet.contains("needle"))
+ assertFalse("a lone surrogate would render as a broken character: $snippet", hasLoneSurrogate(snippet))
+ }
+
+ private fun hasLoneSurrogate(text: String): Boolean {
+ var i = 0
+ while (i < text.length) {
+ val c = text[i]
+ when {
+ c.isHighSurrogate() -> {
+ if (i + 1 >= text.length || !text[i + 1].isLowSurrogate()) return true
+ i += 2
+ }
+ c.isLowSurrogate() -> return true
+ else -> i++
+ }
+ }
+ return false
+ }
+
+ @Test
+ fun `a long chat gets a short snippet around the match`() {
+ val long = "start " + "filler ".repeat(200) + "needle" + " tail ".repeat(200)
+ val hit = ChatSearch.search(listOf(chat("a", "Long", long)), "needle").single()
+ val snippet = hit.snippet!!
+
+ assertTrue("snippet must stay short: ${snippet.length}", snippet.length <= 130)
+ assertTrue(snippet.contains("needle"))
+ assertTrue("a cut snippet marks the cut", snippet.startsWith("…"))
+ assertTrue(snippet.endsWith("…"))
+ }
+
+ @Test
+ fun `blank lines are skipped, so a match never lands on whitespace`() {
+ val sessions = listOf(
+ ChatSession(
+ id = "a",
+ title = "Blanks",
+ lastModified = 0L,
+ messages = emptyList(),
+ displayMessages = listOf(
+ UiMessage(id = 0, kind = MessageKind.USER, text = " "),
+ UiMessage(id = 1, kind = MessageKind.ASSISTANT, text = "the answer")
+ )
+ )
+ )
+ val hit = ChatSearch.search(sessions, "answer").single()
+ assertEquals("the answer", hit.snippet)
+ }
+
+ @Test
+ fun `a match at the very start is not prefixed with an ellipsis`() {
+ val hit = ChatSearch.search(listOf(chat("a", "T", "needle at the start")), "needle").single()
+ assertTrue(hit.snippet!!.startsWith("needle"))
+ }
+}