Phone actions: the confirm card and the capability (harness spec 3.6.0, server e463621)
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
- Contract and strings pinned at server dev e463621 (event_ask_phone.json); tokens unchanged.
- Every message declares client ["phone_actions"] (POST /chats and /chats/{id}/messages).
- CardItem.phone; a phone_action card (chat card sheet, and inline in the assistant's sheet):
the model's summary, how it will be done, its facts, the map app to use when Settings leaves
it open, Google Maps' limits said; Cancel answers declined, Do it runs ActionRunner and
answers {result: {status, message}} -- done or failed with why. Locked: "unlock first".
- Executor on the spec's fields: alarm time HH:MM/days/label, timer, calendar_event
(start/end local, notes), sms_draft (numbers only; names left to the person), email_draft
with cc, dial, open_app by name, open_url, media command, torch on, settings_panel,
automation_intent (Tasker's ACTION_TASK by name with values as local variables, else
LLeMbas's own AUTOMATION broadcast), navigate (replace_route -> OsmAnd force), add_stop,
search_nearby (near), stop_navigation. Tool-result reasons in English, for the model.
- Tests: PhoneActionsTest reads the fixture; shots 35-38 phone cards.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
26 files changed
+944
-69
No files matched your search
@@ -32,12 +32,12 @@ object ActionRunner {
|
||||
suspend fun run(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean = false): ActionOutcome {
|
||||
when (action) {
|
||||
"torch" -> return PhoneActions.torch(context, args.bool("on"))
|
||||
"media" -> return PhoneActions.media(context, args.str("key").ifBlank { "play_pause" })
|
||||
"media" -> return PhoneActions.media(context, args.str("command").ifBlank { "toggle" })
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" -> return navigate(context, action, args, nav, askOsmAnd)
|
||||
}
|
||||
val intent = PhoneActions.intentFor(context, action, args)
|
||||
?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return PhoneActions.launch(context, intent, broadcast = action == "automation")
|
||||
return PhoneActions.launch(context, intent, broadcast = action == "automation_intent")
|
||||
}
|
||||
|
||||
private suspend fun navigate(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean): ActionOutcome {
|
||||
@@ -47,13 +47,24 @@ object ActionRunner {
|
||||
// OsmAnd's own position and destination, if the person allowed LLeMbas to ask it.
|
||||
val info = if (app == NavApp.OsmAnd && askOsmAnd && action != "stop_navigation") osmandInfo(context, pkg) else null
|
||||
val step = when (action) {
|
||||
"navigate" -> args.place("destination")?.let { NavIntents.navigate(app, pkg, it, args.places("stops"), travel, info) }
|
||||
"navigate" -> args.place("destination")?.let {
|
||||
NavIntents.navigate(app, pkg, it, args.places("stops"), travel, info, replace = args.bool("replace_route") == true)
|
||||
}
|
||||
|
||||
"add_stop" -> args.place("stop")?.let {
|
||||
NavIntents.addStop(app, pkg, it, args.place("destination"), travel, info, NO_DESTINATION)
|
||||
}
|
||||
|
||||
"search_nearby" -> args.str("query").takeIf { it.isNotBlank() }?.let { NavIntents.searchNearby(app, pkg, it, info) }
|
||||
"search_nearby" -> args.str("query").takeIf { it.isNotBlank() }?.let {
|
||||
NavIntents.searchNearby(
|
||||
app,
|
||||
pkg,
|
||||
it,
|
||||
info,
|
||||
alongRoute =
|
||||
args.str("near") == "route",
|
||||
)
|
||||
}
|
||||
|
||||
else -> NavIntents.stop(app, pkg, GOOGLE_CANNOT_STOP)
|
||||
} ?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
|
||||
@@ -100,18 +100,25 @@ data class OsmAndInfo(val lat: Double?, val lon: Double?, val destination: Place
|
||||
object NavIntents {
|
||||
private const val GOOGLE_STOPS = 9
|
||||
|
||||
fun navigate(app: NavApp, pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?): NavStep = when (app) {
|
||||
NavApp.GoogleMaps -> google(pkg, destination, stops, travel)
|
||||
NavApp.OsmAnd -> osmand(pkg, destination, stops, travel, info)
|
||||
}
|
||||
/** [replace]: a route already running is replaced without the map app asking first (OsmAnd asks otherwise). */
|
||||
fun navigate(app: NavApp, pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, replace: Boolean = false): NavStep =
|
||||
when (app) {
|
||||
NavApp.GoogleMaps -> google(pkg, destination, stops, travel)
|
||||
NavApp.OsmAnd -> osmand(pkg, destination, stops, travel, info, if (replace) "true" else "false")
|
||||
}
|
||||
|
||||
/** A stop on the way to the route's destination ([destination] from the model, else OsmAnd's own). */
|
||||
fun addStop(app: NavApp, pkg: String, stop: Place, destination: Place?, travel: Travel, info: OsmAndInfo?, noDestination: String): NavStep {
|
||||
val to = destination?.takeIf { it.hasCoordinates || it.searchText.isNotBlank() } ?: info?.destination ?: return NavStep.Unsupported(noDestination)
|
||||
return navigate(app, pkg, to, listOf(stop), travel, info)
|
||||
// Planned again from here: the route being replaced is the one the person asked to change.
|
||||
return navigate(app, pkg, to, listOf(stop), travel, info, replace = true)
|
||||
}
|
||||
|
||||
fun searchNearby(app: NavApp, pkg: String, query: String, info: OsmAndInfo?): NavStep = when {
|
||||
/**
|
||||
* [alongRoute] searches near the running route; OsmAnd is given the phone's position for both
|
||||
* (its search ranks along the route itself while one runs), Google Maps searches near here.
|
||||
*/
|
||||
fun searchNearby(app: NavApp, pkg: String, query: String, info: OsmAndInfo?, alongRoute: Boolean = false): NavStep = when {
|
||||
app == NavApp.OsmAnd && info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
@@ -152,12 +159,12 @@ object NavIntents {
|
||||
|
||||
private fun googlePlace(p: Place) = if (p.hasCoordinates) "${p.lat},${p.lon}" else p.searchText
|
||||
|
||||
private fun osmand(pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?): NavStep {
|
||||
private fun osmand(pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, force: String): NavStep {
|
||||
val route = stops + destination
|
||||
return when {
|
||||
// Through stops: OsmAnd follows a route given as GPX, which needs every point's coordinates.
|
||||
stops.isNotEmpty() && route.all { it.hasCoordinates } -> NavStep.Launch(
|
||||
osmandUri(pkg, "navigate_gpx", "force" to "true").putExtra("data", gpx(route)),
|
||||
osmandUri(pkg, "navigate_gpx", "force" to force).putExtra("data", gpx(route)),
|
||||
)
|
||||
|
||||
stops.isNotEmpty() -> NavStep.Unsupported("")
|
||||
@@ -170,7 +177,7 @@ object NavIntents {
|
||||
"dest_lon" to destination.lon.toString(),
|
||||
"dest_name" to destination.label,
|
||||
"profile" to travel.osmand,
|
||||
"force" to "true",
|
||||
"force" to force,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -184,7 +191,7 @@ object NavIntents {
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"profile" to travel.osmand,
|
||||
"force" to "true",
|
||||
"force" to force,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
@@ -45,6 +46,13 @@ class Args(val json: JsonObject) {
|
||||
|
||||
fun list(key: String): List<JsonElement> = (o[key] as? JsonArray).orEmpty()
|
||||
|
||||
/** A list of strings (or one string, which a model sometimes writes for a list of one). */
|
||||
fun strings(key: String): List<String> = when (val v = o[key]) {
|
||||
is JsonArray -> v.mapNotNull { (it as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty) }
|
||||
is JsonPrimitive -> listOfNotNull(v.content.trim().takeIf { it.isNotEmpty() })
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
fun place(key: String): Place? = when (val v = o[key]) {
|
||||
is JsonObject -> placeOf(v)
|
||||
is JsonPrimitive -> v.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
@@ -69,11 +77,13 @@ class Args(val json: JsonObject) {
|
||||
)
|
||||
}
|
||||
|
||||
/** A time the model wrote: ISO 8601 with an offset, or local (the phone's zone). */
|
||||
/** A time the model wrote: `YYYY-MM-DDTHH:MM` in the phone's zone, `YYYY-MM-DD`, or with an offset. */
|
||||
fun time(key: String): Long? {
|
||||
val raw = str(key).ifBlank { return null }
|
||||
return runCatching { OffsetDateTime.parse(raw).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { LocalDateTime.parse(raw).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() }.getOrNull()
|
||||
val zone = ZoneId.systemDefault()
|
||||
return runCatching { LocalDateTime.parse(raw).atZone(zone).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { LocalDate.parse(raw).atStartOfDay(zone).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { OffsetDateTime.parse(raw).toInstant().toEpochMilli() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,17 +98,16 @@ class Args(val json: JsonObject) {
|
||||
* a phone number goes to the dialler and is never called.
|
||||
*/
|
||||
object PhoneActions {
|
||||
/** Media keys the `media` action sends. */
|
||||
/** Media keys, by the action's `command`. */
|
||||
private val MEDIA = mapOf(
|
||||
"play_pause" to KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
|
||||
"toggle" to KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
|
||||
"play" to KeyEvent.KEYCODE_MEDIA_PLAY,
|
||||
"pause" to KeyEvent.KEYCODE_MEDIA_PAUSE,
|
||||
"next" to KeyEvent.KEYCODE_MEDIA_NEXT,
|
||||
"previous" to KeyEvent.KEYCODE_MEDIA_PREVIOUS,
|
||||
"stop" to KeyEvent.KEYCODE_MEDIA_STOP,
|
||||
)
|
||||
|
||||
/** Settings panels, by the action's name. Panels (Android 10+) float over the app; the rest are pages. */
|
||||
/** Settings panels, by the action's `panel`. Panels (Android 10+) float over the app; the rest are pages. */
|
||||
private val PANELS = mapOf(
|
||||
"wifi" to Settings.Panel.ACTION_WIFI,
|
||||
"internet" to Settings.Panel.ACTION_INTERNET_CONNECTIVITY,
|
||||
@@ -106,39 +115,56 @@ object PhoneActions {
|
||||
"volume" to Settings.Panel.ACTION_VOLUME,
|
||||
"bluetooth" to Settings.ACTION_BLUETOOTH_SETTINGS,
|
||||
"location" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
|
||||
"display" to Settings.ACTION_DISPLAY_SETTINGS,
|
||||
"battery" to Intent.ACTION_POWER_USAGE_SUMMARY,
|
||||
"airplane" to Settings.ACTION_AIRPLANE_MODE_SETTINGS,
|
||||
"do_not_disturb" to Settings.ACTION_ZEN_MODE_PRIORITY_SETTINGS,
|
||||
)
|
||||
|
||||
/** A broadcast an automation app (Tasker, Automate, MacroDroid) listens for: never a system one. */
|
||||
fun broadcastAllowed(action: String): Boolean =
|
||||
action.isNotBlank() && action.length <= 200 && !action.startsWith("android.") && !action.startsWith("com.android.") &&
|
||||
Regex("^[A-Za-z0-9_.]+$").matches(action)
|
||||
/** Tasker's public intent for running a task by its name (its TaskerIntent protocol). */
|
||||
const val TASKER_PACKAGE = "net.dinglisch.android.taskerm"
|
||||
private const val TASKER_ACTION = "net.dinglisch.android.tasker.ACTION_TASK"
|
||||
|
||||
/** The broadcast any other automation app (Automate, MacroDroid, …) can listen for. */
|
||||
const val AUTOMATION_ACTION = "eu.llembas.android.action.AUTOMATION"
|
||||
|
||||
/** A URL the phone may open for a model: web pages only. */
|
||||
fun urlAllowed(url: String): Boolean = Uri.parse(url.trim()).scheme?.lowercase() in setOf("http", "https")
|
||||
fun urlAllowed(url: String): Boolean = url.trim().lowercase().let {
|
||||
(it.startsWith("http://") || it.startsWith("https://")) &&
|
||||
it.substringAfter("://").isNotBlank()
|
||||
}
|
||||
|
||||
/** `HH:MM` as hour and minute, or null. */
|
||||
fun clock(time: String): Pair<Int, Int>? {
|
||||
val m = Regex("^(\\d{1,2}):(\\d{2})$").matchEntire(time.trim()) ?: return null
|
||||
val (h, min) = m.destructured
|
||||
return (h.toInt() to min.toInt()).takeIf { it.first in 0..23 && it.second in 0..59 }
|
||||
}
|
||||
|
||||
/** SMS recipients: the numbers among [to]; a name the messaging app has to find is left to the person. */
|
||||
fun smsNumbers(to: List<String>): List<String> = to.map { it.trim() }.filter { Regex("^[+0-9 ()./#*-]{3,}$").matches(it) && it.count(Char::isDigit) >= 3 }
|
||||
|
||||
/**
|
||||
* The intent for an action that is one intent (everything but navigation, the torch and media
|
||||
* keys), or null when [action] is not one of these.
|
||||
* keys), or null when [action] is not one of these or its arguments do not make one.
|
||||
*/
|
||||
fun intentFor(context: Context, action: String, a: Args): Intent? = when (action) {
|
||||
"alarm" -> Intent(AlarmClock.ACTION_SET_ALARM)
|
||||
.putExtra(AlarmClock.EXTRA_HOUR, a.int("hour") ?: 7)
|
||||
.putExtra(AlarmClock.EXTRA_MINUTES, a.int("minute") ?: 0)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
.apply {
|
||||
val days = a.list("days").mapNotNull { (it as? JsonPrimitive)?.content?.let(::calendarDay) }
|
||||
if (days.isNotEmpty()) putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, ArrayList(days))
|
||||
}
|
||||
"alarm" -> clock(a.str("time"))?.let { (hour, minute) ->
|
||||
Intent(AlarmClock.ACTION_SET_ALARM)
|
||||
.putExtra(AlarmClock.EXTRA_HOUR, hour)
|
||||
.putExtra(AlarmClock.EXTRA_MINUTES, minute)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
.apply {
|
||||
val days = a.strings("days").mapNotNull(::calendarDay)
|
||||
if (days.isNotEmpty()) putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, ArrayList(days))
|
||||
}
|
||||
}
|
||||
|
||||
"timer" -> Intent(AlarmClock.ACTION_SET_TIMER)
|
||||
.putExtra(AlarmClock.EXTRA_LENGTH, (a.int("seconds") ?: 60).coerceIn(1, 86_400))
|
||||
.putExtra(AlarmClock.EXTRA_SKIP_UI, false)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
"timer" -> a.int("seconds")?.let { seconds ->
|
||||
Intent(AlarmClock.ACTION_SET_TIMER)
|
||||
.putExtra(AlarmClock.EXTRA_LENGTH, seconds.coerceIn(1, 86_400))
|
||||
.putExtra(AlarmClock.EXTRA_SKIP_UI, false)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
}
|
||||
|
||||
// The calendar's new-event screen, filled in: the person saves it.
|
||||
"calendar_event" -> Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI)
|
||||
.putExtra(CalendarContract.Events.TITLE, a.str("title"))
|
||||
.apply {
|
||||
@@ -146,38 +172,47 @@ object PhoneActions {
|
||||
a.time("end")?.let { putExtra(CalendarContract.EXTRA_EVENT_END_TIME, it) }
|
||||
if (a.bool("all_day") == true) putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true)
|
||||
a.str("location").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
a.str("description").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.DESCRIPTION, it) }
|
||||
a.str("notes").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.DESCRIPTION, it) }
|
||||
}
|
||||
|
||||
"sms_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(a.str("to"))))
|
||||
// A draft: the messaging app opens with it, and the person sends.
|
||||
"sms_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + smsNumbers(a.strings("to")).joinToString(";") { Uri.encode(it) }))
|
||||
.putExtra("sms_body", a.str("body"))
|
||||
|
||||
"email_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
|
||||
.putExtra(
|
||||
Intent.EXTRA_EMAIL,
|
||||
a.list("to").mapNotNull {
|
||||
(it as? JsonPrimitive)?.content
|
||||
}.ifEmpty { listOf(a.str("to")) }.filter { it.isNotBlank() }.toTypedArray(),
|
||||
)
|
||||
.putExtra(Intent.EXTRA_EMAIL, a.strings("to").toTypedArray())
|
||||
.putExtra(Intent.EXTRA_CC, a.strings("cc").toTypedArray())
|
||||
.putExtra(Intent.EXTRA_SUBJECT, a.str("subject"))
|
||||
.putExtra(Intent.EXTRA_TEXT, a.str("body"))
|
||||
|
||||
// The dialler with the number in it: the person presses call.
|
||||
// The dialler with the number in it: the person places the call.
|
||||
"dial" -> Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(a.str("number"))))
|
||||
|
||||
"open_url" -> a.str("url").trim().takeIf(::urlAllowed)?.let { Intent(Intent.ACTION_VIEW, Uri.parse(it)) }
|
||||
|
||||
"open_app" -> appIntent(context, a.str("package"), a.str("name"))
|
||||
"open_app" -> appIntent(context, "", a.str("app"))
|
||||
|
||||
"settings_panel" -> PANELS[a.str("panel")]?.let { Intent(it) }
|
||||
|
||||
"automation" -> a.str("action").takeIf(::broadcastAllowed)?.let { name ->
|
||||
Intent(name).apply {
|
||||
a.str("package").takeIf { it.isNotBlank() }?.let { setPackage(it) }
|
||||
a.obj("extras")?.let { extras ->
|
||||
// Strings only: an automation app reads its variables as text.
|
||||
extras.json.forEach { (k, v) -> (v as? JsonPrimitive)?.let { putExtra(k, it.content) } }
|
||||
}
|
||||
// Tasker (by default) runs the task by its name, the values as its local variables; any
|
||||
// other automation app gets LLeMbas's own broadcast, with the task's name and the values.
|
||||
"automation_intent" -> {
|
||||
val task = a.str("task")
|
||||
val app = a.str("app").trim()
|
||||
val values = a.obj("values")?.json.orEmpty().mapNotNull { (k, v) -> (v as? JsonPrimitive)?.let { k to it.content } }
|
||||
if (app.isBlank() || app.equals("tasker", ignoreCase = true)) {
|
||||
Intent(TASKER_ACTION)
|
||||
.setPackage(TASKER_PACKAGE)
|
||||
.putExtra("version_number", "1.1")
|
||||
.putExtra("task_name", task)
|
||||
.putExtra("task_priority", 5)
|
||||
.putStringArrayListExtra("varNames", ArrayList(values.map { "%" + it.first.lowercase() }))
|
||||
.putStringArrayListExtra("varValues", ArrayList(values.map { it.second }))
|
||||
} else {
|
||||
Intent(AUTOMATION_ACTION)
|
||||
.putExtra("task", task)
|
||||
.putExtra("app", app)
|
||||
.apply { values.forEach { (k, v) -> putExtra(k, v) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,7 +251,7 @@ object PhoneActions {
|
||||
|
||||
/** A media key to whatever is playing. */
|
||||
fun media(context: Context, key: String): ActionOutcome {
|
||||
val code = MEDIA[key] ?: return ActionOutcome(ActionStatus.Failed, "unknown media key: $key")
|
||||
val code = MEDIA[key] ?: return ActionOutcome(ActionStatus.Failed, "unknown media command: $key")
|
||||
val audio = context.getSystemService(AudioManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no audio")
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code))
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code))
|
||||
|
||||
@@ -239,6 +239,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
agents?.let { put("agents", agentsJson(it)) }
|
||||
put("temporary", temporary)
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
put("client", CAPABILITIES)
|
||||
// An agent chat runs on a linked device; an empty directory is the device's first
|
||||
// allowed one. A device that is no longer linked makes it an ordinary chat on the
|
||||
// server, rather than losing the message.
|
||||
@@ -258,6 +259,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
put("text", text)
|
||||
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -513,6 +515,12 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* What this app can do, sent with every message (spec 3.6.0): the phone carries out
|
||||
* `phone_action` calls the person confirms here, so the chat is offered the tool.
|
||||
*/
|
||||
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
|
||||
|
||||
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
|
||||
const val SHOWN_MAX_BYTES = 1_100_000L
|
||||
|
||||
|
||||
@@ -544,6 +544,11 @@ data class CardItem(
|
||||
val job: String = "",
|
||||
/** The tree subagent asking (spec 3.4.0), for a call nobody in the tree may allow; null otherwise. */
|
||||
val subagent: CardSubagent? = null,
|
||||
/**
|
||||
* A `phone_action` card's action (spec 3.6.0, `phone.md` §2): `action`, `summary` and the
|
||||
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
|
||||
*/
|
||||
val phone: JsonObject? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -582,6 +587,8 @@ data class Job(
|
||||
/** The answer to a card, as the page's form says it (see `api/v2/chats.py:answer`). */
|
||||
@Serializable
|
||||
data class CardAnswer(
|
||||
/** A phone card's answer: what the phone did once the person confirmed or declined. */
|
||||
val result: PhoneResult? = null,
|
||||
val verdict: String = "",
|
||||
val reason: String = "",
|
||||
val choices: Map<String, List<String>> = emptyMap(),
|
||||
@@ -589,6 +596,9 @@ data class CardAnswer(
|
||||
val asks: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PhoneResult(val status: String, val message: String = "")
|
||||
|
||||
@Serializable
|
||||
data class PushKey(val key: String = "", val registered: Boolean = false)
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
@@ -104,6 +106,7 @@ interface AssistActions {
|
||||
fun stopReading() {}
|
||||
fun endConversation() {}
|
||||
fun summariseNotifications() {}
|
||||
fun answerCard(card: Card, answer: CardAnswer) {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -474,6 +477,21 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
}
|
||||
}
|
||||
|
||||
/** A phone action's card, answered in the sheet: what the phone did (spec 3.6.0). */
|
||||
override fun answerCard(card: Card, answer: CardAnswer) {
|
||||
val chat = _state.value.chatId ?: return
|
||||
scope.launch {
|
||||
try {
|
||||
context.lembas.instances.client()?.answer(chat, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins: a 409 is somebody answering elsewhere already.
|
||||
if (e.status != 409) _state.update { it.copy(error = context.explain(e)) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun newChat() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
|
||||
@@ -91,6 +91,7 @@ import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.chat.PhoneCard
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -481,6 +482,11 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions:
|
||||
val reply = turn.reply
|
||||
val drawsProgress = reply != null && (progressLineOf(reply.progress) != null || reply.status.isNotBlank())
|
||||
when {
|
||||
// A phone action is confirmed here, where the phone is; any other card in the app.
|
||||
reply != null && reply.cards.any { it.kind == "phone_action" } -> reply.cards.first { it.kind == "phone_action" }.let { card ->
|
||||
PhoneCard(card) { answer -> actions.answerCard(card, answer) }
|
||||
}
|
||||
|
||||
reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) }
|
||||
|
||||
turn.writing && drawsProgress -> ProgressStatus(reply?.progress, reply?.status.orEmpty(), MaterialTheme.typography.labelSmall, palette.inkFaint)
|
||||
|
||||
@@ -58,6 +58,7 @@ fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
}
|
||||
when (card.kind) {
|
||||
"approval" -> Approval(card, onAnswer)
|
||||
"phone_action" -> PhoneCard(card, onAnswer)
|
||||
"plan" -> PlanCard(card, onAnswer)
|
||||
else -> Questions(card, onAnswer)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
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.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.ActionRunner
|
||||
import eu.llembas.android.actions.Args
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.PhoneResult
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
/** The actions a map app carries out. */
|
||||
val NAV_ACTIONS = setOf("navigate", "add_stop", "search_nearby", "stop_navigation")
|
||||
|
||||
/** What the card shows of a phone card while it is being carried out. */
|
||||
data class PhoneCardState(val running: Boolean = false, val locked: Boolean = false, val error: String? = null)
|
||||
|
||||
/**
|
||||
* A `phone_action` card (spec 3.6.0) with the phone behind it: Do it carries the action out
|
||||
* ([ActionRunner]) and answers what happened -- done, or failed and why; Cancel answers declined.
|
||||
* Never while the phone is locked: Do it says to unlock first. Used by the chat's card sheet and
|
||||
* by the assistant's sheet alike.
|
||||
*/
|
||||
@Composable
|
||||
fun PhoneCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val prefs by context.lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val installed = remember { NavApp.installedApps(context) }
|
||||
var state by remember(card.id) { mutableStateOf(PhoneCardState()) }
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
val phone = item.phone ?: JsonObject(emptyMap())
|
||||
PhoneCardContent(
|
||||
phone = phone,
|
||||
navApps = installed,
|
||||
chosen = NavApp.chosen(prefs.navApp, installed),
|
||||
state = state,
|
||||
onDo = { app ->
|
||||
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) {
|
||||
state = state.copy(locked = true)
|
||||
return@PhoneCardContent
|
||||
}
|
||||
state = PhoneCardState(running = true)
|
||||
scope.launch {
|
||||
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val outcome = ActionRunner.run(context, action, Args(phone), app, askOsmAnd = prefs.osmandInfo)
|
||||
state = PhoneCardState(error = outcome.message.takeIf { outcome.status.wire == "failed" })
|
||||
onAnswer(CardAnswer(result = PhoneResult(outcome.status.wire, outcome.message)))
|
||||
}
|
||||
},
|
||||
onDecline = { onAnswer(CardAnswer(result = PhoneResult("declined"))) },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The card from its state alone (what the screenshot tests draw): the phone's icon and "Do this
|
||||
* on your phone?", the model's one line ([phone]'s `summary`), how it will be done and its facts,
|
||||
* the map app to use when Settings leaves it open ([chosen] null, more than one installed), and
|
||||
* Cancel / Do it -- each at least 48 dp, the line above them free to wrap.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun PhoneCardContent(
|
||||
phone: JsonObject,
|
||||
navApps: List<NavApp>,
|
||||
chosen: NavApp?,
|
||||
state: PhoneCardState,
|
||||
onDo: (NavApp?) -> Unit = {},
|
||||
onDecline: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val summary = (phone["summary"] as? JsonPrimitive)?.content.orEmpty().ifBlank { action }
|
||||
val nav = action in NAV_ACTIONS
|
||||
var picked by remember(chosen) { mutableStateOf(chosen ?: navApps.singleOrNull()) }
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.PhoneAndroid, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(stringResource(R.string.action_card_title), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
}
|
||||
Text(summary, style = MaterialTheme.typography.titleMedium)
|
||||
Text(howLine(action, picked), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
phoneFacts(phone).takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (nav && chosen == null && navApps.size > 1) {
|
||||
Text(stringResource(R.string.nav_app_pick), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
navApps.forEach { app ->
|
||||
FilterChip(
|
||||
selected = picked == app,
|
||||
onClick = { picked = app },
|
||||
label = { Text(stringResource(if (app == NavApp.OsmAnd) R.string.nav_app_osmand else R.string.nav_app_google)) },
|
||||
colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft),
|
||||
modifier = Modifier.heightIn(min = 40.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nav && picked == NavApp.GoogleMaps && action in setOf("add_stop", "stop_navigation")) {
|
||||
Text(
|
||||
stringResource(if (action == "add_stop") R.string.action_google_add_stop else R.string.action_google_no_stop),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
)
|
||||
}
|
||||
when {
|
||||
state.locked -> Text(stringResource(R.string.action_unlock), style = MaterialTheme.typography.bodyMedium, color = palette.warning)
|
||||
|
||||
state.error != null -> Text(
|
||||
stringResource(R.string.action_failed, state.error),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.danger,
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = onDecline, enabled = !state.running, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { onDo(picked) },
|
||||
enabled = !state.running && (!nav || picked != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.running) R.string.action_running else R.string.action_do)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How the action will be done, in a sentence: which kind of app, and what is left to the person. */
|
||||
@Composable
|
||||
private fun howLine(action: String, app: NavApp?): String = when (action) {
|
||||
"alarm", "timer" -> stringResource(R.string.action_line_clock)
|
||||
|
||||
"calendar_event" -> stringResource(R.string.action_line_calendar)
|
||||
|
||||
"sms_draft", "email_draft" -> stringResource(R.string.action_line_draft)
|
||||
|
||||
"dial" -> stringResource(R.string.action_line_dial)
|
||||
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" ->
|
||||
stringResource(
|
||||
R.string.action_line_map,
|
||||
stringResource(
|
||||
if (app ==
|
||||
NavApp.OsmAnd
|
||||
) {
|
||||
R.string.nav_app_osmand
|
||||
} else if (app == NavApp.GoogleMaps) {
|
||||
R.string.nav_app_google
|
||||
} else {
|
||||
R.string.nav_app
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
"media", "torch" -> stringResource(R.string.action_line_now)
|
||||
|
||||
"settings_panel" -> stringResource(R.string.action_line_settings)
|
||||
|
||||
"automation_intent" -> stringResource(R.string.action_line_automation)
|
||||
|
||||
else -> stringResource(R.string.action_line_open)
|
||||
}
|
||||
|
||||
/**
|
||||
* The action's facts as one line, values only, in the order the spec lists the fields: what the
|
||||
* person checks before Do it ("07:00 · mon tue wed thu fri · Work"). A place is its name and,
|
||||
* when it has one, what the map app will search, or its coordinates.
|
||||
*/
|
||||
fun phoneFacts(phone: JsonObject): String {
|
||||
fun place(e: JsonElement?): String? {
|
||||
val o = e as? JsonObject ?: return (e as? JsonPrimitive)?.content
|
||||
val name = (o["name"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val query = (o["query"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val lat = (o["lat"] as? JsonPrimitive)?.content
|
||||
val lon = (o["lon"] as? JsonPrimitive)?.content
|
||||
val where = query.ifBlank { if (lat != null && lon != null) "$lat, $lon" else "" }
|
||||
return listOf(name, where).filter { it.isNotBlank() }.distinct().let {
|
||||
if (it.size == 2) "${it[0]} (${it[1]})" else it.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
fun value(key: String, e: JsonElement?): String? = when {
|
||||
e == null -> null
|
||||
key in setOf("destination", "stop") -> place(e)
|
||||
key == "stops" -> (e as? JsonArray)?.mapNotNull { place(it) }?.joinToString(" → ")?.ifBlank { null }
|
||||
e is JsonArray -> e.mapNotNull { (it as? JsonPrimitive)?.content }.joinToString(" ").ifBlank { null }
|
||||
e is JsonObject -> e.entries.joinToString(", ") { (k, v) -> "$k=${(v as? JsonPrimitive)?.content.orEmpty()}" }.ifBlank { null }
|
||||
e is JsonPrimitive -> e.content.takeIf { it.isNotBlank() && it != "false" && it != "true" }
|
||||
else -> null
|
||||
}
|
||||
return FACT_ORDER.mapNotNull { key -> value(key, phone[key]) }.joinToString(" · ")
|
||||
}
|
||||
|
||||
private val FACT_ORDER = listOf(
|
||||
"time", "days", "seconds", "label", "title", "start", "end", "location", "to", "cc", "subject", "number",
|
||||
"stops", "stop", "destination", "mode", "query", "near", "app", "url", "command", "panel", "task", "values",
|
||||
)
|
||||
Reference in new issue
Block a user