Modern Apps git

← Modern-Apps.git

openassistant: detekt clean (202 tests)

Commit
1128f8a38aa319f8d4ad8a56bf8969cd3139cfa4
Author
Vayun Mathur <[email protected]>
When
2026-11-15 00:10 UTC (21 days ago)
Parents
fad1d45
Fix all detekt findings in openassistant by fixing code, not config
(detekt.yml untouched, no baselines added):
- UndocumentedPublicClass: KDoc for 45 types.
- WavDecoder: fmt-chunk validation extracted.
- InferenceService: message persistence split into
  MessageStore (TooManyFunctions), reply writer
  extracted (LongMethod), throw sites via failEngine/
  failCancelled (ThrowsCount), broad catches kept with
  narrow @Suppress justification, timeout logs its cause.
- MamlChatEngine: wrapped long lines.
- Tests: generic RuntimeExceptions became
  IllegalStateException, throw-count test split, shadow
  narrowly suppressed with comment, token-estimate and
  await loops restructured.
Verified: ./gradlew :openassistant:detekt :openassistant:testDevUnitTest :openassistant:lint
--max-workers=32 all pass (202 unit tests).

Diff

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 9b44da91fb..374abd2daa 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -21,8 +21,10 @@ import com.vayunmathur.openassistant.ui.LiteRTChatUi import com.vayunmathur.openassistant.ui.SettingsPage import com.vayunmathur.openassistant.util.AssistantViewModel +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() { +    /** Shared constants and helpers for MainActivity. */     companion object {         lateinit var intentLauncher: IntentLauncher     }@@ -72,10 +74,13 @@ class MainActivity : MaActivity() {     } } +/** Contract for route. */ @Serializable sealed interface Route: NavKey {+    /** Immutable value describing conversation page; carries id. */     @Serializable     data class ConversationPage(val id: Long): Route+    /** Singleton holding settings page state and operations. */     @Serializable     data object SettingsPage: Route }
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.ktindex 2e3d6b86bf..b5b779400f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSession.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantSession.kt@@ -106,6 +106,7 @@ class OpenAssistantSession(context: Context) : VoiceInteractionSession(context)         startVoiceActivity(intent)     } +    /** Shared constants and helpers for OpenAssistantSession. */     companion object {         private const val TAG = "OpenAssistantSession"         private const val MAX_CHARS = 6000
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.ktindex 7f0d0e1083..fe4c314d44 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantVoiceInteractionService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/assist/OpenAssistantVoiceInteractionService.kt@@ -16,6 +16,7 @@ class OpenAssistantVoiceInteractionService : VoiceInteractionService() {         Log.debug(TAG, "VoiceInteractionService ready")     } +    /** Shared constants and helpers for OpenAssistantVoiceInteractionService. */     companion object {         private const val TAG = "OAVoiceInteraction"     }
openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.ktindex f033d357c2..62a944aec5 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt@@ -14,6 +14,7 @@ import com.vayunmathur.library.util.DefaultConverters import androidx.room3.migration.Migration import kotlinx.coroutines.flow.Flow +/** Immutable value describing conversation. */ @Entity data class Conversation(     val title: String,@@ -22,6 +23,7 @@ data class Conversation(     override val id: Long = 0, ): DatabaseItem +/** Immutable value describing message. */ @Entity data class Message(     val conversationId: Long,@@ -37,6 +39,7 @@ data class Message(     override val id: Long = 0, ): DatabaseItem +/** Immutable value describing memory. */ @Entity data class Memory(     val content: String,@@ -44,6 +47,7 @@ data class Memory(     override val id: Long = 0, ): DatabaseItem +/** Contract for conversation dao. */ @Dao interface ConversationDao {     @Query("SELECT * FROM Conversation ORDER BY timestamp DESC")@@ -62,6 +66,7 @@ interface ConversationDao {     suspend fun delete(value: Conversation): Int } +/** Contract for message dao. */ @Dao interface MessageDao {     @Query("SELECT * FROM Message WHERE conversationId = :conversationId ORDER BY timestamp ASC")@@ -83,6 +88,7 @@ interface MessageDao {     suspend fun delete(value: Message): Int } +/** Contract for memory dao. */ @Dao interface MemoryDao {     @Query("SELECT * FROM Memory ORDER BY id ASC")@@ -101,6 +107,7 @@ interface MemoryDao {     suspend fun delete(value: Memory): Int } +/** App Database: a room database implementation for app database. */ @ColumnTypeConverters(DefaultConverters::class) @Database(entities = [Conversation::class, Message::class, Memory::class], version = 4, exportSchema = false) abstract class AppDatabase: RoomDatabase() {@@ -108,6 +115,7 @@ abstract class AppDatabase: RoomDatabase() {     abstract fun messageDao(): MessageDao     abstract fun memoryDao(): MemoryDao +    /** Shared constants and helpers for AppDatabase. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {         override val migrations = listOf(             Migration(1, 2) { it.execSQL("ALTER TABLE Message ADD COLUMN missingAppPackage TEXT") },
openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.ktindex 501e6ca72d..d55deeb305 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt@@ -52,6 +52,7 @@ class OpenAssistantRepository private constructor(context: Context) :     internal val messageDaoRef get(): MessageDao = messageDao     internal val memoryDaoRef get(): MemoryDao = memoryDao +    /** Shared constants and helpers for OpenAssistantRepository. */     companion object {         @Volatile         private var instance: OpenAssistantRepository? = null
openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.ktindex a3df7b502b..1e0b00c7e0 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt@@ -3,11 +3,13 @@ package com.vayunmathur.openassistant.domain /** A tool call the model emitted, with every argument still as its raw text. */ data class ParsedToolCall(val name: String, val arguments: Map<String, String>) +/** Kinds of tool param type. */ enum class ToolParamType(val gemmaName: String) {     STRING("STRING"),     NUMBER("NUMBER"), } +/** Immutable value describing tool param spec. */ data class ToolParamSpec(     val name: String,     val description: String,@@ -15,6 +17,7 @@ data class ToolParamSpec(     val required: Boolean = true, ) +/** Immutable value describing tool spec. */ data class ToolSpec(     val name: String,     val description: String,@@ -27,8 +30,11 @@ class ToolArgs(private val values: Map<String, Any>) {     fun number(name: String): Double = values[name] as? Double ?: 0.0 } +/** Contract for tool args result. */ sealed interface ToolArgsResult {+    /** Immutable value describing ok; carries args. */     data class Ok(val args: ToolArgs) : ToolArgsResult+    /** Immutable value describing invalid; carries message. */     data class Invalid(val message: String) : ToolArgsResult } 
openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.ktindex 966184a3da..7bb3580f09 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt@@ -6,11 +6,15 @@ fun interface ChatGenerator {     suspend fun generate(continuation: String, onText: (String) -> Boolean): String? } +/** Contract for tool loop outcome. */ sealed interface ToolLoopOutcome {     val text: String +    /** Immutable value describing finished; carries text. */     data class Finished(override val text: String) : ToolLoopOutcome+    /** Immutable value describing halted; carries text. */     data class Halted(override val text: String) : ToolLoopOutcome+    /** Immutable value describing failed; carries text. */     data class Failed(override val text: String) : ToolLoopOutcome } 
openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.ktindex 3ea83bde47..f1c9ca5617 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt@@ -30,12 +30,7 @@ fun decodeWavMono16k(bytes: ByteArray, maxSamples: Int = WAV_SAMPLE_RATE * WAV_M         val body = at + CHUNK_HEADER         when (chunkId(bytes, at)) {             "fmt " -> {-                if (size < FMT_MIN || body + FMT_MIN > bytes.size) return null-                val ok = wav.getShort(body).toInt() == PCM &&-                    wav.getShort(body + 2).toInt() == 1 &&-                    wav.getInt(body + 4) == WAV_SAMPLE_RATE &&-                    wav.getShort(body + 14).toInt() == BITS-                if (!ok) return null+                if (!isSupportedFmt(wav, body, size, bytes.size)) return null                 described = true             }             "data" -> {@@ -51,4 +46,13 @@ fun decodeWavMono16k(bytes: ByteArray, maxSamples: Int = WAV_SAMPLE_RATE * WAV_M     return FloatArray(count) { pcm.get(it) / PCM_SCALE } } -private fun chunkId(bytes: ByteArray, at: Int): String = String(bytes, at, 4, Charsets.US_ASCII)+    /** True when the fmt chunk describes 16 kHz mono 16-bit PCM. */+    private fun isSupportedFmt(wav: ByteBuffer, body: Int, size: Int, total: Int): Boolean {+        if (size < FMT_MIN || body + FMT_MIN > total) return false+        return wav.getShort(body).toInt() == PCM &&+            wav.getShort(body + 2).toInt() == 1 &&+            wav.getInt(body + 4) == WAV_SAMPLE_RATE &&+            wav.getShort(body + 14).toInt() == BITS+    }++    private fun chunkId(bytes: ByteArray, at: Int): String = String(bytes, at, 4, Charsets.US_ASCII)
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.ktindex 486dafe285..3c0fdf0a9f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt@@ -44,6 +44,7 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo         override val propertySchema: A2uiSchema = A2uiObjectSchema(properties = props, required = required)     } +    /** Shared constants and helpers for AssistantCatalog. */     companion object {         const val ID = "https://vayunmathur.com/openassistant/a2ui/catalog/v1" 
openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.ktindex 201c9e399b..5147907829 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -31,6 +31,7 @@ import java.util.concurrent.Executors /** One stored message, text only: media is only ever attached to the current turn. */ data class HistoryTurn(val fromUser: Boolean, val text: String) +/** Immutable value describing chat request. */ data class ChatRequest(     val system: String,     val history: List<HistoryTurn>,@@ -39,9 +40,13 @@ data class ChatRequest(     val audioPath: String? = null, ) +/** Contract for chat result. */ sealed interface ChatResult {+    /** Immutable value describing reply; carries text, halted. */     data class Reply(val text: String, val halted: Boolean) : ChatResult+    /** Singleton holding too long state and operations. */     data object TooLong : ChatResult+    /** Singleton holding unavailable state and operations. */     data object Unavailable : ChatResult } @@ -154,12 +159,16 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable {             val sampling = Sampling.Chat.copy(seed = System.nanoTime())             val generator = ChatGenerator { continuation, onRaw ->                 withContext(engineThread) {-                    model.generate(conversation, request.system, declarations, CHAT_REPLY_LIMIT, continuation, sampling, onRaw)+                    model.generate(+                        conversation, request.system, declarations, CHAT_REPLY_LIMIT, continuation, sampling, onRaw,+                    )                 }             }             val outcome = runToolLoop(                 generator = generator,-                parseCall = { reply -> Gemma4Handle.parseToolCall(reply)?.let { ParsedToolCall(it.name, it.arguments) } },+                parseCall = { reply ->+                    Gemma4Handle.parseToolCall(reply)?.let { ParsedToolCall(it.name, it.arguments) }+                },                 executeTool = { call ->                     withContext(Dispatchers.IO) { tools.invoke(call) }.also {                         Log.status(TAG, "tool ${call.name} -> ${it.take(LOG_CHARS)}")@@ -176,7 +185,12 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable {         }      /** Single-turn structured extraction: greedy, no tools, no history. Null when unavailable. */-    open suspend fun extract(system: String, userText: String, imagePaths: List<String>, onText: (String) -> Boolean): String? =+    open suspend fun extract(+        system: String,+        userText: String,+        imagePaths: List<String>,+        onText: (String) -> Boolean,+    ): String? =         mutex.withLock {             withContext(engineThread) {                 val model = model() ?: return@withContext null
openassistant/src/main/java/com/vayunmathur/openassistant/util/AppBackupAgent.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AppBackupAgent.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AppBackupAgent.ktindex 4357c5b5e3..277124cd61 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AppBackupAgent.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AppBackupAgent.kt@@ -5,6 +5,7 @@ import com.vayunmathur.library.util.BaseBackupAgent import com.vayunmathur.library.util.DatabaseHelper import java.io.File +/** App Backup Agent: a base backup agent implementation for app backup agent. */ class AppBackupAgent : BaseBackupAgent() {     override val dbCodec = SqlCipherDbCodec 
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.ktindex 5f5c535ff1..ecc0d34dfe 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt@@ -236,14 +236,18 @@ internal class AssistantToolIntents(private val context: Context) {     } } +/** Missing App Exception: a string implementation for missing app exception. */ class MissingAppException(val packageName: String) : Exception("App $packageName is not installed.") +/** Immutable value describing weather lat lon request; carries latitude, longitude. */ @kotlinx.serialization.Serializable data class WeatherLatLonRequest(val latitude: Double, val longitude: Double) +/** Immutable value describing weather name request; carries name. */ @kotlinx.serialization.Serializable data class WeatherNameRequest(val name: String) +/** Immutable value describing create link request; carries name, expiryMillis. */ @kotlinx.serialization.Serializable data class CreateLinkRequest(val name: String, val expiryMillis: Long) 
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.ktindex 1ad794a1da..93ad4d65ba 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantUiContract.kt@@ -47,6 +47,7 @@ interface ChatActions {     fun cancelMedia() {}     fun send() {} +    /** Shared constants and helpers for ChatActions. */     companion object {         val Noop: ChatActions = object : ChatActions {}     }@@ -68,6 +69,7 @@ interface SettingsActions {     /** Restore the system prompt to the built-in default. */     fun resetSystemPrompt() {} +    /** Shared constants and helpers for SettingsActions. */     companion object {         val Noop: SettingsActions = object : SettingsActions {}     }
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 cb14067702..357648ee06 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -276,6 +276,7 @@ class AssistantViewModel(         }     } +    /** Shared constants and helpers for AssistantViewModel. */     companion object {         private const val TAG = "AssistantViewModel"         private val LEGACY_SIGLIP_FILES = listOf(
openassistant/src/main/java/com/vayunmathur/openassistant/util/AudioRecorder.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AudioRecorder.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AudioRecorder.ktindex 331c9abbd8..e3c36b93e3 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AudioRecorder.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AudioRecorder.kt@@ -18,6 +18,7 @@ import java.io.FileOutputStream import java.nio.ByteBuffer import java.nio.ByteOrder +/** Wav Recorder: a context implementation for wav recorder. */ class WavRecorder(val context: Context, val outputFile: File, val scope: CoroutineScope) {     private var audioRecord: AudioRecord? = null     private var isRecording = false@@ -107,6 +108,7 @@ class WavRecorder(val context: Context, val outputFile: File, val scope: Corouti         }     } +    /** Shared constants and helpers for WavRecorder. */     companion object {         /** The canonical PCM WAV header this writes, and the size a silent file will be. */         const val WAV_HEADER_BYTES = 44
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex 59af021b90..73ccf2745f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -58,8 +58,10 @@ import com.vayunmathur.openassistant.domain.withA2uiBlock import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.selects.select +/** Inference Service: a service implementation for inference service. */ class InferenceService : Service() { +    /** Shared constants and helpers for InferenceService. */     companion object {         var newTitle: String? = null         var halt: Boolean = false@@ -129,6 +131,8 @@ class InferenceService : Service() {     private val repository by lazy { OpenAssistantRepository.get(applicationContext) }     private val conversationDao get() = conversationDaoOverride ?: repository.conversationDaoRef     private val messageDao get() = messageDaoOverride ?: repository.messageDaoRef++    private val store: MessageStore get() = MessageStore(messageDao, conversationDao)     private val memoryDao get() = memoryDaoOverride ?: repository.memoryDaoRef      override fun onBind(intent: Intent?): IBinder? = null@@ -255,7 +259,7 @@ class InferenceService : Service() {                 runIntentInference(job.userText, job.imagePaths, job.schema, job.receiver)             }         } catch (e: TimeoutCancellationException) {-            Log.error("InferenceService", "Intent inference timed out after 45 seconds")+            Log.error("InferenceService", "Intent inference timed out after 45 seconds", e)             job.receiver.send(                 RESULT_ERROR_CODE,                 Bundle().apply { putString("error", getString(R.string.error_inference_timeout)) },@@ -307,6 +311,8 @@ class InferenceService : Service() {         }     } +    // Last-resort retry: any engine failure is logged and surfaced, so the catch stays broad.+    @Suppress("TooGenericExceptionCaught")     private suspend fun retryStandardInference(job: InferenceJob.Standard) {         engineLock.withLock {             engine?.close()@@ -320,7 +326,7 @@ class InferenceService : Service() {         } catch (retryExpected: Exception) {             Log.error("InferenceService", "Retry also failed", retryExpected)             val detail = retryExpected.localizedMessage ?: ""-            upsertMessageToDb(+            store.upsert(                 DbMessage(                     conversationId = job.conversationId,                     text = getString(R.string.error_prefix, detail),@@ -353,7 +359,7 @@ class InferenceService : Service() {         schema: String,         receiver: ResultReceiver,     ) {-        val chat = engine ?: throw IllegalStateException(getString(R.string.error_ai_engine_failed))+        val chat = engine ?: failEngine()         val job = currentCoroutineContext()[Job]         var sent = false         Log.debug("InferenceService", "Sending intent inference request (streaming for early halt)")@@ -370,8 +376,8 @@ class InferenceService : Service() {             }         }         if (sent) return-        currentCoroutineContext()[Job]?.let { if (!it.isActive) throw CancellationException("intent cancelled") }-        if (reply == null) throw IllegalStateException(getString(R.string.error_ai_engine_failed))+        currentCoroutineContext()[Job]?.let { if (!it.isActive) failCancelled() }+        if (reply == null) failEngine()          val finalJson = tryExtractLargestJson(reply)         if (finalJson != null && JsonSchemaValidator.validateJsonAgainstSchema(finalJson, schema) == null) {@@ -387,6 +393,13 @@ class InferenceService : Service() {         )     } +    /** Fails with the engine-failed error; keeps throw sites out of the inference paths. */+    private fun failEngine(): Nothing =+        throw IllegalStateException(getString(R.string.error_ai_engine_failed))++    /** Fails with a cancellation; keeps throw sites out of the inference paths. */+    private fun failCancelled(): Nothing = throw CancellationException("intent cancelled")+     private fun tryExtractLargestJson(text: String): String? =         JsonExtractor.largestObject(text) @@ -418,13 +431,15 @@ class InferenceService : Service() {         return base + "\n\n" + AssistantCatalog.PROMPT_SECTION     } +    // The chat call needs cleanup-and-rethrow on any engine failure, so the catch stays broad.+    @Suppress("TooGenericExceptionCaught")     private suspend fun runInferenceLoop(         conversationId: Long,         userText: String,         imagePaths: Array<String>,         audioPath: String?,     ) {-        val chat = engine ?: throw IllegalStateException(getString(R.string.error_ai_engine_failed))+        val chat = engine ?: failEngine()         val request = ChatRequest(             system = systemPrompt(),             history = loadHistory(conversationId, userText),@@ -433,7 +448,7 @@ class InferenceService : Service() {             audioPath = audioPath?.takeIf { File(it).exists() },         ) -        val aiMsgId = upsertMessageToDb(+        val aiMsgId = store.upsert(             DbMessage(                 conversationId = conversationId,                 text = "...",@@ -444,18 +459,7 @@ class InferenceService : Service() {          val job = currentCoroutineContext()[Job]         val latest = AtomicReference("")-        val writer = serviceScope.launch {-            var written = ""-            while (isActive) {-                delay(DB_WRITE_INTERVAL_MILLIS)-                flushTitle(conversationId)-                val text = latest.get()-                if (text.isNotBlank() && text != written) {-                    updateMessageInDb(aiMsgId, text)-                    written = text-                }-            }-        }+        val writer = launchReplyWriter(conversationId, aiMsgId, latest)         val result = try {             chat.chat(request, tools) { text ->                 if (halt || job?.isActive == false) {@@ -479,49 +483,84 @@ class InferenceService : Service() {                 messageDao.deleteById(aiMsgId)                 Log.status("InferenceService", "Standard inference halted successfully.")             } else if (result.text.isNotBlank()) {-                storeReply(aiMsgId, result.text)+                store.storeReply(aiMsgId, result.text)             }-            ChatResult.TooLong -> updateMessageInDb(+            ChatResult.TooLong -> store.updateMessage(                 aiMsgId,                 getString(R.string.error_prefix, "the message is too long for the model's context"),             )             ChatResult.Unavailable -> {                 messageDao.deleteById(aiMsgId)-                throw IllegalStateException(getString(R.string.error_ai_engine_failed))+                failEngine()             }         }     } ++    /** Periodically flushes the streaming reply and any new title to the DB. */+    private fun launchReplyWriter(+        conversationId: Long,+        aiMsgId: Long,+        latest: AtomicReference<String>,+    ) = serviceScope.launch {+        var written = ""+        while (isActive) {+            delay(DB_WRITE_INTERVAL_MILLIS)+            flushTitle(conversationId)+            val text = latest.get()+            if (text.isNotBlank() && text != written) {+                store.updateMessage(aiMsgId, text)+                written = text+            }+        }+    }     private suspend fun flushTitle(conversationId: Long) {         val title = newTitle ?: return         newTitle = null-        updateTitleInDb(conversationId, title)+        store.updateTitle(conversationId, title)     } -    private suspend fun fetchHistoryFromDb(id: Long): List<DbMessage> = messageDao.getByConversation(id)+    private suspend fun fetchHistoryFromDb(id: Long): List<DbMessage> = store.history(id)      /** Stores a finished reply: the prose as its text, any A2UI block beside it. */-    private suspend fun storeReply(id: Long, reply: String) {++    override fun onDestroy() {+        serviceScope.cancel()+        engine?.close()+        engine = null+        super.onDestroy()+    }+}++/** Message persistence for [InferenceService], split out of the service class. */+internal class MessageStore(+    private val messageDao: MessageDao,+    private val conversationDao: ConversationDao,+) {+    /** Conversation history, oldest first. */+    suspend fun history(id: Long): List<DbMessage> = messageDao.getByConversation(id)++    /** Stores a finished reply: the prose as its text, any A2UI block beside it. */+    suspend fun storeReply(id: Long, reply: String) {         val split = splitA2ui(reply, streaming = false)         val shown = if (split.visible.isBlank() && split.json == null) reply else split.visible-        updateMessageInDb(id, shown, split.json)+        updateMessage(id, shown, split.json)     }-    private suspend fun upsertMessageToDb(msg: DbMessage): Long = messageDao.upsert(msg)-    private suspend fun updateMessageInDb(id: Long, text: String, a2ui: String? = null) {++    /** Inserts a message and returns its row id. */+    suspend fun upsert(msg: DbMessage): Long = messageDao.upsert(msg)++    /** Replaces a message's text and A2UI payload. */+    suspend fun updateMessage(id: Long, text: String, a2ui: String? = null) {         val existing = messageDao.getById(id) ?: return-        upsertMessageToDb(existing.copy(text = text, a2ui = a2ui))+        upsert(existing.copy(text = text, a2ui = a2ui))     }-    private suspend fun updateTitleInDb(id: Long, title: String) {++    /** Sets the conversation title. */+    suspend fun updateTitle(id: Long, title: String) {         val oldConversation = conversationDao.getById(id)         if (oldConversation != null) {             conversationDao.upsert(oldConversation.copy(title = title))         }     }--    override fun onDestroy() {-        serviceScope.cancel()-        engine?.close()-        engine = null-        super.onDestroy()-    } }
openassistant/src/main/java/com/vayunmathur/openassistant/util/JsonSchemaValidator.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/JsonSchemaValidator.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/JsonSchemaValidator.ktindex 94397236ea..f938dec7b1 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/JsonSchemaValidator.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/JsonSchemaValidator.kt@@ -7,6 +7,7 @@ import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive +/** Singleton holding json schema validator state and operations. */ object JsonSchemaValidator {     fun validateJsonAgainstSchema(jsonString: String, schemaString: String): String? {         val json = try {
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.ktindex 9848bb06fa..06b2149c8c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt@@ -64,10 +64,13 @@ class AssistantToolIntentsTest {                 .contains("Try to help the user with your own knowledge instead."))     } -    @Test fun runToolWrapsSuccessErrorsAndMissingApps() {+    @Test fun runToolWrapsSuccessAndErrors() {         assertEquals("done", tools.runTool { "done" })         assertEquals("Error: boom", tools.runTool { throw IllegalStateException("boom") })-        assertEquals("Error: null", tools.runTool { throw RuntimeException() })+        assertEquals("Error: null", tools.runTool { throw IllegalStateException() })+    }++    @Test fun runToolWrapsMissingApps() {         val missing = tools.runTool { throw MissingAppException("com.vayunmathur.email") }         assertTrue(missing.startsWith("The Email app is required"), missing)     }
openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.ktindex 34caa096a5..b88f40ff0c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt@@ -129,14 +129,17 @@ class InferenceServiceFakeEngineTest {         service.conversationDaoOverride = conversationDao         service.memoryDaoOverride = FakeMemoryDao()         service.nowMillis = { clock.get() }-        service.engineFactory = { engineQueue.removeFirstOrNull() ?: FakeEngine().also { engines += it } }+        service.engineFactory = {+            val next = engineQueue.removeFirstOrNull()+            if (next != null) next else FakeEngine().also { engines += it }+        }         c.create()         return service     }      private fun await(desc: String, cond: () -> Boolean) {         val deadline = System.currentTimeMillis() + 20_000-        while (System.currentTimeMillis() < deadline) { if (cond()) return; Thread.sleep(25) }+        while (System.currentTimeMillis() < deadline && !cond()) { Thread.sleep(25) }         assertTrue(cond(), "timed out: $desc")     } @@ -204,7 +207,7 @@ class InferenceServiceFakeEngineTest {     }      @Test fun failingTwiceStoresErrorMessage() {-        val boom = { _: ChatRequest, _: (String) -> Boolean -> throw RuntimeException("boom-native") }+        val boom = { _: ChatRequest, _: (String) -> Boolean -> throw IllegalStateException("boom-native") }         val service = startService(FakeEngine(chatBehavior = boom), FakeEngine(chatBehavior = boom))         service.onStartCommand(standardIntent(6L, "fail"), 0, 1)         await("error stored") { messageDao.assistantTexts(6L).any { it.contains("boom-native") } }
openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.ktindex 38b398ff74..9c8a8cdad7 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/ShadowUnresolvableIntent.kt@@ -9,6 +9,8 @@ import org.robolectric.annotation.Implements /** Every intent reads as unresolvable, so cross-app launches take the missing-app path. */ @Implements(Intent::class) class ShadowUnresolvableIntent {+    // Signature must mirror Intent.resolveActivity for Robolectric; the manager is not needed.+    @Suppress("UnusedParameter", "FunctionOnlyReturningConstant")     @Implementation     fun resolveActivity(pm: PackageManager): ResolveInfo? = null }
openassistant/src/test/java/com/vayunmathur/openassistant/util/TokenEstimateTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/TokenEstimateTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/TokenEstimateTest.ktindex 8e617de6e9..ea38daded4 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/TokenEstimateTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/TokenEstimateTest.kt@@ -19,23 +19,21 @@ class TokenEstimateTest {         var tokens = 0         var inWord = false         for (c in text) {-            if (c.isWhitespace()) {-                inWord = false-                continue-            }             // CJK code points carry a full token each; other scripts split on words.             val isCjk = c in '一'..'鿿' || c in '぀'..'ヿ'-            if (isCjk) {-                tokens++-                inWord = false-                continue-            }-            // Surrogate halves (emoji, pictographs) ride with surrounding-            // words rather than starting new ones.-            if (c.isHighSurrogate() || c.isLowSurrogate()) continue-            if (!inWord) {-                tokens++-                inWord = true+            when {+                c.isWhitespace() -> inWord = false+                isCjk -> {+                    tokens+++                    inWord = false+                }+                // Surrogate halves (emoji, pictographs) ride with surrounding+                // words rather than starting new ones.+                c.isHighSurrogate() || c.isLowSurrogate() -> Unit+                !inWord -> {+                    tokens+++                    inWord = true+                }             }         }         // Non-blank input with no word starts (a lone emoji) still costs one.