Drawer search: the chats whose messages hold the words, under the title matches
CI / check (push) Canceled after 0s

GET /api/v2/search?in=chats (server f7f2ff2), 400 ms after typing pauses and from two
characters; the title filter stays local and instant. Hits under "In the messages" with the
snippet as plain text and the server's marks drawn (markedSnippet clamps ranges that do not
fit). A failed search leaves the title filter alone. ContractTest reads search.json;
ChatGroupsTest the marks; shot 05-drawer-search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-10 14:04:17 +00:00
1 parent 6ed3498bc0
commit 9b1bf688a1
21 files changed
+216 -2

No files matched your search

@@ -231,6 +231,8 @@ class MainActivity : ComponentActivity() {
override fun more() = chats.more()
override fun retry() = chats.load()
override fun search(query: String) = chats.search(query)
}
}
val menu: () -> Unit = { scope.launch { drawer.open() } }
@@ -171,6 +171,9 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
/** The folder and the folders inside it; their chats fall back to no folder. */
suspend fun deleteFolder(id: String) = empty(authed("$v2/folders/${segment(id)}").delete().build())
/** The web's search in JSON: chats by their words (and meaning, where indexed), files, memories. */
suspend fun search(q: String, within: String = "all", limit: Int = 20): SearchResults = get("/search?q=${segment(q)}&in=${segment(within)}&limit=$limit")
// --- Memory (`library.use`) -----------------------------------------------------------------
/** The person's memories, every data group, and the groups they may file one in. */
@@ -191,6 +191,35 @@ data class Folder(
@Serializable
data class FolderEnvelope(val folder: Folder)
/**
* One hit of `GET /api/v2/search`: a chat (by [id]), a file (by [path]) or a memory. [snippet] is
* plain text -- a chat's may be model output -- and [marks] the `[start, end)` ranges matched in it.
*/
@Serializable
data class SearchHit(
val kind: String = "",
val id: String? = null,
val title: String = "",
val snippet: String = "",
val marks: List<List<Int>> = emptyList(),
val archived: Boolean = false,
val agent: Boolean = false,
val path: String? = null,
)
@Serializable
data class SearchGroup(val kind: String = "", val more: Boolean = false, val hits: List<SearchHit> = emptyList())
@Serializable
data class SearchResults(
val q: String = "",
@SerialName("in") val within: String = "",
val offered: List<String> = emptyList(),
val results: List<SearchGroup> = emptyList(),
) {
fun hits(kind: String): List<SearchHit> = results.firstOrNull { it.kind == kind }?.hits.orEmpty()
}
/** A data group: whose records a memory is kept among. */
@Serializable
data class DataGroup(val id: String = "", val name: String = "")
@@ -1,5 +1,8 @@
package eu.llembas.android.ui.home
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Folder
import java.time.LocalDate
@@ -85,3 +88,17 @@ fun groupChats(chats: List<Chat>, query: String, today: LocalDate, zone: ZoneId,
val (now, before) = plain.partition { it.day(zone) == today }
return ChatGroups(today = now, earlier = before, agents = agents, pinned = pinned, folders = groups)
}
/**
* A search hit's snippet with its [marks] drawn in [style]. The ranges are the server's; one that
* runs past the text (it counts characters, not UTF-16 units) is cut to fit, and a broken one is
* left out, so a bad range never throws.
*/
fun markedSnippet(snippet: String, marks: List<List<Int>>, style: SpanStyle): AnnotatedString = buildAnnotatedString {
append(snippet)
marks.forEach { range ->
val start = range.getOrNull(0)?.coerceIn(0, snippet.length) ?: return@forEach
val end = range.getOrNull(1)?.coerceIn(start, snippet.length) ?: return@forEach
if (end > start) addStyle(style, start, end)
}
}
@@ -65,6 +65,8 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
@@ -73,11 +75,14 @@ import eu.llembas.android.R
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.Folder
import eu.llembas.android.api.SearchHit
import eu.llembas.android.api.fit
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.signin.refusal
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
@@ -95,6 +100,9 @@ data class ChatsState(
val error: String? = null,
/** The person's chat folders (`GET /folders`); empty where they have none. */
val folders: List<Folder> = emptyList(),
/** Chats whose messages hold the search words (`GET /search?in=chats`), and the words asked. */
val found: List<SearchHit> = emptyList(),
val foundFor: String = "",
)
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
@@ -161,6 +169,28 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
}
}
private var searching: Job? = null
/**
* Search the chats' messages on the instance for [query], once typing pauses: the title
* filter is the phone's own, this finds the words inside. Under two characters, nothing.
*/
fun search(query: String) {
searching?.cancel()
val q = query.trim()
if (q.length < 2) {
_state.update { it.copy(found = emptyList(), foundFor = "") }
return
}
searching = viewModelScope.launch {
delay(SEARCH_PAUSE_MS)
// A failure leaves the title filter alone; the search is the extra.
runCatching { getApplication<Application>().lembas.instances.client()?.search(q, within = "chats") }
.getOrNull()
?.let { found -> _state.update { it.copy(found = found.hits("chats"), foundFor = q) } }
}
}
/** Pinned chats stay at the top of the list, wherever they are filed (the web's Pin). */
fun pin(chat: Chat, pinned: Boolean) = changeChat(chat.copy(pinned = pinned), buildJsonObject { put("pinned", pinned) })
@@ -216,6 +246,8 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
}
}
private const val SEARCH_PAUSE_MS = 400L
/** Where the drawer can go, besides a chat. */
interface DrawerActions {
fun newChat() {}
@@ -235,6 +267,7 @@ interface DrawerActions {
fun settings() {}
fun more() {}
fun retry() {}
fun search(query: String) {}
}
/**
@@ -252,9 +285,11 @@ fun DrawerContent(
modifier: Modifier = Modifier,
today: LocalDate = LocalDate.now(),
zone: ZoneId = ZoneId.systemDefault(),
initialQuery: String = "",
) {
val palette = LocalPalette.current
var query by rememberSaveable { mutableStateOf("") }
var query by rememberSaveable { mutableStateOf(initialQuery) }
LaunchedEffect(query) { actions.search(query) }
val groups = remember(state.chats, state.folders, query, today) { groupChats(state.chats, query, today, zone, state.folders) }
// The one dialog open at a time: a chat to file, a folder to name (new or renamed), one to delete.
var moving by remember { mutableStateOf<Chat?>(null) }
@@ -326,7 +361,20 @@ fun DrawerContent(
section(R.string.chats_today, groups.today, current, chatActions)
section(R.string.chats_earlier, groups.earlier, current, chatActions)
section(R.string.chats_agents, groups.agents, current, chatActions)
if (groups.isEmpty && !state.loading && state.error == null) {
// What the instance found inside the messages, for the words in the box now.
val inMessages = if (query.isNotBlank() && state.foundFor == query.trim()) state.found.filter { it.id != null } else emptyList()
if (inMessages.isNotEmpty()) {
item(key = "hfound") {
Text(
stringResource(R.string.chats_found_in_messages),
style = MaterialTheme.typography.labelLarge,
color = palette.inkFaint,
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp),
)
}
items(inMessages, key = { "s${it.id}" }) { hit -> FoundItem(hit, onOpen = { actions.open(hit.id!!) }) }
}
if (groups.isEmpty && inMessages.isEmpty() && !state.loading && state.error == null) {
item {
Text(
stringResource(if (query.isBlank()) R.string.empty_chats else R.string.chats_none_found),
@@ -386,6 +434,38 @@ fun DrawerContent(
}
}
/**
* A chat found by its words: its title, and the snippet with the matched words marked (plain
* text -- a snippet can be model output).
*/
@Composable
private fun FoundItem(hit: SearchHit, onOpen: () -> Unit) {
val palette = LocalPalette.current
val marked = remember(hit.snippet, hit.marks, palette) {
markedSnippet(hit.snippet, hit.marks, SpanStyle(color = palette.ink, fontWeight = FontWeight.SemiBold, background = palette.accentSoft))
}
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.clip(RoundedCornerShape(20.dp))
.clickable(onClick = onOpen)
.heightIn(min = 48.dp)
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
Text(
hit.title.ifBlank { stringResource(R.string.new_chat) },
style = MaterialTheme.typography.bodyLarge,
color = palette.ink,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (hit.snippet.isNotBlank()) {
Text(marked, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
}
/** A folder to name: [folder] to rename, or a new one (into which [then] is filed, if given). */
private data class FolderNaming(val folder: Folder? = null, val then: Chat? = null)