Show pushed approvals as in-place chat cards

Render a server-pushed chat_permission as an approval card in the
transcript instead of a transient bar above the composer, matching the
reference opencode/Jarvis chat: the requested action, its resources, the
amber RISK REVIEW panel, and once/always/reject actions wired to the
server's chat_reply.

- ChatFormat: a pure approvalCard()/ApprovalCard model and one
  ChatProtocol.replyRequest() builder shared by the card's actions and
  the repository, so the wire frame and the controls cannot drift.
- ChatStore/AppViewModel: answerPermission() settles the card in place
  optimistically and survives a chat switch; a failed reply reopens the
  same request rather than showing an unacknowledged decision.
- ChatPermissionFrame gains optional resolved/decision fields so a
  request the server reports as already settled shows its verdict with
  no stale actions; a new request replaces a settled card.
- Findability: a gold PanTool top-bar action and chat-chip marker jump
  to the pending card; the running indicator stands down while waiting.
- Tests: ChatApprovalTest covers pending/answered/resolved, the reply
  builder's once/reject decisions and the missing-summary fallback;
  ChatProtocolTest covers the server-resolution frame. README records
  the 265-test/assembleDebug evidence and the emulator-5556 captures,
  and .approval_check/chat_stub_approval.py is the test double used.

android/ only; no new dependency beyond material-icons-extended; no
Pipelines server, Go, installer or Docker file touched; no run started
from the app. The live brokered server is not verified (the resolved
frame fields are an additive contract it does not emit yet).
This commit is contained in:
2026-10-16 16:12:22 +01:00
parent 78d5bd38fc
commit 609721d53b
11 changed files with 849 additions and 59 deletions
@@ -10,7 +10,6 @@ import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPromptRequest
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatQuery
import net.awan.pipelines.data.protocol.ChatReplyRequest
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.PipelineDetail
@@ -182,17 +181,7 @@ class PipelinesRepository(
if (sessionId.isBlank() || requestId.isBlank()) {
throw ProtocolException("A pending permission request is required.")
}
client.call(
Message(
type = Protocol.CHAT_REPLY,
chatReply = ChatReplyRequest(
sessionId = sessionId,
requestId = requestId,
decision = decision,
message = message,
),
),
)
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message))
}
private fun requireConfigured() {
@@ -138,7 +138,15 @@ data class ChatUsage(
val cost: Double = 0.0,
)
/** One pending OpenCode approval request the phone answers with chat_reply. */
/**
* One pending OpenCode approval request the phone answers with chat_reply.
*
* [resolved] and [decision] carry the server's outcome when it reports a request
* that is no longer open (another client answered it, or it expired): the phone
* then shows the verdict instead of live controls. They are additive and
* optional, so an older peer simply never sets them and every request stays
* pending.
*/
@Serializable
data class ChatPermissionFrame(
@SerialName("session_id") val sessionId: String = "",
@@ -149,6 +157,8 @@ data class ChatPermissionFrame(
val metadata: JsonObject? = null,
val source: ChatPermissionSource? = null,
val message: String = "",
val resolved: Boolean = false,
val decision: String = "",
)
@Serializable
@@ -203,4 +213,21 @@ object ChatProtocol {
*/
fun interruptRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_reply` frame that answers one permission request: [decision] is
* one of [DECISION_ONCE]/[DECISION_ALWAYS]/[DECISION_REJECT]. Built here (not
* inline in the repository) so the approval card's actions and their unit
* test share the one wire shape.
*/
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = ""): Message =
Message(
type = Protocol.CHAT_REPLY,
chatReply = ChatReplyRequest(
sessionId = sessionId,
requestId = requestId,
decision = decision,
message = message,
),
)
}
@@ -128,7 +128,7 @@ class AppViewModel(
repository.events.collect { message ->
message.chatEvent?.let { chatStore.event(it) }
// Never silently drop an approval request: it is held per chat and
// answered with chat_reply from the conversation's approval bar.
// answered with chat_reply from the conversation's approval card.
message.chatPermission?.let { chatStore.permission(it) }
// An unsolicited server error has no request id to match, so it is
// the chat stream failing mid-turn: settle the running chat instead
@@ -422,15 +422,21 @@ class AppViewModel(
}
}
/** Answers a pending approval: optimistically clears it, then reports a failed reply. */
/**
* Answers a pending approval. The card settles in place optimistically so a
* laggy round-trip over a tunnel never shows the old buttons again; a failed
* reply reopens the same request and reports why, so the operator can retry
* instead of trusting a decision the server never received.
*/
fun replyChatPermission(sessionId: String, requestId: String, decision: String) {
if (sessionId.isBlank() || requestId.isBlank()) return
chatStore.answerPermission(sessionId, requestId, decision)
viewModelScope.launch {
try {
repository.chatReply(sessionId, requestId, decision)
chatStore.clearPermission(sessionId)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.permissionReplyFailed(sessionId, requestId)
chatStore.failed(sessionId, ErrorMessages.describe(t))
}
}
@@ -6,6 +6,7 @@ import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatToolState
@@ -201,3 +202,99 @@ private fun lineDiff(old: List<String>, new: List<String>): List<DiffLine> {
internal const val MAX_RENDERED_DIFF_LINES = 200
private const val MAX_DIFF_LINES = 400
/**
* How one permission request stands: still waiting for the operator, answered
* here (optimistically, while the reply is in flight), or already settled by the
* server (another client answered it, or it expired).
*/
enum class ApprovalState { PENDING, ANSWERED, RESOLVED }
/**
* What the conversation renders for one permission request. Derived purely from
* the server's [ChatPermissionFrame] plus the operator's local answer, so the
* approval card and its unit test share one model instead of each reading the
* frame. [actionable] is true only while nothing has settled the request, which
* is what keeps a resolved request from offering stale once/always/reject
* controls.
*/
data class ApprovalCard(
val requestId: String,
val action: String,
val resources: List<String>,
val risk: String,
val state: ApprovalState,
val decision: String = "",
val note: String = "",
) {
/** The once/always/reject controls are live only while the request is open. */
val actionable: Boolean get() = state == ApprovalState.PENDING
/**
* The amber risk box is shown while the request is open and after the
* operator denies it (jarvis shows it while "pending/denied"), but not for a
* request the server already settled, whose note carries the outcome.
*/
val showRisk: Boolean
get() = state == ApprovalState.PENDING ||
(state == ApprovalState.ANSWERED && decision == ChatProtocol.DECISION_REJECT)
/** The card headline: what is being requested, or the verdict once settled. */
val headline: String
get() = when (state) {
ApprovalState.PENDING -> "Approve " + action.ifBlank { "tool call" }
ApprovalState.ANSWERED -> decisionLabel(decision)
ApprovalState.RESOLVED -> if (decision.isBlank()) "Already resolved" else decisionLabel(decision)
}
/** The one-line explanation under the headline. */
val statusLine: String
get() = when (state) {
ApprovalState.PENDING -> "Waiting for your response"
ApprovalState.ANSWERED -> "Waiting for the agent to continue…"
ApprovalState.RESOLVED -> note.ifBlank { "Another client already answered this request." }
}
}
/**
* The approval card for [permission], or null when there is no request to show.
* A request the server reports as settled wins over any local answer, so a stale
* tap can never reopen controls for a request that is already done.
*/
internal fun approvalCard(permission: ChatPermissionFrame?, answer: String): ApprovalCard? {
if (permission == null || permission.requestId.isBlank()) return null
val resolvedByServer = permission.resolved || permission.decision.isNotBlank()
val state = when {
resolvedByServer -> ApprovalState.RESOLVED
answer.isNotBlank() -> ApprovalState.ANSWERED
else -> ApprovalState.PENDING
}
return ApprovalCard(
requestId = permission.requestId,
action = permission.action,
resources = permission.resources.filter { it.isNotBlank() },
risk = permissionRiskText(permission),
state = state,
decision = if (resolvedByServer) permission.decision else answer,
note = if (resolvedByServer) permission.message else "",
)
}
/**
* The text in the amber risk-review box: the server's own summary when it carries
* one (jarvis shows the model's risk summary), otherwise a neutral sentence
* naming the action so the box is never blank.
*/
internal fun permissionRiskText(permission: ChatPermissionFrame): String {
if (permission.message.isNotBlank()) return permission.message
val what = permission.action.ifBlank { "a tool call" }
return "The agent is asking to run $what; review the request before allowing."
}
/** A human label for a once/always/reject decision, blank-safe. */
internal fun decisionLabel(decision: String): String = when (decision) {
ChatProtocol.DECISION_ONCE -> "Allowed once"
ChatProtocol.DECISION_ALWAYS -> "Always allowed"
ChatProtocol.DECISION_REJECT -> "Rejected"
else -> "Resolved"
}
@@ -1,5 +1,6 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
@@ -37,9 +38,12 @@ import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.PanTool
import androidx.compose.material.icons.filled.Psychology
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.outlined.Shield
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
@@ -62,6 +66,7 @@ import androidx.compose.runtime.key
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -83,9 +88,9 @@ import androidx.activity.compose.PredictiveBackHandler
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.transport.ConnectionState
@@ -113,6 +118,13 @@ internal val CHAT_ITEM_GAP = 8.dp
private val CHAT_COMPOSER_GAP = 12.dp
private val CHAT_STATUS_DOT = 8.dp
/**
* The approval card's amber review panel and pending-card border strengths,
* echoing the reference app's 10%-alpha amber `RISK REVIEW` box.
*/
private const val RISK_REVIEW_ALPHA = 0.12f
private const val APPROVAL_PENDING_BORDER_ALPHA = 0.5f
/** The tool panel floats over the transcript; these bound its width and offsets. */
private val TOOL_PANEL_MAX_WIDTH = 420.dp
private val TOOL_PANEL_GAP = 4.dp
@@ -362,6 +374,16 @@ private fun OpenChatStrip(
.background(MaterialTheme.colorScheme.tertiary),
)
}
if (approvalCard(thread.permission, thread.permissionAnswer)?.actionable == true) {
// A request waiting on the operator is surfaced on the
// chat's own chip, so it is findable without opening it.
Icon(
Icons.Default.PanTool,
contentDescription = "Waiting for your approval",
tint = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.size(14.dp),
)
}
Text(
text = thread.title.ifBlank { thread.sessionId.take(12) },
style = MaterialTheme.typography.labelMedium,
@@ -403,6 +425,16 @@ private fun ChatConversationPane(
onDispose { vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) }
}
val approval = approvalCard(thread.permission, thread.permissionAnswer)
val awaiting = approval?.actionable == true
// A turn blocked on an approval is not generating, so the running indicator
// (and its ticking clock) stands down while the card is unanswered.
val showRunning = thread.running && !awaiting
// The card is the transcript's last item; the top bar's approval action jumps
// to it so a pending request is reachable without scrolling the whole chat.
val approvalIndex = thread.messages.size + if (showRunning) 1 else 0
val scope = rememberCoroutineScope()
Scaffold(
modifier = modifier,
topBar = {
@@ -420,6 +452,19 @@ private fun ChatConversationPane(
}
},
actions = {
if (awaiting) {
IconButton(
onClick = {
scope.launch { listState.animateScrollToItem(approvalIndex.coerceAtLeast(0)) }
},
) {
Icon(
Icons.Default.PanTool,
contentDescription = "Waiting for your approval",
tint = MaterialTheme.colorScheme.tertiary,
)
}
}
if (thread.running) {
IconButton(onClick = { vm.stopChat(thread.sessionId) }) {
Icon(Icons.Default.Stop, contentDescription = "Stop")
@@ -438,14 +483,22 @@ private fun ChatConversationPane(
message = thread.error,
onRetry = { vm.loadChatHistory(thread.sessionId) },
)
thread.messages.isEmpty() && !thread.running -> EmptyState(
thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState(
message = if (thread.readOnly) {
"This chat is read-only while another client holds the session."
} else {
"This chat has no messages yet. Ask something below."
},
)
else -> ChatTranscript(thread = thread, listState = listState)
else -> ChatTranscript(
thread = thread,
listState = listState,
approval = approval,
showRunning = showRunning,
onDecision = { decision ->
approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) }
},
)
}
}
if (thread.error != null && thread.loaded) {
@@ -456,14 +509,6 @@ private fun ChatConversationPane(
modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp),
)
}
thread.permission?.let { permission ->
PermissionBar(
permission = permission,
onDecision = { decision ->
vm.replyChatPermission(thread.sessionId, permission.requestId, decision)
},
)
}
ChatComposer(
thread = thread,
onDraft = { vm.updateChatDraft(thread.sessionId, it) },
@@ -485,7 +530,13 @@ private fun ChatConversationPane(
* resumes following.
*/
@Composable
private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.foundation.lazy.LazyListState) {
private fun ChatTranscript(
thread: ChatThread,
listState: androidx.compose.foundation.lazy.LazyListState,
approval: ApprovalCard?,
showRunning: Boolean,
onDecision: (String) -> Unit,
) {
var follow by remember(thread.sessionId) { mutableStateOf(true) }
// Only a *user* drag changes whether the transcript follows: programmatic
// jumps (below) never touch `interactionSource`, so they cannot un-stick the
@@ -501,9 +552,13 @@ private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.found
}
}
}
val itemCount = thread.messages.size + if (thread.running) 1 else 0
LaunchedEffect(thread.running, thread.messages, follow, itemCount) {
if (thread.running && follow && itemCount > 0) {
val awaiting = approval?.actionable == true
val itemCount = thread.messages.size + (if (showRunning) 1 else 0) + (if (approval != null) 1 else 0)
// Follow the newest content while a turn streams, and scroll a freshly
// arrived approval card into view the same way so a pending request is not
// left below the fold.
LaunchedEffect(thread.running, thread.messages, follow, itemCount, awaiting) {
if (follow && itemCount > 0 && (thread.running || awaiting)) {
listState.scrollToItem(itemCount - 1)
}
}
@@ -516,9 +571,14 @@ private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.found
items(thread.messages, key = { it.id }) { message ->
MessageItem(message)
}
if (thread.running) {
if (showRunning) {
item(key = "pending") { RunningIndicator(thread) }
}
if (approval != null) {
// Keyed by request id so switching between requests swaps the card
// instead of reusing the previous one's state.
item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) }
}
}
}
@@ -961,35 +1021,67 @@ private fun ChatComposer(
}
/**
* The approval bar for a pending tool-call permission: the request's action and
* resources, with Allow-once / Always / Deny. A decision is answered through
* `chat_reply`, so the server-held credentials and the tool never leave it.
* One approval request as a card in the conversation (research §1.3 `_CodeRun` /
* risk review): the action being requested, the affected resources, the amber
* `RISK REVIEW` panel repeating the server's risk summary, and once/always/reject
* actions answered with `chat_reply`, so the server-held credentials and the tool
* never leave it. A card that is already answered or resolved keeps its place but
* drops the actions and states the outcome, so it can never offer a stale choice.
*/
@Composable
private fun PermissionBar(permission: ChatPermissionFrame, onDecision: (String) -> Unit) {
Surface(color = MaterialTheme.colorScheme.tertiaryContainer, modifier = Modifier.fillMaxWidth()) {
private fun ApprovalCardItem(card: ApprovalCard, onDecision: (String) -> Unit) {
val amber = MaterialTheme.colorScheme.tertiary
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
border = if (card.actionable) BorderStroke(1.dp, amber.copy(alpha = APPROVAL_PENDING_BORDER_ALPHA)) else null,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
Text(
text = "Approve: ${permission.action.ifBlank { "tool call" }}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onTertiaryContainer,
)
if (permission.resources.isNotEmpty()) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(20.dp))
Column(Modifier.weight(1f)) {
Text(card.headline, style = pipelinesText().cardTitle)
Text(
text = card.statusLine,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (card.resources.isNotEmpty()) {
Text(
text = permission.resources.joinToString("\n"),
text = card.resources.joinToString("\n"),
style = pipelinesText().mono,
color = MaterialTheme.colorScheme.onTertiaryContainer,
maxLines = 3,
maxLines = 6,
overflow = TextOverflow.Ellipsis,
)
}
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
TextButton(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") }
TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always") }
TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Deny") }
if (card.showRisk && card.risk.isNotBlank()) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(CHAT_ITEM_GAP))
.background(amber.copy(alpha = RISK_REVIEW_ALPHA))
.padding(CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(14.dp))
Text("RISK REVIEW", style = MaterialTheme.typography.labelSmall, color = amber)
}
Text(card.risk, style = MaterialTheme.typography.bodySmall)
}
}
if (card.actionable) {
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Button(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") }
TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always allow") }
TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Reject") }
}
}
}
}
@@ -49,6 +49,12 @@ data class ChatThread(
val scroll: ChatScrollPosition = ChatScrollPosition(),
/** The server's pending approval for this session, answered with chat_reply. */
val permission: ChatPermissionFrame? = null,
/**
* The operator's local answer to [permission] (`once`/`always`/`reject`), or
* blank while it is still open. Held on the thread so the approval card can
* settle in place optimistically and survives a chat switch.
*/
val permissionAnswer: String = "",
) {
/**
* Read-only while another client holds the session: the composer must never
@@ -269,15 +275,38 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) {
update(target.sessionId) { setRunning(it.copy(error = message), false) }
}
/** The server pushed an approval request for this session; the composer answers it. */
/**
* The server pushed an approval request for this session, or reported one it
* has already settled. A frame for a *new* request replaces any leftover card
* from the previous one; a frame for the same request (for example a resolved
* re-push) keeps the local answer and applies the server's outcome.
*/
fun permission(frame: ChatPermissionFrame) {
if (frame.sessionId.isBlank()) return
ensureThread(frame.sessionId)
update(frame.sessionId) { it.copy(permission = frame) }
update(frame.sessionId) {
val sameRequest = it.permission?.requestId == frame.requestId && frame.requestId.isNotBlank()
it.copy(
permission = frame,
permissionAnswer = if (sameRequest) it.permissionAnswer else "",
)
}
}
/** Drops the pending approval once it has been answered or is no longer valid. */
fun clearPermission(sessionId: String) = update(sessionId) { it.copy(permission = null) }
/**
* The operator's decision on the pending request, recorded optimistically so
* the card settles in place before the round-trip: the buttons are never left
* offering a decision already made. A request that is no longer the one on
* screen is ignored.
*/
fun answerPermission(sessionId: String, requestId: String, decision: String) = update(sessionId) {
if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = decision)
}
/** The reply failed: reopen the same request so the operator can try again. */
fun permissionReplyFailed(sessionId: String, requestId: String) = update(sessionId) {
if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = "")
}
/**
* Appends the operator's just-sent prompt optimistically, so the bubble is
@@ -156,6 +156,22 @@ class ChatProtocolTest {
assertEquals("edit", permission.action)
assertEquals("src/a.kt", permission.resources.single())
assertEquals("c1", permission.source!!.id)
// An open request defaults to unresolved; nothing is invented.
assertTrue(!permission.resolved)
assertEquals("", permission.decision)
}
/** A request the server reports as already settled carries the outcome. */
@Test
fun chatPermissionFrameCarriesTheServerResolution() {
val json = """
{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9",
"action":"edit","resolved":true,"decision":"reject","message":"another client rejected it"}}
""".trimIndent()
val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!!
assertTrue(permission.resolved)
assertEquals(ChatProtocol.DECISION_REJECT, permission.decision)
assertEquals("another client rejected it", permission.message)
}
@Test
@@ -0,0 +1,154 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.PipelinesJson
import net.awan.pipelines.data.protocol.Protocol
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The approval card the conversation shows for a pushed permission request: the
* request appears as a card, answering it updates the card in place with the
* decision the reply frame carries, and a request the server reports as already
* resolved offers no stale actions. Driven through [ChatStore] and the pure
* [approvalCard] the composable renders, so no device, server or Compose runtime
* is needed.
*/
class ChatApprovalTest {
private fun frame(
requestId: String = "req_9",
action: String = "edit",
resources: List<String> = listOf("src/a.kt"),
message: String = "This edits a file in your workspace.",
resolved: Boolean = false,
decision: String = "",
) = ChatPermissionFrame(
sessionId = "ses_1",
requestId = requestId,
action = action,
resources = resources,
message = message,
resolved = resolved,
decision = decision,
)
private fun storeWithPermission(permission: ChatPermissionFrame): ChatStore {
val store = ChatStore()
store.open(ChatSession(id = "ses_1", title = "Chat"))
store.permission(permission)
return store
}
private fun card(store: ChatStore): ApprovalCard {
val thread = store.value.thread("ses_1")!!
return approvalCard(thread.permission, thread.permissionAnswer)!!
}
@Test
fun permissionFrameShowsAPendingApprovalCard() {
val card = card(storeWithPermission(frame()))
assertEquals(ApprovalState.PENDING, card.state)
assertTrue(card.actionable)
assertEquals("Approve edit", card.headline)
assertEquals("Waiting for your response", card.statusLine)
assertEquals(listOf("src/a.kt"), card.resources)
assertEquals("This edits a file in your workspace.", card.risk)
assertTrue(card.showRisk)
}
@Test
fun onceAndRejectSendTheRightDecision() {
// The same builder the repository sends, so the card's actions and this
// assertion cannot drift from the wire frame.
val once = ChatProtocol.replyRequest("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
assertEquals(Protocol.CHAT_REPLY, once.type)
assertEquals("ses_1", once.chatReply!!.sessionId)
assertEquals("req_9", once.chatReply!!.requestId)
assertEquals("once", once.chatReply!!.decision)
val decodedOnce = PipelinesJson.decodeFromString(
Message.serializer(),
PipelinesJson.encodeToString(Message.serializer(), once.copy(id = "android-1")),
)
assertEquals(ChatProtocol.DECISION_ONCE, decodedOnce.chatReply!!.decision)
val reject = ChatProtocol.replyRequest("ses_1", "req_9", ChatProtocol.DECISION_REJECT)
assertEquals("reject", reject.chatReply!!.decision)
assertEquals("req_9", reject.chatReply!!.requestId)
}
@Test
fun answeringOnceUpdatesTheCardInPlace() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
val settled = card(store)
assertEquals(ApprovalState.ANSWERED, settled.state)
assertFalse(settled.actionable)
assertEquals(ChatProtocol.DECISION_ONCE, settled.decision)
assertEquals("Allowed once", settled.headline)
// The request is still on screen, not removed: it just stopped asking.
assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId)
}
@Test
fun rejectingKeepsTheRiskReviewWhileItSettles() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_REJECT)
val settled = card(store)
assertEquals(ApprovalState.ANSWERED, settled.state)
assertEquals("Rejected", settled.headline)
assertTrue(settled.showRisk)
}
@Test
fun serverResolvedRequestOffersNoActions() {
val store = storeWithPermission(frame(resolved = true, message = "Another client already answered."))
val resolved = card(store)
assertEquals(ApprovalState.RESOLVED, resolved.state)
assertFalse(resolved.actionable)
assertEquals("Already resolved", resolved.headline)
assertEquals("Another client already answered.", resolved.statusLine)
}
@Test
fun serverResolvedDecisionIsNamed() {
val store = storeWithPermission(
frame(resolved = true, decision = ChatProtocol.DECISION_REJECT, message = ""),
)
assertEquals("Rejected", card(store).headline)
}
@Test
fun failedReplyReopensTheRequest() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
store.permissionReplyFailed("ses_1", "req_9")
assertTrue(card(store).actionable)
}
@Test
fun riskFallsBackToTheActionWhenTheServerSendsNoSummary() {
val store = storeWithPermission(frame(message = "", resources = emptyList()))
val card = card(store)
assertTrue(card.risk.contains("edit"))
assertEquals(emptyList<String>(), card.resources)
}
@Test
fun aRequestWithoutAnIdShowsNoCard() {
val store = storeWithPermission(frame(requestId = ""))
val thread = store.value.thread("ses_1")!!
assertNull(approvalCard(thread.permission, thread.permissionAnswer))
}
}
@@ -9,7 +9,6 @@ import net.awan.pipelines.data.protocol.ChatSession
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -196,13 +195,24 @@ class MultiChatStateTest {
}
@Test
fun permissionIsStoredUntilAnswered() {
fun permissionIsStoredAndAnsweredInPlace() {
val store = ChatStore()
store.open(session("a"))
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r1", action = "edit"))
assertEquals("r1", store.value.thread("a")!!.permission!!.requestId)
store.clearPermission("a")
assertNull(store.value.thread("a")!!.permission)
store.answerPermission("a", "r1", ChatProtocol.DECISION_ONCE)
assertEquals(ChatProtocol.DECISION_ONCE, store.value.thread("a")!!.permissionAnswer)
// A different request replaces the settled card and drops the old answer.
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r2", action = "bash"))
assertEquals("r2", store.value.thread("a")!!.permission!!.requestId)
assertEquals("", store.value.thread("a")!!.permissionAnswer)
// A failed reply reopens the request it answers.
store.answerPermission("a", "r2", ChatProtocol.DECISION_REJECT)
store.permissionReplyFailed("a", "r2")
assertEquals("", store.value.thread("a")!!.permissionAnswer)
}
@Test