openassistant: read screen via Assist API (VoiceInteractionService/Session)
- Commit
ac22e8f9418b89b9326aff0dec774b1fb349a8cf- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 03:50 UTC (3 months ago)
- Parents
9b1030e
Diff
openassistant/src/main/AndroidManifest.xml
diff --git a/openassistant/src/main/AndroidManifest.xml b/openassistant/src/main/AndroidManifest.xmlindex ed1d0ef434..93fc7c0bbd 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -84,6 +84,34 @@ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="On-device AI inference engine that must stay resident 24/7 to serve inference requests from the other apps on demand; not time-bounded like a data sync." /> </service>++ <service+ android:name=".assist.OpenAssistantVoiceInteractionService"+ android:permission="android.permission.BIND_VOICE_INTERACTION"+ android:exported="true">+ <intent-filter>+ <action android:name="android.service.voice.VoiceInteractionService" />+ </intent-filter>+ <meta-data+ android:name="android.voice_interaction"+ android:resource="@xml/voice_interaction_service" />+ </service>++ <service+ android:name=".assist.OpenAssistantSessionService"+ android:permission="android.permission.BIND_VOICE_INTERACTION"+ android:exported="true" />++ <service+ android:name=".assist.StubRecognitionService"+ android:exported="true">+ <intent-filter>+ <action android:name="android.speech.RecognitionService" />+ </intent-filter>+ <meta-data+ android:name="android.speech"+ android:resource="@xml/recognition_service" />+ </service> </application> </manifest>\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.ktindex 8ab3eb1c2d..b1502c0ecd 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -1,5 +1,6 @@ package com.vayunmathur.openassistant +import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent@@ -42,6 +43,8 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() intentLauncher = IntentLauncher(this) + readAssistScreenContext(intent)+ val ds = DataStoreUtils.getInstance(this) setContent {@@ -54,6 +57,24 @@ class MainActivity : ComponentActivity() { } } }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ setIntent(intent)+ readAssistScreenContext(intent)+ }++ /**+ * Picks up the flattened screen text captured by the Assist API session+ * ([com.vayunmathur.openassistant.assist.OpenAssistantSession]) and hands it to+ * the ViewModel so it seeds the next inference turn as context.+ */+ private fun readAssistScreenContext(intent: Intent?) {+ val screenText = intent?.getStringExtra("assist_screen_text")+ if (!screenText.isNullOrBlank()) {+ assistantViewModel.setScreenContext(screenText)+ }+ } } @Serializable
openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSession.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSession.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSession.ktnew file mode 100644index 0000000000..649be9fe2a--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSession.kt@@ -0,0 +1,116 @@+package com.vayunmathur.openassistant.assist++import android.app.assist.AssistContent+import android.app.assist.AssistStructure+import android.content.Context+import android.content.Intent+import android.graphics.Bitmap+import android.os.Bundle+import android.service.voice.VoiceInteractionSession+import android.util.Log+import com.vayunmathur.openassistant.MainActivity+import java.io.File+import java.io.FileOutputStream++/**+ * The session that actually receives the current screen when the user triggers the+ * assist gesture while OpenAssistant is the default digital assistant AND "use screen+ * context" is enabled. It flattens the [AssistStructure] view tree into a single text+ * blob (visible text + content descriptions), folds in any [AssistContent], then hands+ * off to [MainActivity] via [startVoiceActivity] so the chat can answer about the screen.+ *+ * We render no custom session UI — [setUiEnabled] is false and MainActivity is the UI.+ */+class OpenAssistantSession(context: Context) : VoiceInteractionSession(context) {++ private var screenshotPath: String? = null++ override fun onCreate() {+ super.onCreate()+ // We hand off to MainActivity for UI; don't draw a session overlay.+ setUiEnabled(false)+ }++ override fun onHandleAssist(state: AssistState) {+ super.onHandleAssist(state)+ val text = buildScreenText(state.assistStructure, state.assistContent)+ Log.d(TAG, "Captured screen text (${text.length} chars)")+ handOffToChat(text)+ }++ override fun onHandleScreenshot(screenshot: Bitmap?) {+ super.onHandleScreenshot(screenshot)+ if (screenshot == null) return+ try {+ val file = File(context.cacheDir, "assist_screenshot.png")+ FileOutputStream(file).use { out ->+ screenshot.compress(Bitmap.CompressFormat.PNG, 90, out)+ }+ screenshotPath = file.absolutePath+ } catch (e: Exception) {+ Log.w(TAG, "Failed to save assist screenshot", e)+ }+ }++ /** Flattens the view tree + assist content into a single length-capped string. */+ private fun buildScreenText(+ structure: AssistStructure?,+ content: AssistContent?,+ ): String {+ val sb = StringBuilder()+ if (structure != null) {+ val windowCount = structure.windowNodeCount+ for (i in 0 until windowCount) {+ if (sb.length >= MAX_CHARS) break+ val root = structure.getWindowNodeAt(i).rootViewNode+ appendNode(root, sb)+ }+ }+ content?.let { c ->+ c.structuredData?.takeIf { it.isNotBlank() }?.let {+ appendCapped(sb, "\n[structured] $it")+ }+ c.webUri?.let { appendCapped(sb, "\n[url] $it") }+ }+ return sb.toString().trim().take(MAX_CHARS)+ }++ private fun appendNode(node: AssistStructure.ViewNode?, sb: StringBuilder) {+ if (node == null || sb.length >= MAX_CHARS) return+ node.text?.toString()?.trim()?.takeIf { it.isNotEmpty() }?.let {+ appendCapped(sb, it)+ }+ node.contentDescription?.toString()?.trim()?.takeIf { it.isNotEmpty() }?.let {+ appendCapped(sb, it)+ }+ val childCount = node.childCount+ for (i in 0 until childCount) {+ if (sb.length >= MAX_CHARS) return+ appendNode(node.getChildAt(i), sb)+ }+ }++ private fun appendCapped(sb: StringBuilder, s: String) {+ if (sb.length >= MAX_CHARS) return+ if (sb.isNotEmpty()) sb.append('\n')+ val remaining = MAX_CHARS - sb.length+ if (s.length <= remaining) sb.append(s) else sb.append(s, 0, remaining)+ }++ private fun handOffToChat(text: String) {+ val intent = Intent(context, MainActivity::class.java).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ putExtra(EXTRA_SCREEN_TEXT, text)+ screenshotPath?.let { putExtra(EXTRA_SCREENSHOT_PATH, it) }+ }+ startVoiceActivity(intent)+ }++ companion object {+ private const val TAG = "OpenAssistantSession"+ private const val MAX_CHARS = 6000++ const val EXTRA_SCREEN_TEXT = "assist_screen_text"+ const val EXTRA_SCREENSHOT_PATH = "assist_screenshot_path"+ }+}
openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSessionService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSessionService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSessionService.ktnew file mode 100644index 0000000000..05f47083ba--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSessionService.kt@@ -0,0 +1,14 @@+package com.vayunmathur.openassistant.assist++import android.service.voice.VoiceInteractionSession+import android.service.voice.VoiceInteractionSessionService++/**+ * Factory the platform binds (via @xml/voice_interaction_service's sessionService+ * attribute) to create one [OpenAssistantSession] per assist invocation.+ */+class OpenAssistantSessionService : VoiceInteractionSessionService() {+ override fun onNewSession(args: android.os.Bundle?): VoiceInteractionSession {+ return OpenAssistantSession(this)+ }+}
openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantVoiceInteractionService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantVoiceInteractionService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantVoiceInteractionService.ktnew file mode 100644index 0000000000..247f869d82--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantVoiceInteractionService.kt@@ -0,0 +1,22 @@+package com.vayunmathur.openassistant.assist++import android.service.voice.VoiceInteractionService+import android.util.Log++/**+ * Entry point that registers OpenAssistant as a system voice interaction (digital+ * assistant) provider. It does almost nothing itself: the platform binds this+ * service to discover the app as an assistant, then routes each assist gesture to+ * [OpenAssistantSessionService] (declared in @xml/voice_interaction_service), which+ * spawns an [OpenAssistantSession] to actually receive the screen's AssistStructure.+ */+class OpenAssistantVoiceInteractionService : VoiceInteractionService() {+ override fun onReady() {+ super.onReady()+ Log.d(TAG, "VoiceInteractionService ready")+ }++ companion object {+ private const val TAG = "OAVoiceInteraction"+ }+}
openassistant/src/main/java/com/vayunmathur/openassistant/assist/StubRecognitionService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/assist/StubRecognitionService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/StubRecognitionService.ktnew file mode 100644index 0000000000..794c14831c--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/StubRecognitionService.kt@@ -0,0 +1,23 @@+package com.vayunmathur.openassistant.assist++import android.speech.RecognitionService+import android.speech.SpeechRecognizer++/**+ * Minimal no-op recognition service. It exists solely because the+ * `recognitionService` attribute in @xml/voice_interaction_service is REQUIRED by+ * the platform for a voice interaction service — OpenAssistant does not perform+ * on-device ASR here, so every listen request is immediately failed.+ */+class StubRecognitionService : RecognitionService() {+ override fun onStartListening(recognizerIntent: android.content.Intent?, listener: Callback?) {+ try {+ listener?.error(SpeechRecognizer.ERROR_CLIENT)+ } catch (_: android.os.RemoteException) {+ }+ }++ override fun onStopListening(listener: Callback?) {}++ override fun onCancel(listener: Callback?) {}+}
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.ktindex bf08700626..701c45a0d2 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -54,6 +54,20 @@ class AssistantViewModel( private var audioRecorder: WavRecorder? = null + /**+ * Screen contents captured by the Assist API (see+ * [com.vayunmathur.openassistant.assist.OpenAssistantSession]) when the app was+ * invoked as the default digital assistant. Prepended to the next inference+ * request as context so the model can answer about what is on screen, then+ * cleared so it only seeds a single turn.+ */+ private var pendingScreenContext: String? = null++ /** Stores screen text captured by the Assist API for the next inference turn. */+ fun setScreenContext(text: String?) {+ pendingScreenContext = text?.takeIf { it.isNotBlank() }+ }+ /** All conversations, newest first. */ val conversations: StateFlow<List<Conversation>> = repository.conversationsFlow() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())@@ -155,10 +169,17 @@ class AssistantViewModel( imagePaths: List<String>, audioPath: String?, ) {+ val screenContext = pendingScreenContext+ pendingScreenContext = null+ val effectiveText = if (screenContext != null) {+ "Current screen contents:\n$screenContext\n\nUser request: $userText"+ } else {+ userText+ } val context = getApplication<Application>() context.startService(Intent(context, InferenceService::class.java).apply { putExtra("conversation_id", conversationId)- putExtra("user_text", userText)+ putExtra("user_text", effectiveText) putExtra("image_paths", imagePaths.toTypedArray()) putExtra("audio_path", audioPath) })
openassistant/src/main/res/xml/recognition_service.xml
diff --git a/openassistant/src/main/res/xml/recognition_service.xml b/openassistant/src/main/res/xml/recognition_service.xmlnew file mode 100644index 0000000000..6ce891f0fc--- /dev/null+++ b/openassistant/src/main/res/xml/recognition_service.xml@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<recognition-service xmlns:android="http://schemas.android.com/apk/res/android" />
openassistant/src/main/res/xml/voice_interaction_service.xml
diff --git a/openassistant/src/main/res/xml/voice_interaction_service.xml b/openassistant/src/main/res/xml/voice_interaction_service.xmlnew file mode 100644index 0000000000..4d29b743c5--- /dev/null+++ b/openassistant/src/main/res/xml/voice_interaction_service.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<voice-interaction-service+ xmlns:android="http://schemas.android.com/apk/res/android"+ android:sessionService="com.vayunmathur.openassistant.assist.OpenAssistantSessionService"+ android:recognitionService="com.vayunmathur.openassistant.assist.StubRecognitionService"+ android:supportsAssist="true"+ android:supportsLaunchVoiceAssistFromKeyguard="false" />