Merge main into chat-tool-group: combine the tool-call summary chip with the chat-activity feature

Brings the tool-call summary chip (7fbbd95) together with main's chat in-flight
state and background-process surface (7b0dc94). Both edit ChatFormat.kt and
ChatTranscript.kt; the merge combined them cleanly (no conflict markers) — the
chip's live gating (live = streaming, toolStartedAt) now sits alongside main's
turn-phase labels and background-process bar, and both sides' pure helpers
coexist.

Re-ran the repository checks on the resolved tree: gradle --offline --no-daemon
:app:testDebugUnitTest :app:assembleDebug => BUILD SUCCESSFUL; JUnit XML
aggregate classes=70 tests=680 failures=0 errors=0 skipped=0.
This commit is contained in:
2026-10-18 09:58:30 +01:00
14 changed files with 1053 additions and 34 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
@@ -215,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) {
@@ -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
@@ -294,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) {
@@ -318,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,
@@ -383,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
@@ -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())
}
}