Modern Apps git

← Modern-Apps.git

sdk-openassistant: send plain ResultReceiver over IPC

Commit
f7e6274e92bf3adcdecfc515e6849b7d55da2274
Author
Vayun Mathur <[email protected]>
When
2026-12-05 15:13 UTC (12 hours ago)
Parents
f203887
The SDK put its own SecureResultReceiver subclass in the
InferenceService intent. Parcel writes the subclass name, and the
OpenAssistant app does not ship that class (the SDK deliberately
avoids the base library dependency), so InferenceService died with
BadParcelableException: ClassNotFoundException when unmarshalling
the RECEIVER extra, crashing the OpenAssistant process on every
SDK call. Health's new lab-results PDF import was the first caller
to hit it, via generateJsonWithImages.

Fix by stripping the subclass before the intent crosses processes:
a parcel round-trip through ResultReceiver.CREATOR makes the wire
class the framework android.os.ResultReceiver, whose binder still
forwards send() to the in-process SecureResultReceiver callback.
This matches the existing IntentLauncher.forIpc pattern in the
base library, works against already-installed OpenAssistant
builds, and needs no keep rules or new OpenAssistant dependency
on the SDK. SecureResultReceiver now documents that it must never
cross IPC directly, and the result-code mapping is split into
decodeInferenceResult so it stays unit-testable without a live
binder.

Tests: OpenAssistantTest now asserts the dispatched intent (text,
image, and schema calls) carries exactly android.os.ResultReceiver
as the RECEIVER extra, Robolectric's parcel shadow drops the
receiver binder so dispatch tests assert the launch side (same
limitation the base library documents), and decodeInferenceResult
covers success, null-data, error, and fallback-error mapping.
SecureResultReceiver's callback forwarding is still covered
directly.

Verified: :sdk:openassistant:lint and
:sdk:openassistant:testDebugUnitTest green.

Diff

sdk/openassistant/AGENTS.md
diff --git a/sdk/openassistant/AGENTS.md b/sdk/openassistant/AGENTS.mdindex b246e7f22b..1fc9abd846 100644--- a/sdk/openassistant/AGENTS.md+++ b/sdk/openassistant/AGENTS.md@@ -16,7 +16,7 @@ **Gotchas:** Tool schemas are a compatibility surface on both ends โ€” changes need assistant + provider updated together.  ## Key files-- com/vayunmathur/sdk/openassistant/OpenAssistant.kt โ€” `generate`/`generateJson` text, `generateJsonWithImages(prompt, schema, imagePaths)` for vision structured extraction (sends `image_paths` to InferenceService)+- com/vayunmathur/sdk/openassistant/OpenAssistant.kt โ€” `generate`/`generateJson` text, `generateJsonWithImages(prompt, schema, imagePaths)` for vision structured extraction (sends `image_paths` to InferenceService); the result receiver crosses as the plain framework `ResultReceiver` (subclass stripped by a parcel round-trip), never this module's `SecureResultReceiver`, which the OpenAssistant app does not ship - com/vayunmathur/sdk/openassistant/Exceptions.kt  ## Verify (this module only)
sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt
diff --git a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.ktindex 326a782ff0..bcfae9641d 100644--- a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt+++ b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt@@ -4,8 +4,10 @@ import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager+import android.os.Bundle import android.os.Handler import android.os.Looper+import android.os.Parcel import android.os.ResultReceiver import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeout@@ -71,12 +73,10 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long =     ): String =         suspendCancellableCoroutine { cont ->             val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data ->-                if (code == 0) {-                    val result = data?.getString("json_result") ?: ""-                    cont.resume(result)-                } else {-                    val error = data?.getString("error") ?: "Inference failed"-                    cont.resumeWithException(AssistantException(error))+                try {+                    cont.resume(decodeInferenceResult(code, data))+                } catch (e: AssistantException) {+                    cont.resumeWithException(e)                 }             } @@ -85,7 +85,7 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long =                 putExtra("user_text", prompt)                 putExtra("schema", schema ?: DEFAULT_SCHEMA)                 if (imagePaths.isNotEmpty()) putExtra("image_paths", imagePaths.toTypedArray())-                putExtra("RECEIVER", receiver as ResultReceiver)+                putExtra("RECEIVER", receiver.forIpc())             }              try {@@ -98,4 +98,39 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long =                 cont.resumeWithException(AssistantException(message))             }         }++    // Strips the subclass name from the parcel so the OpenAssistant app+    // (which does not ship this SDK's SecureResultReceiver, and must never+    // need to) can unmarshal it. Putting the SecureResultReceiver itself in+    // the intent wrote `com.vayunmathur.sdk.openassistant.SecureResultReceiver`+    // into the parcel; InferenceService.onStartCommand then died with+    // BadParcelableException: ClassNotFoundException when unmarshalling,+    // crashing the OpenAssistant process on every SDK call (health lab-PDF+    // import was the first caller to hit it). The parcel round-trip below+    // re-creates the receiver through ResultReceiver.CREATOR, so the wire+    // class is the framework's android.os.ResultReceiver while the binder+    // still forwards send() to this process's SecureResultReceiver callback.+    // Same pattern as library's IntentLauncher.forIpc.+    private fun ResultReceiver.forIpc(): ResultReceiver {+        val parcel = Parcel.obtain()+        try {+            writeToParcel(parcel, 0)+            parcel.setDataPosition(0)+            return ResultReceiver.CREATOR.createFromParcel(parcel)+        } finally {+            parcel.recycle()+        }+    }+}++/**+ * Maps an InferenceService result to the value the awaiting caller resumes+ * with: the `json_result` string on success (empty when the reply carries+ * no data), otherwise an [AssistantException] with the service's `error`+ * or the generic fallback. Split out so the mapping is unit-testable+ * without a live binder (Robolectric's parcel shadow drops it).+ */+internal fun decodeInferenceResult(resultCode: Int, resultData: Bundle?): String {+    if (resultCode == 0) return resultData?.getString("json_result") ?: ""+    throw AssistantException(resultData?.getString("error") ?: "Inference failed") }
sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/SecureResultReceiver.kt
diff --git a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/SecureResultReceiver.kt b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/SecureResultReceiver.ktindex c30c16d058..5b2a81f5b5 100644--- a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/SecureResultReceiver.kt+++ b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/SecureResultReceiver.kt@@ -9,6 +9,11 @@ import android.os.ResultReceiver  *  * Lives in this SDK (rather than `:library`) so the SDK does not depend on  * the whole base library for one 14-line class (#884).+ *+ * Never put this class itself into a cross-app intent: the receiving app+ * does not ship it, so unmarshalling dies with ClassNotFoundException.+ * [OpenAssistant] sends only the plain framework [ResultReceiver] produced+ * by a parcel round-trip, whose binder forwards back to an instance here.  */ class SecureResultReceiver(     handler: Handler?,
sdk/openassistant/src/test/java/com/vayunmathur/sdk/openassistant/OpenAssistantTest.kt
diff --git a/sdk/openassistant/src/test/java/com/vayunmathur/sdk/openassistant/OpenAssistantTest.kt b/sdk/openassistant/src/test/java/com/vayunmathur/sdk/openassistant/OpenAssistantTest.ktindex 396d39e28e..7e701151b2 100644--- a/sdk/openassistant/src/test/java/com/vayunmathur/sdk/openassistant/OpenAssistantTest.kt+++ b/sdk/openassistant/src/test/java/com/vayunmathur/sdk/openassistant/OpenAssistantTest.kt@@ -14,13 +14,13 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking-import kotlinx.coroutines.withTimeoutOrNull import org.junit.runner.RunWith import org.robolectric.Shadows import org.robolectric.shadows.ShadowLooper import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith+import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue@@ -44,6 +44,20 @@ class OpenAssistantTest {         return assertNotNull(receiver)     } +    // Regression for the OpenAssistant process crash on SDK calls: the+    // receiver on the wire must be the plain framework ResultReceiver, not+    // this SDK's SecureResultReceiver subclass, which the OpenAssistant app+    // does not ship and died unmarshalling (ClassNotFoundException in+    // InferenceService.onStartCommand). Robolectric's parcel shadow drops+    // the ResultReceiver binder, so a simulated service can never answer+    // through it; the dispatch tests assert the launch side here and the+    // result mapping is covered directly in decodeInferenceResult tests.+    private fun assertPlainFrameworkReceiver(intent: Intent) {+        val receiver = receiverOf(intent)+        assertEquals(ResultReceiver::class.java, receiver.javaClass)+        assertEquals("android.os.ResultReceiver", receiver.javaClass.name)+    }+     private fun idleMain() {         ShadowLooper.idleMainLooper()         Shadows.shadowOf(Looper.getMainLooper()).idle()@@ -67,7 +81,7 @@ class OpenAssistantTest {         assertTrue(OpenAssistant(app).isAvailable())     } -    @Test fun generateReturnsJsonResultAndSendsIntent() = runBlocking {+    @Test fun generateSendsIntentWithPlainFrameworkReceiver() = runBlocking {         installAssistant()         val oa = OpenAssistant(app, timeoutMs = 10_000)         val deferred = async(Dispatchers.Default) { oa.generate("hello") }@@ -87,9 +101,9 @@ class OpenAssistantTest {         assertEquals("hello", started.getStringExtra("user_text"))         // generate() without a schema must send the default response schema.         assertTrue(started.getStringExtra("schema")!!.contains("\"response\""))-        receiverOf(started).send(0, Bundle().apply { putString("json_result", "{\"a\":1}") })-        idleMain()-        assertEquals("{\"a\":1}", withTimeoutOrNull(5_000) { deferred.await() })+        assertPlainFrameworkReceiver(started)+        assertFalse(deferred.isCompleted)+        deferred.cancel()     }      @Test fun generateJsonSendsCustomSchema() = runBlocking {@@ -107,56 +121,29 @@ class OpenAssistantTest {         val started = assertNotNull(intent)         assertEquals(schema, started.getStringExtra("schema"))         assertEquals("count", started.getStringExtra("user_text"))-        receiverOf(started).send(0, Bundle().apply { putString("json_result", "{\"x\":2}") })-        idleMain()-        assertEquals("{\"x\":2}", withTimeoutOrNull(5_000) { deferred.await() })+        assertPlainFrameworkReceiver(started)+        assertFalse(deferred.isCompleted)+        deferred.cancel()     } -    @Test fun successWithNullDataReturnsEmpty() = runBlocking {-        installAssistant()-        val oa = OpenAssistant(app, timeoutMs = 10_000)-        val deferred = async(Dispatchers.Default) { oa.generate("hi") }-        var intent: Intent? = null-        var guard = 0-        while (intent == null && guard++ < 100) {-            idleMain(); intent = nextStartedService(); if (intent == null) Thread.sleep(10)-        }-        receiverOf(assertNotNull(intent)).send(0, null)-        idleMain()-        assertEquals("", withTimeoutOrNull(5_000) { deferred.await() })+    @Test fun successResultDecodesJsonAndNullDataReturnsEmpty() {+        assertEquals("{\"a\":1}", decodeInferenceResult(0, Bundle().apply { putString("json_result", "{\"a\":1}") }))+        assertEquals("", decodeInferenceResult(0, null))+        assertEquals("", decodeInferenceResult(0, Bundle()))     } -    @Test fun errorResultThrowsAssistantException() = runBlocking {-        installAssistant()-        val oa = OpenAssistant(app, timeoutMs = 10_000)-        val deferred = async(Dispatchers.Default) { runCatching { oa.generate("hi") } }-        var intent: Intent? = null-        var guard = 0-        while (intent == null && guard++ < 100) {-            idleMain(); intent = nextStartedService(); if (intent == null) Thread.sleep(10)+    @Test fun errorResultThrowsAssistantException() {+        val e = assertFailsWith<AssistantException> {+            decodeInferenceResult(1, Bundle().apply { putString("error", "model exploded") })         }-        receiverOf(assertNotNull(intent)).send(1, Bundle().apply { putString("error", "model exploded") })-        idleMain()-        val result = withTimeoutOrNull(5_000) { deferred.await() }-        val e = assertNotNull(result).exceptionOrNull()-        assertTrue(e is AssistantException, "got $e")-        assertEquals("model exploded", e!!.message)+        assertEquals("model exploded", e.message)     } -    @Test fun errorResultWithoutMessageUsesFallback() = runBlocking {-        installAssistant()-        val oa = OpenAssistant(app, timeoutMs = 10_000)-        val deferred = async(Dispatchers.Default) { runCatching { oa.generate("hi") } }-        var intent: Intent? = null-        var guard = 0-        while (intent == null && guard++ < 100) {-            idleMain(); intent = nextStartedService(); if (intent == null) Thread.sleep(10)-        }-        receiverOf(assertNotNull(intent)).send(7, null)-        idleMain()-        val e = assertNotNull(withTimeoutOrNull(5_000) { deferred.await() }).exceptionOrNull()-        assertTrue(e is AssistantException, "got $e")-        assertEquals("Inference failed", e!!.message)+    @Test fun errorResultWithoutMessageUsesFallback() {+        val e = assertFailsWith<AssistantException> { decodeInferenceResult(7, null) }+        assertEquals("Inference failed", e.message)+        val e2 = assertFailsWith<AssistantException> { decodeInferenceResult(-1, Bundle()) }+        assertEquals("Inference failed", e2.message)     }      @Test fun generateTimesOutWhenServiceNeverResponds() = runBlocking {@@ -184,7 +171,7 @@ class OpenAssistantTest {         assertTrue(e2.message!!.contains("bg start"), e2.message)     } -    @Test fun generateJsonWithImagesSendsImagePaths() = runBlocking {+    @Test fun generateJsonWithImagesSendsImagePathsWithPlainFrameworkReceiver() = runBlocking {         installAssistant()         val oa = OpenAssistant(app, timeoutMs = 10_000)         val deferred = async(Dispatchers.Default) {@@ -197,9 +184,12 @@ class OpenAssistantTest {         }         val started = assertNotNull(intent)         assertEquals(listOf("/tmp/page-1.png"), started.getStringArrayExtra("image_paths")!!.toList())-        receiverOf(started).send(0, Bundle().apply { putString("json_result", "{}") })-        idleMain()-        assertEquals("{}", withTimeoutOrNull(5_000) { deferred.await() })+        // The image path is the input shape that crashed OpenAssistant:+        // many-page PDFs arrive as page images through this same extra,+        // with the receiver that must be the plain framework class.+        assertPlainFrameworkReceiver(started)+        assertFalse(deferred.isCompleted)+        deferred.cancel()     }      @Test fun closeIsNoOp() = runBlocking {