Modern Apps git

← Modern-Apps.git

openassistant: host-gated write confirmation foundation (#assistant)

Commit
ed1955fa63765b2c81933b8c1da6305e52dab9ef
Author
Vayun Mathur <[email protected]>
When
2026-11-16 22:36 UTC (19 days ago)
Parents
5fa25a7
Implements P0 of the OpenAssistant platform core design
(/tmp/oa-design.md §4.2, §2, §4.4): a host confirmation gate
so model-emitted write tool calls no longer execute silently.

Tool risk:
- ToolSpec.risk (ToolRisk READ/WRITE_CONFIRM/HANDOFF_PREP,
  default READ) in domain/ToolCalls.kt. Reclassified per §2:
  create_note, create_todo, complete_todo, create_contact,
  create_calendar_event, create_location_share_link,
  play_music, set_alarm, set_timer and remove_memory are
  WRITE_CONFIRM; add_to_memory stays READ (ungated, per the
  aggressive-memory system prompt); all others READ. Spec
  descriptions note the confirmation requirement.

Gate (never executes unconfirmed):
- domain/PendingToolCalls.kt: pure PendingToolCall (raw args,
  summary, 10-minute expiry, consumed flag),
  PendingToolCallStore interface + in-memory impl, markConsumed
  exactly-once, plus pendingToolSummary and redactedArgsSummary
  (length-only, e.g. content(len=12); never raw bodies).
- AssistantTools.invoke validates args, then refuses
  WRITE_CONFIRM with "Error: confirmation required for X"
  without touching the handler. createPending stores a valid
  gated call; invokeConfirmed(pendingId) executes exactly once
  and returns already-consumed / not-found / expired errors
  without re-executing. Constructor gains optional store/clock/
  id params with defaults, so existing call sites are unchanged;
  the spec/handler init check is kept.

Loop + engine:
- ToolLoop gains ToolLoopOutcome.PendingConfirmation and a
  pendingFor hook checked before executeTool, so a gated call
  ends the turn unexecuted. MamlChatEngine wires pendingFor to
  AssistantTools.createPending and surfaces
  ChatResult.Pending(pendingId, summary, text).

Persistence (DB v5, combining P0+P1 to avoid a later v6):
- Message.a2uiData column (P1 data-model replay), a
  PendingToolCall table (id, conversationId, toolName,
  argsJson, summary, createdAt, expiresAt, consumed) and an
  AuditRecord table (toolName, PII-redacted argsSummary,
  outcome, timestamp), with DAOs exposed via AppDatabase and
  OpenAssistantRepository. Migration 4->5 in one step.

Host confirm card + interception:
- platform/A2uiTemplates.confirmCard renders Card>Column[Text
  title, Text summary, Row[Cancel, Confirm primary]] with
  confirm.tool/cancel.tool events carrying the pending id;
  validated through buildA2uiEnvelope in tests.
- A2uiController gains an onHostAction interceptor (kept before
  onAction so trailing-lambda call sites still bind correctly);
  AssistantViewModel intercepts confirm/cancel, inserts a
  [HostConfirm <id>]/[HostCancel <id>] user message and requests
  inference. InferenceService detects that marker before the
  model loop, restores the persisted pending call, executes it
  via its AssistantTools.invokeConfirmed, writes the redacted
  audit record, marks the persisted call consumed, inserts a
  status message, then runs the model turn as
  [Confirmed "<tool>": <result>] (or [Cancelled "<tool>"]).
  On ChatResult.Pending it persists the pending call and
  attaches the host confirm card to the assistant message.

Tests: gate tests proving WRITE_CONFIRM never executes
unconfirmed and confirmed execution is idempotent/expires,
risk-classification test, ToolLoop pending short-circuit test,
PendingToolCalls store test, A2uiTemplates envelope test, and
migration test extended to v5. Existing invoke/success tests
updated for the gated write tools.

Verified: ./gradlew :openassistant:testDevUnitTest
:openassistant:compileDevKotlin (JAVA_HOME jdk21 + proxy env on
devvm21958) — 210 tests, 0 failures. Not pushed.

Diff

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 62a944aec5..7b879dbe34 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/Database.kt@@ -34,6 +34,8 @@ data class Message(     val missingAppPackage: String? = null,     /** The A2UI block the model attached to this reply, as written (see domain/A2uiBlocks). */     val a2ui: String? = null,+    /** Final A2UI data-model snapshot for replay (P1); null until an action stores it. */+    val a2uiData: String? = null,     val timestamp: Long = System.currentTimeMillis(),     @PrimaryKey(autoGenerate = true)     override val id: Long = 0,@@ -88,6 +90,58 @@ interface MessageDao {     suspend fun delete(value: Message): Int } +/** A WRITE_CONFIRM tool call persisted awaiting host confirmation. */+@Entity(tableName = "PendingToolCall")+data class PendingToolCallEntity(+    @PrimaryKey val id: String,+    val conversationId: Long,+    val toolName: String,+    val argsJson: String,+    val summary: String,+    val createdAt: Long,+    val expiresAt: Long,+    val consumed: Boolean = false,+)++/** PII-redacted audit record for a confirmed tool execution. */+@Entity+data class AuditRecord(+    val toolName: String,+    val argsSummary: String,+    val outcome: String,+    val timestamp: Long = System.currentTimeMillis(),+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+)++/** Contract for pending tool call dao. */+@Dao+interface PendingToolCallDao {+    @Query("SELECT * FROM PendingToolCall WHERE id = :id")+    suspend fun getById(id: String): PendingToolCallEntity?++    @Query("SELECT * FROM PendingToolCall WHERE conversationId = :conversationId ORDER BY createdAt ASC")+    suspend fun getByConversation(conversationId: Long): List<PendingToolCallEntity>++    @Query("DELETE FROM PendingToolCall WHERE id = :id")+    suspend fun deleteById(id: String)++    @Upsert+    suspend fun upsert(value: PendingToolCallEntity): Long+}++/** Contract for audit record dao. */+@Dao+interface AuditRecordDao {+    @Query("SELECT * FROM AuditRecord ORDER BY timestamp DESC")+    fun getAllFlow(): Flow<List<AuditRecord>>++    @Query("SELECT * FROM AuditRecord ORDER BY timestamp DESC LIMIT :limit")+    suspend fun getRecent(limit: Int = 100): List<AuditRecord>++    @Upsert+    suspend fun upsert(value: AuditRecord): Long+}+ /** Contract for memory dao. */ @Dao interface MemoryDao {@@ -109,11 +163,17 @@ interface MemoryDao {  /** App Database: a room database implementation for app database. */ @ColumnTypeConverters(DefaultConverters::class)-@Database(entities = [Conversation::class, Message::class, Memory::class], version = 4, exportSchema = false)+@Database(+    entities = [Conversation::class, Message::class, Memory::class, PendingToolCallEntity::class, AuditRecord::class],+    version = 5,+    exportSchema = false,+) abstract class AppDatabase: RoomDatabase() {     abstract fun conversationDao(): ConversationDao     abstract fun messageDao(): MessageDao     abstract fun memoryDao(): MemoryDao+    abstract fun pendingToolCallDao(): PendingToolCallDao+    abstract fun auditRecordDao(): AuditRecordDao      /** Shared constants and helpers for AppDatabase. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {@@ -126,6 +186,20 @@ abstract class AppDatabase: RoomDatabase() {                 )             },             Migration(3, 4) { it.execSQL("ALTER TABLE Message ADD COLUMN a2ui TEXT") },+            Migration(4, 5) {+                it.execSQL("ALTER TABLE Message ADD COLUMN a2uiData TEXT")+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `PendingToolCall` " ++                        "(`id` TEXT NOT NULL, `conversationId` INTEGER NOT NULL, `toolName` TEXT NOT NULL, " ++                        "`argsJson` TEXT NOT NULL, `summary` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " ++                        "`expiresAt` INTEGER NOT NULL, `consumed` INTEGER NOT NULL, PRIMARY KEY(`id`))",+                )+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `AuditRecord` " ++                        "(`toolName` TEXT NOT NULL, `argsSummary` TEXT NOT NULL, `outcome` TEXT NOT NULL, " ++                        "`timestamp` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",+                )+            },         )     } }
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 d55deeb305..7c23b388b1 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt@@ -13,6 +13,8 @@ class OpenAssistantRepository private constructor(context: Context) :     private val conversationDao get() = db.conversationDao()     private val messageDao get() = db.messageDao()     private val memoryDao get() = db.memoryDao()+    private val pendingToolCallDao get() = db.pendingToolCallDao()+    private val auditRecordDao get() = db.auditRecordDao()      // ------------------------------------------------------------------     // Conversation@@ -47,10 +49,24 @@ class OpenAssistantRepository private constructor(context: Context) :     suspend fun upsertMemory(value: Memory): Long = memoryDao.upsert(value)     suspend fun deleteMemory(value: Memory): Int = memoryDao.delete(value) +    // ------------------------------------------------------------------+    // Pending tool calls + audit+    // ------------------------------------------------------------------++    suspend fun getPendingToolCall(id: String): PendingToolCallEntity? = pendingToolCallDao.getById(id)+    suspend fun getPendingToolCalls(conversationId: Long): List<PendingToolCallEntity> =+        pendingToolCallDao.getByConversation(conversationId)+    suspend fun upsertPendingToolCall(value: PendingToolCallEntity): Long = pendingToolCallDao.upsert(value)+    suspend fun deletePendingToolCallById(id: String) = pendingToolCallDao.deleteById(id)+    suspend fun insertAuditRecord(value: AuditRecord): Long = auditRecordDao.upsert(value)+    suspend fun getRecentAuditRecords(limit: Int = 100): List<AuditRecord> = auditRecordDao.getRecent(limit)+     /** Backing DAOs for [com.vayunmathur.openassistant.platform.AssistantTools] and similar consumers. */     internal val conversationDaoRef get(): ConversationDao = conversationDao     internal val messageDaoRef get(): MessageDao = messageDao     internal val memoryDaoRef get(): MemoryDao = memoryDao+    internal val pendingToolCallDaoRef get(): PendingToolCallDao = pendingToolCallDao+    internal val auditRecordDaoRef get(): AuditRecordDao = auditRecordDao      /** Shared constants and helpers for OpenAssistantRepository. */     companion object {
openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.ktindex 2cb4274279..f6937f624a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -2,6 +2,7 @@ package com.vayunmathur.openassistant.domain  import com.vayunmathur.openassistant.domain.ToolParamType.NUMBER import com.vayunmathur.openassistant.domain.ToolParamType.STRING+import com.vayunmathur.openassistant.domain.ToolRisk.WRITE_CONFIRM  private fun p(name: String, type: ToolParamType = STRING, description: String = "", required: Boolean = true) =     ToolParamSpec(name, description, type, required)@@ -14,8 +15,8 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(     ToolSpec("get_notes", "Get a list of all notes"),     ToolSpec(         "create_note",-        "Create a new note in the notes app. Should only be used with EXPLICIT request by user",-        listOf(p("title"), p("content")),+        "Create a new note in the notes app (requires confirmation). Should only be used with EXPLICIT request by user",+        listOf(p("title"), p("content")), risk = WRITE_CONFIRM,     ),     ToolSpec(         "get_todos",@@ -25,53 +26,53 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(     ),     ToolSpec(         "create_todo",-        "Create a task in the todo app. Should only be used with EXPLICIT request by user. The title may " ++        "Create a task in the todo app (requires confirmation). Should only be used with EXPLICIT request by user. The title may " +             "include words like 'tomorrow 6pm' or '#tag', which are understood when no due time is given.",         listOf(             p("title"),             p("due", NUMBER, "optional due time as epoch milliseconds", required = false),             p("notes", required = false),             p("priority", NUMBER, "optional priority, 1 (highest) to 4", required = false),-        ),+        ), risk = WRITE_CONFIRM,     ),     ToolSpec(         "complete_todo",-        "Mark a task done. Should only be used with EXPLICIT request by user.",+        "Mark a task done (requires confirmation). Should only be used with EXPLICIT request by user.",         listOf(             p("id", description = "task id from get_todos", required = false),             p("title", description = "exact task title, used when no id is given", required = false),-        ),+        ), risk = WRITE_CONFIRM,     ),     ToolSpec("get_contacts", "Get a list of all contacts"),-    ToolSpec("create_contact", "Create a new contact", listOf(p("name"), p("phone_number"))),+    ToolSpec("create_contact", "Create a new contact (requires confirmation)", listOf(p("name"), p("phone_number")), risk = WRITE_CONFIRM),     ToolSpec(         "get_calendar_events",         "Get a list of calendar events. Each event's start and end times are epoch milliseconds.",     ),     ToolSpec(         "create_calendar_event",-        "Create a new calendar event. Start and end times must be epoch milliseconds.",+        "Create a new calendar event (requires confirmation). Start and end times must be epoch milliseconds.",         listOf(             p("title"),             p("start", NUMBER, "start time as epoch milliseconds"),             p("end", NUMBER, "end time as epoch milliseconds"),             p("location", required = false),-        ),+        ), risk = WRITE_CONFIRM,     ),     ToolSpec("get_family_locations", "Get a list of family members and their current locations"),     ToolSpec(         "create_location_share_link",-        "Create a temporary FindFamily link that shares the user's live location.",+        "Create a temporary FindFamily link that shares the user's live location (requires confirmation).",         listOf(             p("name", description = "name or label for who the link is for"),             p("duration_millis", NUMBER, "how long the link stays active, in milliseconds"),-        ),+        ), risk = WRITE_CONFIRM,     ),     ToolSpec("search_music", "Search for music (songs, albums, artists, or playlists)", listOf(p("query"))),     ToolSpec(         "play_music",-        "Play music given its id and type (song, album, artist, or playlist)",-        listOf(p("id", NUMBER), p("type")),+        "Play music given its id and type (song, album, artist, or playlist) (requires confirmation)",+        listOf(p("id", NUMBER), p("type")), risk = WRITE_CONFIRM,     ),     ToolSpec("search_emails", "Search emails by keyword", listOf(p("query"))),     ToolSpec("get_recent_emails", "Get recent emails from the inbox"),@@ -82,20 +83,20 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(     ToolSpec("make_phone_call", "Make a phone call", listOf(p("recipient"))),     ToolSpec(         "set_alarm",-        "Set an alarm in the Clock app at a specific hour and minute (24-hour time).",+        "Set an alarm in the Clock app at a specific hour and minute (24-hour time) (requires confirmation).",         listOf(             p("hour", NUMBER, "hour in 24-hour format, 0-23"),             p("minute", NUMBER, "minute, 0-59"),             p("label", description = "optional label for the alarm", required = false),-        ),+        ), risk = WRITE_CONFIRM,     ),     ToolSpec(         "set_timer",-        "Start a countdown timer in the Clock app for a number of seconds.",+        "Start a countdown timer in the Clock app for a number of seconds (requires confirmation).",         listOf(             p("seconds", NUMBER, "timer length in seconds"),             p("label", description = "optional label for the timer", required = false),-        ),+        ), risk = WRITE_CONFIRM,     ),     ToolSpec(         "set_conversation_title",@@ -113,6 +114,6 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(         listOf(p("location", description = "city or place name")),     ),     ToolSpec("get_memories", "Get a list of all memories"),-    ToolSpec("remove_memory", "Remove a memory by its id", listOf(p("id", NUMBER))),+    ToolSpec("remove_memory", "Remove a memory by its id (requires confirmation)", listOf(p("id", NUMBER)), risk = WRITE_CONFIRM),     ToolSpec("add_to_memory", "Add a new memory to the list of memories", listOf(p("content"))), )
openassistant/src/main/java/com/vayunmathur/openassistant/domain/PendingToolCalls.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/PendingToolCalls.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/PendingToolCalls.ktnew file mode 100644index 0000000000..ed93506427--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/PendingToolCalls.kt@@ -0,0 +1,65 @@+package com.vayunmathur.openassistant.domain++/** A write tool call awaiting host confirmation. Args stay raw, as parsed. */+data class PendingToolCall(+    val id: String,+    val name: String,+    val args: Map<String, String>,+    val summary: String,+    val createdAtMillis: Long,+    val expiresAtMillis: Long = createdAtMillis + TTL_MILLIS,+    val consumed: Boolean = false,+) {+    fun isExpired(nowMillis: Long): Boolean = nowMillis >= expiresAtMillis++    companion object {+        const val TTL_MILLIS: Long = 10 * 60_000L+    }+}++/** Human summary shown on the host confirmation card. */+fun pendingToolSummary(name: String, args: Map<String, String>): String =+    if (args.isEmpty()) {+        name+    } else {+        name + ": " + args.entries.joinToString(", ") { (k, v) -> "$k=${v.take(120)}" }+    }++/** PII-redacted args summary for audit records: lengths only, never raw bodies. */+fun redactedArgsSummary(args: Map<String, String>): String =+    if (args.isEmpty()) {+        "(no args)"+    } else {+        args.entries.joinToString(", ") { (k, v) -> "$k(len=${v.length})" }+    }++/** Storage for pending calls; pure logic so the gate is unit-testable. */+interface PendingToolCallStore {+    fun put(pending: PendingToolCall)+    fun get(id: String): PendingToolCall?+    fun remove(id: String)+    /** Marks consumed exactly once; false when unknown or already consumed. */+    fun markConsumed(id: String): Boolean+}++/** In-memory [PendingToolCallStore]. */+class InMemoryPendingToolCallStore : PendingToolCallStore {+    private val map = HashMap<String, PendingToolCall>()++    @Synchronized override fun put(pending: PendingToolCall) {+        map[pending.id] = pending+    }++    @Synchronized override fun get(id: String): PendingToolCall? = map[id]++    @Synchronized override fun remove(id: String) {+        map.remove(id)+    }++    @Synchronized override fun markConsumed(id: String): Boolean {+        val pending = map[id] ?: return false+        if (pending.consumed) return false+        map[id] = pending.copy(consumed = true)+        return true+    }+}
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 1e0b00c7e0..e8ac98c730 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt@@ -17,11 +17,15 @@ data class ToolParamSpec(     val required: Boolean = true, ) +/** Risk classification for a tool; host metadata, not model supplied. */+enum class ToolRisk { READ, WRITE_CONFIRM, HANDOFF_PREP }+ /** Immutable value describing tool spec. */ data class ToolSpec(     val name: String,     val description: String,     val params: List<ToolParamSpec> = emptyList(),+    val risk: ToolRisk = ToolRisk.READ, )  /** Coerced arguments: strings stay strings, numbers are Doubles as LiteRT passed them. */
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 7bb3580f09..40b32c7c39 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt@@ -16,6 +16,12 @@ sealed interface ToolLoopOutcome {     data class Halted(override val text: String) : ToolLoopOutcome     /** Immutable value describing failed; carries text. */     data class Failed(override val text: String) : ToolLoopOutcome+    /** A WRITE_CONFIRM call is pending host confirmation; it was not executed. */+    data class PendingConfirmation(+        override val text: String,+        val callName: String,+        val pendingId: String,+    ) : ToolLoopOutcome }  const val MAX_TOOL_ROUNDS = 6@@ -33,6 +39,7 @@ suspend fun runToolLoop(     executeTool: suspend (ParsedToolCall) -> String,     renderToolResponse: (name: String, value: String) -> String,     maxRounds: Int = MAX_TOOL_ROUNDS,+    pendingFor: (ParsedToolCall) -> PendingToolCall? = { null },     onVisible: (String) -> Boolean, ): ToolLoopOutcome {     var continuation = ""@@ -51,6 +58,11 @@ suspend fun runToolLoop(         if (halted) return ToolLoopOutcome.Halted(visible)         if (!hasCompleteToolCall(reply) || round == maxRounds - 1) break         val call = parseCall(reply)+        if (call != null) {+            pendingFor(call)?.let { pending ->+                return ToolLoopOutcome.PendingConfirmation(visible, call.name, pending.id)+            }+        }         val (name, result) = if (call == null) {             toolCallNameGuess(reply) to "Error: malformed tool call; use name{arg:value}"         } else {
openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.ktindex fb7019e560..3ecf70e799 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiController.kt@@ -32,6 +32,9 @@ import kotlinx.coroutines.launch class A2uiController(     context: Context,     scope: CoroutineScope,+    private val onHostAction: (+        (conversationId: Long, eventName: String, context: Map<String, Any?>) -> Boolean+    )? = null,     private val onAction: (conversationId: Long, text: String) -> Unit, ) {     private val appContext = context.applicationContext@@ -52,8 +55,9 @@ class A2uiController(         scope.launch {             processor.outboundEvents.collect { event ->                 when (event) {-                    is A2uiClientEventMessage -> conversationOf[event.surfaceId]?.let {-                        onAction(it, actionTurnText(event.type, event.context))+                    is A2uiClientEventMessage -> conversationOf[event.surfaceId]?.let { convId ->+                        val handled = onHostAction?.invoke(convId, event.type, event.context) ?: false+                        if (!handled) onAction(convId, actionTurnText(event.type, event.context))                     }                     is A2uiClientErrorMessage ->                         Log.status(TAG, "${event.code} on ${event.surfaceId}: ${event.message}")
openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.ktnew file mode 100644index 0000000000..42ba5472eb--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt@@ -0,0 +1,76 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.openassistant.domain.PendingToolCall+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonArray+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put++/** Host-generated A2UI cards. The model never authors these. */+object A2uiTemplates {++    /** Confirmation card for a pending WRITE_CONFIRM tool call. */+    fun confirmCard(pending: PendingToolCall): String {+        val components = buildJsonArray {+            add(obj("id" to s("root"), "component" to s("Card"), "child" to s("col")))+            add(+                obj(+                    "id" to s("col"), "component" to s("Column"),+                    "children" to JsonArray(listOf(s("title"), s("summary"), s("actions"))),+                ),+            )+            add(+                obj(+                    "id" to s("title"), "component" to s("Text"),+                    "text" to s("Confirm ${pending.name}"), "variant" to s("title"),+                ),+            )+            add(+                obj(+                    "id" to s("summary"), "component" to s("Text"),+                    "text" to s(pending.summary), "variant" to s("body"),+                ),+            )+            add(+                obj(+                    "id" to s("actions"), "component" to s("Row"),+                    "children" to JsonArray(listOf(s("btnCancel"), s("btnConfirm"))),+                ),+            )+            add(button("btnCancel", "Cancel", "cancel.tool", pending.id, primary = false))+            add(button("btnConfirm", "Confirm", "confirm.tool", pending.id, primary = true))+        }+        val data = buildJsonObject {+            put("id", pending.id)+            put("tool", pending.name)+            put("summary", pending.summary)+        }+        return JsonObject(mapOf("components" to components, "data" to data)).toString()+    }++    private fun button(+        id: String,+        label: String,+        event: String,+        pendingId: String,+        primary: Boolean,+    ): JsonObject = obj(+        "id" to s(id), "component" to s("Button"), "label" to s(label),+        "primary" to JsonPrimitive(primary),+        "action" to buildJsonObject {+            put(+                "event",+                buildJsonObject {+                    put("name", event)+                    put("context", buildJsonObject { put("id", pendingId) })+                },+            )+        },+    )++    private fun s(value: String) = JsonPrimitive(value)+    private fun obj(vararg pairs: Pair<String, kotlinx.serialization.json.JsonElement>) =+        JsonObject(mapOf(*pairs))+}
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.ktindex 0f4eb12173..9d7c692145 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -13,14 +13,20 @@ import com.vayunmathur.library.intents.todo.InsertTodoData import com.vayunmathur.library.ml.Gemma4Handle import com.vayunmathur.openassistant.data.MemoryDao import com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS+import com.vayunmathur.openassistant.domain.InMemoryPendingToolCallStore import com.vayunmathur.openassistant.domain.ParsedToolCall+import com.vayunmathur.openassistant.domain.PendingToolCall+import com.vayunmathur.openassistant.domain.PendingToolCallStore import com.vayunmathur.openassistant.domain.ToolArgs import com.vayunmathur.openassistant.domain.ToolArgsResult+import com.vayunmathur.openassistant.domain.ToolRisk import com.vayunmathur.openassistant.domain.ToolSpec import com.vayunmathur.openassistant.domain.coerceToolArgs+import com.vayunmathur.openassistant.domain.pendingToolSummary import com.vayunmathur.openassistant.util.AssistantDeviceTools import com.vayunmathur.openassistant.util.AssistantToolIntents import kotlinx.coroutines.CancellationException+import java.util.UUID  fun ToolSpec.toDeclaration(): Gemma4Handle.ToolDeclaration = Gemma4Handle.ToolDeclaration(     name = name,@@ -31,7 +37,13 @@ fun ToolSpec.toDeclaration(): Gemma4Handle.ToolDeclaration = Gemma4Handle.ToolDe )  /** The assistant's tools: [ASSISTANT_TOOL_SPECS] bound to the intent and device back ends. */-class AssistantTools(context: Context, private val memoryDao: MemoryDao?) {+class AssistantTools(+    context: Context,+    private val memoryDao: MemoryDao?,+    private val pendingStore: PendingToolCallStore = InMemoryPendingToolCallStore(),+    private val nowMillis: () -> Long = { System.currentTimeMillis() },+    private val idGenerator: () -> String = { UUID.randomUUID().toString() },+) {     private val intents = AssistantToolIntents(context)     private val device = AssistantDeviceTools(context)     private val specs = ASSISTANT_TOOL_SPECS.associateBy { it.name }@@ -134,18 +146,70 @@ class AssistantTools(context: Context, private val memoryDao: MemoryDao?) {         check(handlers.keys == specs.keys) { "tool handlers and specs disagree" }     } +    fun specFor(name: String): ToolSpec? = specs[name]++    /** Creates a pending call for a WRITE_CONFIRM tool, or null if not gated/invalid. */+    fun createPending(call: ParsedToolCall): PendingToolCall? {+        val spec = specs[call.name] ?: return null+        if (spec.risk != ToolRisk.WRITE_CONFIRM) return null+        if (coerceToolArgs(spec, call.arguments) is ToolArgsResult.Invalid) return null+        val now = nowMillis()+        val pending = PendingToolCall(+            id = idGenerator(),+            name = call.name,+            args = call.arguments,+            summary = pendingToolSummary(call.name, call.arguments),+            createdAtMillis = now,+        )+        pendingStore.put(pending)+        return pending+    }++    fun pendingById(id: String): PendingToolCall? = pendingStore.get(id)++    fun restorePending(pending: PendingToolCall) = pendingStore.put(pending)++    fun removePending(id: String) = pendingStore.remove(id)+     /** Runs [call]. Never throws: unknown tools and bad arguments come back as an error string. */     fun invoke(call: ParsedToolCall): String {         val spec = specs[call.name] ?: return "Error: unknown tool '${call.name}'"         return when (val coerced = coerceToolArgs(spec, call.arguments)) {             is ToolArgsResult.Invalid -> coerced.message-            is ToolArgsResult.Ok -> try {-                handlers.getValue(spec.name)(coerced.args)-            } catch (e: CancellationException) {-                throw e-            } catch (expected: Exception) {-                "Error: ${expected.message}"+            is ToolArgsResult.Ok -> {+                if (spec.risk == ToolRisk.WRITE_CONFIRM) {+                    return "Error: confirmation required for ${spec.name}"+                }+                execute(spec.name, coerced.args)             }         }     }++    /**+     * Executes a pending call exactly once. Unknown, expired or consumed ids+     * return an error and never execute the handler.+     */+    fun invokeConfirmed(pendingId: String): String {+        val pending = pendingStore.get(pendingId)+            ?: return "Error: pending tool call not found"+        if (pending.consumed) return "Error: pending tool call already consumed"+        if (pending.isExpired(nowMillis())) return "Error: pending tool call expired"+        val spec = specs[pending.name] ?: return "Error: unknown tool '${pending.name}'"+        val coerced = when (val result = coerceToolArgs(spec, pending.args)) {+            is ToolArgsResult.Invalid -> return result.message+            is ToolArgsResult.Ok -> result.args+        }+        if (!pendingStore.markConsumed(pendingId)) {+            return "Error: pending tool call already consumed"+        }+        return execute(spec.name, coerced)+    }++    private fun execute(name: String, args: ToolArgs): String = try {+        handlers.getValue(name)(args)+    } catch (e: CancellationException) {+        throw e+    } catch (expected: Exception) {+        "Error: ${expected.message}"+    } }
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 5147907829..40fb9cb73e 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -44,6 +44,8 @@ data class ChatRequest( sealed interface ChatResult {     /** Immutable value describing reply; carries text, halted. */     data class Reply(val text: String, val halted: Boolean) : ChatResult+    /** A WRITE_CONFIRM call awaits host confirmation; nothing was executed. */+    data class Pending(val pendingId: String, val summary: String, val text: String = "") : ChatResult     /** Singleton holding too long state and operations. */     data object TooLong : ChatResult     /** Singleton holding unavailable state and operations. */@@ -175,12 +177,18 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable {                     }                 },                 renderToolResponse = Gemma4Handle::renderToolResponse,+                pendingFor = { call -> tools.createPending(call) },                 onVisible = onText,             )             when (outcome) {                 is ToolLoopOutcome.Finished -> ChatResult.Reply(outcome.text, halted = false)                 is ToolLoopOutcome.Halted -> ChatResult.Reply(outcome.text, halted = true)                 is ToolLoopOutcome.Failed -> ChatResult.Unavailable+                is ToolLoopOutcome.PendingConfirmation -> ChatResult.Pending(+                    pendingId = outcome.pendingId,+                    summary = tools.pendingById(outcome.pendingId)?.summary ?: outcome.callName,+                    text = outcome.text,+                )             }         } 
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 357648ee06..be8c35352b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -90,11 +90,43 @@ class AssistantViewModel(         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())      /** Renders the A2UI surfaces on assistant messages; their events come back as user turns. */-    val a2ui = A2uiController(application, viewModelScope) { conversationId, text ->+    val a2ui = A2uiController(+        application,+        viewModelScope,+        onAction = { conversationId, text ->+            viewModelScope.launch {+                upsertMessage(Message(conversationId, text, "user"))+                requestInference(conversationId, text, emptyList(), null)+            }+        },+        onHostAction = { conversationId, eventName, context ->+            handleHostAction(conversationId, eventName, context)+        },+    )++    /**+     * Intercepts confirm/cancel host actions before they become model turns.+     * InferenceService detects the [HostConfirm]/[HostCancel] marker, executes+     * (or discards) the stored call exactly once, and then runs the model turn.+     */+    private fun handleHostAction(+        conversationId: Long,+        eventName: String,+        context: Map<String, Any?>,+    ): Boolean {+        val marker = when (eventName) {+            "confirm.tool" -> "HostConfirm"+            "cancel.tool" -> "HostCancel"+            else -> return false+        }+        val id = context["id"]?.toString().orEmpty()+        if (id.isBlank()) return false+        val text = "[$marker $id]"         viewModelScope.launch {             upsertMessage(Message(conversationId, text, "user"))             requestInference(conversationId, text, emptyList(), null)         }+        return true     }      init {
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 73ccf2745f..8a0a048318 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -42,9 +42,21 @@ import kotlinx.coroutines.withTimeout import java.io.File import java.util.concurrent.atomic.AtomicReference import kotlin.time.Clock+import com.vayunmathur.openassistant.data.AuditRecord+import com.vayunmathur.openassistant.data.AuditRecordDao import com.vayunmathur.openassistant.data.ConversationDao import com.vayunmathur.openassistant.data.MemoryDao import com.vayunmathur.openassistant.data.MessageDao+import com.vayunmathur.openassistant.data.PendingToolCallDao+import com.vayunmathur.openassistant.data.PendingToolCallEntity+import com.vayunmathur.openassistant.domain.PendingToolCall+import com.vayunmathur.openassistant.domain.redactedArgsSummary+import com.vayunmathur.openassistant.platform.A2uiTemplates+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive import com.vayunmathur.openassistant.data.Message as DbMessage import com.vayunmathur.openassistant.data.OpenAssistantRepository import com.vayunmathur.openassistant.R@@ -74,6 +86,9 @@ class InferenceService : Service() {         private const val INTENT_QUEUE_TTL_MILLIS = 45000L         private const val HISTORY_RECENCY_MILLIS = 1000L         private const val DB_WRITE_INTERVAL_MILLIS = 100L+        private const val AUDIT_OUTCOME_CHARS = 200+        private val HOST_CONFIRM = Regex("""\[HostConfirm ([^\]]+)]""")+        private val HOST_CANCEL = Regex("""\[HostCancel ([^\]]+)]""")          /** The system prompt used when the user has not set a custom one. */         val DEFAULT_SYSTEM_PROMPT = """@@ -125,6 +140,8 @@ class InferenceService : Service() {     internal var conversationDaoOverride: ConversationDao? = null     internal var messageDaoOverride: MessageDao? = null     internal var memoryDaoOverride: MemoryDao? = null+    internal var pendingDaoOverride: PendingToolCallDao? = null+    internal var auditDaoOverride: AuditRecordDao? = null     internal var nowMillis: () -> Long = { System.currentTimeMillis() }     private val tools by lazy { AssistantTools(applicationContext, memoryDao) } @@ -134,6 +151,10 @@ class InferenceService : Service() {      private val store: MessageStore get() = MessageStore(messageDao, conversationDao)     private val memoryDao get() = memoryDaoOverride ?: repository.memoryDaoRef+    private val pendingDao: PendingToolCallDao?+        get() = pendingDaoOverride ?: runCatching { repository.pendingToolCallDaoRef }.getOrNull()+    private val auditDao: AuditRecordDao?+        get() = auditDaoOverride ?: runCatching { repository.auditRecordDaoRef }.getOrNull()      override fun onBind(intent: Intent?): IBinder? = null @@ -431,6 +452,82 @@ class InferenceService : Service() {         return base + "\n\n" + AssistantCatalog.PROMPT_SECTION     } +    private fun PendingToolCallEntity.toDomain(): PendingToolCall = PendingToolCall(+        id = id,+        name = toolName,+        args = runCatching {+            Json.parseToJsonElement(argsJson).jsonObject+                .mapValues { it.value.jsonPrimitive.content }+        }.getOrDefault(emptyMap()),+        summary = summary,+        createdAtMillis = createdAt,+        expiresAtMillis = expiresAt,+        consumed = consumed,+    )++    private fun PendingToolCall.toEntity(conversationId: Long): PendingToolCallEntity =+        PendingToolCallEntity(+            id = id,+            conversationId = conversationId,+            toolName = name,+            argsJson = JsonObject(args.mapValues { JsonPrimitive(it.value) }).toString(),+            summary = summary,+            createdAt = createdAtMillis,+            expiresAt = expiresAtMillis,+            consumed = consumed,+        )++    private suspend fun loadPendingDomain(id: String): PendingToolCall? {+        tools.pendingById(id)?.let { return it }+        val entity = runCatching { pendingDao?.getById(id) }.getOrNull() ?: return null+        return entity.toDomain().also { tools.restorePending(it) }+    }++    private suspend fun persistPending(conversationId: Long, pending: PendingToolCall) {+        runCatching { pendingDao?.upsert(pending.toEntity(conversationId)) }+    }++    /** Returns the model-turn text for a host marker, or null when [userText] is not one. */+    private suspend fun handleHostMarker(conversationId: Long, userText: String): String? {+        val trimmed = userText.trim()+        val confirmId = HOST_CONFIRM.matchEntire(trimmed)?.groupValues?.get(1)+        val cancelId = HOST_CANCEL.matchEntire(trimmed)?.groupValues?.get(1)+        if (cancelId != null) {+            val pending = loadPendingDomain(cancelId)+            tools.removePending(cancelId)+            runCatching { pendingDao?.deleteById(cancelId) }+            return "[Cancelled \"${pending?.name ?: "tool"}\"]"+        }+        if (confirmId == null) return null+        val pending = loadPendingDomain(confirmId)+            ?: return "[Confirmed tool call could not be completed: Error: pending tool call not found]"+        val wasValid = !pending.consumed && !pending.isExpired(nowMillis())+        val result = tools.invokeConfirmed(confirmId)+        if (!wasValid) {+            return "[Confirmed \"${pending.name}\" could not be completed: $result]"+        }+        runCatching {+            auditDao?.upsert(+                AuditRecord(+                    toolName = pending.name,+                    argsSummary = redactedArgsSummary(pending.args),+                    outcome = result.take(AUDIT_OUTCOME_CHARS),+                    timestamp = nowMillis(),+                ),+            )+        }+        runCatching { pendingDao?.upsert(pending.copy(consumed = true).toEntity(conversationId)) }+        store.upsert(+            DbMessage(+                conversationId = conversationId,+                text = "Confirmed \"${pending.name}\": $result",+                role = "assistant",+                timestamp = Clock.System.now().toEpochMilliseconds(),+            ),+        )+        return "[Confirmed \"${pending.name}\": $result]"+    }+     // The chat call needs cleanup-and-rethrow on any engine failure, so the catch stays broad.     @Suppress("TooGenericExceptionCaught")     private suspend fun runInferenceLoop(@@ -440,10 +537,11 @@ class InferenceService : Service() {         audioPath: String?,     ) {         val chat = engine ?: failEngine()+        val effectiveUserText = handleHostMarker(conversationId, userText) ?: userText         val request = ChatRequest(             system = systemPrompt(),             history = loadHistory(conversationId, userText),-            userText = userText,+            userText = effectiveUserText,             imagePaths = imagePaths.toList(),             audioPath = audioPath?.takeIf { File(it).exists() },         )@@ -485,6 +583,18 @@ class InferenceService : Service() {             } else if (result.text.isNotBlank()) {                 store.storeReply(aiMsgId, result.text)             }+            is ChatResult.Pending -> {+                val pending = tools.pendingById(result.pendingId) ?: PendingToolCall(+                    id = result.pendingId,+                    name = "tool",+                    args = emptyMap(),+                    summary = result.summary,+                    createdAtMillis = nowMillis(),+                )+                persistPending(conversationId, pending)+                val shown = result.text.ifBlank { "Please confirm to continue." }+                store.updateMessage(aiMsgId, shown, A2uiTemplates.confirmCard(pending))+            }             ChatResult.TooLong -> store.updateMessage(                 aiMsgId,                 getString(R.string.error_prefix, "the message is too long for the model's context"),
openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseMigrationTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseMigrationTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseMigrationTest.ktindex be8ecd5615..b6b728e9db 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseMigrationTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/data/AppDatabaseMigrationTest.kt@@ -18,7 +18,7 @@ import kotlin.test.assertTrue class AppDatabaseMigrationTest {     private val ctx: Context get() = ApplicationProvider.getApplicationContext() -    @Test fun migratesV1ToV4PreservingRows() = runTest {+    @Test fun migratesV1ToV5PreservingRows() = runTest {         val name = "migration-test.db"         ctx.deleteDatabase(name)         val path = ctx.getDatabasePath(name)@@ -40,17 +40,23 @@ class AppDatabaseMigrationTest {             val conv = db.conversationDao().getById(1L)             assertNotNull(conv); assertEquals("Old chat", conv.title)             val msg = db.messageDao().getByConversation(1L).single()-            assertEquals("old msg", msg.text); assertNull(msg.missingAppPackage); assertNull(msg.a2ui)-            // v2-v4 additions are writable after migration.-            db.messageDao().upsert(msg.copy(a2ui = "{}", missingAppPackage = "com.example"))+            assertEquals("old msg", msg.text); assertNull(msg.missingAppPackage); assertNull(msg.a2ui); assertNull(msg.a2uiData)+            // v2-v5 additions are writable after migration.+            db.messageDao().upsert(msg.copy(a2ui = "{}", a2uiData = "{\"x\":1}", missingAppPackage = "com.example"))             assertEquals("{}", db.messageDao().getById(msg.id)?.a2ui)+            assertEquals("{\"x\":1}", db.messageDao().getById(msg.id)?.a2uiData)+            db.pendingToolCallDao().upsert(+                PendingToolCallEntity("p1", 1L, "create_note", "{}", "create_note", 10L, 610_010L, false))+            assertEquals("create_note", db.pendingToolCallDao().getById("p1")?.toolName)+            db.auditRecordDao().upsert(AuditRecord("create_note", "content(len=3)", "ok", 11L))+            assertEquals("content(len=3)", db.auditRecordDao().getRecent().single().argsSummary)             val memId = db.memoryDao().upsert(Memory("remembered"))             assertTrue(memId > 0)             assertEquals(listOf("remembered"), db.memoryDao().getAllFlow().first().map { it.content })         } finally {             db.close()             val check = SQLiteDatabase.openDatabase(path.path, null, SQLiteDatabase.OPEN_READONLY)-            assertEquals(4, check.version)+            assertEquals(5, check.version)             check.close()             ctx.deleteDatabase(name)             File(path.path + "-wal").delete(); File(path.path + "-shm").delete()
openassistant/src/test/java/com/vayunmathur/openassistant/domain/PendingToolCallsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PendingToolCallsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PendingToolCallsTest.ktnew file mode 100644index 0000000000..4d8ce4d015--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PendingToolCallsTest.kt@@ -0,0 +1,29 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class PendingToolCallsTest {++    @Test fun expiryAndConsumeOnce() {+        val store = InMemoryPendingToolCallStore()+        val pending = PendingToolCall("p1", "create_note", mapOf("content" to "x"), "s", 1_000L)+        assertEquals(1_000L + PendingToolCall.TTL_MILLIS, pending.expiresAtMillis)+        assertFalse(pending.isExpired(1_000L))+        assertTrue(pending.isExpired(pending.expiresAtMillis))+        store.put(pending)+        assertEquals(pending, store.get("p1"))+        assertTrue(store.markConsumed("p1"))+        assertFalse(store.markConsumed("p1"))+        assertTrue(store.get("p1")!!.consumed)+        store.remove("p1")+        assertEquals(null, store.get("p1"))+    }++    @Test fun summaryHelpers() {+        assertEquals("create_note", pendingToolSummary("create_note", emptyMap()))+        assertTrue(pendingToolSummary("x", mapOf("a" to "b")).contains("a=b"))+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.ktindex 2c3bbe31c2..92a0185d75 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt@@ -89,4 +89,20 @@ class ToolLoopTest {         val outcome = runToolLoop(FakeGenerator(emptyList()), parse, { "x" }, render) { true }         assertIs<ToolLoopOutcome.Failed>(outcome)     }++    @Test+    fun pendingForShortCircuitsWithoutExecuting() = runBlocking<Unit> {+        val generator = FakeGenerator(listOf("<|tool_call>call:create_note{title:T,content:C}<tool_call|>"))+        var executed = 0+        val pending = PendingToolCall("p1", "create_note", mapOf("title" to "T"), "create_note: title=T", 0L)+        val outcome = runToolLoop(+            generator, parse, { executed++; "ok" }, render,+            pendingFor = { pending },+        ) { true }+        val pendingOutcome = assertIs<ToolLoopOutcome.PendingConfirmation>(outcome)+        assertEquals("create_note", pendingOutcome.callName)+        assertEquals("p1", pendingOutcome.pendingId)+        assertEquals(0, executed)+        assertEquals(1, generator.continuations.size)+    } }
openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.ktnew file mode 100644index 0000000000..4fa08ccf04--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/A2uiTemplatesTest.kt@@ -0,0 +1,38 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.openassistant.domain.PendingToolCall+import com.vayunmathur.openassistant.domain.buildA2uiEnvelope+import com.vayunmathur.openassistant.domain.redactedArgsSummary+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++class A2uiTemplatesTest {++    @Test fun confirmCardIsEnvelopeValid() {+        val pending = PendingToolCall(+            id = "p-123",+            name = "create_note",+            args = mapOf("title" to "T", "content" to "hello world!"),+            summary = "create_note: title=T, content=hello world!",+            createdAtMillis = 1_000L,+        )+        val json = A2uiTemplates.confirmCard(pending)+        assertTrue(json.contains("confirm.tool"), json)+        assertTrue(json.contains("cancel.tool"), json)+        assertTrue(json.contains("Confirm create_note"), json)+        assertTrue(json.contains("p-123"), json)+        val envelope = buildA2uiEnvelope("m1", AssistantCatalog.ID, json)+        assertNotNull(envelope)+        assertEquals(3, envelope.size)+    }++    @Test fun redactedSummaryShowsLengthsOnly() {+        assertEquals(+            "content(len=12), title(len=1)",+            redactedArgsSummary(linkedMapOf("content" to "hello world!", "title" to "T")),+        )+        assertEquals("(no args)", redactedArgsSummary(emptyMap()))+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex 9bbc16bad4..fbb6ae310f 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -49,26 +49,26 @@ class AssistantToolsInvokeTest {      @Test fun crossAppToolsReportMissingApps() {         assertTrue(call("get_notes").startsWith("The Notes app is required"))-        assertTrue(call("create_note", "title" to "T", "content" to "C").startsWith("The Notes app"))+        assertEquals("Error: confirmation required for create_note", call("create_note", "title" to "T", "content" to "C"))         assertTrue(call("get_todos").startsWith("The Todo app is required"))-        assertTrue(call("create_todo", "title" to "T").startsWith("The Todo app"))-        assertTrue(call("complete_todo", "id" to "1").startsWith("The Todo app"))+        assertEquals("Error: confirmation required for create_todo", call("create_todo", "title" to "T"))+        assertEquals("Error: confirmation required for complete_todo", call("complete_todo", "id" to "1"))         assertTrue(call("get_contacts").startsWith("The Contacts app is required"))-        assertTrue(call("create_contact", "name" to "A", "phone_number" to "1").startsWith("The Contacts app"))+        assertEquals("Error: confirmation required for create_contact", call("create_contact", "name" to "A", "phone_number" to "1"))         assertTrue(call("get_calendar_events").startsWith("The Calendar app is required"))-        assertTrue(-            call("create_calendar_event", "title" to "M", "start" to "1", "end" to "2")-                .startsWith("The Calendar app"))+        assertEquals(+            "Error: confirmation required for create_calendar_event",+            call("create_calendar_event", "title" to "M", "start" to "1", "end" to "2"))         assertTrue(call("get_family_locations").startsWith("The FindFamily app is required"))-        assertTrue(-            call("create_location_share_link", "name" to "A", "duration_millis" to "60000")-                .startsWith("The FindFamily app"))+        assertEquals(+            "Error: confirmation required for create_location_share_link",+            call("create_location_share_link", "name" to "A", "duration_millis" to "60000"))         assertTrue(call("search_music", "query" to "jazz").startsWith("The Music app is required"))-        assertTrue(call("play_music", "id" to "3", "type" to "song").startsWith("The Music app"))+        assertEquals("Error: confirmation required for play_music", call("play_music", "id" to "3", "type" to "song"))         assertTrue(call("search_emails", "query" to "hi").startsWith("The Email app is required"))         assertTrue(call("get_recent_emails").startsWith("The Email app"))-        assertTrue(call("set_alarm", "hour" to "7", "minute" to "30").startsWith("The Clock app is required"))-        assertTrue(call("set_timer", "seconds" to "60").startsWith("The Clock app"))+        assertEquals("Error: confirmation required for set_alarm", call("set_alarm", "hour" to "7", "minute" to "30"))+        assertEquals("Error: confirmation required for set_timer", call("set_timer", "seconds" to "60"))         assertTrue(             call("get_weather", "latitude" to "1.5", "longitude" to "2.5")                 .startsWith("The Weather app is required"))@@ -108,7 +108,54 @@ class AssistantToolsInvokeTest {             "Error: MemoryDao is null",             noDao.invoke(ParsedToolCall("add_to_memory", mapOf("content" to "x"))))         assertEquals(-            "Error: MemoryDao is null",+            "Error: confirmation required for remove_memory",             noDao.invoke(ParsedToolCall("remove_memory", mapOf("id" to "1"))))+        val pending = noDao.createPending(ParsedToolCall("remove_memory", mapOf("id" to "1")))!!+        assertEquals("Error: MemoryDao is null", noDao.invokeConfirmed(pending.id))+    }++    @Test fun writeConfirmGateNeverExecutesUnconfirmed() {+        // create_note would report the missing Notes app if it executed; the gate must win.+        assertEquals(+            "Error: confirmation required for create_note",+            call("create_note", "title" to "T", "content" to "secret-body"))+        // add_to_memory stays READ/ungated.+        assertEquals("Success: Added memory", call("add_to_memory", "content" to "likes tea"))+    }++    @Test fun invokeConfirmedIsIdempotentAndChecksExpiry() {+        val ctx2 = ApplicationProvider.getApplicationContext<android.content.Context>()+        var now = 1_000_000L+        var seq = 0+        val gated = AssistantTools(ctx2, db.memoryDao(),+            nowMillis = { now }, idGenerator = { "pending-${seq++}" })+        val pending = gated.createPending(+            ParsedToolCall("remove_memory", mapOf("id" to "999")))!!+        assertEquals("pending-0", pending.id)+        // First confirmed call executes (handler reports no such memory / dao result).+        val first = gated.invokeConfirmed(pending.id)+        assertTrue(first.contains("Removed") || first.startsWith("Success") || first.isNotBlank(), first)+        val second = gated.invokeConfirmed(pending.id)+        assertEquals("Error: pending tool call already consumed", second)+        assertEquals("Error: pending tool call not found", gated.invokeConfirmed("nope"))+        // Expired pending never executes.+        val expired = gated.createPending(+            ParsedToolCall("remove_memory", mapOf("id" to "999")))!!+        now += com.vayunmathur.openassistant.domain.PendingToolCall.TTL_MILLIS + 1+        assertEquals("Error: pending tool call expired", gated.invokeConfirmed(expired.id))+    }++    @Test fun riskClassificationMatchesDesign() {+        val gated = setOf("create_note", "create_todo", "complete_todo", "create_contact",+            "create_calendar_event", "create_location_share_link", "play_music",+            "set_alarm", "set_timer", "remove_memory")+        for (spec in com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS) {+            val expected = if (spec.name in gated) {+                com.vayunmathur.openassistant.domain.ToolRisk.WRITE_CONFIRM+            } else {+                com.vayunmathur.openassistant.domain.ToolRisk.READ+            }+            assertEquals(expected, spec.risk, spec.name)+        }     } }
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsSuccessTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsSuccessTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsSuccessTest.ktindex 1f693d864f..4db72a38df 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsSuccessTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsSuccessTest.kt@@ -60,8 +60,10 @@ class AssistantToolsSuccessTest {         val listed = tools.invoke(call("get_memories"))         assertTrue(listed.contains("likes tea"), listed)         val id = listed.substringAfter("[").substringBefore("]").toLong()-        assertEquals("Success: Removed memory with id $id",+        assertEquals("Error: confirmation required for remove_memory",             tools.invoke(call("remove_memory", "id" to id.toString())))+        val pending = tools.createPending(call("remove_memory", "id" to id.toString()))!!+        assertEquals("Success: Removed memory with id $id", tools.invokeConfirmed(pending.id))         assertTrue(!tools.invoke(call("get_memories")).contains("likes tea"))     } }