Merge main into session-html-only: combine the html-only session export with chat-tool-group and chat-activity

This commit is contained in:
2026-10-18 10:06:54 +01:00
18 changed files with 1471 additions and 158 deletions
@@ -165,11 +165,31 @@ data class ChatEventFrame(
val part: ChatPart? = null,
val step: ChatStep? = null,
val usage: ChatUsage? = null,
// The payload of a `shell` frame: the lifecycle of one shell the agent
// started. Nil on every other kind. A shell carries no message id, because a
// background process outlives the tool call (and the turn) that started it.
val shell: ChatShell? = null,
// The sending device's label on a `user` frame (another client's prompt), so
// the transcript can say who sent it. Empty on the agent's own frames.
val client: String = "",
)
/**
* The state of one shell command the agent started, mirroring
* `internal/protocol/chat.go`'s ChatShell. [id] is stable across the created and
* exited frames so a running process is keyed by it; [status] is one of
* [ChatProtocol.SHELL_RUNNING]/[ChatProtocol.SHELL_EXITED]; [command] is the
* command line the shell was given (present on the created frame); [exit] is the
* process exit code and is non-null only once the shell has exited.
*/
@Serializable
data class ChatShell(
val id: String = "",
val status: String = "",
val command: String = "",
val exit: Int? = null,
)
@Serializable
data class ChatStep(
val status: String = "",
@@ -242,6 +262,16 @@ object ChatProtocol {
const val EVENT_STEP = "step"
const val EVENT_USAGE = "usage"
/**
* The lifecycle of one shell the agent started. It carries a [ChatShell],
* no message id and no [ChatPart]: a background process can outlive the turn
* that started it, so it is a frame of its own and never a tool part.
*/
const val EVENT_SHELL = "shell"
const val SHELL_RUNNING = "running"
const val SHELL_EXITED = "exited"
/**
* A prompt another client sent, echoed live to this client so it appears in
* the transcript attributed to the sending device. The sender never receives
@@ -215,7 +215,8 @@ internal fun ChatConversationPane(
message = thread.error,
onRetry = { vm.loadChatHistory(thread.sessionId) },
)
thread.messages.isEmpty() && thread.notices.isEmpty() && !thread.running && approval == null ->
thread.messages.isEmpty() && thread.notices.isEmpty() && !thread.running &&
approval == null && thread.runningShells.isEmpty() ->
EmptyState(
message = "This chat has no messages yet. Ask something below.",
)
@@ -237,6 +238,13 @@ internal fun ChatConversationPane(
)
}
}
// The background processes still running, shown whether or not a turn
// is: a shell can outlive the turn that started it, so this is a strip
// of its own rather than part of the turn indicator, and it clears the
// moment each shell exits.
if (thread.runningShells.isNotEmpty()) {
BackgroundProcessBar(thread.runningShells)
}
if (thread.error != null && thread.loaded) {
Text(
text = thread.error,
@@ -10,6 +10,7 @@ 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.ChatShell
import net.awan.pipelines.data.protocol.ChatToolState
import net.awan.pipelines.ui.humanBytes
@@ -80,6 +81,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<ChatPart>): Int =
parts.count { it.type == ChatProtocol.PART_TOOL }
/** True while any tool call in [parts] is still in flight. */
internal fun toolsRunning(parts: List<ChatPart>): 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 +160,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
@@ -157,6 +216,76 @@ 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
/**
* How recently a text or reasoning delta must have arrived for a turn to read as
* still thinking. Long enough that the once-a-second tick the indicator runs on
* cannot flicker between thinking and waiting on a steady stream, short enough
* that a stalled turn starts reading as waiting while the operator still wonders.
*/
internal const val TURN_THINKING_WINDOW_MILLIS: Long = 2_500L
/**
* What an in-flight turn is actually doing, from evidence already on the wire.
* It is the one derivation the running indicator and its unit test share, so the
* headline never disagrees with the tool lines under it:
*
* - [THINKING] while text or reasoning deltas are still arriving (within
* [TURN_THINKING_WINDOW_MILLIS] of the last one);
* - [TOOL] while one or more tool calls are in flight, which the indicator names
* separately;
* - [WAITING] otherwise — the turn is running but nothing is arriving and no
* tool is running, for example while the model is awaited between steps.
*
* No percentage, ETA or progress is ever invented: the only inputs are the calls
* the stream reported and the time since the last delta.
*/
internal enum class TurnPhase { THINKING, TOOL, WAITING }
/**
* The [TurnPhase] of a turn in flight. [runningTools] are the calls the stream
* reports as still running; [silentMillis] is how long ago the last text or
* reasoning delta arrived, or null when none has (a turn that has not streamed
* yet reads as waiting rather than inventing thinking).
*/
internal fun turnPhase(runningTools: List<ChatPart>, silentMillis: Long?): TurnPhase = when {
runningTools.isNotEmpty() -> TurnPhase.TOOL
silentMillis != null && silentMillis in 0 until TURN_THINKING_WINDOW_MILLIS -> TurnPhase.THINKING
else -> TurnPhase.WAITING
}
/** The running indicator's headline for [phase], naming what is happening. */
internal fun turnPhaseLabel(phase: TurnPhase): String = when (phase) {
TurnPhase.THINKING -> "Thinking…"
TurnPhase.TOOL -> "Running a tool…"
TurnPhase.WAITING -> "Waiting…"
}
/**
* The background processes still running for a session, in the order they
* started, from the shells the server reported and the session retains. A shell
* that has exited is never listed — that is what clears the indicator — and the
* set is independent of the turn, because a background process outlives the tool
* call (and often the turn) that started it.
*/
internal fun runningBackgroundShells(shells: Map<String, ChatShell>): List<ChatShell> =
shells.values.filter { it.id.isNotBlank() && it.status == ChatProtocol.SHELL_RUNNING }
/**
* The one-line command a background process is running, collapsed to a single
* line and elided past [TOOL_DETAIL_MAX_LENGTH] like a tool call's detail, so a
* long command line cannot flood the indicator. A shell that reported no command
* reads as a generic `background process` rather than a blank line.
*/
internal fun shellCommandSummary(command: String): String {
val text = command.trim().replace(TOOL_DETAIL_WHITESPACE, " ")
if (text.isEmpty()) return "background process"
return if (text.length <= TOOL_DETAIL_MAX_LENGTH) {
text
} else {
text.take(TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…"
}
}
/**
* 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
@@ -9,6 +9,7 @@ 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.ChatShell
/**
* A saved scroll position inside one conversation. Kept as Android-free
@@ -99,6 +100,23 @@ data class ChatThread(
* [runningSince] does for the turn.
*/
val toolStartedAt: Map<String, Long> = emptyMap(),
/**
* Wall-clock epoch millis the last text or reasoning delta of the in-flight
* turn arrived, or 0 when none has. Kept on the thread so the running
* indicator can tell "thinking" (deltas still arriving) from "waiting"
* (nothing arriving) without guessing, and so it survives a chat switch like
* [runningSince]. Cleared the moment the turn settles.
*/
val lastDeltaAt: Long = 0,
/**
* The agent's shell commands still running for this session, keyed by the
* shell id the server reported and in the order they started. A background
* process can outlive the tool call (and the turn) that started it, so this is
* thread state of its own rather than part of the turn: it keeps showing after
* the turn's indicator has gone, and a shell leaves the map the moment its
* exited frame arrives. Kept on the thread so it survives a chat switch.
*/
val shells: Map<String, ChatShell> = emptyMap(),
/** The unsent composer text for this chat. */
val draft: String = "",
/**
@@ -175,6 +193,20 @@ data class ChatThread(
*/
fun toolElapsedMillis(part: ChatPart, nowMillis: Long): Long =
runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, nowMillis)
/**
* The background processes this session is still running, in start order, so
* a conversation shows what is running even when no turn is.
*/
val runningShells: List<ChatShell> get() = runningBackgroundShells(shells)
/**
* What the in-flight turn is doing at [nowMillis] (see [turnPhase]): its
* running tool calls, and how long ago the last delta arrived. Pure, so the
* indicator and its unit test share the one derivation.
*/
internal fun phase(nowMillis: Long): TurnPhase =
turnPhase(runningTools, lastDeltaAt.takeIf { it in 1 until nowMillis }?.let { nowMillis - it })
}
/**
@@ -777,7 +809,14 @@ class ChatStore(
if (ids.isEmpty()) return ids
_state.value = _state.value.copy(
open = _state.value.open.map {
if (it.running) it.copy(running = false, runningSince = 0, toolStartedAt = emptyMap()) else it
if (it.running || it.shells.isNotEmpty()) {
// A shell's exit may have been swallowed by the gap too, so the
// retained shells are dropped as well and re-learned from the
// re-subscribe's replay of the ones still running.
it.copy(running = false, runningSince = 0, toolStartedAt = emptyMap(), lastDeltaAt = 0, shells = emptyMap())
} else {
it
}
},
)
return ids
@@ -887,6 +926,7 @@ class ChatStore(
ChatProtocol.EVENT_USER -> applyRemoteUser(frame)
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
ChatProtocol.PART_TOOL -> applyTool(frame)
ChatProtocol.EVENT_SHELL -> applyShell(frame)
ChatProtocol.EVENT_STEP -> {
val started = frame.step?.status != ChatProtocol.STEP_ENDED
update(frame.sessionId) { setRunning(it, started) }
@@ -895,6 +935,27 @@ class ChatStore(
}
}
/**
* Folds one shell frame: a running shell joins the thread's background
* processes, keyed by its id and kept in start order, and an exited one leaves
* — which is what clears the indicator the moment the shell exits. It never
* marks the thread running, because a background process is not the turn: a
* shell that outlives the turn keeps showing after the turn's own indicator
* has gone, which is the one state it exists to make visible.
*/
private fun applyShell(frame: ChatEventFrame) {
val shell = frame.shell ?: return
if (shell.id.isBlank()) return
update(frame.sessionId) { thread ->
val shells = if (shell.status == ChatProtocol.SHELL_EXITED) {
thread.shells - shell.id
} else {
thread.shells + (shell.id to shell)
}
if (shells == thread.shells) thread else thread.copy(shells = shells)
}
}
/**
* Folds a user turn another client sent into the transcript, in place, once.
* The server never echoes this client's own prompts, so the sender's own
@@ -941,7 +1002,9 @@ class ChatStore(
val rawId = frame.part?.id.orEmpty()
if (rawId.isEmpty() || frame.delta.isEmpty()) return
val kind = frame.kind
upsertParts(frame) { parts ->
// A delta just arrived, so the turn is thinking right now: stamp the
// arrival so the indicator can tell thinking from waiting.
upsertParts(frame, deltaArrivedAt = now()) { parts ->
val id = deltaPartId(parts, kind, rawId)
val index = parts.indexOfFirst { it.id == id }
if (index < 0) {
@@ -970,7 +1033,11 @@ class ChatStore(
* parts with [upsert]'s result, then marks the thread running. The text and
* reasoning delta fold and the tool upsert share this so the two cannot drift.
*/
private fun upsertParts(frame: ChatEventFrame, upsert: (List<ChatPart>) -> List<ChatPart>) {
private fun upsertParts(
frame: ChatEventFrame,
deltaArrivedAt: Long? = null,
upsert: (List<ChatPart>) -> List<ChatPart>,
) {
update(frame.sessionId) { thread ->
val messages = thread.messages.toMutableList()
val index = messages.indexOfLast { it.id == frame.messageId }
@@ -989,7 +1056,8 @@ class ChatStore(
val message = messages[resolvedIndex]
messages[resolvedIndex] = message.copy(parts = upsert(message.parts))
val stamped = runningToolStamps(thread.toolStartedAt, messages, now())
setRunning(thread.copy(messages = messages, toolStartedAt = stamped), true)
val running = setRunning(thread.copy(messages = messages, toolStartedAt = stamped), true)
if (deltaArrivedAt == null) running else running.copy(lastDeltaAt = deltaArrivedAt)
}
}
@@ -1002,7 +1070,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, toolStartedAt = emptyMap())
else -> thread.copy(running = false, runningSince = 0, toolStartedAt = emptyMap(), lastDeltaAt = 0)
}
private fun update(sessionId: String, block: (ChatThread) -> ChatThread) {
@@ -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<ChatPart>) {
// 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<String?>(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<ChatPart>, 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<ChatPart>, onDismiss: () -> Unit, modifier: Modifier = Modifier) {
var expandedIds by remember { mutableStateOf<Set<String>>(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)
}
}
}
}
@@ -23,6 +23,7 @@ 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.PlayArrow
import androidx.compose.material.icons.filled.Psychology
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
@@ -56,6 +57,7 @@ import kotlinx.coroutines.launch
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.ChatShell
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
@@ -195,6 +197,7 @@ internal fun ChatTranscript(
reasoning = reasoning,
streaming = row.key == streamingTurnKey,
runningSince = thread.runningSince,
toolStartedAt = thread.toolStartedAt,
onToggleReasoning = onToggleReasoning,
)
}
@@ -293,15 +296,16 @@ private fun LazyListState.bottomDistancePx(itemCount: Int): Int? {
}
/**
* The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed
* 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
* The in-flight turn indicator: a spinner, the turn's actual state (see
* [TurnPhase] — `Thinking…` while deltas arrive, `Running a tool…` while calls are
* in flight, `Waiting…` otherwise) and its live elapsed 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 headline is derived
* from [ChatThread.phase] so the operator can tell generating from waiting on a
* command instead of watching a bare `Working…`; the elapsed values come 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`.
* and the tick loop stops the moment the turn settles.
*/
@Composable
private fun RunningIndicator(thread: ChatThread) {
@@ -317,7 +321,7 @@ private fun RunningIndicator(thread: ChatThread) {
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(turnPhaseLabel(thread.phase(now)), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
text = "· ${formatDuration(elapsedMillis / 1_000)}",
style = MaterialTheme.typography.bodySmall,
@@ -382,6 +386,58 @@ private fun RunningToolLine(part: ChatPart, elapsedMillis: Long) {
}
}
/**
* The always-visible indicator that the agent has a background process running —
* a dev server, a watching build, a sleep whose tool call has already returned.
* It is deliberately separate from the turn's spinner: a background process can
* outlive the turn, so this is shown whenever a shell is running, whether or not
* a turn is, and each line names the command the way the running-tool line names
* a call. It clears the moment the shell exits, because the exited frame removes
* it from the thread's shells. It survives a chat switch like the other live
* state, since it is read from the thread rather than held here.
*/
@Composable
internal fun BackgroundProcessBar(shells: List<ChatShell>, modifier: Modifier = Modifier) {
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = 4.dp),
) {
shells.forEach { shell ->
key(shell.id) { BackgroundProcessLine(shell) }
}
}
}
/** One background process: a distinct glyph, a `Background process` label and its command. */
@Composable
private fun BackgroundProcessLine(shell: ChatShell) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth(),
) {
Icon(
Icons.Default.PlayArrow,
contentDescription = null,
tint = MaterialTheme.colorScheme.tertiary,
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = "Background process",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.tertiary,
)
Text(
text = shellCommandSummary(shell.command),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
}
/**
* The wall clock, re-read once a second while a turn is in flight, so the
* indicator derives the elapsed time with [ChatThread.elapsedMillis] — the one
@@ -434,10 +490,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 +502,17 @@ private fun AgentTurnItem(
reasoning: ReasoningExpansion,
streaming: Boolean,
runningSince: Long,
toolStartedAt: Map<String, Long>,
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 +536,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)
}
}
@@ -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
@@ -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)
}
}
@@ -0,0 +1,211 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatEventFrame
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.ChatShell
import net.awan.pipelines.data.protocol.ChatStep
import net.awan.pipelines.data.protocol.ChatToolState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The two in-flight states a conversation now names: what a running turn is
* actually doing (thinking, running a tool or waiting) and whether a background
* process is still running. Both are derived from evidence already on the wire
* (the tool calls and delta timing the stream reports, and the shell frames), so
* they are tested as pure folds and against [ChatStore] with an injected clock —
* no device, server or Compose runtime.
*/
class ChatInFlightStateTest {
private fun tool(id: String, status: String) = ChatPart(
type = ChatProtocol.PART_TOOL,
id = id,
name = "shell",
state = ChatToolState(status = status),
)
private fun deltaFrame(sessionId: String, text: String = "hi") = ChatEventFrame(
sessionId = sessionId,
messageId = "m1",
kind = ChatProtocol.PART_TEXT,
delta = text,
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "m1#text#0"),
)
private fun toolFrame(sessionId: String, part: ChatPart) =
ChatEventFrame(sessionId = sessionId, messageId = "m1", kind = ChatProtocol.PART_TOOL, part = part)
private fun stepFrame(sessionId: String, status: String) =
ChatEventFrame(sessionId = sessionId, kind = ChatProtocol.EVENT_STEP, step = ChatStep(status = status))
private fun shellFrame(
sessionId: String,
id: String,
status: String,
command: String = "",
exit: Int? = null,
) = ChatEventFrame(
sessionId = sessionId,
kind = ChatProtocol.EVENT_SHELL,
shell = ChatShell(id = id, status = status, command = command, exit = exit),
)
// ---- Part 1: the turn's phase --------------------------------------------
@Test
fun aToolInFlightOutranksThinking() {
// A running call is named separately by the tool lines, so it is the
// phase even while deltas are still arriving.
assertEquals(TurnPhase.TOOL, turnPhase(listOf(tool("c1", ChatProtocol.TOOL_RUNNING)), silentMillis = 100L))
}
@Test
fun aRecentDeltaReadsAsThinking() {
assertEquals(TurnPhase.THINKING, turnPhase(emptyList(), silentMillis = 0L))
assertEquals(TurnPhase.THINKING, turnPhase(emptyList(), silentMillis = TURN_THINKING_WINDOW_MILLIS - 1))
}
@Test
fun silenceAndANeverStreamedTurnReadAsWaiting() {
// At the window boundary the turn has stopped arriving: waiting.
assertEquals(TurnPhase.WAITING, turnPhase(emptyList(), silentMillis = TURN_THINKING_WINDOW_MILLIS))
assertEquals(TurnPhase.WAITING, turnPhase(emptyList(), silentMillis = 10_000L))
// No delta has arrived at all: waiting, never an invented "thinking".
assertEquals(TurnPhase.WAITING, turnPhase(emptyList(), silentMillis = null))
}
@Test
fun thePhaseNamesItself() {
assertEquals("Thinking…", turnPhaseLabel(TurnPhase.THINKING))
assertEquals("Running a tool…", turnPhaseLabel(TurnPhase.TOOL))
assertEquals("Waiting…", turnPhaseLabel(TurnPhase.WAITING))
}
@Test
fun theStoreDerivesThinkingThenWaitingFromDeltaTiming() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.event(deltaFrame("s"))
val thread = store.value.thread("s")!!
// The delta arrived at 1_000; 500ms later the turn is still thinking.
assertEquals(TurnPhase.THINKING, thread.phase(1_500L))
// Past the window with no new delta the same turn reads as waiting.
clock = 5_000L
assertEquals(TurnPhase.WAITING, store.value.thread("s")!!.phase(5_000L))
}
@Test
fun aToolFrameMakesTheTurnReadAsRunningATool() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(deltaFrame("s"))
store.event(toolFrame("s", tool("c1", ChatProtocol.TOOL_RUNNING)))
assertEquals(TurnPhase.TOOL, store.value.thread("s")!!.phase(1_100L))
}
@Test
fun aSettledTurnClearsTheDeltaStamp() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(deltaFrame("s"))
store.event(stepFrame("s", ChatProtocol.STEP_ENDED))
val thread = store.value.thread("s")!!
assertFalse(thread.running)
assertEquals(0L, thread.lastDeltaAt)
}
// ---- Part 2: the background process --------------------------------------
@Test
fun onlyRunningShellsAreListed() {
val shells = mapOf(
"sh_1" to ChatShell(id = "sh_1", status = ChatProtocol.SHELL_RUNNING, command = "npm run dev"),
"sh_2" to ChatShell(id = "sh_2", status = ChatProtocol.SHELL_EXITED, command = "ls", exit = 0),
)
assertEquals(listOf("sh_1"), runningBackgroundShells(shells).map { it.id })
}
@Test
fun aCommandIsCollapsedElidedAndNeverBlank() {
assertEquals("npm run dev", shellCommandSummary(" npm run \n dev "))
val long = shellCommandSummary("x".repeat(500))
assertTrue(long.length < 500)
assertTrue(long.endsWith("…"))
assertEquals("background process", shellCommandSummary(" "))
}
@Test
fun aRunningShellIsShownAndClearedOnExit() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_RUNNING, command = "npm run dev"))
val running = store.value.thread("s")!!.runningShells
assertEquals(listOf("sh_1"), running.map { it.id })
assertEquals("npm run dev", running.single().command)
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_EXITED, exit = 0))
assertTrue(store.value.thread("s")!!.runningShells.isEmpty())
}
@Test
fun aBackgroundProcessOutlivesTheTurnItStartedIn() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(deltaFrame("s"))
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_RUNNING, command = "sleep 120"))
assertTrue(store.value.thread("s")!!.running)
// The turn settles while the shell keeps running: the spinner is gone but
// the background process is still shown rather than assumed finished.
store.event(stepFrame("s", ChatProtocol.STEP_ENDED))
val settled = store.value.thread("s")!!
assertFalse(settled.running)
assertEquals(listOf("sh_1"), settled.runningShells.map { it.id })
}
@Test
fun aBackgroundProcessSurvivesAChatSwitch() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "a", title = "a"))
store.event(shellFrame("a", "sh_1", ChatProtocol.SHELL_RUNNING, command = "npm run dev"))
store.open(ChatSession(id = "b", title = "b"))
store.activate("a")
assertEquals(listOf("sh_1"), store.value.thread("a")!!.runningShells.map { it.id })
}
@Test
fun theSameShellRepeatedDoesNotDuplicateAndAForeignOneIsKeyedApart() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_RUNNING, command = "a"))
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_RUNNING, command = "a"))
store.event(shellFrame("s", "sh_2", ChatProtocol.SHELL_RUNNING, command = "b"))
assertEquals(listOf("sh_1", "sh_2"), store.value.thread("s")!!.runningShells.map { it.id })
}
@Test
fun aShellFrameWithNoIdentityIsIgnored() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(ChatEventFrame(sessionId = "s", kind = ChatProtocol.EVENT_SHELL, shell = null))
store.event(shellFrame("s", "", ChatProtocol.SHELL_RUNNING, command = "x"))
assertTrue(store.value.thread("s")!!.runningShells.isEmpty())
}
@Test
fun resumingClearsShellsSoTheReplayCanResyncThem() {
val store = ChatStore(now = { 1_000L })
store.open(ChatSession(id = "s", title = "s"))
store.event(shellFrame("s", "sh_1", ChatProtocol.SHELL_RUNNING, command = "npm run dev"))
assertEquals(listOf("s"), store.streamResumed())
assertTrue(store.value.thread("s")!!.runningShells.isEmpty())
}
}