Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: implement real-time sub-agent step tracking and UI reporting in ChatScreen

Rishabh Bajpaic7fc93fd3715
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 1562775..dc93097 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -57,7 +57,15 @@ data class UiMessage(
val id: Long,
val kind: MessageKind,
val text: String,
- val imageBase64: String? = null
+ val imageBase64: String? = null,
+ val subAgentSteps: List<String> = emptyList(),
+ val subAgentCollapsed: Boolean = true
+)
+
+data class SubAgentStepUi(
+ val action: String,
+ val status: String,
+ val detail: String = ""
)
/** A batch of tool calls waiting for the user's confirm/deny (Phase 7). */
@@ -76,15 +84,15 @@ data class PendingQuestion(
data class ChatUiState(
val messages: List<UiMessage> = emptyList(),
val isBusy: Boolean = false,
- val activity: String? = null, // e.g. "Running: set_brightness…"
- val subAgentRunning: String? = null, // description while sub-agent is active
+ val activity: String? = null,
+ val subAgentRunning: String? = null,
+ val subAgentCurrentAction: String? = null,
val pendingConfirmation: PendingConfirmation? = null,
val pendingQuestion: PendingQuestion? = null,
val isConfigured: Boolean = false,
val activeSessionId: String? = null,
val activeAgent: AgentMode = AgentMode.OPERATOR,
val contextUsagePercent: Float = 0f,
- // TTS / STT state
val isListening: Boolean = false,
val isRecording: Boolean = false,
val ttsModels: List<AudioModel> = emptyList(),
@@ -137,20 +145,35 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
init {
toolExecutor = ToolExecutor(application) { description, prompt ->
- _uiState.update { it.copy(subAgentRunning = description) }
+ _uiState.update { it.copy(subAgentRunning = description, subAgentCurrentAction = "starting…") }
+ val steps = mutableListOf<SubAgentStepUi>()
val subSession = SubAgentSession(
appContext = getApplication(),
toolExecutor = toolExecutor,
settings = settings,
description = description,
- prompt = prompt
+ prompt = prompt,
+ onStep = { action, status, detail ->
+ steps.add(SubAgentStepUi(action, status, detail))
+ _uiState.update {
+ it.copy(
+ subAgentCurrentAction = when (status) {
+ "running" -> "→ $action"
+ "completed" -> if (detail.isNotBlank()) "✓ $action → ${detail.take(60)}"
+ else "✓ $action"
+ else -> "$action: ${detail.take(60)}"
+ }
+ )
+ }
+ }
)
- val result = subSession.run()
- _uiState.update { it.copy(subAgentRunning = null) }
- if (result.startsWith("Task failed") || result.startsWith("Task exceeded")) {
- ToolResult.error(result)
+ val output = subSession.run()
+ val stepsEncoded = output.steps.joinToString("\n")
+ _uiState.update { it.copy(subAgentRunning = null, subAgentCurrentAction = null) }
+ if (output.finalAnswer.startsWith("Task failed") || output.finalAnswer.startsWith("Task exceeded")) {
+ ToolResult.error(output.finalAnswer)
} else {
- ToolResult.ok("TASK_RESULT:$description:$result")
+ ToolResult.ok("TASK_RESULT:$description:$stepsEncoded\n|||\n${output.finalAnswer}")
}
}
refreshSettings()
@@ -233,7 +256,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
} finally {
withContext(NonCancellable) {
saveCurrentSession()
- _uiState.update { it.copy(isBusy = false, activity = null, subAgentRunning = null) }
+ _uiState.update { it.copy(isBusy = false, activity = null, subAgentRunning = null, subAgentCurrentAction = null) }
agentJob = null
}
}
@@ -882,22 +905,40 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
/**
- * Handles a tool result prefixed with TASK_RESULT:description:result.
- * Shows the result as a SUBAGENT message bubble and stores a clean
- * tool result in the LLM history.
+ * Handles a tool result prefixed with TASK_RESULT:description:steps|||answer.
+ * Shows a collapsible SUBAGENT bubble with intermediate steps and renders
+ * the final answer with markdown.
*/
private fun handleTaskResult(call: ToolCall, result: ToolResult) {
val body = result.message.removePrefix("TASK_RESULT:")
val colon = body.indexOf(':')
if (colon < 0) return
val description = body.substring(0, colon)
- val answer = body.substring(colon + 1)
- // Show as a styled SUBAGENT bubble in the UI
- appendUi(MessageKind.SUBAGENT, "$description\n\n$answer")
- // Store clean text in LLM history
+ val payload = body.substring(colon + 1)
+ val marker = "\n|||\n"
+ val splitIdx = payload.indexOf(marker)
+ val steps: List<String>
+ val answer: String
+ if (splitIdx >= 0) {
+ steps = payload.substring(0, splitIdx).split("\n").filter { it.isNotBlank() }
+ answer = payload.substring(splitIdx + marker.length)
+ } else {
+ steps = emptyList()
+ answer = payload
+ }
+ // Show as a collapsible SUBAGENT bubble in the UI
+ appendUi(MessageKind.SUBAGENT, answer, subAgentSteps = steps)
+ // Store in LLM history with steps embedded for persistence
+ val stepsBlock = if (steps.isNotEmpty()) {
+ "\n── Steps ──\n" + steps.joinToString("\n") + "\n── Result ──\n"
+ } else ""
llmHistory += ChatMessage(
role = "tool",
- content = JsonPrimitive("Task \"$description\" completed. Result:\n$answer"),
+ content = JsonPrimitive(
+ "SUBAGENT_STEPS:$description" +
+ stepsBlock +
+ answer
+ ),
toolCallId = call.id
)
}
@@ -960,6 +1001,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
"to grant and ask again. After changing device state, confirm what was done. " +
"Use the sleep tool to pause and wait between operations (e.g. wait for " +
"a recording to finish before reading it). " +
+ "Use the task tool to delegate complex multi-step operations to the General " +
+ "sub-agent. Prefer delegation whenever a task involves many tool calls whose " +
+ "intermediate steps are not important — only the final result matters. " +
+ "For example: organizing files, gathering information from multiple sources, " +
+ "or performing a series of device checks. The sub-agent runs in the foreground; " +
+ "you will receive its complete report when done. " +
"Keep replies short and conversational. Be careful with destructive actions.\n" +
"If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
"When using uninstall_app: after calling it, the system will open a dialog. " +
@@ -1091,19 +1138,50 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
else -> "Something went wrong: ${e.message}"
}
- private fun appendUi(kind: MessageKind, text: String, imageBase64: String? = null) {
+ private fun appendUi(
+ kind: MessageKind,
+ text: String,
+ imageBase64: String? = null,
+ subAgentSteps: List<String> = emptyList()
+ ) {
_uiState.update {
- it.copy(messages = it.messages + UiMessage(nextId++, kind, text, imageBase64))
+ it.copy(messages = it.messages + UiMessage(
+ nextId++, kind, text, imageBase64, subAgentSteps, subAgentCollapsed = true
+ ))
}
}
private fun rebuildUiMessages() {
val rebuilt = llmHistory.mapNotNull { msg ->
+ val text = msg.textContent
when {
- msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" })
- msg.role == "assistant" && msg.hasText ->
- UiMessage(nextId++, MessageKind.ASSISTANT, msg.textContent)
- msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, msg.textContent.ifEmpty { "(no result)" })
+ msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, text.ifEmpty { "(image attached)" })
+ msg.role == "assistant" && text.isNotBlank() ->
+ UiMessage(nextId++, MessageKind.ASSISTANT, text)
+ msg.role == "tool" && text.startsWith("SUBAGENT_STEPS:") -> {
+ val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
+ val rest = if (descEnd > 0) text.substring(descEnd + 1) else text.substring("SUBAGENT_STEPS:".length)
+ val stepsMarker = "\n── Steps ──\n"
+ val resultMarker = "\n── Result ──\n"
+ val steps: List<String>
+ val answer: String
+ if (rest.startsWith(stepsMarker)) {
+ val afterSteps = rest.removePrefix(stepsMarker)
+ val resIdx = afterSteps.indexOf(resultMarker)
+ if (resIdx >= 0) {
+ steps = afterSteps.substring(0, resIdx).split("\n").filter { it.isNotBlank() }
+ answer = afterSteps.substring(resIdx + resultMarker.length)
+ } else {
+ steps = emptyList()
+ answer = afterSteps
+ }
+ } else {
+ steps = emptyList()
+ answer = rest
+ }
+ UiMessage(nextId++, MessageKind.SUBAGENT, answer, subAgentSteps = steps)
+ }
+ msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, text.ifEmpty { "(no result)" })
else -> null
}
}
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index 52493b1..b2764ad 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -11,25 +11,30 @@ import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonPrimitive
+data class SubAgentOutput(
+ val finalAnswer: String,
+ val steps: List<String>
+)
+
/**
* Runs an independent LLM tool loop for a delegated sub-agent task.
- * Intermediate tool calls and results stay internal — only the final
- * answer (from [ask_final_answer] or a text-only response) is returned.
+ * Intermediate tool calls and results are reported via [onStep] and
+ * returned as part of [SubAgentOutput] alongside the final answer.
*/
class SubAgentSession(
private val appContext: Context,
private val toolExecutor: ToolExecutor,
private val settings: Settings,
private val description: String,
- private val prompt: String
+ private val prompt: String,
+ private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> }
) {
private val TAG = "SubAgentSession"
private val json = Json { ignoreUnknownKeys = true }
-
- /** Sub-agent session token tracking for model-appropriate trim. */
private var activeTokenCount = 0
+ private val collectedSteps = mutableListOf<String>()
- suspend fun run(): String {
+ suspend fun run(): SubAgentOutput {
val model = settings.subAgentModel.ifBlank { settings.model }
Log.d(TAG, "Starting sub-agent with model=$model: $description")
@@ -50,8 +55,7 @@ class SubAgentSession(
"Use the available tools to perform the required steps. " +
"When you have fully completed the task and have the final answer, " +
"call the ask_final_answer tool with your complete result. " +
- "Do NOT call ask_final_answer until all work is actually done. " +
- "Keep intermediate tool calls focused; only the final answer will be delivered."
+ "Do NOT call ask_final_answer until all work is actually done."
)
)
@@ -75,50 +79,60 @@ class SubAgentSession(
throw e
} catch (e: Exception) {
Log.e(TAG, "Sub-agent LLM call failed: ${e.message}")
- return "Task failed: ${e.message}"
+ onStep("error", "completed", e.message ?: "LLM call failed")
+ return SubAgentOutput("Task failed: ${e.message}", collectedSteps.toList())
}
response.usage?.totalTokens?.let { activeTokenCount = it }
val message = response.choices.firstOrNull()?.message
if (message == null) {
- return "Task failed: empty response from model"
+ return SubAgentOutput("Task failed: empty response from model", collectedSteps.toList())
}
val toolCalls = message.toolCalls.orEmpty()
+ // Capture any reasoning / text before tool calls
+ if (message.hasText && round == 0) {
+ val thought = message.textContent.take(120)
+ collectedSteps.add("reasoning: $thought")
+ onStep("reasoning", "completed", thought)
+ }
+
if (toolCalls.isEmpty()) {
history.add(message)
val text = message.textContent.ifEmpty { "(no output)" }
Log.d(TAG, "Sub-agent finished (text response): ${text.take(100)}")
- return text
+ return SubAgentOutput(text, collectedSteps.toList())
}
history.add(message)
+ // Check for ask_final_answer
val finalCall = toolCalls.firstOrNull { it.function.name == "ask_final_answer" }
if (finalCall != null) {
val answer = try {
val args = json.decodeFromString<JsonObject>(finalCall.function.arguments)
args["answer"]?.jsonPrimitive?.content ?: "(no answer provided)"
} catch (e: Exception) {
- "(failed to parse ask_final_answer arguments: ${e.message})"
+ "(failed to parse ask_final_answer: ${e.message})"
}
- Log.d(TAG, "Sub-agent finished (ask_final_answer): ${answer.take(100)}")
- return answer
+ Log.d(TAG, "Sub-agent finished (ask_final_answer)")
+ return SubAgentOutput(answer, collectedSteps.toList())
}
for (call in toolCalls) {
+ val toolName = call.function.name
+ onStep(toolName, "running", "")
+ collectedSteps.add("$toolName → (running)")
+
val args = try {
json.decodeFromString<JsonObject>(call.function.arguments.ifBlank { "{}" })
} catch (e: Exception) {
- history.add(
- ChatMessage(
- role = "tool",
- content = JsonPrimitive("Malformed arguments: ${call.function.arguments.take(200)}"),
- toolCallId = call.id
- )
- )
+ val err = "Malformed args: ${call.function.arguments.take(100)}"
+ history.add(ChatMessage(role = "tool", content = JsonPrimitive(err), toolCallId = call.id))
+ collectedSteps[collectedSteps.lastIndex] = "$toolName → failed: bad arguments"
+ onStep(toolName, "completed", "failed: bad arguments")
continue
}
@@ -130,6 +144,10 @@ class SubAgentSession(
ToolResult.error("Tool '${call.function.name}' failed: ${e.message}")
}
+ val summary = result.message.take(80)
+ collectedSteps[collectedSteps.lastIndex] = "$toolName → ${if (result.success) "completed" else "failed"}: $summary"
+ onStep(toolName, "completed", summary)
+
history.add(
ChatMessage(
role = "tool",
@@ -137,19 +155,27 @@ class SubAgentSession(
toolCallId = call.id
)
)
+
+ // Report reasoning text that sometimes comes alongside tool calls
+ if (message.hasText && collectedSteps.none { it.startsWith("reasoning:") }) {
+ val thought = message.textContent.take(120)
+ if (thought.isNotBlank()) {
+ collectedSteps.add("reasoning: $thought")
+ onStep("reasoning", "completed", thought)
+ }
+ }
}
- // Compact history if it exceeds 80% of context limit
if (activeTokenCount > settings.maxContextTokens * 0.8) {
trimHistory(history)
}
}
- return "Task exceeded $maxRounds tool rounds without producing a final answer."
+ val msg = "Task exceeded $maxRounds tool rounds without producing a final answer."
+ return SubAgentOutput(msg, collectedSteps.toList())
}
private fun trimHistory(history: MutableList<ChatMessage>) {
- // Keep system prompt + last ~10 messages
val sysPrompt = history.firstOrNull { it.role == "system" }
history.clear()
if (sysPrompt != null) history.add(sysPrompt)
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index bb2a3d8..560840a 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -56,6 +56,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.gotcha.agent.ChatUiState
import com.gotcha.agent.PendingQuestion
@@ -145,23 +146,34 @@ fun ChatScreen(
}
if (state.subAgentRunning != null) {
- Row(
+ Column(
modifier = Modifier
.fillMaxWidth()
.background(Color(0xFF1A1A2E), RoundedCornerShape(8.dp))
- .padding(horizontal = 16.dp, vertical = 8.dp),
- verticalAlignment = Alignment.CenterVertically
+ .padding(horizontal = 16.dp, vertical = 8.dp)
) {
- CircularProgressIndicator(
- modifier = Modifier.width(16.dp),
- color = Color(0xFFE0D4FF)
- )
- Spacer(modifier = Modifier.width(8.dp))
- Text(
- "⚡ ${state.subAgentRunning}",
- style = MaterialTheme.typography.bodySmall,
- color = Color(0xFFE0D4FF)
- )
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(
+ modifier = Modifier.width(16.dp),
+ color = Color(0xFFE0D4FF)
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(
+ "⚡ ${state.subAgentRunning}",
+ style = MaterialTheme.typography.bodySmall,
+ color = Color(0xFFE0D4FF)
+ )
+ }
+ state.subAgentCurrentAction?.let { action ->
+ Spacer(modifier = Modifier.height(2.dp))
+ Text(
+ action,
+ style = MaterialTheme.typography.bodySmall,
+ color = Color(0xFFE0D4FF).copy(alpha = 0.7f),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
}
}
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
index 7399400..3a56ac2 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -6,6 +6,7 @@ import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
@@ -22,8 +23,11 @@ import com.halilibo.richtext.markdown.Markdown
import com.halilibo.richtext.ui.material3.Material3RichText
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
+import androidx.compose.material.icons.filled.ExpandLess
+import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -37,9 +41,12 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.gotcha.agent.MessageKind
@@ -55,6 +62,7 @@ fun MessageBubble(
val isUser = message.kind == MessageKind.USER
val isAssistant = message.kind == MessageKind.ASSISTANT
val isTool = message.kind == MessageKind.TOOL
+ val isSubAgent = message.kind == MessageKind.SUBAGENT
val colors = MaterialTheme.colorScheme
val (container, contentColor) = when (message.kind) {
MessageKind.USER -> colors.primaryContainer to colors.onPrimaryContainer
@@ -62,9 +70,8 @@ fun MessageBubble(
MessageKind.TOOL -> colors.secondaryContainer to colors.onSecondaryContainer
MessageKind.ERROR -> colors.errorContainer to colors.onErrorContainer
MessageKind.SUBAGENT -> {
- // Distinct indigo/purple palette for sub-agent messages
- val bg = androidx.compose.ui.graphics.Color(0xFF1A1A2E)
- val fg = androidx.compose.ui.graphics.Color(0xFFE0D4FF)
+ val bg = Color(0xFF1A1A2E)
+ val fg = Color(0xFFE0D4FF)
bg to fg
}
}
@@ -92,8 +99,8 @@ fun MessageBubble(
modifier = Modifier
.widthIn(max = 320.dp)
.then(
- if (isTool) Modifier.combinedClickable(
- onClick = { expanded.value = !expanded.value },
+ if (isTool || isSubAgent) Modifier.combinedClickable(
+ onClick = { if (isTool) expanded.value = !expanded.value },
onLongClick = { showMenu = true }
)
else Modifier.combinedClickable(
@@ -123,11 +130,6 @@ fun MessageBubble(
if (message.text.isNotEmpty()) {
val displayText = when (message.kind) {
MessageKind.TOOL -> "🔧 ${message.text}"
- MessageKind.SUBAGENT -> {
- val firstLine = message.text.substringBefore("\n")
- val rest = message.text.substringAfter("\n", "")
- "⚡ General Agent: $firstLine" + if (rest.isNotBlank()) "\n$rest" else ""
- }
else -> message.text
}
val firstLine = displayText.substringBefore("\n").trimEnd()
@@ -147,16 +149,20 @@ fun MessageBubble(
color = contentColor.copy(alpha = 0.6f)
)
}
+ } else if (isSubAgent) {
+ SubAgentContent(
+ message = message,
+ contentColor = contentColor,
+ expanded = expanded
+ )
+ } else if (isTool || isSubAgent) {
+ Text(
+ text = displayText,
+ style = MaterialTheme.typography.bodySmall
+ )
} else {
- if (message.kind == MessageKind.TOOL || message.kind == MessageKind.SUBAGENT) {
- Text(
- text = displayText,
- style = MaterialTheme.typography.bodySmall
- )
- } else {
- Material3RichText {
- Markdown(displayText)
- }
+ Material3RichText {
+ Markdown(displayText)
}
}
}
@@ -182,7 +188,6 @@ fun MessageBubble(
}
}
- // Context menu on long press
DropdownMenu(
expanded = showMenu,
onDismissRequest = { showMenu = false }
@@ -190,14 +195,14 @@ fun MessageBubble(
DropdownMenuItem(
text = { Text("Copy as text") },
onClick = {
- copyPlainText(context, message.text, isTool)
+ copyPlainText(context, message.text, isTool || isSubAgent)
showMenu = false
}
)
DropdownMenuItem(
text = { Text("Copy as markdown") },
onClick = {
- copyMarkdown(context, message.text, isTool)
+ copyMarkdown(context, message.text, isTool || isSubAgent)
showMenu = false
}
)
@@ -205,6 +210,98 @@ fun MessageBubble(
}
}
+@Composable
+private fun SubAgentContent(
+ message: UiMessage,
+ contentColor: Color,
+ expanded: androidx.compose.runtime.MutableState<Boolean>
+) {
+ val steps = message.subAgentSteps
+ val answer = message.text
+
+ // Header row — always visible, clickable to toggle
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { expanded.value = !expanded.value }
+ .padding(vertical = 2.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = "⚡ General Agent",
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = FontWeight.Bold,
+ color = contentColor
+ )
+ Spacer(modifier = Modifier.weight(1f))
+ if (steps.isNotEmpty()) {
+ Text(
+ text = "${steps.size} step${if (steps.size != 1) "s" else ""}",
+ style = MaterialTheme.typography.labelSmall,
+ color = contentColor.copy(alpha = 0.6f)
+ )
+ Spacer(modifier = Modifier.width(4.dp))
+ }
+ Icon(
+ imageVector = if (expanded.value) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
+ contentDescription = if (expanded.value) "Collapse" else "Expand",
+ modifier = Modifier.size(20.dp),
+ tint = contentColor.copy(alpha = 0.7f)
+ )
+ }
+
+ if (expanded.value) {
+ // Steps section
+ if (steps.isNotEmpty()) {
+ Spacer(modifier = Modifier.height(6.dp))
+ steps.forEach { step ->
+ val icon = when {
+ step.startsWith("reasoning:") -> "💭"
+ step.contains("→ (running)") -> "⋯"
+ step.contains("→ completed") || step.contains("→ completed:") -> "✓"
+ step.contains("→ failed") -> "✗"
+ else -> "·"
+ }
+ val display = step.removePrefix("reasoning:")
+ Row(modifier = Modifier.padding(vertical = 1.dp)) {
+ Text(
+ text = icon,
+ style = MaterialTheme.typography.bodySmall,
+ fontFamily = FontFamily.Monospace,
+ color = contentColor.copy(alpha = 0.7f)
+ )
+ Spacer(modifier = Modifier.width(6.dp))
+ Text(
+ text = display.trimStart(),
+ style = MaterialTheme.typography.bodySmall,
+ fontFamily = FontFamily.Monospace,
+ color = contentColor.copy(alpha = 0.7f),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+
+ // Divider
+ if (answer.isNotBlank()) {
+ Spacer(modifier = Modifier.height(6.dp))
+ HorizontalDivider(
+ color = contentColor.copy(alpha = 0.2f),
+ thickness = 1.dp
+ )
+ Spacer(modifier = Modifier.height(6.dp))
+ }
+
+ // Final answer with markdown rendering
+ if (answer.isNotBlank()) {
+ Material3RichText {
+ Markdown(answer)
+ }
+ }
+ }
+}
+
private fun copyPlainText(context: Context, text: String, isTool: Boolean) {
val source = if (isTool) text else text
val plain = stripMarkdown(source)