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 d50c87cc..58d7c8ac 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 @@ -7,6 +7,7 @@ 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.ChatMessage import net.awan.pipelines.data.protocol.ChatProtocol import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.protocol.ChatToolState @@ -79,6 +80,126 @@ 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" } +/** + * 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 + * and its order is stable from frame to frame (a chip is never re-ordered by a + * rebuild). A call drops out the moment it completes or errors, which is what + * clears the indicator, so nothing here ever invents a finish time. + */ +internal fun runningToolCalls(messages: List): List = + messages.flatMap { it.parts } + .filter { it.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(it.state) } + +/** + * The input keys, in preference order, that carry a human-facing command or a + * short description of what a tool call is doing. OpenCode's tools put the + * substance in different places (`command` for a shell, `description` for a task, + * a path or pattern for the file/search tools), so the first one present is shown + * rather than the raw arguments. + */ +private val TOOL_DETAIL_KEYS = listOf( + "description", "command", "filePath", "file_path", "path", "pattern", "query", "url", +) + +/** How much of a command/description the phone shows before it is elided. */ +private const val TOOL_DETAIL_MAX_LENGTH = 72 + +private val TOOL_DETAIL_WHITESPACE = Regex("\\s+") + +/** + * A one-line command or short description for [part], taken from the input the + * part actually carries: the first of [TOOL_DETAIL_KEYS] present, collapsed to a + * single line and elided past [TOOL_DETAIL_MAX_LENGTH]. Null when the input + * carries no such key (a partial-JSON string while the call is still streaming, + * or a tool that reports none), so a caller shows the name alone rather than a + * fabricated summary. + */ +internal fun toolDetail(part: ChatPart): String? { + val obj = part.state?.input as? JsonObject ?: return null + for (key in TOOL_DETAIL_KEYS) { + val value = obj[key] as? JsonPrimitive ?: continue + if (!value.isString) continue + val text = value.content.trim().replace(TOOL_DETAIL_WHITESPACE, " ") + if (text.isBlank()) continue + return if (text.length <= TOOL_DETAIL_MAX_LENGTH) { + text + } else { + text.take(TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…" + } + } + return null +} + +/** + * 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 + * has `time.ran`, the moment it started); otherwise the elapsed is measured + * locally from [startedAt] — the wall clock at which this client first saw the + * part running. Zero when neither is usable, so a caller never shows a time it + * cannot stand behind. + */ +internal fun runningToolElapsedMillis(part: ChatPart, startedAt: Long, nowMillis: Long): Long { + val protocolStart = part.time?.let { if (it.ran > 0) it.ran else it.created } ?: 0L + val start = if (protocolStart > 0) protocolStart else startedAt + return if (start in 1 until nowMillis) nowMillis - start else 0L +} + +/** + * A tool call running longer than this reads as unusually long on the phone and + * is marked, so a genuinely stuck call is visible without a fabricated ETA. One + * minute: long enough that ordinary calls (a build, a search, a command) are not + * flagged, short enough that a hung call stands out while the operator is still + * wondering. + */ +internal const val TOOL_LONG_RUNNING_MILLIS: Long = 60_000L + +/** Whether a running call has been going long enough to be marked as unusual. */ +internal fun toolLongRunning(elapsedMillis: Long): Boolean = elapsedMillis >= TOOL_LONG_RUNNING_MILLIS + +/** + * The running-tool start stamps after a thread's [messages] changed: every tool + * part in flight keeps the stamp it already had, or is stamped with [now] when it + * has just turned running, and a part that is no longer running loses its stamp. + * Kept free of Compose and of [ChatStore] so the bookkeeping and its unit test + * share one rule, and a stamp never moves forward while a call keeps running. + */ +internal fun runningToolStamps( + current: Map, + messages: List, + now: Long, +): Map { + val stamps = LinkedHashMap() + messages.forEach { message -> + message.parts.forEach { part -> + if (part.id.isNotEmpty() && part.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(part.state)) { + stamps[part.id] = current[part.id] ?: now + } + } + } + return stamps +} + +/** + * The status a session row reports while a turn is in flight: it names the tool + * call it is parked on (or how many, when several run at once) so a working chat + * says what it is doing rather than just `Running`, and a chat only generating + * text still reads as plain `Running` — the two are never confused. A chat with + * nothing running falls back to the ordinary busy/idle label, so a session + * waiting on another client is never shown as idle. + */ +internal fun sessionWorkLabel(busy: Boolean, thread: ChatThread?): String = when { + thread?.running == true -> runningSessionLabel(thread.runningTools) + busy -> "Busy · read-only" + else -> "Idle" +} + +private fun runningSessionLabel(tools: List): String = when (tools.size) { + 0 -> "Running" + 1 -> "Running ${toolLabel(tools.single())}" + else -> "Running ${tools.size} tools" +} + /** * A session's short title: the server title, or a truncated id when untitled, so * a row never renders as a blank line. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt index e58ec9cf..a35e6154 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt @@ -255,8 +255,8 @@ private fun SessionListItem( val thread = state.thread(session.id) SessionRow( session = session, + thread = thread, open = thread != null, - running = thread?.running == true, unseen = state.isUnseen(session), active = state.activeId == session.id, onClick = { vm.openChatSession(session) }, @@ -289,8 +289,8 @@ private const val NO_DIRECTORY_LABEL = "No directory" @Composable private fun SessionRow( session: ChatSession, + thread: ChatThread?, open: Boolean, - running: Boolean, unseen: Boolean, active: Boolean, onClick: () -> Unit, @@ -298,6 +298,7 @@ private fun SessionRow( onRemove: () -> Unit, ) { val texts = pipelinesText() + val running = thread?.running == true val activity = sessionActivity(running, unseen) ListRow(selected = active, onClick = onClick) { Row( @@ -321,7 +322,7 @@ private fun SessionRow( SessionMenu(onRename = onRename, onRemove = onRemove) } val meta = buildList { - add(sessionStatusLabel(session, running)) + add(sessionWorkLabel(session.busy, thread)) if (session.directory.isNotBlank()) add(session.directory) if (session.model.isNotBlank()) add(session.model) }.joinToString(" · ") diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index a3d80f75..14d02ef2 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -70,6 +70,15 @@ data class ChatThread( * the turn settles. */ val runningSince: Long = 0, + /** + * Wall-clock epoch millis each currently-running tool call was first seen + * running, keyed by the tool part's id. The brokered stream pushes a tool part + * with no timing envelope, so a running call's elapsed time is measured from + * here; a call that settles loses its stamp. Kept on the thread (not in the + * composable) so the elapsed time survives a chat switch, exactly like + * [runningSince] does for the turn. + */ + val toolStartedAt: Map = emptyMap(), /** The unsent composer text for this chat. */ val draft: String = "", /** @@ -120,6 +129,22 @@ data class ChatThread( */ fun elapsedMillis(nowMillis: Long): Long = if (running && runningSince in 1 until nowMillis) nowMillis - runningSince else 0 + + /** + * The tool calls still in flight for this session, in transcript order, so the + * conversation's in-flight indicator and the session row both read the same + * set. Empty once every call has completed or errored, which is what clears + * the indicator. + */ + val runningTools: List get() = runningToolCalls(messages) + + /** + * How long [part] has been running at [nowMillis]: the protocol's own timing + * when the part carries it, else the local start recorded in [toolStartedAt] + * (see [runningToolElapsedMillis]). Zero when neither is usable. + */ + fun toolElapsedMillis(part: ChatPart, nowMillis: Long): Long = + runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, nowMillis) } /** @@ -580,7 +605,16 @@ class ChatStore( */ fun history(sessionId: String, messages: List) { update(sessionId) { - it.copy(messages = messages, loading = false, loaded = true, error = null) + it.copy( + messages = messages, + loading = false, + loaded = true, + error = null, + // A running call the history reports (a turn that started before + // this fetch) is stamped now, the best local measurement there is; + // a call that already settled drops its stamp. + toolStartedAt = runningToolStamps(it.toolStartedAt, messages, now()), + ) } // A conversation on screen is read as its history arrives: its recency // watermark advances to the newest message the server reports (its own @@ -605,7 +639,9 @@ class ChatStore( val ids = _state.value.open.map { it.sessionId } if (ids.isEmpty()) return ids _state.value = _state.value.copy( - open = _state.value.open.map { if (it.running) it.copy(running = false, runningSince = 0) else it }, + open = _state.value.open.map { + if (it.running) it.copy(running = false, runningSince = 0, toolStartedAt = emptyMap()) else it + }, ) return ids } @@ -777,7 +813,8 @@ class ChatStore( val updated = upsert(if (partIndex >= 0) parts[partIndex] else null) if (partIndex >= 0) parts[partIndex] = updated else parts.add(updated) messages[resolvedIndex] = message.copy(parts = parts) - setRunning(thread.copy(messages = messages), true) + val stamped = runningToolStamps(thread.toolStartedAt, messages, now()) + setRunning(thread.copy(messages = messages, toolStartedAt = stamped), true) } } @@ -790,7 +827,7 @@ class ChatStore( private fun setRunning(thread: ChatThread, running: Boolean): ChatThread = when { running && !thread.running -> thread.copy(running = true, runningSince = now()) running -> thread - else -> thread.copy(running = false, runningSince = 0) + else -> thread.copy(running = false, runningSince = 0, toolStartedAt = emptyMap()) } private fun update(sessionId: String, block: (ChatThread) -> ChatThread) { 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 ddb3f115..7193487a 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 @@ -20,6 +20,7 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.Psychology @@ -34,6 +35,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -46,6 +48,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect @@ -57,6 +60,7 @@ import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.theme.CHAT_BUBBLE_MAX_WIDTH_DP import net.awan.pipelines.ui.theme.CHAT_FOLLOW_THRESHOLD_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.SPACING_XS /** The running indicator's elapsed time ticks once a second, never per frame. */ @@ -274,24 +278,90 @@ private fun LazyListState.bottomDistancePx(itemCount: Int): Int? { /** * The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed - * time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]), - * so it keeps counting across a chat switch, and the tick loop stops the moment - * the turn settles. + * time, then one compact line for each tool call in flight — its name, the + * command or description the part carries, and how long that call has been + * running. The elapsed values are derived from the turn's own start + * ([ChatThread.elapsedMillis]) and each call's own start + * ([ChatThread.toolElapsedMillis]), so they keep counting across a chat switch, + * and the tick loop stops the moment the turn settles. This is what makes the + * otherwise-silent part of a turn legible: the operator can tell `working on X` + * from `waiting on something` instead of watching a bare `Running`. */ @Composable private fun RunningIndicator(thread: ChatThread) { - val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince)) + val now = rememberElapsedNow(thread.runningSince) + val elapsedMillis = thread.elapsedMillis(now) + val tools = thread.runningTools + Column( + verticalArrangement = Arrangement.spacedBy(SPACING_XS), + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + text = "· ${formatDuration(elapsedMillis / 1_000)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + // One line per call in flight, in transcript order and keyed by the part, + // so several running at once read together rather than flickering between + // them; a call's line drops out the moment it completes or errors. + tools.forEach { part -> + key(part.id) { RunningToolLine(part, thread.toolElapsedMillis(part, now)) } + } + } +} + +/** + * One tool call in flight: its name, the command or short description the part + * carries (when it carries one) and how long it has been running. A call that has + * been running past [TOOL_LONG_RUNNING_MILLIS] is tinted and labelled so a stuck + * call stands out. The elapsed time is the only progress signal; no percentage, + * ETA or progress bar is ever invented. + */ +@Composable +private fun RunningToolLine(part: ChatPart, elapsedMillis: Long) { + val long = toolLongRunning(elapsedMillis) + val tint = if (long) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant + val detail = toolDetail(part) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + modifier = Modifier.fillMaxWidth().padding(start = CHAT_GUTTER), ) { - CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) - Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Icon( + Icons.Default.Build, + contentDescription = null, + tint = tint, + modifier = Modifier.size(ICON_STATUS_DP), + ) Text( - text = "· ${formatDuration(elapsedMillis / 1_000)}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + text = toolLabel(part), + style = MaterialTheme.typography.labelMedium, + color = tint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = if (detail == null) Modifier.weight(1f) else Modifier, + ) + if (detail != null) { + Text( + text = detail, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + } + Text( + text = formatDuration(elapsedMillis / 1_000) + if (long) " · long" else "", + style = MaterialTheme.typography.labelMedium, + color = tint, ) } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatRunningWorkTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatRunningWorkTest.kt new file mode 100644 index 00000000..3e82282d --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatRunningWorkTest.kt @@ -0,0 +1,235 @@ +package net.awan.pipelines.ui.chat + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import net.awan.pipelines.data.protocol.ChatEventFrame +import net.awan.pipelines.data.protocol.ChatMessage +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.data.protocol.ChatTime +import net.awan.pipelines.data.protocol.ChatToolState +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 in-flight work a conversation and its session row show: a running tool with + * its name, the command or description the part carries, and a live elapsed time + * that grows from when the call turned running, uses the protocol's own timing + * when the part has it, and clears the moment the call completes or errors. All + * pure or driven against [ChatStore] with an injected clock, so no device, server + * or Compose runtime is needed. + */ +class ChatRunningWorkTest { + + private fun tool( + id: String, + name: String, + status: String, + input: JsonObject? = null, + time: ChatTime? = null, + ) = ChatPart( + type = ChatProtocol.PART_TOOL, + id = id, + name = name, + state = ChatToolState(status = status, input = input), + time = time, + ) + + private fun toolFrame(sessionId: String, messageId: String, part: ChatPart) = + ChatEventFrame(sessionId = sessionId, messageId = messageId, kind = ChatProtocol.PART_TOOL, part = part) + + private fun input(vararg pairs: Pair): JsonObject = + JsonObject(pairs.associate { (key, value) -> key to JsonPrimitive(value) }) + + private fun threadWith(vararg parts: ChatPart) = ChatThread( + sessionId = "s", + running = true, + messages = listOf( + ChatMessage( + id = "m1", + sessionId = "s", + role = ChatProtocol.ROLE_ASSISTANT, + parts = parts.toList(), + ), + ), + ) + + @Test + fun aRunningToolShowsItsNameDetailAndGrowingTime() { + var clock = 1_000L + val store = ChatStore(now = { clock }) + store.open(ChatSession(id = "s", title = "s")) + store.history("s", emptyList()) + + store.event( + toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls -la"))), + ) + + val thread = store.value.thread("s")!! + assertTrue(thread.running) + val call = thread.runningTools.single() + assertEquals("shell", call.name) + assertEquals("ls -la", toolDetail(call)) + // Elapsed is measured locally from when the call turned running, so it + // starts at zero and grows with the clock. + assertEquals(0L, thread.toolElapsedMillis(call, clock)) + clock = 6_000L + val later = thread.toolElapsedMillis(call, clock) + assertEquals(5_000L, later) + assertTrue(later > 0L) + } + + @Test + fun aToolWithProtocolTimingUsesItsOwnStart() { + val timed = tool("c1", "bash", ChatProtocol.TOOL_RUNNING, time = ChatTime(created = 900, ran = 1_000)) + // The protocol's own `ran` wins over the local stamp, so the elapsed is + // its start to now. + assertEquals(4_000L, runningToolElapsedMillis(timed, startedAt = 0L, nowMillis = 5_000L)) + // Neither a protocol start nor a local one: nothing to show, never a guess. + assertEquals(0L, runningToolElapsedMillis(tool("c2", "bash", ChatProtocol.TOOL_RUNNING), 0L, 5_000L)) + } + + @Test + fun aCompletedOrFailedCallLeavesTheRunningSetAndTheFailureIsVisible() { + var clock = 1_000L + val store = ChatStore(now = { clock }) + store.open(ChatSession(id = "s", title = "s")) + + store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls")))) + assertEquals(1, store.value.thread("s")!!.runningTools.size) + + // Completion clears the call from the in-flight set and drops its stamp. + clock = 2_000L + store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_COMPLETED, input("command" to "ls")))) + val done = store.value.thread("s")!! + assertTrue(done.runningTools.isEmpty()) + assertTrue(done.toolStartedAt.isEmpty()) + assertFalse(toolFailed(done.messages.last().parts.single().state)) + + // A failure is out of the running set too, and reads as failed on its chip. + store.event(toolFrame("s", "m1", tool("c2", "shell", ChatProtocol.TOOL_ERROR))) + val failed = store.value.thread("s")!! + assertTrue(failed.runningTools.isEmpty()) + assertTrue(toolFailed(failed.messages.last().parts.first { it.id == "c2" }.state)) + } + + @Test + fun severalCallsRunTogetherInOrderWithStableStartStamps() { + var clock = 1_000L + val store = ChatStore(now = { clock }) + store.open(ChatSession(id = "s", title = "s")) + + store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "build")))) + clock = 2_000L + store.event(toolFrame("s", "m1", tool("c2", "grep", ChatProtocol.TOOL_RUNNING, input("pattern" to "TODO")))) + + val thread = store.value.thread("s")!! + // Both render, in transcript order, so the list does not flicker between them. + assertEquals(listOf("c1", "c2"), thread.runningTools.map { it.id }) + // Each keeps the clock it first turned running on... + assertEquals(mapOf("c1" to 1_000L, "c2" to 2_000L), thread.toolStartedAt) + + // ...so a later frame for the first call does not restart its timer. + clock = 3_000L + store.event( + toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "build && test"))), + ) + val updated = store.value.thread("s")!! + assertEquals(1_000L, updated.toolStartedAt["c1"]) + clock = 11_000L + assertEquals(10_000L, updated.toolElapsedMillis(updated.runningTools.single { it.id == "c1" }, clock)) + } + + @Test + fun aCallWithoutADescriptionStillRendersNameStatusAndTime() { + var clock = 5_000L + val store = ChatStore(now = { clock }) + store.open(ChatSession(id = "s", title = "s")) + // No input at all: the part carries no description to show. + store.event(toolFrame("s", "m1", tool("c1", "task", ChatProtocol.TOOL_RUNNING))) + + val call = store.value.thread("s")!!.runningTools.single() + assertNull(toolDetail(call)) + assertEquals("task", toolLabel(call)) + assertTrue(ChatProtocol.toolRunning(call.state)) + clock = 9_000L + assertEquals(4_000L, store.value.thread("s")!!.toolElapsedMillis(call, clock)) + } + + @Test + fun toolDetailPrefersDescriptionThenCommandAndIgnoresWhatItCannotRead() { + // A description wins over a command when both are present. + assertEquals( + "Summarise the diff", + toolDetail( + tool( + "c1", "task", ChatProtocol.TOOL_RUNNING, + input("description" to "Summarise the diff", "command" to "git diff"), + ), + ), + ) + // A shell's command is next. + assertEquals( + "ls -la", + toolDetail(tool("c2", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls -la"))), + ) + // A file tool's path is shown when nothing more descriptive exists. + assertEquals( + "/tmp/a.txt", + toolDetail(tool("c3", "read", ChatProtocol.TOOL_RUNNING, input("filePath" to "/tmp/a.txt"))), + ) + // A multi-line command collapses to a single line. + assertEquals( + "run this", + toolDetail(tool("c4", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "run\n this"))), + ) + // A partial (not-yet-object) input, a missing state, and an input with no + // known key all show nothing rather than something invented. + assertNull( + toolDetail( + ChatPart( + type = ChatProtocol.PART_TOOL, + id = "c5", + name = "shell", + state = ChatToolState(status = ChatProtocol.TOOL_STREAMING, input = JsonPrimitive("{\"command\"")), + ), + ), + ) + assertNull(toolDetail(ChatPart(type = ChatProtocol.PART_TOOL, id = "c6", name = "shell"))) + assertNull(toolDetail(tool("c7", "shell", ChatProtocol.TOOL_RUNNING, input("foo" to "bar")))) + } + + @Test + fun aCallRunningTooLongIsMarked() { + assertFalse(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1)) + assertTrue(toolLongRunning(TOOL_LONG_RUNNING_MILLIS)) + } + + @Test + fun theSessionRowReportsWhatIsRunning() { + assertEquals("Running shell", sessionWorkLabel(busy = false, threadWith(tool("c1", "shell", ChatProtocol.TOOL_RUNNING)))) + assertEquals( + "Running 2 tools", + sessionWorkLabel( + busy = false, + threadWith( + tool("c1", "shell", ChatProtocol.TOOL_RUNNING), + tool("c2", "grep", ChatProtocol.TOOL_RUNNING), + ), + ), + ) + // A turn running with no tool yet reads as plain Running, never idle, so a + // text stream and a parked tool call stay distinguishable. + assertEquals("Running", sessionWorkLabel(busy = false, ChatThread(sessionId = "s", running = true))) + assertEquals("Running", sessionWorkLabel(busy = true, ChatThread(sessionId = "s", running = true))) + + // Nothing running falls back to the ordinary busy/idle label. + assertEquals("Busy · read-only", sessionWorkLabel(busy = true, thread = null)) + assertEquals("Idle", sessionWorkLabel(busy = false, thread = null)) + assertEquals("Idle", sessionWorkLabel(busy = false, ChatThread(sessionId = "s"))) + } +} diff --git a/docs/notes/chat-in-flight-tool-work.md b/docs/notes/chat-in-flight-tool-work.md new file mode 100644 index 00000000..605f1bdf --- /dev/null +++ b/docs/notes/chat-in-flight-tool-work.md @@ -0,0 +1,65 @@ +# Chat in-flight tool work + +## What this item changed + +`android/` only, the chat's two "working" surfaces. + +- `ui/chat/ChatFormat.kt` adds `runningToolCalls` (the tool parts still + `running`, in transcript order), `toolDetail` (the command/description the + part's own input carries, from description/command/filePath/file_path/path/ + pattern/query/url, one line, elided at 72 chars, `null` when absent), + `runningToolElapsedMillis` (the protocol's `time.ran`/`created` when present, + else the local per-part stamp), `runningToolStamps` (a stable start per part + across frames), `TOOL_LONG_RUNNING_MILLIS` = 60s with `toolLongRunning`, and + `sessionWorkLabel`. +- `ui/chat/ChatStore.kt`: `ChatThread.toolStartedAt` plus `runningTools` and + `toolElapsedMillis`; `history()`, the frame fold and `setRunning` maintain it. +- `ui/chat/ChatTranscript.kt`: `RunningIndicator` now also lists one line per + running call (name, detail where present, live elapsed), keyed by part id so + concurrent calls render together; a call past 60s is tinted and marked + `· long`. +- `ui/chat/ChatListPane.kt`: the session row renders + `sessionWorkLabel(session.busy, thread)`. +- `ui/chat/ChatRunningWorkTest.kt` covers it (name/detail/elapsed, clear on + completion, error state, concurrent calls, no-detail stream). + +No percentage, ETA or progress bar is invented; only the reported fields (tool +name, `state.status`, `state.input`) are used. + +## Shared documents this change makes stale + +`android/README.md` documents the two surfaces this item changed, in the +`## Streaming replies (16 Oct 2026)` record. The note is written here rather +than edited in place; the `docs-fold` writer should update it. + +- `android/README.md:4633` — the **Running indicator** bullet reads "The + transcript's indicator shows the spinner, `Working…` and the live elapsed + time (ticked once a second, never per frame, through the shared + `formatDuration`)." It should add that the indicator also lists, one line per + tool call still in flight, the call's name, the command/description the part + carries when it carries one, and that call's own live elapsed time; that a + call running 60 seconds or more is tinted and marked `· long`; that a call's + line drops out the moment it completes or errors, which is what clears the + indicator; and that no percentage, ETA or progress bar is shown. The rest of + the bullet (one-second tick, the tick loop keyed on the turn's start, the + elapsed count surviving a chat switch) is still true. +- `android/README.md:4454` — the session-list sentence "the list shows each + session's running/busy/read-only status" is now incomplete: a working session + row names what it is doing (`Running `, or `Running tools` when + several run at once) instead of only `Running`, while a turn that is only + generating text still reads plain `Running`, so the two stay distinguishable; + a busy session with nothing running still reads `Busy · read-only`, and an + idle one `Idle`. + +Dates, counts and capture names in those dated records are past evidence and +stay as they are; only the two behaviour statements above are now stale. + +## Not stale + +- No packaged OpenCode skill reference documents this app surface. The chat + references in `internal/author/skill/references/operations.md` document the + server's brokered `chat_*` protocol, which this change does not touch, and no + packaged template or `internal/author/` managed file names the app's chat + indicator or session label. +- `android/AGENTS.md` already lists `ui/chat/` and its files, so it needs no + change.