Modern Apps git

← Modern-Apps.git

openassistant: register directions, ride estimate, order lookup, contact search (#assistant)

Commit
7ae8ae1f0cbad376eba3db4cb99c64bb44d9a1a6
Author
Vayun Mathur <[email protected]>
When
2026-11-16 22:55 UTC (19 days ago)
Parents
d676689
P2 quick wins from the OpenAssistant design (oa-design.md §2/§5):
the maps DirectionsIntent, taxi RideEstimateIntent and fooddelivery
OrderLookupIntent providers already exist and are consumed by other
apps, so this registers them in the assistant as READ tools with
spec + handler + intents client only. DTOs stay in
library.intents.maps / .taxi / .fooddelivery unchanged.

- domain/AssistantToolSpecs.kt: get_directions (from_lat/from_lng/
  to_lat/to_lng NUMBER, mode STRING optional default drive),
  get_ride_estimate (pickup/dest lat/lng NUMBER, labels optional),
  food_order_lookup (name, lat/lng NUMBER, address optional) and
  search_contacts (query). All READ; get_contacts is unchanged.
- util/AssistantToolIntents.kt: launchIntent clients following the
  existing pattern (maps com.vayunmathur.maps
  com.vayunmathur.maps.intents.DirectionsIntent, taxi
  com.vayunmathur.taxi.intents.RideEstimateIntent, fooddelivery
  OrderLookupIntent), APP_NAMES entries for Maps/Taxi/FoodDelivery,
  and pure helpers filterContacts (case-insensitive name/phone
  substring, cap 10), summarizeDirections, summarizeRideEstimate
  and summarizeOrderLookup.
- Directions is host-truncated: summarizeDirections returns only
  distance/duration plus segment and point counts, never the full
  polyline, respecting the 1024-token reply cap.
- search_contacts reuses the contacts GetIntent list and filters
  host-side via the pure filterContacts function.
- AndroidManifest: signature uses-permissions ACCESS_MAPS /
  ACCESS_RIDES / ACCESS_ORDERS and <queries> packages for the
  three provider apps (INTERNET was already declared).
- platform/AssistantTools.kt: handlers for the four tools via
  intents.runTool, so a missing provider app produces the usual
  friendly install message.

Tests: AssistantToolsInvokeTest covers missing-app results for
the four tools and the 33-tool declaration count;
AssistantToolIntentsTest covers the new MissingApp paths;
AssistantToolsTest covers spec parity and the numeric-param set;
new AssistantWebToolsTest covers filterContacts (name/phone,
case-insensitive, cap) and summarizeDirections (exact summary,
no polyline leak, empty-route case) as pure functions.

Note: adding tools changes the declared tool set hashed into the
baked gemma4_prefix.kv; the prefix is invalidated (still correct,
first turns prefill until rebaked with bake_gemma4_prefix).

Verified: ./gradlew :openassistant:testDevUnitTest
:openassistant:compileDevKotlin green (final tree, both commits).

Diff

openassistant/src/main/AndroidManifest.xml
diff --git a/openassistant/src/main/AndroidManifest.xml b/openassistant/src/main/AndroidManifest.xmlindex fd1eecc2e9..3709a75bb4 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -17,6 +17,9 @@     <uses-permission android:name="com.vayunmathur.email.permissions.ACCESS_EMAIL" />     <uses-permission android:name="com.vayunmathur.clock.permissions.ACCESS_CLOCK" />     <uses-permission android:name="com.vayunmathur.todo.permissions.ACCESS_TODO" />+    <uses-permission android:name="com.vayunmathur.maps.permissions.ACCESS_MAPS" />+    <uses-permission android:name="com.vayunmathur.taxi.permissions.ACCESS_RIDES" />+    <uses-permission android:name="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />      <uses-permission android:name="android.permission.READ_CONTACTS" />     <uses-permission android:name="android.permission.WRITE_CONTACTS" />@@ -50,6 +53,9 @@         <package android:name="com.vayunmathur.email" />         <package android:name="com.vayunmathur.clock" />         <package android:name="com.vayunmathur.todo" />+        <package android:name="com.vayunmathur.maps" />+        <package android:name="com.vayunmathur.taxi" />+        <package android:name="com.vayunmathur.fooddelivery" />     </queries>      <application
openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.ktindex 9988c27b2a..c828e1ca33 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -123,6 +123,44 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(             p("data_json", description = "optional initial data model as a JSON object string", required = false),         ),     ),+    ToolSpec(+        "get_directions",+        "Get directions between two coordinates in the Maps app. Returns distance, duration and segment count.",+        listOf(+            p("from_lat", NUMBER, "origin latitude"),+            p("from_lng", NUMBER, "origin longitude"),+            p("to_lat", NUMBER, "destination latitude"),+            p("to_lng", NUMBER, "destination longitude"),+            p("mode", description = "drive (default), transit, walk, or bicycle", required = false),+        ),+    ),+    ToolSpec(+        "get_ride_estimate",+        "Get a ride fare and pickup ETA estimate from the Taxi app.",+        listOf(+            p("pickup_lat", NUMBER, "pickup latitude"),+            p("pickup_lng", NUMBER, "pickup longitude"),+            p("dest_lat", NUMBER, "destination latitude"),+            p("dest_lng", NUMBER, "destination longitude"),+            p("pickup_label", description = "optional pickup label", required = false),+            p("dest_label", description = "optional destination label", required = false),+        ),+    ),+    ToolSpec(+        "food_order_lookup",+        "Check whether a named restaurant is orderable near a location via the FoodDelivery app.",+        listOf(+            p("name", description = "restaurant name"),+            p("lat", NUMBER, "latitude"),+            p("lng", NUMBER, "longitude"),+            p("address", description = "optional address", required = false),+        ),+    ),+    ToolSpec(+        "search_contacts",+        "Search contacts by name or phone number substring (case-insensitive, max 10 results).",+        listOf(p("query", description = "name or phone substring to search for")),+    ),     ToolSpec("get_memories", "Get a list of all memories"),     ToolSpec("remove_memory", "Remove a memory by its id (requires confirmation)", listOf(p("id", NUMBER)), risk = WRITE_CONFIRM),     ToolSpec("add_to_memory", "Add a new memory to the list of memories", listOf(p("content"))),
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.ktindex 1532bd1649..569461829f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -148,6 +148,32 @@ class AssistantTools(             intents.runTool { intents.getWeather(a.number("latitude"), a.number("longitude")) }         },         "get_weather_by_name" to { a -> intents.runTool { intents.getWeatherByName(a.string("location")) } },+        "get_directions" to { a ->+            intents.runTool {+                intents.getDirections(+                    a.number("from_lat"), a.number("from_lng"),+                    a.number("to_lat"), a.number("to_lng"),+                    a.string("mode", "drive"),+                )+            }+        },+        "get_ride_estimate" to { a ->+            intents.runTool {+                intents.getRideEstimate(+                    a.number("pickup_lat"), a.number("pickup_lng"),+                    a.number("dest_lat"), a.number("dest_lng"),+                    a.string("pickup_label"), a.string("dest_label"),+                )+            }+        },+        "food_order_lookup" to { a ->+            intents.runTool {+                intents.foodOrderLookup(+                    a.string("name"), a.number("lat"), a.number("lng"), a.string("address"),+                )+            }+        },+        "search_contacts" to { a -> intents.runTool { intents.searchContacts(a.string("query")) } },         "render_ui" to { a -> renderUi(a.string("components_json"), a.string("data_json")) },         "get_memories" to { _ -> intents.runTool { device.getMemories(memoryDao) } },         "remove_memory" to { a -> intents.runTool { device.removeMemory(memoryDao, a.number("id")) } },
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.ktindex ecc0d34dfe..56ddd38fa7 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt@@ -19,6 +19,12 @@ import com.vayunmathur.library.intents.todo.CompleteTodoData import com.vayunmathur.library.intents.todo.GetTodosQuery import com.vayunmathur.library.intents.todo.InsertTodoData import com.vayunmathur.library.intents.todo.TodoData+import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult+import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.taxi.RideEstimateRequest+import com.vayunmathur.library.intents.taxi.RideEstimateResult import com.vayunmathur.library.intents.weather.WeatherData import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao@@ -50,6 +56,9 @@ internal class AssistantToolIntents(private val context: Context) {             "com.vayunmathur.weather" to "Weather",             "com.vayunmathur.clock" to "Clock",             "com.vayunmathur.todo" to "Todo",+            "com.vayunmathur.maps" to "Maps",+            "com.vayunmathur.taxi" to "Taxi",+            "com.vayunmathur.fooddelivery" to "FoodDelivery",         )          fun getMissingAppMessage(packageName: String): String {@@ -219,6 +228,63 @@ internal class AssistantToolIntents(private val context: Context) {         return result.error ?: result.toString()     } +    suspend fun getDirections(+        fromLat: Double,+        fromLng: Double,+        toLat: Double,+        toLng: Double,+        mode: String,+    ): String {+        val result: DirectionsResult = launchIntent(+            context,+            "com.vayunmathur.maps",+            "com.vayunmathur.maps.intents.DirectionsIntent",+            DirectionsRequest(fromLat, fromLng, toLat, toLng, mode.ifBlank { "drive" }),+        )+        return summarizeDirections(result)+    }++    suspend fun getRideEstimate(+        pickupLat: Double,+        pickupLng: Double,+        destLat: Double,+        destLng: Double,+        pickupLabel: String,+        destLabel: String,+    ): String {+        val result: RideEstimateResult = launchIntent(+            context,+            "com.vayunmathur.taxi",+            "com.vayunmathur.taxi.intents.RideEstimateIntent",+            RideEstimateRequest(+                pickupLat, pickupLng, destLat, destLng,+                pickupLabel.takeIf { it.isNotBlank() },+                destLabel.takeIf { it.isNotBlank() },+            ),+        )+        return summarizeRideEstimate(result)+    }++    suspend fun foodOrderLookup(name: String, lat: Double, lng: Double, address: String): String {+        val result: OrderLookupResult = launchIntent(+            context,+            "com.vayunmathur.fooddelivery",+            "com.vayunmathur.fooddelivery.intents.OrderLookupIntent",+            OrderLookupRequest(name, lat, lng, address.takeIf { it.isNotBlank() }),+        )+        return summarizeOrderLookup(result)+    }++    suspend fun getContactsList(): List<ContactData> = launchIntent<Unit, List<ContactData>>(+        context,+        "com.vayunmathur.contacts",+        "com.vayunmathur.contacts.intents.GetIntent",+        Unit,+    )++    suspend fun searchContacts(query: String): String =+        filterContacts(query, getContactsList()).toString()+     suspend fun getMemories(memoryDao: MemoryDao?): String =         memoryDao?.getAll()?.joinToString("\n") { "[${it.id}] ${it.content}" }             ?: "Error: MemoryDao is null"@@ -269,6 +335,48 @@ suspend inline fun <reified Input : Any, reified Output : Any> launchIntent(     return Json.decodeFromString(serializer<Output>(), stringOutput) } +/** Pure contact filter for `search_contacts`: case-insensitive substring on name/phone, capped. */+fun filterContacts(query: String, contacts: List<ContactData>, cap: Int = 10): List<ContactData> {+    val needle = query.trim().lowercase()+    if (needle.isEmpty()) return contacts.take(cap)+    return contacts.filter {+        it.name.lowercase().contains(needle) || it.phoneNumber.lowercase().contains(needle)+    }.take(cap)+}++/**+ * Host-truncated directions summary: totals + segment count only. The full polyline/segments+ * never reach the model (token cap) — this string is all `get_directions` returns.+ */+fun summarizeDirections(result: DirectionsResult): String {+    if (result.polyline.isEmpty() && result.distanceMeters <= 0.0) return "No route found"+    val km = result.distanceMeters / 1000.0+    val dist = if (km >= 10) "%.1f km".format(km) else "%.2f km".format(km)+    val mins = kotlin.math.round(result.durationSeconds / 60.0).toInt()+    val dur = when {+        mins >= 60 -> "${mins / 60}h ${mins % 60}m"+        mins > 0 -> "$mins min"+        else -> "${result.durationSeconds.toInt()}s"+    }+    return "Route: $dist, $dur, ${result.segments.size} segment(s), ${result.polyline.size} point(s)"+}++/** Short ride-estimate summary for the model. */+fun summarizeRideEstimate(result: RideEstimateResult): String =+    if (!result.available) {+        "No ride available for this trip"+    } else {+        "Ride estimate: ${result.fareEstimate}, pickup ETA ${result.etaMinutes} min"+    }++/** Short order-lookup summary for the model. */+fun summarizeOrderLookup(result: OrderLookupResult): String =+    if (!result.available) {+        "Not orderable nearby"+    } else {+        "Orderable: merchantId=${result.merchantId}, link=${result.deepLink}"+    }+ @OptIn(ExperimentalSerializationApi::class) suspend inline fun <reified Input : Any> launchIntentU(     context: Context,
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex d75ea967fc..b9dc6b4707 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -44,7 +44,7 @@ class AssistantToolsInvokeTest {         assertEquals("Error: create_note needs title", call("create_note", "content" to "x"))         assertTrue(             call("set_timer", "seconds" to "abc").contains("must be a number"))-        assertEquals(29, tools.declarations.size)+        assertEquals(33, tools.declarations.size)     }      @Test fun crossAppToolsReportMissingApps() {@@ -73,6 +73,21 @@ class AssistantToolsInvokeTest {             call("get_weather", "latitude" to "1.5", "longitude" to "2.5")                 .startsWith("The Weather app is required"))         assertTrue(call("get_weather_by_name", "location" to "Lisbon").startsWith("The Weather app"))+        assertTrue(+            call(+                "get_directions",+                "from_lat" to "1.0", "from_lng" to "2.0", "to_lat" to "3.0", "to_lng" to "4.0",+            ).startsWith("The Maps app is required"))+        assertTrue(+            call(+                "get_ride_estimate",+                "pickup_lat" to "1.0", "pickup_lng" to "2.0", "dest_lat" to "3.0", "dest_lng" to "4.0",+            ).startsWith("The Taxi app is required"))+        assertTrue(+            call("food_order_lookup", "name" to "Sushi", "lat" to "1.0", "lng" to "2.0")+                .startsWith("The FoodDelivery app is required"))+        assertTrue(+            call("search_contacts", "query" to "ann").startsWith("The Contacts app is required"))     }      @Test fun deviceToolsRunLocally() {
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktindex 460f982af6..aa6c327117 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -14,7 +14,7 @@ class AssistantToolsTest {     @Test     fun namesAreUniqueSnakeCase() {         val names = ASSISTANT_TOOL_SPECS.map { it.name }-        assertEquals(29, names.size)+        assertEquals(33, names.size)         assertEquals(names.size, names.toSet().size)         for (spec in ASSISTANT_TOOL_SPECS) {             assertTrue(snake.matches(spec.name), spec.name)@@ -56,6 +56,11 @@ class AssistantToolsTest {                 "set_alarm.hour", "set_alarm.minute", "set_timer.seconds",                 "get_weather.latitude", "get_weather.longitude", "remove_memory.id",                 "create_todo.due", "create_todo.priority",+                "get_directions.from_lat", "get_directions.from_lng",+                "get_directions.to_lat", "get_directions.to_lng",+                "get_ride_estimate.pickup_lat", "get_ride_estimate.pickup_lng",+                "get_ride_estimate.dest_lat", "get_ride_estimate.dest_lng",+                "food_order_lookup.lat", "food_order_lookup.lng",             ),             numeric,         )
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.ktindex 06b2149c8c..056bcd4b3d 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt@@ -99,6 +99,17 @@ class AssistantToolIntentsTest {         assertFailsWith<MissingAppException> { tools.setTimer(SetTimerData(seconds = 300)) }         assertFailsWith<MissingAppException> { tools.getWeather(1.0, 2.0) }         assertFailsWith<MissingAppException> { tools.getWeatherByName("Lisbon") }+        assertFailsWith<MissingAppException> { tools.getDirections(1.0, 2.0, 3.0, 4.0, "drive") }+        assertFailsWith<MissingAppException> { tools.getRideEstimate(1.0, 2.0, 3.0, 4.0, "", "") }+        assertFailsWith<MissingAppException> { tools.foodOrderLookup("Sushi", 1.0, 2.0, "") }+        assertFailsWith<MissingAppException> { tools.searchContacts("ann") }+        assertTrue(+            AssistantToolIntents.getMissingAppMessage("com.vayunmathur.maps").contains("The Maps app"))+        assertTrue(+            AssistantToolIntents.getMissingAppMessage("com.vayunmathur.taxi").contains("The Taxi app"))+        assertTrue(+            AssistantToolIntents.getMissingAppMessage("com.vayunmathur.fooddelivery")+                .contains("The FoodDelivery app"))         // And via runTool they become the friendly message instead of a throw.         assertTrue(tools.runTool { tools.getNotes() }.startsWith("The Notes app is required"))     }
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.ktnew file mode 100644index 0000000000..fc02bb3e18--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt@@ -0,0 +1,51 @@+package com.vayunmathur.openassistant.util++import com.vayunmathur.library.intents.contacts.ContactData+import com.vayunmathur.library.intents.maps.DirectionsLatLng+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.maps.DirectionsSegment+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** P2 pure helpers: contact filtering and directions summarisation. */+class AssistantWebToolsTest {++    @Test fun filterContactsMatchesNameAndPhoneCaseInsensitively() {+        val contacts = listOf(+            ContactData("Alice Smith", "555-0100"),+            ContactData("bob jones", "555-0199"),+            ContactData("Carol Alice", "555-0111"),+            ContactData("Dan", "555-ALICE"),+        )+        assertEquals(+            listOf("Alice Smith", "Carol Alice", "Dan"),+            filterContacts("alice", contacts).map { it.name },+        )+        assertEquals(listOf("bob jones"), filterContacts("BOB", contacts).map { it.name })+        assertEquals(listOf("Alice Smith"), filterContacts("0100", contacts).map { it.name })+        assertTrue(filterContacts("zzz", contacts).isEmpty())+        // Cap holds at 10.+        val many = (1..20).map { ContactData("Ann $it", "1$it") }+        assertEquals(10, filterContacts("ann", many).size)+    }++    @Test fun summarizeDirectionsDropsPolyline() {+        val points = (1..500).map { DirectionsLatLng(1.0 + it * 0.001, 2.0) }+        val result = DirectionsResult(+            polyline = points,+            segments = listOf(+                DirectionsSegment(points.take(250), 1.0),+                DirectionsSegment(points.drop(250), 0.4),+            ),+            distanceMeters = 12_340.0,+            durationSeconds = 2_700.0,+        )+        val out = summarizeDirections(result)+        assertEquals("Route: 12.3 km, 45 min, 2 segment(s), 500 point(s)", out)+        // No coordinate text leaks into the model-visible summary.+        assertFalse(out.contains("DirectionsLatLng"), out)+        assertEquals("No route found", summarizeDirections(DirectionsResult(emptyList(), emptyList(), 0.0, 0.0)))+    }+}