diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index 1df0166c..3c2f7bce 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -80,6 +80,34 @@ internal fun formatToolDuration(millis: Long): String = when { /** The chip label for a tool call: its name, or a placeholder when unnamed. */ internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" } +/** + * A turn's one summary chip: `N tools called`, and `1 tool called` for a single + * call — a count of one is never pluralised. The chip is the transcript's only + * tool-call surface, so this label stands in for every call of the turn. + */ +internal fun toolCallsLabel(count: Int): String = + if (count == 1) "1 tool called" else "$count tools called" + +/** + * What the summary chip announces to a screen reader, since the individual + * calls only exist inside the popup: the count, plus how to reach the detail. + * Singular and plural follow [toolCallsLabel] so the two never disagree. + */ +internal fun toolCallsAnnouncement(count: Int): String = + if (count == 1) "1 tool call, expand for details" else "$count tool calls, expand for details" + +/** + * How many tool calls [parts] holds. Counted by kind rather than by + * `parts.size`, so a turn that also carries text or reasoning never inflates + * the number the summary chip shows. + */ +internal fun toolCallCount(parts: List): Int = + parts.count { it.type == ChatProtocol.PART_TOOL } + +/** True while any tool call in [parts] is still in flight. */ +internal fun toolsRunning(parts: List): Boolean = + parts.any { it.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(it.state) } + /** * The in-flight tool calls across a conversation's [messages], in transcript * order, so the conversation's indicator and the session row read the same set @@ -131,6 +159,36 @@ internal fun toolDetail(part: ChatPart): String? { return null } +/** + * Everything one row of the tool panel shows for a single call, derived once so + * the row, the summary chip and their unit test agree: the call's real name (the + * name the earlier frames taught it, only falling back to `tool` when none was + * ever seen), its one-line detail, its duration, the pretty-printed INPUT, the + * OUTPUT, the ERROR text for a failed call and the synthesised edit diff. + * [error] is null for a call that did not fail, and [diff] is null for every + * non-edit call, so the row shows only the sections that have content. + */ +internal data class ToolCallRow( + val name: String, + val detail: String?, + val duration: String?, + val input: String, + val output: String, + val error: String?, + val diff: ToolDiff?, +) + +/** Builds the one row a turn's tool panel shows for [part]. */ +internal fun toolCallRow(part: ChatPart): ToolCallRow = ToolCallRow( + name = toolLabel(part), + detail = toolDetail(part), + duration = toolDurationMillis(part)?.let(::formatToolDuration), + input = prettyToolInput(part.state?.input), + output = toolOutputText(part.state), + error = if (toolFailed(part.state)) toolErrorText(part.state) else null, + diff = toolEditDiff(part.state?.input), +) + /** * How long a running [part] has been going at [nowMillis]. The protocol's own * timing wins whenever the part carries it (a running call from stored history diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt index ed9738cd..1e0708be 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt @@ -4,14 +4,15 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.Close @@ -25,6 +26,7 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -33,6 +35,9 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect @@ -48,6 +53,7 @@ import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP +import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_HEIGHT_DP import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP /** The tool panel floats over the transcript; these bound its width and offsets. */ @@ -57,109 +63,115 @@ private val TOOL_PANEL_MARGIN = 8.dp private val TOOL_PANEL_ELEVATION = 12.dp /** - * One turn's tool calls as a single group of compact chips, mirroring the - * reference transcript's `_ToolCalls`/`_ToolChip` (research §1.3): each call - * shows its name (or the edited file), its duration and a spinner while it runs, - * and the chips of the turn wrap together on as few lines as they fit instead of - * each taking a row. + * One turn's tool calls behind a single summary chip: `N tools called`, with the + * existing spinner while any call is still in flight and a `· long` mark while a + * running call has passed [TOOL_LONG_RUNNING_MILLIS]. A settled turn never shows + * either mark, so a finished turn cannot fake work it is not doing. * - * Tapping a chip opens its INPUT (pretty JSON) / OUTPUT (monospace) panel as an - * overlay anchored to that chip (research §1.3 `_buildPanel`), dismissed by its - * own X or by tapping outside. Because the panel is a popup and not part of the - * transcript layout, opening or closing it never re-flows the conversation nor - * moves its scroll position — the transcript stays exactly where the operator - * left it. + * The chip is the transcript's only tool-call surface: tapping it opens the tool + * panel as a popup listing every call of the turn in the order the agent made + * them, each row collapsing independently. Because the panel is a popup and not + * part of the transcript layout, opening or closing it never re-flows the + * conversation nor moves its scroll position. * - * An `edit`-family call expands to a diff card (research §1.3 `_CodeRun` / - * `_DiffView`): the `+N -M` stat on the chip and a green/red unified diff derived - * from the arguments, since the brokered protocol carries no diff field. An - * `error` call is visibly failed — an error-tinted chip and error icon — and its - * panel shows the error text. + * [elapsedMillis] is the live age of a call — the conversation supplies it from + * its own clock, so the `long` mark is derived from real elapsed time rather + * than guessed. [live] is whether the turn is still streaming: a stored call can + * carry a stale `running` status long after the turn ended, and a settled chip + * must not spin (or wear the `long` mark) on that. */ -@OptIn(ExperimentalLayoutApi::class) @Composable -internal fun ToolCalls(parts: List) { - // One id at a time: the reference shows a single panel, and a focusable popup - // dismisses the previous one on open. No key is needed: an id that is no - // longer among the calls simply matches nothing, so a streaming rebuild keeps - // the panel the operator just opened without allocating a key list per frame. - var openId by remember { mutableStateOf(null) } - FlowRow( - modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - ) { - parts.forEach { part -> - ToolChip( - part = part, - expanded = openId == part.id, - onToggle = { openId = if (openId == part.id) null else part.id }, - onDismiss = { openId = null }, - ) +internal fun ToolCalls(parts: List, live: Boolean, elapsedMillis: (ChatPart) -> Long = { 0L }) { + val calls = parts.filter { it.type == ChatProtocol.PART_TOOL } + if (calls.isEmpty()) return + // One panel at a time: the chip toggles it, and the panel's own X or a tap + // outside dismisses it. No key is needed: the calls belong to this turn. + var open by remember { mutableStateOf(false) } + val running = live && toolsRunning(calls) + val failed = calls.any { toolFailed(it.state) } + // The "long" mark is a running-call signal only: it is meaningful on the + // summary chip while a call is in flight, so a settled chip never wears it. + val long = running && calls.any { toolLongRunning(elapsedMillis(it)) } + Box(Modifier.fillMaxWidth().padding(vertical = CHAT_ITEM_GAP)) { + ToolCallsChip( + count = toolCallCount(calls), + running = running, + failed = failed, + long = long, + expanded = open, + onToggle = { open = !open }, + ) + if (open) { + Popup( + popupPositionProvider = rememberToolPanelPositionProvider(), + onDismissRequest = { open = false }, + properties = PopupProperties(focusable = true), + ) { + ToolPanel(calls = calls, onDismiss = { open = false }) + } } } } -/** A compact tool-call chip: kind icon, label, diff stat, duration and chevron. */ +/** + * The turn's one summary chip: the call count, the running spinner (or a state + * icon once settled), the optional `long` mark and a chevron naming the popup + * it opens. Its content description carries the count and how to reach the + * calls, so the summary is understandable without opening the panel. + */ @Composable -private fun ToolChip(part: ChatPart, expanded: Boolean, onToggle: () -> Unit, onDismiss: () -> Unit) { - val running = ChatProtocol.toolRunning(part.state) - val failed = toolFailed(part.state) - val diff = toolEditDiff(part.state?.input) - Box { - Surface( - shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp), - color = if (failed) { - MaterialTheme.colorScheme.errorContainer - } else { - MaterialTheme.colorScheme.surfaceContainerHigh - }, - modifier = Modifier.clickable(onClick = onToggle), +private fun ToolCallsChip( + count: Int, + running: Boolean, + failed: Boolean, + long: Boolean, + expanded: Boolean, + onToggle: () -> Unit, +) { + Surface( + shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp), + color = if (failed) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + modifier = Modifier + .semantics { contentDescription = toolCallsAnnouncement(count) } + .clickable(onClick = onToggle), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP), ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP), - ) { - if (running) { - CircularProgressIndicator(Modifier.size(ICON_STATUS_DP), strokeWidth = 2.dp) - } else { - Icon( - imageVector = when { - failed -> Icons.Default.ErrorOutline - diff != null -> Icons.Default.Edit - else -> Icons.Default.Build - }, - contentDescription = if (failed) "Failed tool call" else null, - modifier = Modifier.size(16.dp), - tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Text( - text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - diff?.let { DiffStat(it) } - toolDurationMillis(part)?.let { - Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - } + if (running) { + CircularProgressIndicator(Modifier.size(ICON_STATUS_DP), strokeWidth = 2.dp) + } else { Icon( - imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, - contentDescription = if (expanded) "Collapse tool call" else "Expand tool call", + imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build, + contentDescription = null, modifier = Modifier.size(ICON_INLINE_DP), + tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, ) } - } - if (expanded) { - Popup( - popupPositionProvider = rememberToolPanelPositionProvider(), - onDismissRequest = onDismiss, - properties = PopupProperties(focusable = true), - ) { - ToolPanel(part = part, onDismiss = onDismiss) + Text( + text = toolCallsLabel(count), + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (long) { + Text( + text = "· long", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.error, + ) } + Icon( + imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, + contentDescription = if (expanded) "Hide tool calls" else "Show tool calls", + modifier = Modifier.size(ICON_INLINE_DP), + ) } } } @@ -198,17 +210,15 @@ private fun rememberToolPanelPositionProvider(): PopupPositionProvider { } /** - * The expanded panel of one tool call, mirroring the reference panel - * (`_buildPanel`, research §1.3): a header naming the call and its duration with - * a close X, then the pretty-printed INPUT and the monospace OUTPUT (or the - * synthesised edit diff). Both content blocks carry the shared whole-block copy - * action from [CodeBlock]. A failed call always renders its error text in an - * ERROR block — even an edit-family call, whose diff is still shown alongside it. + * The turn's whole tool history as one panel, grown from the single-call panel: a + * header naming the count with a close X, then one collapsible row per call in + * the order the agent made them. The list is bounded ([TOOL_PANEL_MAX_HEIGHT_DP]) + * and scrolls inside the panel, so a turn with many calls neither grows the popup + * past the window nor moves the transcript behind it. */ @Composable -private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier = Modifier) { - val diff = toolEditDiff(part.state?.input) - val failed = toolFailed(part.state) +private fun ToolPanel(calls: List, onDismiss: () -> Unit, modifier: Modifier = Modifier) { + var expandedIds by remember { mutableStateOf>(emptySet()) } Surface( shape = RoundedCornerShape(CHAT_ITEM_GAP), color = MaterialTheme.colorScheme.surfaceContainer, @@ -221,35 +231,110 @@ private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { Icon( - imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build, + imageVector = Icons.Default.Build, contentDescription = null, - modifier = Modifier.size(16.dp), - tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + modifier = Modifier.size(ICON_INLINE_DP), + tint = MaterialTheme.colorScheme.primary, ) Text( - text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), + text = toolCallsLabel(calls.size), style = MaterialTheme.typography.labelLarge, - maxLines = 1, - overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) - diff?.let { DiffStat(it) } - toolDurationMillis(part)?.let { - Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - } IconButton(onClick = onDismiss, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { - Icon(Icons.Default.Close, contentDescription = "Close tool call", modifier = Modifier.size(16.dp)) + Icon(Icons.Default.Close, contentDescription = "Close tool calls", modifier = Modifier.size(ICON_INLINE_DP)) } } - if (diff != null) { - DiffView(diff) - } else { - CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input)) - } - if (failed) { - CodeBlock(label = "ERROR", text = toolErrorText(part.state)) - } else if (diff == null) { - CodeBlock(label = "OUTPUT", text = toolOutputText(part.state)) + Column( + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier + .fillMaxWidth() + .heightIn(max = TOOL_PANEL_MAX_HEIGHT_DP) + .verticalScroll(rememberScrollState()), + ) { + calls.forEach { part -> + val row = toolCallRow(part) + ToolCallRowItem( + row = row, + expanded = part.id in expandedIds, + onToggle = { + expandedIds = if (part.id in expandedIds) expandedIds - part.id else expandedIds + part.id + }, + ) + } + } + } + } +} + +/** + * One call inside the panel: a header naming the call, its `+N -M` stat for an + * edit and its duration, and — expanded in place — the pretty-printed INPUT, the + * synthesised diff for an edit-family call, then the ERROR block for a failed + * call or the OUTPUT (or `(no output)`) for a settled one. Rows expand and + * collapse independently, so comparing two calls never loses the other's detail. + */ +@Composable +private fun ToolCallRowItem(row: ToolCallRow, expanded: Boolean, onToggle: () -> Unit) { + Column(Modifier.fillMaxWidth()) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier + .fillMaxWidth() + .minimumInteractiveComponentSize() + .clickable(role = Role.Button, onClick = onToggle) + .padding(vertical = CHAT_ITEM_GAP), + ) { + Icon( + imageVector = when { + row.error != null -> Icons.Default.ErrorOutline + row.diff != null -> Icons.Default.Edit + else -> Icons.Default.Build + }, + contentDescription = if (row.error != null) "Failed tool call" else null, + modifier = Modifier.size(ICON_INLINE_DP), + tint = if (row.error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + ) + Column(Modifier.weight(1f)) { + Text( + text = row.name, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + row.detail?.let { + Text( + text = it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + row.diff?.let { DiffStat(it) } + row.duration?.let { + Text(it, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Icon( + imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, + contentDescription = if (expanded) "Collapse ${row.name}" else "Expand ${row.name}", + modifier = Modifier.size(ICON_INLINE_DP), + ) + } + if (expanded) { + Column( + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth().padding(start = ICON_INLINE_DP + CHAT_ITEM_GAP, bottom = CHAT_ITEM_GAP), + ) { + CodeBlock(label = "INPUT", text = row.input) + row.diff?.let { DiffView(it) } + if (row.error != null) { + CodeBlock(label = "ERROR", text = row.error) + } else { + CodeBlock(label = "OUTPUT", text = row.output) + } } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt index 0434bb23..50860ece 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt @@ -195,6 +195,7 @@ internal fun ChatTranscript( reasoning = reasoning, streaming = row.key == streamingTurnKey, runningSince = thread.runningSince, + toolStartedAt = thread.toolStartedAt, onToggleReasoning = onToggleReasoning, ) } @@ -434,10 +435,11 @@ private fun UserMessageItem(message: ChatMessage) { /** * One agent reply as a single bubble: the turn's one collapsible thinking block - * first, then its tool-call chips in order, then its answer text. A turn's + * first, then its one tool-call summary chip, then its answer text. A turn's * reasoning and answer are never mixed — the fold in [ChatTurn] keeps them * separate, so the answer is never drawn inside the thinking block — and the - * whole reply is one item however many model steps produced it. + * whole reply is one item however many model steps produced it. The individual + * calls live inside the chip's popup, not in the transcript. */ @Composable private fun AgentTurnItem( @@ -445,15 +447,17 @@ private fun AgentTurnItem( reasoning: ReasoningExpansion, streaming: Boolean, runningSince: Long, + toolStartedAt: Map, onToggleReasoning: (String) -> Unit, ) { // The turn's own timing for the collapsed thinking line: a streaming turn // counts live from its own start (the same clock the running indicator uses, // so the two never disagree), a settled turn shows the span its parts' timing // envelopes report, and a turn with neither shows no duration rather than a - // guessed one. + // guessed one. The same tick ages the summary chip's running calls, so its + // "long" mark never comes from a stale clock. + val now = if (streaming && runningSince > 0) rememberElapsedNow(runningSince) else 0L val elapsedMillis: Long? = if (streaming && runningSince > 0) { - val now = rememberElapsedNow(runningSince) if (runningSince < now) now - runningSince else 0L } else { turn.elapsedMillis @@ -477,7 +481,15 @@ private fun AgentTurnItem( elapsedMillis = elapsedMillis, onToggle = { onToggleReasoning(turnKey) }, ) - if (turn.tools.isNotEmpty()) ToolCalls(turn.tools) + if (turn.tools.isNotEmpty()) { + ToolCalls( + parts = turn.tools, + live = streaming, + elapsedMillis = { part -> + runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, now) + }, + ) + } if (turn.answer.isNotBlank()) MarkdownText(turn.answer) } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt index 1b6a9351..caace198 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt @@ -235,6 +235,13 @@ internal val ICON_BUTTON_SMALL_DP = 28.dp /** The floating tool panel's maximum width; it floats over the transcript. */ internal val TOOL_PANEL_MAX_WIDTH_DP = 420.dp +/** + * How tall the tool panel's list of calls may grow before it scrolls inside the + * panel. Bounded so a turn with many calls never grows the popup past the window + * or pushes its own placement above the screen. + */ +internal val TOOL_PANEL_MAX_HEIGHT_DP = 440.dp + /** A chat row's title column stops here so the close action keeps its place. */ internal val CHAT_TITLE_MAX_WIDTH_DP = 160.dp diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt index 74b7bd13..d9f5e03a 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt @@ -179,4 +179,88 @@ class ChatFormatTest { assertEquals("scratch", sessionTagLabel("scratch")) assertNull(sessionTagLabel("")) } + + @Test + fun theToolSummaryReadsAsACallCountAndNeverSaysOneTools() { + // The turn's one chip: the singular is a whole word, not a pluralised count. + assertEquals("1 tool called", toolCallsLabel(1)) + assertEquals("6 tools called", toolCallsLabel(6)) + // The same count is what a screen reader hears, plus how to reach the calls. + assertEquals("1 tool call, expand for details", toolCallsAnnouncement(1)) + assertEquals("6 tool calls, expand for details", toolCallsAnnouncement(6)) + } + + @Test + fun theSummaryCountCountsOnlyTheTurnsToolCalls() { + val parts = listOf( + ChatPart(type = ChatProtocol.PART_TEXT, id = "t1", text = "answer"), + ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", name = "shell"), + ChatPart(type = ChatProtocol.PART_TOOL, id = "c2", name = "grep"), + ) + // Text and reasoning ride in the same turn but never inflate the chip. + assertEquals(2, toolCallCount(parts)) + assertEquals(0, toolCallCount(parts.filter { it.type == ChatProtocol.PART_TEXT })) + // One call still in flight keeps the chip live. + assertTrue(toolsRunning(listOf(parts[1].copy(state = ChatToolState(status = ChatProtocol.TOOL_RUNNING))))) + assertFalse(toolsRunning(listOf(parts[1].copy(state = ChatToolState(status = ChatProtocol.TOOL_COMPLETED))))) + } + + @Test + fun aToolCallRowDerivesItsNameDetailDurationInputAndOutput() { + val part = ChatPart( + type = ChatProtocol.PART_TOOL, + id = "c1", + name = "shell", + state = ChatToolState( + status = ChatProtocol.TOOL_COMPLETED, + input = JsonObject(mapOf("command" to JsonPrimitive("ls"))), + content = listOf(ChatToolContent(type = "text", text = "a.txt")), + ), + time = ChatTime(created = 1_000, ran = 1_000, completed = 2_500), + ) + val row = toolCallRow(part) + assertEquals("shell", row.name) + assertEquals("ls", row.detail) + assertEquals("1.5s", row.duration) + assertTrue(row.input.contains("\"command\"")) + assertEquals("a.txt", row.output) + // A successful non-edit call has neither an error block nor a diff. + assertNull(row.error) + assertNull(row.diff) + } + + @Test + fun aFailedEditRowCarriesItsErrorAndSynthesisedDiff() { + val part = ChatPart( + type = ChatProtocol.PART_TOOL, + id = "c2", + name = "edit", + state = ChatToolState( + status = ChatProtocol.TOOL_ERROR, + input = JsonObject( + mapOf( + "filePath" to JsonPrimitive("/tmp/a.txt"), + "oldString" to JsonPrimitive("one"), + "newString" to JsonPrimitive("two"), + ), + ), + error = ChatError(type = "boom", message = "exploded"), + ), + ) + val row = toolCallRow(part) + assertEquals("edit", row.name) + // The ERROR block wins over any output, and the diff is still shown beside it. + assertEquals("exploded", row.error) + assertEquals("/tmp/a.txt", row.diff?.file) + assertEquals(1, row.diff?.added) + assertEquals(1, row.diff?.removed) + // A call with no completion time shows no duration rather than a guess. + assertNull(row.duration) + } + + @Test + fun aToolCallRowKeepsTheRealNameAndOnlyFallsBackWhenNoneWasEverSeen() { + assertEquals("shell", toolCallRow(ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", name = "shell")).name) + assertEquals("tool", toolCallRow(ChatPart(type = ChatProtocol.PART_TOOL, id = "c2")).name) + } } diff --git a/docs/notes/chat-tool-group.md b/docs/notes/chat-tool-group.md new file mode 100644 index 00000000..bdd35672 --- /dev/null +++ b/docs/notes/chat-tool-group.md @@ -0,0 +1,48 @@ +# Chat transcript: one tool-call summary chip per agent turn + +## What this item changed + +`android/` only — the chat transcript's tool-call surface. + +- **One chip per turn.** `ui/chat/ChatToolCalls.kt` no longer renders a chip per + call in a `FlowRow`; `ToolCalls` renders a single summary chip reading + `N tools called` (`1 tool called` for one), the transcript's only tool-call + surface. The individual calls are not chips any more. +- **Live summary.** The chip shows the existing spinner while any call is in + flight and a `· long` mark while a running call has passed + `TOOL_LONG_RUNNING_MILLIS`; both are gated on the turn still streaming + (`AgentTurnItem` passes `live = streaming`), so a settled turn never shows the + spinner or a long mark for a stored call whose status is stale. +- **Popup list.** Tapping the chip opens `ToolPanel` as a bounded + (`TOOL_PANEL_MAX_HEIGHT_DP`), scrollable list of one collapsible row per call in + the order the agent made them. A row shows the call's name, its one-line detail, + its `+N -M` stat for an edit and its duration, and expands in place to the + pretty-printed INPUT, the synthesised diff for an `edit`-family call, then the + ERROR block for a failed call or the OUTPUT (or `(no output)`). Rows expand and + collapse independently, and the popup still does not re-flow or scroll the + transcript. +- **Pure logic.** `ui/chat/ChatFormat.kt` adds `toolCallsLabel`, + `toolCallsAnnouncement` (the chip's accessibility line, e.g. "6 tool calls, + expand for details"), `toolCallCount`, `toolsRunning` and `toolCallRow` (the + per-row detail derivation), with cases added to `ChatFormatTest`. +- **Geometry.** `ui/theme/Dimens.kt` adds `TOOL_PANEL_MAX_HEIGHT_DP`; no raw + literal was introduced, so `DimensTest` is unchanged. + +## Shared documents this change makes stale + +`android/README.md` describes the surface this item changed. The note is written +here rather than edited in place; the `docs-fold` writer should update it. + +- `android/README.md` — the section **"Tool-call chips and the expandable panel + (16 Oct 2026)"** and its **Grouped chips** bullet ("A run of consecutive `tool` + parts in one assistant turn is now one `FlowRow` of compact chips") describe the + per-call chips this item removed. It should say the turn renders one summary + chip (`N tools called`) as the transcript's only tool-call surface, and that + tapping it opens one popup listing every call of the turn as independently + collapsible rows, with the chip's spinner/`long` marks gated on the turn still + streaming. The **Overlay panel, scroll preserved** bullet stays true. +- `docs/chat-verification.md:140` — the "Conversation — tool chip expanding" row + names `ChatToolCalls.kt` and the per-chip panel; it should name the summary chip + and the per-turn popup list, and the pure tests now include the label, count, + announcement and per-row derivations in `ChatFormatTest` (the placement maths in + `ToolPanelPositionProviderTest` is unchanged).