diff --git a/androidApp/build.gradle.kts b/androidApp/build.gradle.kts index c5b39288..9bbb9422 100644 --- a/androidApp/build.gradle.kts +++ b/androidApp/build.gradle.kts @@ -6,6 +6,7 @@ plugins { alias(libs.plugins.androidApplication) alias(libs.plugins.composeMultiplatform) alias(libs.plugins.composeCompiler) + alias(libs.plugins.ksp) } val keystorePropertiesFile = rootProject.file("keystore.properties") @@ -59,13 +60,33 @@ kotlin { jvmTarget = JvmTarget.JVM_17 } } +ksp { + arg("appfunctions:aggregateAppFunctions", "true") +} + dependencies { implementation(projects.shared) implementation(libs.androidx.activity.compose) + // Ask GalwayBus: AppFunctions (also exposed to the system's assistants) and the on-device + // ML Kit agent that uses them as its tools. + implementation(libs.androidx.appfunctions) + ksp(libs.androidx.appfunctions.compiler) + implementation(libs.mlkit.genai.agent) + implementation(libs.markdown.renderer.m3) + implementation(libs.compose.runtime) + implementation(libs.compose.foundation) + implementation(libs.compose.material3) + implementation(libs.compose.material.icons.extended) + implementation(libs.compose.ui) + implementation(libs.androidx.lifecycle.viewmodelCompose) + implementation(libs.androidx.lifecycle.runtimeCompose) + implementation(libs.compose.uiToolingPreview) debugImplementation(libs.compose.uiTooling) + + testImplementation(libs.junit) } android { @@ -92,7 +113,8 @@ android { defaultConfig { applicationId = "dev.johnoreilly.galwaybus" - minSdk = libs.versions.android.minSdk.get().toInt() + // 26 rather than the shared minSdk: ML Kit genai-agent requires it + minSdk = 26 targetSdk = libs.versions.android.targetSdk.get().toInt() versionCode = versionCode() versionName = versionName() diff --git a/androidApp/proguard-rules.pro b/androidApp/proguard-rules.pro index 300f2482..cc5900d8 100644 --- a/androidApp/proguard-rules.pro +++ b/androidApp/proguard-rules.pro @@ -49,3 +49,12 @@ -dontwarn org.conscrypt.** -dontwarn org.bouncycastle.** -dontwarn org.openjsse.** + +# ML Kit (its bundled firebase-components) creates component registrars by reflection from +# manifest metadata, so R8 sees their no-arg constructors as unused and removes them. ML Kit then +# starts with no components and Generation.getClient() throws (BikeShare 1.0.17 crashed at launch +# this way: "Could not instantiate com.google.mlkit.common.internal.CommonComponentRegistrar"). +-keep class * implements com.google.firebase.components.ComponentRegistrar { (); } + +# AppFunctions: the system and the agent reach these by name, through KSP-generated code. +-keep class dev.johnoreilly.galwaybus.functions.** { *; } diff --git a/androidApp/src/main/AndroidManifest.xml b/androidApp/src/main/AndroidManifest.xml index 984b356b..a79260a5 100644 --- a/androidApp/src/main/AndroidManifest.xml +++ b/androidApp/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ - + @@ -32,6 +33,26 @@ + + + + + + + + + + \ No newline at end of file diff --git a/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/MainActivity.kt b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/MainActivity.kt index 132c0ae0..3d18b087 100644 --- a/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/MainActivity.kt +++ b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/MainActivity.kt @@ -6,14 +6,19 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview +import dev.johnoreilly.galwaybus.agent.AskGalwayBusAction +import dev.johnoreilly.galwaybus.agent.GalwayBusAgentViewModel import dev.johnoreilly.galwaybus.location.LocationController import dev.johnoreilly.galwaybus.scan.CameraController import kotlinx.coroutines.CompletableDeferred class MainActivity : ComponentActivity() { + private val agentViewModel: GalwayBusAgentViewModel by viewModels() + // Bridges the one-shot permission dialog (an Activity concern) to the shared LocationProvider's // suspend request. Only one request is ever in flight at a time. private var pendingPermission: CompletableDeferred? = null @@ -56,7 +61,7 @@ class MainActivity : ComponentActivity() { deferred.await() } - setContent { App() } + setContent { App(extraActions = { AskGalwayBusAction(agentViewModel) }) } } } diff --git a/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/agent/AskGalwayBus.kt b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/agent/AskGalwayBus.kt new file mode 100644 index 00000000..5df05857 --- /dev/null +++ b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/agent/AskGalwayBus.kt @@ -0,0 +1,494 @@ +package dev.johnoreilly.galwaybus.agent + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.AutoAwesome +import androidx.compose.material.icons.filled.Build +import androidx.compose.material.icons.filled.DeleteSweep +import androidx.compose.material.icons.filled.DirectionsBus +import androidx.compose.material.icons.filled.NearMe +import androidx.compose.material.icons.filled.Place +import androidx.compose.material.icons.filled.RssFeed +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Star +import androidx.compose.material3.AssistChip +import androidx.compose.material3.AssistChipDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +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.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.mikepenz.markdown.m3.Markdown +import com.mikepenz.markdown.model.rememberMarkdownState +import dev.johnoreilly.galwaybus.RouteBadge +import kotlinx.coroutines.withTimeoutOrNull +import java.util.Locale + +/** + * An "Ask" button for the top app bar that opens a chat with the on-device agent. Shows nothing + * until the agent is known to work on this device. + */ +@Composable +fun AskGalwayBusAction(viewModel: GalwayBusAgentViewModel) { + val availability by viewModel.availability.collectAsStateWithLifecycle() + var open by rememberSaveable { mutableStateOf(false) } + + // Only once the model is known to be usable, so the button doesn't flash up and vanish on the + // many devices where it isn't. In the app bar rather than a floating button, which would sit + // over the bottom navigation and the map's own refresh button. + if (availability == GalwayBusAgentViewModel.Availability.Ready || + availability is GalwayBusAgentViewModel.Availability.Downloading + ) { + IconButton(onClick = { open = true }) { + Icon(Icons.Filled.AutoAwesome, contentDescription = "Ask GalwayBus") + } + } + if (open) AskGalwayBusSheet(viewModel, onDismiss = { open = false }) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AskGalwayBusSheet(viewModel: GalwayBusAgentViewModel, onDismiss: () -> Unit) { + val availability by viewModel.availability.collectAsStateWithLifecycle() + val messages by viewModel.messages.collectAsStateWithLifecycle() + val busy by viewModel.busy.collectAsStateWithLifecycle() + val ready = availability == GalwayBusAgentViewModel.Availability.Ready + var input by rememberSaveable { mutableStateOf("") } + val listState = rememberLazyListState() + val lastReply = messages.lastOrNull() as? ChatMessage.Agent + + // Animate to a new message, but follow a streaming reply without animating: restarting an + // animation on every chunk of text made the list jitter. + LaunchedEffect(messages.size) { + if (messages.isNotEmpty()) listState.animateScrollToItem(messages.lastIndex) + } + LaunchedEffect(lastReply?.text?.length, lastReply?.departures, lastReply?.stops) { + if (messages.isNotEmpty() && !listState.isScrollInProgress) listState.scrollToItem(messages.lastIndex) + } + // Once the reply is complete, keep its end in view while it settles: the scroll above is + // skipped while another is animating, and the reply grows after it finishes, when the + // Markdown render replaces the plain text. Either left the answer below the input. + LaunchedEffect(lastReply?.inProgress) { + if (messages.isEmpty()) return@LaunchedEffect + withTimeoutOrNull(1_500) { + snapshotFlow { listState.canScrollForward }.collect { more -> + if (more) listState.scrollToItem(messages.lastIndex, scrollOffset = Int.MAX_VALUE) + } + } + } + + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + // Put the keyboard away once a question is asked: left open, it takes most of the sheet + // and only the first line or two of the answer is visible. Read inside the sheet, which + // is its own window: from outside, this acts on the activity's window instead. Focus + // stays put: clearing it moved focus to the drag handle, which then showed a grey box. + val keyboard = LocalSoftwareKeyboardController.current + val ask = { question: String -> + keyboard?.hide() + viewModel.ask(question) + } + Column(Modifier.fillMaxHeight(0.85f).imePadding()) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 16.dp)) { + Column(Modifier.weight(1f)) { + Text("Ask GalwayBus", style = MaterialTheme.typography.titleLarge) + Text( + "On-device Gemini Nano, using GalwayBus's AppFunctions", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton(onClick = viewModel::clear, enabled = messages.isNotEmpty() && !busy) { + Icon(Icons.Filled.DeleteSweep, contentDescription = "Clear conversation") + } + } + + when (val a = availability) { + GalwayBusAgentViewModel.Availability.Checking -> + Status("Checking for Gemini Nano…", progress = true) + is GalwayBusAgentViewModel.Availability.Downloading -> + Status("Downloading Gemini Nano" + (a.bytes?.let { " (${it / 1_000_000} MB)" } ?: "") + "…", progress = true) + is GalwayBusAgentViewModel.Availability.Unsupported -> Status(a.reason, progress = false) + GalwayBusAgentViewModel.Availability.Ready -> Unit + } + HorizontalDivider(Modifier.padding(top = 8.dp), color = MaterialTheme.colorScheme.outlineVariant) + + LazyColumn( + state = listState, + modifier = Modifier.weight(1f).fillMaxWidth(), + contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (messages.isEmpty() && ready) { + item { Suggestions(onPick = ask) } + } + itemsIndexed(messages) { index, message -> + when (message) { + is ChatMessage.User -> UserBubble(message) + is ChatMessage.Agent -> AgentReply( + message, + // Only the latest reply's stops ask a follow-up; older ones are history. + onStopClick = if (index == messages.lastIndex && !busy) { + { stop -> ask("When are the next buses from ${stop.name}, stop ${stop.stopNumber}?") } + } else null, + ) + } + } + } + + val send = { + if (input.isNotBlank() && !busy && ready) { + ask(input) + input = "" + } + } + OutlinedTextField( + value = input, + onValueChange = { input = it }, + enabled = ready, + placeholder = { Text("Ask about Galway buses") }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), + keyboardActions = KeyboardActions(onSend = { send() }), + singleLine = true, + shape = RoundedCornerShape(28.dp), + trailingIcon = { + IconButton(onClick = send, enabled = input.isNotBlank() && !busy && ready) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send") + } + }, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp) + .navigationBarsPadding(), + ) + } + } +} + +@Composable +private fun Status(text: String, progress: Boolean) { + Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) { + Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (progress) LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) + } +} + +@Composable +private fun Suggestions(onPick: (String) -> Unit) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("Try asking", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + listOf( + // Each is one or two calls. The places work because the functions look them up + // themselves; models asked for coordinates guess them. + Icons.Filled.Schedule to "When's the next bus from Eyre Square?", + Icons.Filled.DirectionsBus to "When does the next 405 leave Eyre Square for Rahoon?", + Icons.Filled.Place to "Which bus stops are near Galway Cathedral?", + Icons.Filled.NearMe to "Which bus stop is nearest me?", + ).forEach { (icon, suggestion) -> + AssistChip( + onClick = { onPick(suggestion) }, + label = { Text(suggestion) }, + leadingIcon = { Icon(icon, contentDescription = null, Modifier.size(AssistChipDefaults.IconSize)) }, + ) + } + } +} + +@Composable +private fun UserBubble(message: ChatMessage.User) { + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) { + Surface( + color = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + shape = RoundedCornerShape(18.dp, 18.dp, 4.dp, 18.dp), + modifier = Modifier.widthIn(max = 300.dp), + ) { + Text(message.text, Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) + } + } +} + +@Composable +private fun AgentReply(message: ChatMessage.Agent, onStopClick: ((StopItem) -> Unit)?) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + // Which AppFunctions the agent called: shows the tools are doing the work, not the model's + // memory. Tapping one shows the call exactly as the model made it. + // A stop the model passed by number reads better by name, which the results carry. + val stopNames = message.departures.associate { it.stopNumber to it.stopName } + + message.stops.associate { it.stopNumber to it.name } + ToolCalls(message.toolCalls, stopNames) + + // The tool results themselves, as the app shows them, so the times on screen come from + // the data rather than from the model's retelling of it. + when { + message.departures.isNotEmpty() -> DeparturesCard(message.departures) + message.stops.isNotEmpty() -> StopsCard(message.stops, onStopClick) + } + + when { + // Gemini Nano answers in Markdown (bold names, numbered and bulleted lists). The reply + // streams in, and each change is re-parsed: retainState keeps the last render on + // screen meanwhile, where the default blanks it to a loading state, which flashed. + message.text.isNotEmpty() -> Markdown( + rememberMarkdownState(message.text, retainState = true), + // The default for both is an empty box: a reply that hadn't parsed yet, or + // didn't parse, drew nothing at all (seen on a reply with no tool calls). + loading = { Text(message.text, it) }, + error = { Text(message.text, it) }, + ) + message.inProgress -> Working(message.toolCalls.lastOrNull()) + } + message.error?.let { + Text("Something went wrong: $it", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun ToolCalls(calls: List, stopNames: Map) { + if (calls.isEmpty()) return + var showRaw by remember { mutableStateOf(false) } + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + calls.forEach { call -> + AssistChip( + onClick = { showRaw = !showRaw }, + label = { + Text( + if (showRaw) call.raw else call.label(stopNames), + style = MaterialTheme.typography.labelMedium, + maxLines = if (showRaw) 3 else 1, + overflow = TextOverflow.Ellipsis, + ) + }, + leadingIcon = { Icon(call.icon(), contentDescription = null, Modifier.size(AssistChipDefaults.IconSize)) }, + modifier = Modifier.semantics { contentDescription = "Called ${call.raw}" }, + ) + } + } +} + +/** What the agent is doing while there's no answer yet. */ +@Composable +private fun Working(lastCall: ToolCall?) { + Row(verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Spacer(Modifier.width(10.dp)) + Text( + when (lastCall?.function) { + null -> "Thinking…" + "getDepartures" -> "Checking departures…" + "listRoutes" -> "Looking up routes…" + "listSavedStops" -> "Looking up your saved stops…" + else -> "Finding stops…" + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +private fun ToolCall.arg(name: String): String? = args[name]?.toString()?.takeIf { it.isNotBlank() } + +/** A tool call as a person would put it, e.g. "Departures · Eyre Square → Salthill". */ +internal fun ToolCall.label(stopNames: Map = emptyMap()): String = when (function) { + "getDepartures" -> buildString { + val stop = arg("stop") + append("Departures · ").append(stop?.let { stopNames[it] ?: it } ?: "stop") + arg("routeNumber")?.let { append(" · ").append(it) } + arg("towards")?.let { append(" → ").append(it) } + } + "findNearbyStops" -> when { + args["nearMe"] == true || arg("place") == null && arg("latitude") == null -> "Stops near you" + arg("place") != null -> "Stops near ${arg("place")}" + else -> "Stops near a location" + } + "findStops" -> "Stops matching “${arg("query").orEmpty()}”" + "listRoutes" -> "Routes" + "listSavedStops" -> "Your saved stops" + else -> function +} + +private fun ToolCall.icon(): ImageVector = when (function) { + "getDepartures" -> Icons.Filled.Schedule + "findNearbyStops" -> if (arg("place") == null) Icons.Filled.NearMe else Icons.Filled.Place + "findStops" -> Icons.Filled.Search + "listRoutes" -> Icons.AutoMirrored.Filled.List + "listSavedStops" -> Icons.Filled.Star + else -> Icons.Filled.Build +} + +@Composable +private fun ResultCard(content: @Composable () -> Unit) { + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth(), + ) { + Column(Modifier.padding(vertical = 4.dp)) { content() } + } +} + +@Composable +private fun DeparturesCard(departures: List) { + // Name the stop on each row only when they leave from different stops (a name like Eyre + // Square covers several); otherwise it's the same on every row. + val severalStops = departures.map { it.stopName }.distinct().size > 1 + ResultCard { + departures.take(MAX_CARD_ROWS).forEachIndexed { index, d -> + if (index > 0) HorizontalDivider(Modifier.padding(horizontal = 12.dp), color = MaterialTheme.colorScheme.outlineVariant) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), + ) { + RouteBadge(d.route, large = index == 0) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text(d.destination, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis) + val detail = listOfNotNull( + d.stopName.takeIf { severalStops }?.let { "from $it" }, + d.lateness(), + ).joinToString(" · ") + if (detail.isNotEmpty()) { + Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + DepartureTime(d, emphasised = index == 0) + } + } + } +} + +/** "Due", a countdown, or the clock time further out, as the app's own lists show it. */ +@Composable +private fun DepartureTime(d: DepartureItem, emphasised: Boolean) { + val live = d.minutesLate != null + val color = when { + !live -> MaterialTheme.colorScheme.onSurfaceVariant // timetable only + d.minutesLate!! > 0 -> MaterialTheme.colorScheme.error + else -> MaterialTheme.colorScheme.primary + } + Row(verticalAlignment = Alignment.CenterVertically) { + if (live) { + Icon(Icons.Filled.RssFeed, contentDescription = "Live", tint = color, modifier = Modifier.size(14.dp)) + Spacer(Modifier.width(4.dp)) + } + Text( + when { + d.minutesAway <= 0 -> "Due" + d.minutesAway < CLOCK_TIME_FROM_MINUTES -> "${d.minutesAway} min" + else -> d.departs + }, + style = if (emphasised) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyLarge, + fontWeight = if (emphasised) FontWeight.SemiBold else FontWeight.Normal, + color = color, + ) + } +} + +private fun DepartureItem.lateness(): String? = when { + minutesLate == null -> "Timetabled" + minutesLate > 0 -> "$minutesLate min late" + minutesLate < 0 -> "${-minutesLate} min early" + else -> null +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun StopsCard(stops: List, onStopClick: ((StopItem) -> Unit)?) { + ResultCard { + stops.take(MAX_CARD_ROWS).forEachIndexed { index, stop -> + if (index > 0) HorizontalDivider(Modifier.padding(horizontal = 12.dp), color = MaterialTheme.colorScheme.outlineVariant) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .then(if (onStopClick != null) Modifier.clickable { onStopClick(stop) } else Modifier) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Icon(Icons.Filled.Place, contentDescription = null, tint = MaterialTheme.colorScheme.primary) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(stop.name, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium) + Text( + listOfNotNull(stop.towards?.let { "Towards $it" }, "Stop ${stop.stopNumber}", stop.distanceMetres?.let(::distanceLabel)) + .joinToString(" · "), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (stop.routes.isNotEmpty()) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(top = 2.dp)) { + stop.routes.forEach { RouteBadge(it, large = false) } + } + } + } + if (onStopClick != null) { + Icon( + Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = "Next buses from ${stop.name}", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } +} + +private fun distanceLabel(metres: Int): String = + if (metres < 1_000) "$metres m" else String.format(Locale.getDefault(), "%.1f km", metres / 1_000.0) + +private const val MAX_CARD_ROWS = 6 + +// Matches the app's own lists (DepartureDisplay.kt): further out than this, a clock time is +// easier to plan with than a countdown. +private const val CLOCK_TIME_FROM_MINUTES = 20 diff --git a/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/agent/GalwayBusAgentViewModel.kt b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/agent/GalwayBusAgentViewModel.kt new file mode 100644 index 00000000..403b2815 --- /dev/null +++ b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/agent/GalwayBusAgentViewModel.kt @@ -0,0 +1,293 @@ +package dev.johnoreilly.galwaybus.agent + +import android.app.Application +import android.os.Build +import android.util.Log +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import com.google.mlkit.genai.agent.Agent +import com.google.mlkit.genai.agent.AgentEvent +import com.google.mlkit.genai.agent.AgentRunner +import com.google.mlkit.genai.agent.AgentSession +import com.google.mlkit.genai.common.DownloadStatus +import com.google.mlkit.genai.common.FeatureStatus +import com.google.mlkit.genai.prompt.Content +import com.google.mlkit.genai.prompt.Generation +import com.google.mlkit.genai.prompt.GenerativeModel +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * "Ask GalwayBus": an on-device agent (ML Kit GenAI agent API, Gemini Nano via AICore) whose tools + * are the app's own AppFunctions in [dev.johnoreilly.galwaybus.functions.BaseGalwayBusAppFunctionService], + * the same functions the system exposes to assistants. + * + * Needs Android 16 (AppFunctions), a device that supports Gemini Nano custom generation, and a + * Google account enrolled in the AICore Developer Preview. Anywhere else [availability] ends up + * [Availability.Unsupported] and the UI hides the entry point. + */ +class GalwayBusAgentViewModel(application: Application) : AndroidViewModel(application) { + + sealed interface Availability { + data object Checking : Availability + /** Gemini Nano is downloading; [bytes] so far, when known. */ + data class Downloading(val bytes: Long?) : Availability + data object Ready : Availability + data class Unsupported(val reason: String) : Availability + } + + private val _availability = MutableStateFlow(Availability.Checking) + val availability: StateFlow = _availability.asStateFlow() + + private val _messages = MutableStateFlow>(emptyList()) + val messages: StateFlow> = _messages.asStateFlow() + + private val _busy = MutableStateFlow(false) + val busy: StateFlow = _busy.asStateFlow() + + private val agent = Agent.builder() + .setName("GalwayBus") + .setInstructions(INSTRUCTIONS) + // Tools are discovered from the app's AppFunctions (getDepartures, findStops, + // findNearbyStops, listRoutes, listSavedStops); nothing is declared twice. + .enableAppFunctions(true) + .setMaxTurns(8) + .build() + + // Created on first use, after the model is known to be available. The session keeps the + // conversation history; living in the ViewModel, it survives rotation. + private var runner: AgentRunner? = null + private var session: AgentSession? = null + + init { + if (Build.VERSION.SDK_INT < 36) { + unsupported("AppFunctions need Android 16 (API 36); this is API ${Build.VERSION.SDK_INT}") + } else { + viewModelScope.launch { prepareModel() } + } + } + + private suspend fun prepareModel() { + // Everything ML Kit, getClient() included, stays inside the try: this runs at app start, + // and a failure here must hide "Ask", never crash the app (BikeShare 1.0.17 did, when R8 + // broke ML Kit's initialisation). + var model: GenerativeModel? = null + try { + model = Generation.getClient() + when (val status = model.checkStatus()) { + FeatureStatus.AVAILABLE -> _availability.value = Availability.Ready + FeatureStatus.DOWNLOADABLE, FeatureStatus.DOWNLOADING -> { + _availability.value = Availability.Downloading(null) + model.download().collect { download -> + when (download) { + is DownloadStatus.DownloadStarted -> _availability.value = Availability.Downloading(null) + is DownloadStatus.DownloadProgress -> + _availability.value = Availability.Downloading(download.totalBytesDownloaded) + DownloadStatus.DownloadCompleted -> _availability.value = Availability.Ready + is DownloadStatus.DownloadFailed -> + unsupported("Gemini Nano download failed: ${download.e.message}") + } + } + } + else -> unsupported( + "Gemini Nano isn't available here (status $status). The agent API needs a supported " + + "device and a Google account in the AICore Developer Preview." + ) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + unsupported("Couldn't check for Gemini Nano: ${e.message}") + } finally { + model?.close() + } + } + + fun ask(question: String) { + val text = question.trim() + if (text.isEmpty() || _busy.value || _availability.value != Availability.Ready) return + _busy.value = true + _messages.update { it + ChatMessage.User(text) + ChatMessage.Agent() } + viewModelScope.launch { + try { + val session = session ?: AgentRunner(getApplication(), agent).let { newRunner -> + runner = newRunner + newRunner.getOrCreateSession(SESSION_ID).also { session = it } + } + session.runAsync(Content.builder().text(text).build()).collect { event -> + _messages.update { it.withAgentEvent(event) } + } + _messages.update { it.finishAgentReply(error = null) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Agent run failed", e) + _messages.update { it.finishAgentReply(error = e.message ?: e.javaClass.simpleName) } + } finally { + _busy.value = false + } + } + } + + /** Forgets the conversation; the next question starts a fresh session. */ + fun clear() { + if (_busy.value) return + val current = session + session = null + _messages.value = emptyList() + viewModelScope.launch { runCatching { current?.delete() } } + } + + private fun unsupported(reason: String) { + Log.i(TAG, "Ask GalwayBus unavailable: $reason") + _availability.value = Availability.Unsupported(reason) + } + + override fun onCleared() { + session?.close() + runner?.close() + } + + private companion object { + const val TAG = "GalwayBusAgent" + const val SESSION_ID = "ask-galwaybus" + val INSTRUCTIONS = """ + You help people catch Galway city buses using GalwayBus's tools. + Never invent stops, routes or times: look them up with the tools. + For when buses leave a stop, call getDepartures with the stop's name, number or a + nearby place as stop. Only add routeNumber when the user names a route, and only add + towards when they say where they're going; otherwise leave them out. + For a stop from an earlier answer, pass its stopNumber as stop. + For stops near a place, call findNearbyStops with that place's name as place. Never + guess latitude and longitude. + For stops near the user ("near me", "closest to me"), call findNearbyStops with + nearMe true. For the next bus near them, then call getDepartures with the nearest + stop's stopNumber. + For the user's saved stops, call listSavedStops, then getDepartures with each stop's + stopNumber. + Your answer appears under a list of everything the tools returned, so never list + departures or stops yourself. Reply with one sentence about the first one only: + for a bus, its route, where it's going and minutesAway (and minutesLate when it + isn't 0 or null); for stops, the nearest stop's name. + """.trimIndent() + } +} + +/** One entry in the conversation. */ +sealed interface ChatMessage { + data class User(val text: String) : ChatMessage + + data class Agent( + val text: String = "", + /** AppFunctions called while answering, in order. */ + val toolCalls: List = emptyList(), + /** Departures from the latest getDepartures result, shown as cards. */ + val departures: List = emptyList(), + /** Stops from the latest stop search, shown as cards when there are no departures. */ + val stops: List = emptyList(), + val inProgress: Boolean = true, + val error: String? = null, + ) : ChatMessage +} + +/** An AppFunction call: [function] is the bare name, such as `getDepartures`. */ +data class ToolCall(val function: String, val args: Map) { + /** The call as the model made it, e.g. `getDepartures(stop=Eyre Square)`. */ + val raw: String get() = "$function(" + args.entries.joinToString { "${it.key}=${it.value}" } + ")" +} + +/** One row of a departure card, read from a [dev.johnoreilly.galwaybus.functions.DepartureResponse]. */ +data class DepartureItem( + val route: String, + val destination: String, + val stopName: String, + val stopNumber: String, + val departs: String, + val minutesAway: Int, + val minutesLate: Int?, +) + +/** One row of a stop card, read from a [dev.johnoreilly.galwaybus.functions.StopResponse]. */ +data class StopItem( + val name: String, + val stopNumber: String, + val towards: String?, + val routes: List, + val distanceMetres: Int?, +) + +/** + * Folds one [AgentEvent] into the reply being built (the last message). Partial text may arrive as + * deltas or as the text so far, so a partial that extends what we have replaces it, any other is + * appended; a complete message replaces the partials before it. + */ +internal fun List.withAgentEvent(event: AgentEvent): List { + val reply = lastOrNull() as? ChatMessage.Agent ?: return this + val updated = when (event) { + is AgentEvent.FunctionCall -> reply.copy( + toolCalls = reply.toolCalls + ToolCall(event.name.functionName(), event.args.filterValues { it != null }), + // The text so far was the model deciding what to call, not an answer. + text = "", + ) + is AgentEvent.FunctionResponse -> { + val results = (event.response["result"] as? List<*>).orEmpty().mapNotNull { it as? Map<*, *> } + when (event.name.functionName()) { + "getDepartures" -> reply.copy(departures = results.mapNotNull { it.toDeparture() }) + "findStops", "findNearbyStops", "listSavedStops" -> reply.copy(stops = results.mapNotNull { it.toStop() }) + else -> reply + } + } + // Gemini Nano's own function-call syntax arrives as text before each FunctionCall + // ("call:getDepartures{...}"); shown, it flashed up as the answer. + is AgentEvent.TextMessage -> if (event.text.contains(" event.text + event.text.startsWith(reply.text) -> event.text + else -> reply.text + event.text + } + ) + else -> reply + } + return dropLast(1) + updated +} + +internal fun List.finishAgentReply(error: String?): List { + val reply = lastOrNull() as? ChatMessage.Agent ?: return this + return dropLast(1) + reply.copy(text = reply.text.trim(), inProgress = false, error = error) +} + +// AppFunction ids look like "package.Class#function". +private fun String.functionName() = substringAfterLast('#').substringAfterLast('.') + +private fun Map<*, *>.string(key: String): String? = this[key]?.toString()?.takeIf { it.isNotBlank() } +private fun Map<*, *>.int(key: String): Int? = when (val v = this[key]) { + is Number -> v.toInt() + is String -> v.toIntOrNull() + else -> null +} + +internal fun Map<*, *>.toDeparture(): DepartureItem? = DepartureItem( + route = string("route") ?: return null, + destination = string("destination").orEmpty(), + stopName = string("stopName").orEmpty(), + stopNumber = string("stopNumber").orEmpty(), + departs = string("departs").orEmpty(), + minutesAway = int("minutesAway") ?: return null, + minutesLate = int("minutesLate"), +) + +internal fun Map<*, *>.toStop(): StopItem? = StopItem( + name = string("name") ?: return null, + stopNumber = string("stopNumber") ?: return null, + towards = string("towards"), + routes = when (val r = this["routes"]) { + is List<*> -> r.mapNotNull { it?.toString() } + null -> emptyList() + else -> listOf(r.toString()) + }, + distanceMetres = int("distanceMetres"), +) diff --git a/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/functions/GalwayBusAppFunctionService.kt b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/functions/GalwayBusAppFunctionService.kt new file mode 100644 index 00000000..2e9055cd --- /dev/null +++ b/androidApp/src/main/kotlin/dev/johnoreilly/galwaybus/functions/GalwayBusAppFunctionService.kt @@ -0,0 +1,474 @@ +package dev.johnoreilly.galwaybus.functions + +import android.Manifest +import android.content.pm.PackageManager +import android.location.Address +import android.location.Geocoder +import androidx.annotation.RequiresApi +import androidx.appfunctions.AppFunctionAppUnknownException +import androidx.appfunctions.AppFunctionDeclaration +import androidx.appfunctions.AppFunctionElementNotFoundException +import androidx.appfunctions.AppFunctionInvalidArgumentException +import androidx.appfunctions.AppFunctionNotSupportedException +import androidx.appfunctions.AppFunctionPermissionRequiredException +import androidx.appfunctions.AppFunctionSerializable +import androidx.appfunctions.AppFunctionService +import androidx.appfunctions.AppFunctionServiceEntryPoint +import dev.johnoreilly.galwaybus.GalwayBusPrefs +import dev.johnoreilly.galwaybus.GalwayBusRepository +import dev.johnoreilly.galwaybus.location.LocationController +import dev.johnoreilly.galwaybus.location.LocationProvider +import dev.johnoreilly.galwaybus.location.LocationResult +import dev.johnoreilly.galwaybus.location.distanceMeters +import dev.johnoreilly.galwaybus.model.DepartureTime +import dev.johnoreilly.galwaybus.model.Stop +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import kotlin.coroutines.resume +import kotlin.math.roundToInt + +/** + * AppFunctions for GalwayBus. KSP generates the concrete [GalwayBusAppFunctionService] registered + * in the manifest. They're what the system offers assistants, and the tools of the in-app + * "Ask GalwayBus" agent. + */ +@RequiresApi(36) +@AppFunctionServiceEntryPoint( + serviceName = "GalwayBusAppFunctionService", + appFunctionXmlFileName = "galwaybus_app_function_service", +) +abstract class BaseGalwayBusAppFunctionService : AppFunctionService() { + + private val repository by lazy { + // The service can start without the activity (an assistant calling in), and saved stops + // are read from preferences, which need a context. + GalwayBusPrefs.appContext = applicationContext + GalwayBusRepository() + } + + /** + * Lists Galway's city bus routes. + * + * @return Every route, with its number and the places it runs between. + */ + @AppFunctionDeclaration(isDescribedByKDoc = true) + suspend fun listRoutes(): List = withContext(Dispatchers.IO) { + load("the list of routes") { repository.getRoutes() } + .values + .sortedBy { it.short_name } + .map { RouteResponse(number = it.short_name, name = it.long_name) } + } + + /** + * Finds Galway bus stops by name or stop number. Most names cover several stops, one for each + * direction, so check [StopResponse.towards]. + * + * @param query Name of the stop ("Eyre Square", "Salthill"), or the number shown on the stop. + * Stop names are often shortened, such as "Hospl" for hospital and "Pk" for park. + * @param routeNumber Only include stops served by this route, such as "405". + * @param limit Maximum number of stops to return, from 1 to 20. Defaults to 10. + * @return The matching stops. + */ + @AppFunctionDeclaration(isDescribedByKDoc = true) + suspend fun findStops( + query: String, + routeNumber: String? = null, + limit: Int = 0, + ): List = withContext(Dispatchers.IO) { + if (query.isBlank()) throw AppFunctionInvalidArgumentException("Give a stop name or number to search for.") + stops() + .filter { it.matchesName(query) && it.servesRoute(routeNumber) } + .take(limit.inRange(DEFAULT_STOP_LIMIT)) + .map { it.toResponse(distanceMetres = null) } + } + + /** + * Finds the Galway bus stops closest to a place, or to the user, nearest first. + * + * @param place Name or address of a place in Galway, such as a landmark, street or area + * ("Galway Cathedral", "Shop Street"). The app looks up where it is, so use this for named + * places instead of guessing coordinates. + * @param nearMe True to search around the user's current location, for questions like + * "nearest stop to me". The app finds the location itself. + * @param latitude Latitude to search around, in degrees. Only when already known. + * @param longitude Longitude to search around, in degrees. Only when already known. + * @param routeNumber Only include stops served by this route, such as "405". + * @param limit Maximum number of stops to return, from 1 to 20. Defaults to 5. + * @return The nearest stops, with their distance from the place or the user. + */ + @AppFunctionDeclaration(isDescribedByKDoc = true) + suspend fun findNearbyStops( + place: String? = null, + nearMe: Boolean = false, + latitude: Double? = null, + longitude: Double? = null, + routeNumber: String? = null, + limit: Int = 0, + ): List = withContext(Dispatchers.IO) { + val (lat, lon) = when { + nearMe -> currentLocation() + !place.isNullOrBlank() -> locate(place) + latitude != null && longitude != null -> latitude to longitude + // With nothing to search around, "near me" is the only reading that makes sense. + else -> currentLocation() + } + stops() + .filter { it.servesRoute(routeNumber) } + .map { it to distanceMeters(lat, lon, it.latitude, it.longitude).roundToInt() } + .sortedBy { it.second } + .take(limit.inRange(DEFAULT_NEARBY_LIMIT)) + .map { (stop, distance) -> stop.toResponse(distance) } + } + + /** + * The next buses leaving a stop, soonest first, with live delays where buses are being tracked. + * + * @param stop The stop: its name ("Eyre Square"), the number shown on it, or a place near it + * ("Galway Cathedral"). A name covers every stop of that name, in both directions, unless + * [routeNumber] or [towards] narrow it. + * @param routeNumber Only include buses on this route, such as "405". Only when the user + * names a route; omit it to include every route at the stop. + * @param towards Only include buses that go to this place: where they end ("Rahoon") or a + * stop or place on the way ("Salthill"). Only when the user says where they're going. + * @param limit Maximum number of departures to return, from 1 to 20. Defaults to 8. + * @return The departures, with the stop each one leaves from. + */ + @AppFunctionDeclaration(isDescribedByKDoc = true) + suspend fun getDepartures( + stop: String, + routeNumber: String? = null, + towards: String? = null, + limit: Int = 0, + ): List = withContext(Dispatchers.IO) { + val candidates = resolveStops(stop).filter { it.servesRoute(routeNumber) } + if (candidates.isEmpty()) { + throw AppFunctionElementNotFoundException( + if (routeNumber.isNullOrBlank()) "No stop called '$stop'. Try findStops or findNearbyStops." + else "No stop called '$stop' is served by route $routeNumber." + ) + } + // Where "towards" is, as stops: a bus goes there if its route reaches one of them after the + // stop it leaves from. Matching the destination alone missed places on the way: no route + // ends at Salthill, so "Eyre Square to Salthill" found nothing, though the 401 goes there. + val destinations = towards?.takeIf { it.isNotBlank() }?.let { place -> + resolveStops(place).mapTo(mutableSetOf()) { it.stop_ref } + }.orEmpty() + val now = Instant.now() + val departures = coroutineScope { + candidates.take(MAX_STOPS_PER_DEPARTURES).map { s -> + async { s to load("departures for ${s.long_name}") { repository.getStopDeparturesWithLive(s.stop_ref) } } + }.awaitAll() + } + .flatMap { (s, departures) -> departures.times.map { s to it } } + .filter { (_, d) -> routeNumber.isNullOrBlank() || d.timetable_id.equals(routeNumber.trim(), ignoreCase = true) } + val routes = if (destinations.isEmpty()) emptyMap() else coroutineScope { + departures.map { it.second.timetable_id }.distinct().map { route -> + // Route details are cached, and come back empty rather than failing. + async { + route to RouteStops( + repository.getDirectionHeadsigns(route), + repository.getStopsForRoute(route).map { direction -> direction.map { it.stop_ref } }, + ) + } + }.awaitAll().toMap() + } + departures + .filter { (s, d) -> + towards.isNullOrBlank() || d.display_name.matchesText(towards) || + routes[d.timetable_id]?.reaches(s.stop_ref, d.display_name, destinations) == true + } + .mapNotNull { (s, d) -> d.toResponse(s, now) } + .sortedBy { it.minutesAway } + .take(limit.inRange(DEFAULT_DEPARTURE_LIMIT)) + } + + /** + * Lists the stops the user has saved as favourites in the app. + * + * @return The saved stops, in the order the user keeps them. Empty if they haven't saved any. + */ + @AppFunctionDeclaration(isDescribedByKDoc = true) + suspend fun listSavedStops(): List = withContext(Dispatchers.IO) { + val saved = repository.getFavouriteStops() + if (saved.isEmpty()) return@withContext emptyList() + val byRef = stops().associateBy { it.stop_ref } + saved.mapNotNull { byRef[it.stopRef]?.toResponse(distanceMetres = null) } + } + + /** + * The stops [stop] could mean: a stop number, then a stop name, then (when no stop has that + * name) the stops near a place of that name. The last is what makes "the next bus from the + * cathedral" one call: models otherwise guess a stop name, or coordinates. + */ + private suspend fun resolveStops(stop: String): List { + val text = stop.trim() + if (text.isEmpty()) throw AppFunctionInvalidArgumentException("Give a stop name, number or nearby place.") + val all = stops() + all.firstOrNull { it.stop_id == text || it.stop_ref.equals(text, ignoreCase = true) }?.let { return listOf(it) } + all.filter { it.matchesName(text) }.takeIf { it.isNotEmpty() }?.let { return it } + val (lat, lon) = try { + locate(text) + } catch (e: AppFunctionElementNotFoundException) { + return emptyList() + } catch (e: AppFunctionNotSupportedException) { + return emptyList() + } + // The nearest stop, and the others of its name close by (the far side of the road). A + // plain radius took in neighbouring stops too, and listed the same bus at each of them. + val nearest = all.minByOrNull { distanceMeters(lat, lon, it.latitude, it.longitude) } ?: return emptyList() + if (distanceMeters(lat, lon, nearest.latitude, nearest.longitude) > NEAR_PLACE_METRES) return emptyList() + return all.filter { + it.long_name == nearest.long_name && + distanceMeters(nearest.latitude, nearest.longitude, it.latitude, it.longitude) <= SAME_STOP_METRES + } + } + + /** + * Where the user is, from the same location provider as the app's "Near me" tab. It never asks + * for permission: an assistant can call this with no activity to show the prompt from, so + * the agent is told to have the user allow it in the app, or to name a place instead. + */ + private suspend fun currentLocation(): Pair { + val fine = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED + val coarse = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED + if (!fine && !coarse) { + throw AppFunctionPermissionRequiredException( + "GalwayBus doesn't have location permission. Ask the user to allow it from the app's Near me tab, or to name a place near them." + ) + } + LocationController.appContext = applicationContext + val location = when (val result = LocationProvider().currentLocation()) { + is LocationResult.Available -> result.location + LocationResult.PermissionDenied -> throw AppFunctionPermissionRequiredException( + "GalwayBus doesn't have location permission. Ask the user to allow it from the app's Near me tab, or to name a place near them." + ) + LocationResult.Unavailable -> throw AppFunctionNotSupportedException( + "The user's location isn't available right now (location may be off). Ask them to name a place near them." + ) + } + val fromCentre = distanceMeters(GALWAY_LAT, GALWAY_LON, location.lat, location.lon) + if (fromCentre > MAX_PLACE_DISTANCE_METRES) { + throw AppFunctionElementNotFoundException( + "The user is about ${(fromCentre / 1000).roundToInt()}km from Galway city, so no Galway bus stop is near them." + ) + } + return location.lat to location.lon + } + + /** + * Where [place] is, looked up with [Geocoder] within Galway first, so "the cathedral" is + * Galway's. Gemini Nano, given only names, guesses coordinates; the BikeShare agent put + * "near Tower Bridge" 3.5km out. + */ + private suspend fun locate(place: String): Pair { + if (!Geocoder.isPresent()) { + throw AppFunctionNotSupportedException( + "Looking up places isn't available on this device. Use findStops with a stop name instead." + ) + } + val geocoder = Geocoder(applicationContext) + // A place Galway doesn't have ("Tower Bridge") comes back as Galway itself, the city's + // centre, which would answer with Eyre Square's buses. Only a match more precise than + // the city counts. + val address = geocoder.find(place, GALWAY_SOUTH, GALWAY_WEST, GALWAY_NORTH, GALWAY_EAST) + ?.takeUnless { it.isJustTheCity() } + ?: geocoder.find("$place, Galway")?.takeUnless { it.isJustTheCity() } + ?: throw AppFunctionElementNotFoundException("Couldn't find a place called '$place' in Galway.") + if (distanceMeters(GALWAY_LAT, GALWAY_LON, address.latitude, address.longitude) > MAX_PLACE_DISTANCE_METRES) { + throw AppFunctionElementNotFoundException("'$place' was found, but it isn't in Galway.") + } + return address.latitude to address.longitude + } + + private fun Address.isJustTheCity(): Boolean = + thoroughfare == null && premises == null && subLocality == null && + (featureName == null || featureName.equals(locality, ignoreCase = true)) + + private suspend fun Geocoder.find(name: String, vararg box: Double): Address? = + suspendCancellableCoroutine { continuation -> + val listener = object : Geocoder.GeocodeListener { + override fun onGeocode(addresses: MutableList
) = + continuation.resume(addresses.firstOrNull()) + override fun onError(errorMessage: String?) = continuation.resume(null) + } + if (box.size == 4) { + getFromLocationName(name, 1, box[0], box[1], box[2], box[3], listener) + } else { + getFromLocationName(name, 1, listener) + } + } + + private suspend fun stops(): List = load("the list of stops") { repository.getStops() } + + /** + * Runs [block], turning a failure to reach the GalwayBus backend into an error the agent can + * relay, rather than an unexplained failure or an empty result. + */ + private suspend fun load(what: String, block: suspend () -> T): T = + try { + block() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + println("AppFunctions: loading $what failed: $e") + throw AppFunctionAppUnknownException("Couldn't load $what. Check the connection and try again.") + } + + private companion object { + const val DEFAULT_STOP_LIMIT = 10 + const val DEFAULT_NEARBY_LIMIT = 5 + const val DEFAULT_DEPARTURE_LIMIT = 8 + const val MAX_LIMIT = 20 + // Eyre Square alone has seven stops; more than this and the answer is too long to use. + const val MAX_STOPS_PER_DEPARTURES = 8 + // A place this far from its nearest stop has no stop of its own to answer for. + const val NEAR_PLACE_METRES = 500 + // Stops of the same name this close together are one stop, either side of the road. + const val SAME_STOP_METRES = 300 + + // Galway city, roughly: the area place lookups search first and the stops cover. + const val GALWAY_LAT = 53.2740 + const val GALWAY_LON = -9.0490 + const val GALWAY_SOUTH = 53.22 + const val GALWAY_NORTH = 53.34 + const val GALWAY_WEST = -9.20 + const val GALWAY_EAST = -8.88 + const val MAX_PLACE_DISTANCE_METRES = 15_000 + + // An omitted limit arrives as 0, not the declared default. + fun Int.inRange(default: Int) = if (this <= 0) default else coerceAtMost(MAX_LIMIT) + } +} + +/** A route's stops in order, one list per direction, and where each direction is headed. */ +internal class RouteStops(private val headsigns: List, private val directions: List>) { + /** + * Whether a bus leaving stop [from] for [headsign] reaches any of [destinations] after it. The + * headsign picks the direction; when it matches none (or the data is missing it), any + * direction that reaches a destination after [from] counts. + */ + fun reaches(from: String, headsign: String, destinations: Set): Boolean { + val chosen = headsigns.indices.filter { headsigns[it].equals(headsign, ignoreCase = true) } + .ifEmpty { directions.indices.toList() } + return chosen.any { i -> + val stops = directions.getOrNull(i) ?: return@any false + val start = stops.indexOf(from) + start >= 0 && stops.drop(start + 1).any { it in destinations } + } + } +} + +/** A Galway city bus route. */ +@AppFunctionSerializable(isDescribedByKDoc = true) +data class RouteResponse( + /** Route number, such as "405". */ + val number: String, + /** The places the route runs between, such as "Rahoon - Eyre Square - Ballybane". */ + val name: String, +) + +/** A Galway bus stop. */ +@AppFunctionSerializable(isDescribedByKDoc = true) +data class StopResponse( + /** Name of the stop, such as "Eyre Square". Several stops can share a name. */ + val name: String, + /** The number shown on the stop, which identifies it uniquely. */ + val stopNumber: String, + /** Where buses from this stop are heading, such as "Rahoon", or null when unknown. */ + val towards: String?, + /** Numbers of the routes that stop here. */ + val routes: List, + /** Latitude of the stop, in degrees. */ + val latitude: Double, + /** Longitude of the stop, in degrees. */ + val longitude: Double, + /** Distance from the searched place in metres, or null when no place was searched. */ + val distanceMetres: Int?, +) + +/** A bus due to leave a stop. */ +@AppFunctionSerializable(isDescribedByKDoc = true) +data class DepartureResponse( + /** Route number, such as "405". */ + val route: String, + /** Where the bus is going. */ + val destination: String, + /** Name of the stop it leaves from. */ + val stopName: String, + /** The number shown on the stop it leaves from. */ + val stopNumber: String, + /** Time it leaves, as 24-hour local time such as "14:05". */ + val departs: String, + /** Minutes from now until it leaves; 0 means it's due now. */ + val minutesAway: Int, + /** + * Minutes behind the timetable (negative if early), when the bus is being tracked live; null + * when this is the timetabled time only. + */ + val minutesLate: Int?, +) + +internal fun Stop.toResponse(distanceMetres: Int?) = StopResponse( + name = long_name, + stopNumber = stop_id, + towards = direction, + routes = routes.orEmpty(), + latitude = latitude, + longitude = longitude, + distanceMetres = distanceMetres, +) + +private val DUBLIN = ZoneId.of("Europe/Dublin") +private val CLOCK = DateTimeFormatter.ofPattern("HH:mm") + +internal fun DepartureTime.toResponse(stop: Stop, now: Instant): DepartureResponse? { + val at = depart_timestamp?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return null + return DepartureResponse( + route = timetable_id, + destination = display_name, + stopName = stop.long_name, + stopNumber = stop.stop_id, + departs = CLOCK.format(at.atZone(DUBLIN)), + // Rounded like the app's own countdown, so the two agree. + minutesAway = (((at.epochSecond - now.epochSecond) + 30) / 60).toInt().coerceAtLeast(0), + minutesLate = delaySeconds?.let { (it / 60.0).roundToInt() }, + ) +} + +internal fun Stop.servesRoute(routeNumber: String?): Boolean = + routeNumber.isNullOrBlank() || routes.orEmpty().any { it.equals(routeNumber.trim(), ignoreCase = true) } + +/** + * Whether a stop answers to [query]: its number, or every word of the query starting a word of + * its English or Irish name ("eyre sq" finds "Eyre Square", "salthill prom" finds "Salthill Prom"). + */ +internal fun Stop.matchesName(query: String): Boolean { + val text = query.trim() + if (text == stop_id) return true + return long_name.matchesText(text) || long_name_ga?.matchesText(text) == true +} + +/** Every word of [query] starts a word of this text, ignoring case, accents and punctuation. */ +internal fun String.matchesText(query: String): Boolean { + val wanted = query.words() + if (wanted.isEmpty()) return false + val have = words() + return wanted.all { w -> have.any { it.startsWith(w) } } +} + +private fun String.words(): List = + java.text.Normalizer.normalize(lowercase(), java.text.Normalizer.Form.NFD) + .replace(Regex("\\p{Mn}+"), "") + .split(Regex("[^a-z0-9]+")) + .filter { it.isNotEmpty() && it !in STOP_WORDS } + +// Words models add that stop names don't have ("the Eyre Square stop"). +private val STOP_WORDS = setOf("the", "stop", "bus", "an", "na", "galway") diff --git a/androidApp/src/main/res/values/strings.xml b/androidApp/src/main/res/values/strings.xml index 7830ad0f..942f15fe 100644 --- a/androidApp/src/main/res/values/strings.xml +++ b/androidApp/src/main/res/values/strings.xml @@ -1,3 +1,4 @@ GalwayBus - \ No newline at end of file + Lets assistants find Galway city bus stops and check when the next buses leave them, with live delays. + diff --git a/androidApp/src/main/res/xml/app_metadata.xml b/androidApp/src/main/res/xml/app_metadata.xml new file mode 100644 index 00000000..092e1c1e --- /dev/null +++ b/androidApp/src/main/res/xml/app_metadata.xml @@ -0,0 +1,12 @@ + + diff --git a/androidApp/src/test/kotlin/dev/johnoreilly/galwaybus/agent/ChatMessageReducerTest.kt b/androidApp/src/test/kotlin/dev/johnoreilly/galwaybus/agent/ChatMessageReducerTest.kt new file mode 100644 index 00000000..07a7bdf8 --- /dev/null +++ b/androidApp/src/test/kotlin/dev/johnoreilly/galwaybus/agent/ChatMessageReducerTest.kt @@ -0,0 +1,94 @@ +package dev.johnoreilly.galwaybus.agent + +import com.google.mlkit.genai.agent.AgentEvent +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ChatMessageReducerTest { + + private val start: List = listOf(ChatMessage.User("q"), ChatMessage.Agent()) + private val fn = "dev.johnoreilly.galwaybus.functions.BaseGalwayBusAppFunctionService#" + + private fun List.reply() = last() as ChatMessage.Agent + + @Test + fun `partial text deltas are appended and the complete message replaces them`() { + val messages = start + .withAgentEvent(AgentEvent.TextMessage("The next", true)) + .withAgentEvent(AgentEvent.TextMessage(" bus", true)) + assertEquals("The next bus", messages.reply().text) + assertEquals("Done.", messages.withAgentEvent(AgentEvent.TextMessage("Done.", false)).reply().text) + } + + @Test + fun `the model's raw function-call text is not shown`() { + val messages = start.withAgentEvent( + AgentEvent.TextMessage("call:getDepartures{stop:Eyre Square}", false) + ) + assertEquals("", messages.reply().text) + } + + @Test + fun `a function call is recorded by name, and clears text written before it`() { + val messages = start + .withAgentEvent(AgentEvent.TextMessage("call:get", true)) + .withAgentEvent(AgentEvent.FunctionCall(fn + "getDepartures", mapOf("stop" to "Eyre Square", "towards" to null))) + val call = messages.reply().toolCalls.single() + assertEquals("getDepartures", call.function) + assertEquals("getDepartures(stop=Eyre Square)", call.raw) + assertEquals("", messages.reply().text) + } + + @Test + fun `departures are read from the function response`() { + val response = mapOf( + "result" to arrayListOf( + mapOf("route" to "405", "destination" to "Rahoon", "stopName" to "Eyre Square", "stopNumber" to "524371", + "departs" to "12:02", "minutesAway" to 12L, "minutesLate" to 0L), + mapOf("route" to "405", "destination" to "Rahoon", "stopName" to "Eyre Square", "stopNumber" to "524371", + "departs" to "12:22", "minutesAway" to 31), + mapOf("destination" to "no route, dropped"), + ) + ) + val departures = start.withAgentEvent(AgentEvent.FunctionResponse(fn + "getDepartures", response)).reply().departures + assertEquals(2, departures.size) + assertEquals(DepartureItem("405", "Rahoon", "Eyre Square", "524371", "12:02", 12, 0), departures[0]) + assertEquals(null, departures[1].minutesLate) + } + + @Test + fun `stops are read from a stop search, with one route or several`() { + val response = mapOf( + "result" to listOf( + mapOf("name" to "Galway Cathdrl", "stopNumber" to "522571", "towards" to "Rahoon", + "routes" to listOf("402", "404"), "distanceMetres" to 41), + mapOf("name" to "University Hospl", "stopNumber" to "522551", "routes" to "402"), + ) + ) + val stops = start.withAgentEvent(AgentEvent.FunctionResponse(fn + "findNearbyStops", response)).reply().stops + assertEquals(listOf("402", "404"), stops[0].routes) + assertEquals(41, stops[0].distanceMetres) + assertEquals(listOf("402"), stops[1].routes) + assertEquals(null, stops[1].towards) + } + + @Test + fun `finishing trims the text and stops progress`() { + val done = start.withAgentEvent(AgentEvent.TextMessage(" Hi \n", false)).finishAgentReply(null).reply() + assertEquals("Hi", done.text) + assertTrue(!done.inProgress) + } + + @Test + fun `tool calls read as a person would put them`() { + assertEquals( + "Departures · Eyre Square · 405 → Rahoon", + ToolCall("getDepartures", mapOf("stop" to "Eyre Square", "routeNumber" to "405", "towards" to "Rahoon")).label(), + ) + assertEquals("Departures · Galway Cathdrl", ToolCall("getDepartures", mapOf("stop" to "523181")).label(mapOf("523181" to "Galway Cathdrl"))) + assertEquals("Stops near you", ToolCall("findNearbyStops", mapOf("nearMe" to true)).label()) + assertEquals("Stops near Galway Cathedral", ToolCall("findNearbyStops", mapOf("place" to "Galway Cathedral")).label()) + assertEquals("Stops matching “Salthill”", ToolCall("findStops", mapOf("query" to "Salthill")).label()) + } +} diff --git a/androidApp/src/test/kotlin/dev/johnoreilly/galwaybus/functions/StopMatchingTest.kt b/androidApp/src/test/kotlin/dev/johnoreilly/galwaybus/functions/StopMatchingTest.kt new file mode 100644 index 00000000..1082864d --- /dev/null +++ b/androidApp/src/test/kotlin/dev/johnoreilly/galwaybus/functions/StopMatchingTest.kt @@ -0,0 +1,117 @@ +package dev.johnoreilly.galwaybus.functions + +import dev.johnoreilly.galwaybus.model.DepartureTime +import dev.johnoreilly.galwaybus.model.Stop +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant + +class StopMatchingTest { + + private val eyreSquare = Stop( + stop_ref = "8460B5243701", + stop_id = "524371", + long_name = "Eyre Square", + long_name_ga = "An Fhaiche Mhór", + short_name = "Eyre Square", + latitude = 53.2749, + longitude = -9.0491, + routes = listOf("404", "405"), + direction = "Rahoon", + ) + + @Test + fun `matches a name ignoring case and the words models add`() { + assertTrue(eyreSquare.matchesName("eyre square")) + assertTrue(eyreSquare.matchesName("the Eyre Square stop")) + assertTrue(eyreSquare.matchesName("Eyre Sq")) + assertFalse(eyreSquare.matchesName("Salthill")) + } + + @Test + fun `matches the Irish name without accents`() { + assertTrue(eyreSquare.matchesName("Fhaiche Mhor")) + } + + @Test + fun `matches the stop number`() { + assertTrue(eyreSquare.matchesName("524371")) + assertFalse(eyreSquare.matchesName("52437")) + } + + @Test + fun `every word of the query has to match`() { + assertFalse(eyreSquare.matchesName("Eyre Road")) + assertFalse("Dr. Mannix Road".matchesText("")) + assertTrue("Dr. Mannix Road".matchesText("mannix")) + } + + @Test + fun `route filter`() { + assertTrue(eyreSquare.servesRoute(null)) + assertTrue(eyreSquare.servesRoute(" 405 ")) + assertFalse(eyreSquare.servesRoute("401")) + } + + @Test + fun `departure in local time, rounded minutes and delay`() { + val now = Instant.parse("2026-11-28T11:00:00Z") + val live = DepartureTime( + display_name = "Rahoon", + timetable_id = "405", + depart_timestamp = "2026-11-28T11:02:39Z", + delaySeconds = -141, + ).toResponse(eyreSquare, now)!! + assertEquals("11:02", live.departs) // Irish winter time is UTC + assertEquals(3, live.minutesAway) + assertEquals(-2, live.minutesLate) + assertEquals("524371", live.stopNumber) + + val timetabled = DepartureTime("Newcastle", "404", "2026-07-01T11:18:30Z").toResponse(eyreSquare, now)!! + assertEquals("12:18", timetabled.departs) // summer time is UTC+1 + assertNull(timetabled.minutesLate) + } + + @Test + fun `departure without a time is dropped`() { + assertNull(DepartureTime("Rahoon", "405").toResponse(eyreSquare, Instant.now())) + } +} + +class RouteStopsTest { + + // Route 401's shape: Eyre Square in the middle, Salthill only on the way to Dr. Mannix Road. + private val route401 = RouteStops( + headsigns = listOf("An Phairc Mhor", "Dr. Mannix Road"), + directions = listOf( + listOf("mannix", "salthill-a", "eyre-a", "parkmore"), + listOf("parkmore", "eyre-b", "salthill-b", "mannix"), + ), + ) + private val salthill = setOf("salthill-a", "salthill-b") + + @Test + fun `a place on the way counts`() { + assertTrue(route401.reaches("eyre-b", "Dr. Mannix Road", salthill)) + } + + @Test + fun `a place already passed does not`() { + assertFalse(route401.reaches("eyre-a", "An Phairc Mhor", salthill)) + } + + @Test + fun `an unknown headsign checks every direction`() { + assertTrue(route401.reaches("eyre-b", "Somewhere else", salthill)) + assertFalse(route401.reaches("parkmore", "Somewhere else", setOf("nowhere"))) + } + + @Test + fun `a stop not on the route never reaches`() { + assertFalse(route401.reaches("elsewhere", "Dr. Mannix Road", salthill)) + assertFalse(RouteStops(emptyList(), emptyList()).reaches("eyre-b", "Dr. Mannix Road", salthill)) + } +} diff --git a/build.gradle.kts b/build.gradle.kts index d8d60e34..be44166c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -6,6 +6,7 @@ plugins { alias(libs.plugins.composeMultiplatform) apply false alias(libs.plugins.composeCompiler) apply false alias(libs.plugins.kotlinJvm) apply false + alias(libs.plugins.ksp) apply false alias(libs.plugins.kotlinMultiplatform) apply false } // Ktor's JS/wasm client pins ws 8.20.1 (still on Ktor main), which is in the range of a ws security diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c9846b2a..704f577d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,6 +2,13 @@ agp = "9.1.1" androidx-camera = "1.7.0" mlkit-text = "16.0.1" +# Held at alpha13: ML Kit genai-agent 1.0.0-alpha1 calls into AppFunctions and was built against +# alpha13. beta01 moved AppFunctionName out of the metadata package, so agent tool discovery fails +# with NoSuchMethodError on anything newer. Move both together once ML Kit ships a new agent. +androidx-appfunctions = "1.0.0-alpha13" +mlkit-genai-agent = "1.0.0-alpha1" +markdownRenderer = "0.46.0" +ksp = "2.3.14" android-compileSdk = "37" android-minSdk = "24" android-targetSdk = "36" @@ -45,6 +52,10 @@ androidx-camera-camera2 = { module = "androidx.camera:camera-camera2", version.r androidx-camera-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = "androidx-camera" } androidx-camera-view = { module = "androidx.camera:camera-view", version.ref = "androidx-camera" } mlkit-text-recognition = { module = "com.google.mlkit:text-recognition", version.ref = "mlkit-text" } +mlkit-genai-agent = { module = "com.google.mlkit:genai-agent", version.ref = "mlkit-genai-agent" } +androidx-appfunctions = { module = "androidx.appfunctions:appfunctions", version.ref = "androidx-appfunctions" } +androidx-appfunctions-compiler = { module = "androidx.appfunctions:appfunctions-compiler", version.ref = "androidx-appfunctions" } +markdown-renderer-m3 = { module = "com.mikepenz:multiplatform-markdown-renderer-m3", version.ref = "markdownRenderer" } maps-compose = { module = "com.google.maps.android:maps-compose", version.ref = "maps-compose" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity" } compose-uiTooling = { module = "org.jetbrains.compose.ui:ui-tooling", version.ref = "composeMultiplatform" } @@ -83,5 +94,6 @@ composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "composeMul composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } kotlinJvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } shadowPlugin = { id = "com.gradleup.shadow", version.ref = "shadowPlugin" } \ No newline at end of file diff --git a/renovate.json b/renovate.json index a95b04c6..52035267 100644 --- a/renovate.json +++ b/renovate.json @@ -21,6 +21,13 @@ "gradle" ], "allowedVersions": "<9.7" + }, + { + "description": "ML Kit genai-agent 1.0.0-alpha1 was built against AppFunctions 1.0.0-alpha13 and fails (NoSuchMethodError) with beta01 and later, which moved AppFunctionName. Hold AppFunctions until a new genai-agent is out, then update both together.", + "matchPackageNames": [ + "/^androidx\\.appfunctions:/" + ], + "enabled": false } ] } diff --git a/shared/src/commonMain/kotlin/dev/johnoreilly/galwaybus/App.kt b/shared/src/commonMain/kotlin/dev/johnoreilly/galwaybus/App.kt index 11ae214a..4cdbe3df 100644 --- a/shared/src/commonMain/kotlin/dev/johnoreilly/galwaybus/App.kt +++ b/shared/src/commonMain/kotlin/dev/johnoreilly/galwaybus/App.kt @@ -125,8 +125,12 @@ private val GalwayDarkColors = darkColorScheme( outlineVariant = Color(0xFF524343) ) +/** + * @param extraActions Extra buttons for the main screen's top app bar, ahead of Settings. Android + * uses it for "Ask GalwayBus", which needs Android-only APIs. + */ @Composable -fun App() { +fun App(extraActions: @Composable () -> Unit = {}) { val repository = remember { GalwayBusRepository() } val viewModel = viewModel { GalwayBusViewModel(repository) } var showSettings by remember { mutableStateOf(false) } @@ -143,7 +147,8 @@ fun App() { viewModel = viewModel, showSettings = showSettings, onOpenSettings = { showSettings = true }, - onCloseSettings = { showSettings = false } + onCloseSettings = { showSettings = false }, + extraActions = extraActions ) } } @@ -448,7 +453,8 @@ fun GalwayBusApp( viewModel: GalwayBusViewModel, showSettings: Boolean = false, onOpenSettings: () -> Unit = {}, - onCloseSettings: () -> Unit = {} + onCloseSettings: () -> Unit = {}, + extraActions: @Composable () -> Unit = {} ) { if (showSettings) { SettingsScreen(viewModel = viewModel, onBack = onCloseSettings) @@ -568,6 +574,7 @@ fun GalwayBusApp( modifier = Modifier.padding(end = 8.dp) ) } + extraActions() IconButton(onClick = onOpenSettings) { Icon(Icons.Filled.Settings, contentDescription = stringResource(Res.string.settings)) } @@ -1787,10 +1794,11 @@ private fun RouteChip(route: String) { /** * Route number badge against a departure. The `large` (next-bus) badge is filled with the - * brand maroon to anchor the card; smaller "later" badges use the light container tint. + * brand maroon to anchor the card; smaller "later" badges use the light container tint. Public + * so Android's Ask GalwayBus cards match the app's own departure lists. */ @Composable -private fun RouteBadge(route: String, large: Boolean) { +fun RouteBadge(route: String, large: Boolean) { val bg = if (large) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.primaryContainer val fg = if (large) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onPrimaryContainer Box(