openassistant: run assistant intents headlessly, finishing synchronously without opening the target app
- Commit
a617caddc0d30f2c960fa6453f06e287542cd2cd- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-14 03:44 UTC (3 months ago)
- Parents
2f644ef
Diff
library/src/main/java/com/vayunmathur/library/util/AssistantIntent.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/AssistantIntent.kt b/library/src/main/java/com/vayunmathur/library/util/AssistantIntent.ktindex 0b8540ae5b..2773c24bbb 100644--- a/library/src/main/java/com/vayunmathur/library/util/AssistantIntent.kt+++ b/library/src/main/java/com/vayunmathur/library/util/AssistantIntent.kt@@ -1,15 +1,19 @@ package com.vayunmathur.library.util import android.annotation.SuppressLint+import android.app.Activity import android.util.Log import android.content.Context import android.content.Intent import android.os.Bundle+import android.os.Handler+import android.os.Looper import android.os.ResultReceiver import androidx.activity.ComponentActivity-import androidx.activity.result.contract.ActivityResultContracts-import androidx.lifecycle.lifecycleScope-import kotlinx.coroutines.CancellableContinuation+import androidx.core.content.IntentCompat+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.sync.Mutex@@ -21,86 +25,91 @@ import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.json.Json import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException-import androidx.core.content.IntentCompat abstract class AssistantIntent<Input: Any, Output: Any>(val inputSerializer: KSerializer<Input>, val outputSerializer: KSerializer<Output>): ComponentActivity() { @OptIn(InternalSerializationApi::class, kotlinx.serialization.ExperimentalSerializationApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - // 1. Get the incoming data+ // 1. Get the incoming data + the channel to answer on. val inputString = intent.getStringExtra("DATA")- if (inputString == null) {- finish()- return+ val receiver = IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java)++ // 2. These activities are themed @android:style/Theme.NoDisplay, which+ // REQUIRES finish() to be called before onResume() completes. If we finish+ // asynchronously (after suspending work) Android throws+ // IllegalStateException "did not call finish() prior to onResume()+ // completing" and force-finishes the whole task โ which previously tore+ // down the OpenAssistant caller sharing that task. So we finish+ // synchronously here and run the real work on a scope that outlives this+ // activity, delivering the result over the ResultReceiver binder (which is+ // task/lifecycle independent).+ finish()++ // Decode defensively: this activity runs in the caller's task, so an+ // exception escaping onCreate would crash and tear that task down.+ val input = try {+ inputString?.let { Json.decodeFromString(inputSerializer, it) }+ } catch (e: Throwable) {+ Log.e(TAG, "Failed to decode input for ${javaClass.name}", e)+ null }- val input = Json.decodeFromString(inputSerializer, inputString)-- lifecycleScope.launch {- // 2. Do your "rare" processing- val result = performCalculation(input) - // 3. Prepare the response- val responseData = Json.encodeToString(outputSerializer, result)- val responseIntent = Intent()- responseIntent.putExtra("RESPONSE_DATA", responseData)-- // 4. Send the result back to the calling app- setResult(RESULT_OK, responseIntent)-- // Also send to ResultReceiver if present (useful for Services)- val receiver = IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java)- receiver?.send(RESULT_OK, Bundle().apply {- putString("RESPONSE_DATA", responseData)- })+ if (input == null) {+ receiver?.send(Activity.RESULT_CANCELED, Bundle())+ return+ } - // 5. Vital: Close immediately!- finish()+ scope.launch {+ try {+ val result = performCalculation(input)+ val responseData = Json.encodeToString(outputSerializer, result)+ receiver?.send(Activity.RESULT_OK, Bundle().apply {+ putString("RESPONSE_DATA", responseData)+ })+ } catch (e: Throwable) {+ Log.e(TAG, "performCalculation failed for ${javaClass.name}", e)+ receiver?.send(Activity.RESULT_CANCELED, Bundle())+ } } } abstract suspend fun performCalculation(input: Input): Output++ companion object {+ private const val TAG = "AssistantIntent"++ // Process-scoped (not tied to the activity lifecycle) so the work survives+ // the immediate finish() above and still completes / reports its result.+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ } } /**- * Bridges a suspend call to another app's [AssistantIntent] activity-for-result.+ * Bridges a suspend call to another app's [AssistantIntent] activity. * * This is driven from the OpenAssistant tool-calling path, which runs on a single- * background inference coroutine (via `runBlocking`). Three properties are+ * background inference coroutine (via `runBlocking`). Four properties are * therefore essential and were the source of T495 ("assistant hangs/crashes and- * stops responding until reboot" when creating a note):- * - The ActivityResult API must be invoked on the main thread; the inference- * coroutine is on [Dispatchers.IO].- * - The result callback must resume the in-flight call exactly once โ a stale or- * duplicate result must not resume an already-completed continuation (that- * throws IllegalStateException and crashes the process).+ * stops responding until reboot" when creating a note) and its follow-up (the+ * NoDisplay activity force-crashing the caller's task):+ * - The result is delivered over a [ResultReceiver] binder rather than an+ * activity result, because the target activity is NoDisplay and finishes+ * synchronously before its async work has produced a value.+ * - The target is launched into the caller's own task via the [activity]+ * context (no FLAG_ACTIVITY_NEW_TASK). A new task would match the target's+ * default task affinity and surface that app's MainActivity once the NoDisplay+ * activity finishes; keeping it in the caller's task means nothing ever shows.+ * - The launch must happen on the main thread; the inference coroutine is on+ * [Dispatchers.IO]. * - The call must be time-bounded. If the launched activity never returns a * result (e.g. it was killed, or a background-launch was blocked), the call * must fail instead of blocking the sole inference coroutine forever, which * would wedge every future prompt.- * A [mutex] serializes launches so the single shared [continuation] is only ever- * used by one in-flight call.+ * A [mutex] serializes launches so only one call is in flight at a time. */ class IntentLauncher(private val activity: ComponentActivity) { private val mutex = Mutex()- @Volatile private var continuation: CancellableContinuation<String>? = null-- // This MUST be a property so it registers during class initialization.- private val launcher = activity.registerForActivityResult(- ActivityResultContracts.StartActivityForResult()- ) { result ->- val data = result.data?.getStringExtra("RESPONSE_DATA")- if (data != null) resumeOnce(value = data)- else resumeOnce(error = Exception("No data returned"))- }-- /** Resumes the current continuation at most once, then clears it. */- private fun resumeOnce(value: String? = null, error: Throwable? = null) {- val cont = continuation ?: return- continuation = null- if (!cont.isActive) return- if (value != null) cont.resume(value) else cont.resumeWithException(error ?: Exception("No data returned"))- } @SuppressLint("QueryPermissionsNeeded") @OptIn(InternalSerializationApi::class)@@ -111,43 +120,59 @@ class IntentLauncher(private val activity: ComponentActivity) { serializer: SerializationStrategy<Input>, input: Input ): String = mutex.withLock {- val intent = Intent().apply {- setClassName(packageName, className)- putExtra("DATA", Json.encodeToString(serializer, input))- }-- // Not installed / not resolvable: report back so callers can raise a- // MissingAppException rather than waiting for a result that never comes.- if (intent.resolveActivity(context.packageManager) == null) {- return@withLock "package $packageName doesn't exist"- }- val result = withTimeoutOrNull(INTENT_TIMEOUT_MS) { suspendCancellableCoroutine { cont ->- continuation = cont- cont.invokeOnCancellation { continuation = null }- // The ActivityResult API is main-thread only; the inference path- // that calls this runs on a background dispatcher.+ // The target answers over this binder callback (main thread),+ // decoupled from the activity's task and lifecycle.+ val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) handler@{ code, data ->+ if (!cont.isActive) return@handler+ val response = data?.getString("RESPONSE_DATA")+ if (code == Activity.RESULT_OK && response != null) {+ cont.resume(response)+ } else {+ cont.resumeWithException(Exception("No data returned"))+ }+ }++ val intent = Intent().apply {+ setClassName(packageName, className)+ putExtra("DATA", Json.encodeToString(serializer, input))+ putExtra("RECEIVER", receiver)+ }++ // Not installed / not resolvable: report back so callers can raise a+ // MissingAppException rather than waiting for a result that never comes.+ if (intent.resolveActivity(context.packageManager) == null) {+ cont.resume("package $packageName doesn't exist")+ return@suspendCancellableCoroutine+ }++ // Launch into the caller's (openassistant's) task via the Activity+ // context โ NOT a new task. FLAG_ACTIVITY_NEW_TASK would match the+ // target's default task affinity and bring that app's existing task+ // (its MainActivity) to the foreground, which then becomes visible+ // once this NoDisplay activity finishes. The target is NoDisplay and+ // finishes synchronously, so it never shows; the result comes back+ // over the task-independent ResultReceiver binder regardless of task.+ // startActivity is main-thread only; the inference path that calls+ // this runs on a background dispatcher. activity.runOnUiThread { try {- launcher.launch(intent)+ activity.startActivity(intent) } catch (e: Exception) { Log.e("IntentLauncher", "Failed to launch $className in $packageName", e)- resumeOnce(error = e)+ if (cont.isActive) cont.resumeWithException(e) } } } } - // Timed out: drop the stale continuation and surface a recoverable error- // instead of blocking the inference loop forever.- result ?: run {- continuation = null- throw Exception("Timed out waiting for a response from $packageName")- }+ // Timed out: surface a recoverable error instead of blocking the+ // inference loop forever.+ result ?: throw Exception("Timed out waiting for a response from $packageName") } companion object { private const val INTENT_TIMEOUT_MS = 30_000L }-}\ No newline at end of file+}