Modern Apps git

← Modern-Apps.git

openassistant: fix hang/crash when creating a note by making IntentLauncher main-thread-safe, single-resume, and timeout-bounded

Commit
d38887171bc370e9f9abe04c97e27ea31fd2ed28
Author
Vayun Mathur <[email protected]>
When
2026-08-11 19:03 UTC (3 months ago)
Parents
5fc54d1

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 ea2a1f5107..0b8540ae5b 100644--- a/library/src/main/java/com/vayunmathur/library/util/AssistantIntent.kt+++ b/library/src/main/java/com/vayunmathur/library/util/AssistantIntent.kt@@ -12,6 +12,9 @@ import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationStrategy@@ -59,20 +62,44 @@ abstract class AssistantIntent<Input: Any, Output: Any>(val inputSerializer: KSe     abstract suspend fun performCalculation(input: Input): Output } -class IntentLauncher(activity: ComponentActivity) {-    private var continuation: CancellableContinuation<String>? = null--    // This MUST be a property so it registers during class initialization+/**+ * Bridges a suspend call to another app's [AssistantIntent] activity-for-result.+ *+ * This is driven from the OpenAssistant tool-calling path, which runs on a single+ * background inference coroutine (via `runBlocking`). Three 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).+ *  - 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.+ */+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) {-            continuation?.resume(data)-        } else {-            continuation?.resumeWithException(Exception("No data returned"))-        }+        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")@@ -83,35 +110,44 @@ class IntentLauncher(activity: ComponentActivity) {         className: String,         serializer: SerializationStrategy<Input>,         input: Input-    ): String = suspendCancellableCoroutine { cont ->-        continuation = cont-+    ): String = mutex.withLock {         val intent = Intent().apply {             setClassName(packageName, className)             putExtra("DATA", Json.encodeToString(serializer, input))         } -        // 1. Check if the package/activity is resolvable-        val packageManager = context.packageManager // You'll need access to context-        if (intent.resolveActivity(packageManager) == null) {-            continuation = null-            // Optional onCancellation cleanup-            cont.resume("package $packageName doesn't exist") { cause, _, _ -> // Optional onCancellation cleanup-                // Optional onCancellation cleanup-            }-            return@suspendCancellableCoroutine+        // 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"         } -        // 2. Setup cancellation logic-        cont.invokeOnCancellation { continuation = null }+        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.+                activity.runOnUiThread {+                    try {+                        launcher.launch(intent)+                    } catch (e: Exception) {+                        Log.e("IntentLauncher", "Failed to launch $className in $packageName", e)+                        resumeOnce(error = e)+                    }+                }+            }+        } -        // 3. Launch if everything looks good-        try {-            launcher.launch(intent)-        } catch (e: Exception) {-            Log.e("IntentLauncher", "Failed to launch $className in $packageName", e)+        // Timed out: drop the stale continuation and surface a recoverable error+        // instead of blocking the inference loop forever.+        result ?: run {             continuation = null-            cont.resume("package $packageName doesn't exist")+            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