chat: fold an agent turn into one reply, split reasoning from answer, keep tool name/input

The phone's chat transcript rendered one agent reply as ~36 bubbles, each with
its own thinking block, and a finished tool call lost its name and its input.

- Turn fold (android): ChatFormat.kt gains the pure ChatTurn / TranscriptRow /
  transcriptRows fold - each run of consecutive assistant messages between two of
  the operator's messages is one agent turn - and ChatTranscript renders one
  bubble per turn: the turn's single collapsible thinking block (all its
  reasoning, in order, growing live while it streams), then its tool-call chips,
  then one answer block of just the turn's text parts. AssistantParts/MessagePart
  are replaced by AgentTurnItem/UserMessageItem; ChatConversationPane counts the
  folded rows.
- Delta part ids (server + client): internal/protocol/chat.go adds
  ChatDeltaPartID(messageID, kind, ordinal), mirrored as ChatProtocol.deltaPartId
  in data/protocol/Chat.kt, and NormalizeChatEvent keys a text or reasoning delta
  on it. OpenCode numbers a message's text and reasoning parts independently from
  0, so the old "%s#%d" gave the first text delta and first reasoning part the
  same id: the answer was appended into the thinking block, and the server's
  retained state (chat_hub.go) re-collided on resume. ChatStore's upsert now
  routes a delta through the kind-aware deltaPartId fold, so it stays robust even
  against a peer that still shares one id.
- Tool fields (server + client): NormalizeChatEvent takes a call's arguments from
  session.tool.input.ended's text as well as session.tool.called's input object
  (toolInput), and chat_hub.go's new mergeChatToolPart folds each tool frame onto
  the retained part so the progress/success frames that omit name and input never
  blank them. ChatFormat.kt's mergeToolPart mirrors that on the client, so the
  chip and panel header keep the real tool name and the panel shows INPUT beside
  OUTPUT.

Tests: chat_v2_test.go and chat_test.go add the text/reasoning id-collision and
the tool name+input retention cases; ChatReasoningTurnTest, ChatTranscriptTest
and ChatRunningWorkTest cover the turn fold, the collision and the tool lifecycle.

Checks: Go build, vet, gofmt and the package tests pass (go build ./... &&
go vet ./...; gofmt -l . empty; go test ./internal/server ./internal/opencode
./internal/protocol ./internal/stage ./internal/pipeline; go test ./...).
Android passes offline with --no-daemon (assembleDebug and the full
testDebugUnitTest suite, 660 tests). The on-phone observation was not performed:
the device lock was held by another run and adb was not available here.

Documentation inventory checked: no packaged OpenCode skill reference in
internal/author/skill/references/ and no packaged template documents the app's
chat transcript, this delta part-id derivation or the tool-field retention, and
no internal/author/ managed file inventory entry names any touched file, so none
of them needs updating. The shared android/README.md behaviour statements are
made stale by this change and are recorded instead in
docs/notes/chat-transcript-turn-fold.md for the docs-fold writer, per the repo
rule that an item never edits a shared document itself.
This commit is contained in:
2026-10-18 01:47:52 +01:00
parent 0d1ddc73a4
commit 798e958cb7
14 changed files with 801 additions and 161 deletions
@@ -277,6 +277,16 @@ object ChatProtocol {
else -> false
}
/**
* The stable part id an incremental text/reasoning delta stream addresses,
* mirroring `ChatDeltaPartID` in `internal/protocol/chat.go`. OpenCode numbers
* one message's text and reasoning parts independently from 0, so the kind is
* part of the id: a message's first text delta and its first reasoning delta
* are distinct parts, and answer text can never be appended into the thinking
* block.
*/
fun deltaPartId(messageId: String, kind: String, ordinal: Int): String = "$messageId#$kind#$ordinal"
/**
* The `chat_prompt` frame the composer sends. [files] are the attached files'
* URIs, in the order they were attached, and are omitted when empty (the
@@ -102,10 +102,12 @@ internal fun ChatConversationPane(
// A turn blocked on an approval is not generating, so the running indicator
// (and its ticking clock) stands down while the card is unanswered.
val showRunning = thread.running && !awaiting
// The count of the transcript's items: the messages, the local command lines,
// the running indicator while a turn is in flight and a pending approval card,
// which is the last item the top bar's approval action jumps to.
val itemCount = thread.messages.size + thread.notices.size +
// The count of the transcript's items: its rows (the operator's messages and
// the folded agent replies), the local command lines, the running indicator
// while a turn is in flight and a pending approval card, which is the last
// item the top bar's approval action jumps to.
val rows = transcriptRows(thread.messages)
val itemCount = rows.size + thread.notices.size +
(if (showRunning) 1 else 0) + (if (approval != null) 1 else 0)
// The position the operator left this conversation at, read once: a
// conversation with none of its own opens at its newest message instead (see
@@ -219,6 +221,7 @@ internal fun ChatConversationPane(
)
else -> ChatTranscript(
thread = thread,
rows = rows,
listState = listState,
savedScroll = savedScroll,
itemCount = itemCount,
@@ -180,6 +180,53 @@ internal fun runningToolStamps(
return stamps
}
/**
* The id a text or reasoning delta must be applied to for [kind] within [parts].
* The broker gives the two kinds distinct ids (see `ChatDeltaPartID`), but a peer
* that still shares one id between them must never have answer text appended into
* a reasoning part (or the reverse): when another kind already holds the bare id,
* the delta is moved onto a suffixed id of its own so the two kinds stay in
* separate parts. Once a part of this kind exists under either id, that part is
* the one addressed, so a stream keeps growing the part it started.
*/
internal fun deltaPartId(parts: List<ChatPart>, kind: String, id: String): String {
if (parts.any { it.type == kind && it.id == id }) return id
val suffixed = "$id#$kind"
if (parts.any { it.type == kind && it.id == suffixed }) return suffixed
return if (parts.any { it.id == id }) suffixed else id
}
/**
* Folds one tool frame's part onto the part retained from earlier frames. A tool
* call is reported across several frames that each carry only part of it (the name
* in `input.started`, the arguments in `input.ended`'s text or `called`'s input,
* then `progress`/`success` carrying neither), so a field already learned is never
* blanked by a later frame that omits it. A non-empty incoming field wins;
* otherwise the retained value is kept.
*/
internal fun mergeToolPart(previous: ChatPart?, incoming: ChatPart): ChatPart {
if (previous == null) return incoming
val priorState = previous.state
val incomingState = incoming.state
return incoming.copy(
type = incoming.type.ifBlank { previous.type },
name = incoming.name.ifBlank { previous.name },
executed = incoming.executed || previous.executed,
time = incoming.time ?: previous.time,
state = when {
incomingState == null -> priorState
priorState == null -> incomingState
else -> incomingState.copy(
status = incomingState.status.ifBlank { priorState.status },
input = incomingState.input ?: priorState.input,
content = incomingState.content.ifEmpty { priorState.content },
metadata = incomingState.metadata ?: priorState.metadata,
error = incomingState.error ?: priorState.error,
)
},
)
}
/**
* 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
@@ -378,6 +425,92 @@ internal fun turnReasoning(parts: List<ChatPart>): ReasoningTurn =
.map { it.text },
)
/**
* One agent reply: everything the agent produced between two of the operator's
* messages, however many model steps that took. OpenCode reports a turn as one
* assistant message per step, so this is the single fold the transcript uses to
* render a reply as one bubble — the turn's thinking block, then its tool-call
* chips, then its answer — instead of one bubble (and one thinking block) per
* step.
*/
internal data class ChatTurn(val key: String, val parts: List<ChatPart>) {
/** The turn's reasoning, folded into the one block the transcript shows first. */
val reasoning: ReasoningTurn get() = turnReasoning(parts)
/** The turn's tool calls, in the order the agent made them. */
val tools: List<ChatPart> get() = parts.filter { it.type == ChatProtocol.PART_TOOL }
/**
* The turn's answer: just its text parts, joined in order. Reasoning feeds the
* folded thinking block and a tool call its chip, so the answer block never
* carries thinking or a command.
*/
val answer: String
get() = parts
.filter {
it.type != ChatProtocol.PART_TOOL &&
(partRendering(it) == PartRendering.MARKDOWN || partRendering(it) == PartRendering.PLAIN)
}
.joinToString("\n\n") { it.text }
/** The turn's own timing, or null when its parts carry none. */
val elapsedMillis: Long? get() = turnElapsedMillis(parts)
/** Whether the turn has anything to draw; an empty turn renders no bubble. */
val visible: Boolean get() = reasoning.count > 0 || tools.isNotEmpty() || answer.isNotBlank()
}
/**
* One item of the transcript: an operator message, or one folded agent reply. The
* key is stable as a reply grows — an agent turn is keyed by its first message id
* — so the list is not rebuilt and an expanded thinking block keeps its state as
* new steps stream in.
*/
internal sealed interface TranscriptRow {
val key: String
data class User(val message: ChatMessage) : TranscriptRow {
override val key: String get() = message.id
}
data class Agent(val turn: ChatTurn) : TranscriptRow {
override val key: String get() = turn.key
}
}
/**
* The transcript's rows for [messages]: each run of consecutive assistant
* messages folds into one [TranscriptRow.Agent], and each of the operator's own
* messages is its own [TranscriptRow.User]. This is the one fold that makes a
* reply a single bubble, so the transcript and its tests cannot disagree about
* where one agent turn ends and the next begins.
*/
internal fun transcriptRows(messages: List<ChatMessage>): List<TranscriptRow> {
val rows = ArrayList<TranscriptRow>(messages.size)
var turnKey: String? = null
var parts = ArrayList<ChatPart>()
fun flush() {
val key = turnKey
if (key != null) {
val turn = ChatTurn(key, parts)
if (turn.visible) rows.add(TranscriptRow.Agent(turn))
}
turnKey = null
parts = ArrayList()
}
for (message in messages) {
if (message.role == ChatProtocol.ROLE_ASSISTANT) {
if (turnKey == null) turnKey = message.id
parts.addAll(message.parts)
} else {
flush()
rows.add(TranscriptRow.User(message))
}
}
flush()
return rows
}
/** The live label of a single-step turn's reasoning block while it streams. */
private const val REASONING_STREAMING_LABEL = "Thinking…"
@@ -938,45 +938,56 @@ class ChatStore(
}
private fun applyDelta(frame: ChatEventFrame) {
val partId = frame.part?.id.orEmpty()
if (partId.isEmpty() || frame.delta.isEmpty()) return
upsertPart(frame, partId) { existing ->
existing?.copy(text = existing.text + frame.delta)
?: ChatPart(type = frame.kind, id = partId, text = frame.delta)
val rawId = frame.part?.id.orEmpty()
if (rawId.isEmpty() || frame.delta.isEmpty()) return
val kind = frame.kind
upsertParts(frame) { parts ->
val id = deltaPartId(parts, kind, rawId)
val index = parts.indexOfFirst { it.id == id }
if (index < 0) {
parts + ChatPart(type = kind, id = id, text = frame.delta)
} else {
parts.toMutableList().also { it[index] = it[index].copy(text = it[index].text + frame.delta) }
}
}
}
private fun applyTool(frame: ChatEventFrame) {
val part = frame.part ?: return
if (part.id.isEmpty()) return
upsertPart(frame, part.id) { part }
val incoming = frame.part ?: return
if (incoming.id.isEmpty()) return
upsertParts(frame) { parts ->
val index = parts.indexOfFirst { it.id == incoming.id && it.type == ChatProtocol.PART_TOOL }
if (index < 0) {
parts + mergeToolPart(null, incoming)
} else {
parts.toMutableList().also { it[index] = mergeToolPart(it[index], incoming) }
}
}
}
/**
* Finds or creates the assistant message [frame] targets and the part [partId]
* inside it, replacing it via [upsert] (the old part when it exists, else
* null), then marks the thread running. The text/reasoning delta and the tool
* upsert share this so the two cannot drift.
* Finds or creates the assistant message [frame] targets and replaces its
* 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 upsertPart(frame: ChatEventFrame, partId: String, upsert: (ChatPart?) -> ChatPart) {
private fun upsertParts(frame: ChatEventFrame, upsert: (List<ChatPart>) -> List<ChatPart>) {
update(frame.sessionId) { thread ->
val messages = thread.messages.toMutableList()
val index = messages.indexOfLast { it.id == frame.messageId }
val message = if (index >= 0) {
messages[index]
val resolvedIndex = if (index >= 0) {
index
} else {
ChatMessage(
id = frame.messageId,
sessionId = frame.sessionId,
role = ChatProtocol.ROLE_ASSISTANT,
).also { messages.add(it) }
messages.add(
ChatMessage(
id = frame.messageId,
sessionId = frame.sessionId,
role = ChatProtocol.ROLE_ASSISTANT,
),
)
messages.lastIndex
}
val resolvedIndex = if (index >= 0) index else messages.lastIndex
val parts = message.parts.toMutableList()
val partIndex = parts.indexOfFirst { it.id == partId }
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)
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)
}
@@ -85,6 +85,7 @@ private const val CHAT_ELAPSED_TICK_MILLIS = 1_000L
@Composable
internal fun ChatTranscript(
thread: ChatThread,
rows: List<TranscriptRow>,
listState: LazyListState,
savedScroll: ChatScrollPosition?,
itemCount: Int,
@@ -177,22 +178,26 @@ internal fun ChatTranscript(
}
Box(Modifier.fillMaxSize()) {
// Only the newest turn can be streaming, so its reasoning wears the live
// label; a settled turn's reasoning is labelled as settled.
val streamingMessageId = thread.messages.lastOrNull()?.id?.takeIf { thread.running }
// label; a settled turn's reasoning is labelled as settled. The turn is
// the transcript's last row only while it is the turn in flight.
val streamingTurnKey = (rows.lastOrNull() as? TranscriptRow.Agent)?.key?.takeIf { thread.running }
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom),
) {
items(thread.messages, key = { it.id }) { message ->
MessageItem(
message = message,
reasoning = reasoning,
streaming = message.id == streamingMessageId,
runningSince = thread.runningSince,
onToggleReasoning = onToggleReasoning,
)
items(rows, key = { it.key }) { row ->
when (row) {
is TranscriptRow.User -> UserMessageItem(row.message)
is TranscriptRow.Agent -> AgentTurnItem(
turn = row.turn,
reasoning = reasoning,
streaming = row.key == streamingTurnKey,
runningSince = thread.runningSince,
onToggleReasoning = onToggleReasoning,
)
}
}
// A slash command reports as its own line, after the turns it acted
// between and visually distinct from any message to the agent.
@@ -398,8 +403,45 @@ private fun rememberElapsedNow(runningSince: Long): Long {
}
@Composable
private fun MessageItem(
message: ChatMessage,
private fun UserMessageItem(message: ChatMessage) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
) {
Surface(
shape = RoundedCornerShape(CHAT_GUTTER),
color = MaterialTheme.colorScheme.secondaryContainer,
modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP),
) {
SelectionContainer {
Column(Modifier.padding(CHAT_GUTTER)) {
// A user turn another device sent is attributed to it, so the
// transcript says who sent the message. Our own messages carry
// no label.
if (message.client.isNotBlank()) {
Text(
text = message.client,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
UserParts(message.parts)
}
}
}
}
}
/**
* 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
* 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.
*/
@Composable
private fun AgentTurnItem(
turn: ChatTurn,
reasoning: ReasoningExpansion,
streaming: Boolean,
runningSince: Long,
@@ -414,46 +456,29 @@ private fun MessageItem(
val now = rememberElapsedNow(runningSince)
if (runningSince < now) now - runningSince else 0L
} else {
turnElapsedMillis(message.parts)
turn.elapsedMillis
}
val isUser = message.role == ChatProtocol.ROLE_USER
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
horizontalArrangement = Arrangement.Start,
) {
Surface(
shape = RoundedCornerShape(CHAT_GUTTER),
color = if (isUser) {
MaterialTheme.colorScheme.secondaryContainer
} else {
MaterialTheme.colorScheme.surfaceContainer
},
color = MaterialTheme.colorScheme.surfaceContainer,
modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP),
) {
SelectionContainer {
Column(Modifier.padding(CHAT_GUTTER)) {
if (isUser) {
// A user turn another device sent is attributed to it, so
// the transcript says who sent the message. Our own
// messages carry no label.
if (message.client.isNotBlank()) {
Text(
text = message.client,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
UserParts(message.parts)
} else {
AssistantParts(
messageId = message.id,
parts = message.parts,
reasoning = reasoning,
streaming = streaming,
elapsedMillis = elapsedMillis,
onToggleReasoning = onToggleReasoning,
)
}
val turnKey = reasoningTurnKey(turn.key)
ReasoningBlock(
turn = turn.reasoning,
expanded = reasoning.isExpanded(turnKey),
streaming = streaming,
elapsedMillis = elapsedMillis,
onToggle = { onToggleReasoning(turnKey) },
)
if (turn.tools.isNotEmpty()) ToolCalls(turn.tools)
if (turn.answer.isNotBlank()) MarkdownText(turn.answer)
}
}
}
@@ -462,7 +487,7 @@ private fun MessageItem(
/**
* A user turn: its text, then the files that rode with it. The attachments are
* the same [ChatProtocol.PART_FILE] parts [MessageItem] already renders, so the
* the same [ChatProtocol.PART_FILE] parts the user bubble already renders, so the
* sent message shows its file in the transcript through the one display path
* rather than a second attachment list under the bubble.
*/
@@ -478,73 +503,6 @@ private fun UserParts(parts: List<ChatPart>) {
}
}
/**
* An assistant turn's parts in order, with each run of consecutive tool calls
* rendered as one wrapping chip group (mirroring the reference transcript's
* `_ToolCalls`, research §1.3): the calls of a turn sit together on as few lines
* as they fit, instead of each taking a row, so the transcript stays scannable.
*
* The turn's reasoning is folded into exactly one collapsible block, anchored
* where the turn's first reasoning part sits, so a turn that reasons several
* times is one entry rather than a stack of boxes and a streaming turn grows the
* block it has instead of gaining another.
*/
@Composable
private fun AssistantParts(
messageId: String,
parts: List<ChatPart>,
reasoning: ReasoningExpansion,
streaming: Boolean,
elapsedMillis: Long?,
onToggleReasoning: (String) -> Unit,
) {
val turn = turnReasoning(parts)
val turnKey = reasoningTurnKey(messageId)
var index = 0
var reasoningShown = false
while (index < parts.size) {
val part = parts[index]
when {
part.type == ChatProtocol.PART_TOOL -> {
var end = index
while (end < parts.size && parts[end].type == ChatProtocol.PART_TOOL) end++
ToolCalls(parts.subList(index, end))
index = end
}
partRendering(part) == PartRendering.REASONING -> {
if (!reasoningShown) {
reasoningShown = true
ReasoningBlock(
turn = turn,
expanded = reasoning.isExpanded(turnKey),
streaming = streaming,
elapsedMillis = elapsedMillis,
onToggle = { onToggleReasoning(turnKey) },
)
}
index++
}
else -> {
MessagePart(part)
index++
}
}
}
}
@Composable
private fun MessagePart(part: ChatPart) {
when (partRendering(part)) {
PartRendering.MARKDOWN -> MarkdownText(part.text)
// Reasoning is folded into the turn's one block by [AssistantParts]; a
// reasoning part never reaches here, but rendering nothing keeps this
// exhaustive and safe if one ever did.
PartRendering.REASONING -> Unit
PartRendering.PLAIN -> Text(part.text, style = MaterialTheme.typography.bodyMedium)
PartRendering.HIDDEN -> Unit
}
}
/**
* A turn's reasoning: one compact, muted line that names the block — its step
* count when it reasoned more than once, and its elapsed time when the turn's own
@@ -1,6 +1,7 @@
package net.awan.pipelines.ui.chat
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
@@ -117,6 +118,77 @@ class ChatReasoningTurnTest {
assertFalse(reasoning.isExpanded(reasoningTurnKey("m2")))
}
@Test
fun aTextDeltaAndAReasoningDeltaInOneMessageNeverShareAPart() {
val store = ChatStore()
store.open(ChatSession(id = "s", title = "s"))
store.history("s", emptyList())
// The broker numbers a message's text and reasoning independently from 0,
// so a peer that still keyed both off the bare ordinal addresses the same
// id for the two kinds: the client must keep them apart anyway, or the
// answer is appended into the thinking block.
store.event(reasoningDelta("s", "m1", "m1#0", "thinking"))
store.event(textDelta("s", "m1", "m1#0", "answer"))
val message = store.value.thread("s")!!.messages.single()
val reasoning = message.parts.single { it.type == ChatProtocol.PART_REASONING }
val answer = message.parts.single { it.type == ChatProtocol.PART_TEXT }
assertEquals("thinking", reasoning.text)
assertEquals("answer", answer.text)
// A later text delta on the same id keeps growing the answer part and
// never touches the reasoning part.
store.event(textDelta("s", "m1", "m1#0", "!"))
val grown = store.value.thread("s")!!.messages.single()
assertEquals("answer!", grown.parts.single { it.type == ChatProtocol.PART_TEXT }.text)
assertEquals("thinking", grown.parts.single { it.type == ChatProtocol.PART_REASONING }.text)
// The broker's own derivation gives the two kinds distinct ids, and the
// client's mirror produces the same ids.
assertEquals("m1#text#0", ChatProtocol.deltaPartId("m1", ChatProtocol.PART_TEXT, 0))
assertEquals("m1#reasoning#0", ChatProtocol.deltaPartId("m1", ChatProtocol.PART_REASONING, 0))
assertFalse(
ChatProtocol.deltaPartId("m1", ChatProtocol.PART_TEXT, 0) ==
ChatProtocol.deltaPartId("m1", ChatProtocol.PART_REASONING, 0),
)
}
@Test
fun agentStepsBetweenTwoUserMessagesFoldIntoOneTurn() {
// The step-by-step reply a live agent produces: several assistant messages,
// then the final one carrying the answer beside its reasoning. They are one
// turn — one bubble, one thinking block, one answer — and the operator's
// next message starts a new one.
val messages = listOf(
ChatMessage(id = "u1", role = ChatProtocol.ROLE_USER, parts = listOf(text("t", "do it"))),
ChatMessage(id = "m0", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(reasoning("r0", "thought 0"), ChatPart(type = ChatProtocol.PART_TOOL, id = "c0", name = "shell"))),
ChatMessage(id = "m1", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(reasoning("r1", "thought 1"), ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", name = "read"))),
ChatMessage(id = "m2", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(reasoning("r2", "thought 2"), text("t2", "the answer"))),
ChatMessage(id = "u2", role = ChatProtocol.ROLE_USER, parts = listOf(text("t", "again"))),
)
val rows = transcriptRows(messages)
assertEquals(listOf("u1", "m0", "u2"), rows.map { it.key })
val turn = (rows[1] as TranscriptRow.Agent).turn
// The turn is keyed by its first message id, so its expansion state and the
// list key survive the later steps.
assertEquals("m0", turn.key)
assertEquals(3, turn.reasoning.count)
assertEquals("thought 0\n\nthought 1\n\nthought 2", turn.reasoning.text)
assertEquals(listOf("c0", "c1"), turn.tools.map { it.id })
assertEquals("the answer", turn.answer)
}
private fun textDelta(sessionId: String, messageId: String, partId: String, delta: String) =
ChatEventFrame(
sessionId = sessionId,
messageId = messageId,
kind = ChatProtocol.PART_TEXT,
delta = delta,
part = ChatPart(type = ChatProtocol.PART_TEXT, id = partId),
)
private fun reasoningDelta(sessionId: String, messageId: String, partId: String, delta: String) =
ChatEventFrame(
sessionId = sessionId,
@@ -8,6 +8,7 @@ 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.ChatToolContent
import net.awan.pipelines.data.protocol.ChatToolState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -160,6 +161,50 @@ class ChatRunningWorkTest {
assertEquals(4_000L, store.value.thread("s")!!.toolElapsedMillis(call, clock))
}
@Test
fun aToolCallKeepsItsNameAndInputForItsWholeLifecycle() {
val store = ChatStore()
store.open(ChatSession(id = "s", title = "s"))
store.history("s", emptyList())
// The verified frame sequence: the name arrives only in input.started,
// the arguments in called's input, and progress/success carry neither.
store.event(toolFrame("s", "m1", ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", name = "shell", state = ChatToolState(status = ChatProtocol.TOOL_STREAMING))))
store.event(toolFrame("s", "m1", ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", state = ChatToolState(status = ChatProtocol.TOOL_RUNNING, input = input("command" to "ls")))))
store.event(toolFrame("s", "m1", ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", state = ChatToolState(status = ChatProtocol.TOOL_RUNNING, metadata = JsonObject(mapOf("exit" to JsonPrimitive(0)))))))
store.event(toolFrame("s", "m1", ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", state = ChatToolState(status = ChatProtocol.TOOL_COMPLETED, content = listOf(ChatToolContent(type = "text", text = "ok"))))))
val part = store.value.thread("s")!!.messages.single().parts.single()
// Nothing blanked the name or the input the earlier frames taught it.
assertEquals("shell", toolLabel(part))
assertEquals("ls", toolDetail(part))
assertEquals("ok", toolOutputText(part.state))
assertEquals(ChatProtocol.TOOL_COMPLETED, part.state?.status)
assertEquals(JsonPrimitive(0), part.state?.metadata?.get("exit"))
}
@Test
fun aStreamingArgumentStringIsShownWhileTheCallRuns() {
val store = ChatStore()
store.open(ChatSession(id = "s", title = "s"))
store.event(
toolFrame(
"s", "m1",
ChatPart(
type = ChatProtocol.PART_TOOL,
id = "c1",
name = "edit",
state = ChatToolState(status = ChatProtocol.TOOL_STREAMING, input = JsonPrimitive("{\"filePath\"")),
),
),
)
val call = store.value.thread("s")!!.messages.single().parts.single()
// A partial-JSON argument string is kept and shown verbatim; it has no
// object key to describe the call yet, so the detail stays absent.
assertEquals("{\"filePath\"", prettyToolInput(call.state?.input))
assertNull(toolDetail(call))
}
@Test
fun toolDetailPrefersDescriptionThenCommandAndIgnoresWhatItCannotRead() {
// A description wins over a command when both are present.
@@ -1,5 +1,6 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import org.junit.Assert.assertEquals
@@ -148,4 +149,42 @@ class ChatTranscriptTest {
// ...and a single open chat leaves nothing to switch to.
assertEquals(emptyList<ChatThread>(), openChatsBeside(listOf(a), "a"))
}
@Test
fun eachConversationalRunOfAgentStepsIsOneRowAndItsTextPartsJoinInOrder() {
// Two user messages with two agent steps between the first pair: the agent
// steps are one turn (one bubble), not one row each, and their text parts
// are one answer joined in order.
val messages = listOf(
ChatMessage(id = "u1", role = ChatProtocol.ROLE_USER, parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = "one"))),
ChatMessage(id = "a1", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "p1", text = "first"))),
ChatMessage(id = "a2", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(ChatPart(type = ChatProtocol.PART_TOOL, id = "c1", name = "shell"), ChatPart(type = ChatProtocol.PART_TEXT, id = "p2", text = "second"))),
ChatMessage(id = "u2", role = ChatProtocol.ROLE_USER, parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = "two"))),
ChatMessage(id = "a3", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "p3", text = "third"))),
)
val rows = transcriptRows(messages)
assertEquals(listOf("u1", "a1", "u2", "a3"), rows.map { it.key })
assertEquals(
listOf("u1", "u2"),
rows.filterIsInstance<TranscriptRow.User>().map { it.key },
)
val first = (rows[1] as TranscriptRow.Agent).turn
assertEquals("first\n\nsecond", first.answer)
assertEquals(listOf("c1"), first.tools.map { it.id })
assertEquals("third", (rows[3] as TranscriptRow.Agent).turn.answer)
}
@Test
fun anAgentMessageWithNothingToDrawAddsNoRow() {
// An assistant message whose parts are all empty (or reasoning without
// text) has nothing to draw, so it folds away instead of leaving a blank
// bubble; a following user message is still its own row.
val rows = transcriptRows(
listOf(
ChatMessage(id = "a1", role = ChatProtocol.ROLE_ASSISTANT, parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "p1"))),
ChatMessage(id = "u1", role = ChatProtocol.ROLE_USER, parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = "hi"))),
),
)
assertEquals(listOf("u1"), rows.map { it.key })
}
}