From ec6a350a17ee480eae2015beeda571998cd516e3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 17 Oct 2026 23:46:00 +0100 Subject: [PATCH] Group a chat turn's reasoning into one collapsible block MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chat rendered every reasoning part as its own ReasoningBlock, so a turn that reasoned several times stacked several thinking boxes between messages. This folds a turn's reasoning parts into a single collapsible entry, anchored where the turn's first reasoning part sits, so a streaming turn grows the block it has instead of gaining another. - ChatFormat.kt: add ReasoningTurn / turnReasoning (the ordered fold of a turn's reasoning parts), reasoningLabel (counted wording for >1 steps, plain one-block wording otherwise) and turnElapsedMillis (elapsed from the turn's own part timing envelopes, null when unknown). ReasoningExpansion is now keyed by the turn's message id via reasoningTurnKey rather than a per-part key. - ChatTranscript.kt: AssistantParts renders exactly one ReasoningBlock per turn (first reasoning part wins the anchor); the collapsed line reads "Thinking · N steps"/"Reasoning · N steps" when the turn reasoned more than once, else "Thinking…"/"Reasoning", with elapsed time appended when known. Streaming elapsed is driven by thread.runningSince so it matches the running indicator. The answer, tool chips, diff cards, attachments and approval cards are untouched. - Tests: ChatTranscriptTest exercises the turn-keyed expansion; new ChatReasoningTurnTest covers the fold (several parts -> one entry in order), the collapsed wording, elapsed derivation and a streaming turn appending into the same entry. Checked for stale packaged artefacts: none needs updating. The packaged authoring skill references (internal/author/skill/references/) document the protocol (reasoning deltas, cost/token budgets), not the Android transcript rendering, so nothing there describes per-part thinking blocks. No packaged template mentions reasoning rendering. Shared docs / the Android area map are left to the single documentation writer; nothing here changes documented behaviour beyond the transcript fold. Verified with the Android toolchain (no daemon): :app:testDebugUnitTest passes 567 tests, 0 failures, 0 errors, including ChatReasoningTurnTest (5), ChatTranscriptTest (7) and DimensTest (2). No new raw geometry literals. --- .../net/awan/pipelines/ui/chat/ChatFormat.kt | 81 +++++++++-- .../awan/pipelines/ui/chat/ChatTranscript.kt | 109 +++++++++------ .../ui/chat/ChatReasoningTurnTest.kt | 128 ++++++++++++++++++ .../pipelines/ui/chat/ChatTranscriptTest.kt | 35 +++-- 4 files changed, 281 insertions(+), 72 deletions(-) create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/ChatReasoningTurnTest.kt diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index 563d261b..d50c87cc 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -199,7 +199,7 @@ internal fun openChatsBeside(open: List, activeSessionId: String): L /** * How the transcript renders one part. The decision is pure so the markdown * route out of the transcript can be tested without Compose: assistant text is - * markdown, reasoning is its own collapsed presentation, any other part with + * markdown, reasoning feeds the turn's one folded block, any other part with * text is plain, and an empty part renders nothing. */ internal enum class PartRendering { MARKDOWN, REASONING, PLAIN, HIDDEN } @@ -212,22 +212,81 @@ internal fun partRendering(part: ChatPart): PartRendering = when { } /** - * Which reasoning parts the operator has opened. A set keyed by the stable - * per-part key, so a streaming part keeps its state as deltas arrive and every - * part starts collapsed in a freshly opened conversation. + * Which turns' reasoning the operator has opened. A set keyed by the turn's own + * stable key, so a streaming turn keeps its state as deltas arrive — the block is + * not rebuilt when the turn grows — and every turn starts collapsed in a freshly + * opened conversation. */ internal data class ReasoningExpansion(private val expanded: Set = emptySet()) { - fun isExpanded(partKey: String): Boolean = partKey in expanded + fun isExpanded(turnKey: String): Boolean = turnKey in expanded - fun toggled(partKey: String): ReasoningExpansion { - if (partKey.isBlank()) return this - return copy(expanded = if (partKey in expanded) expanded - partKey else expanded + partKey) + fun toggled(turnKey: String): ReasoningExpansion { + if (turnKey.isBlank()) return this + return copy(expanded = if (turnKey in expanded) expanded - turnKey else expanded + turnKey) } } -/** The stable key for one reasoning part, even when the server omitted its id. */ -internal fun reasoningKey(messageId: String, part: ChatPart, index: Int): String = - messageId + ":" + part.id.ifBlank { index.toString() } +/** The stable key for one turn's single reasoning block: the turn's own message id. */ +internal fun reasoningTurnKey(messageId: String): String = messageId + +/** + * One assistant turn's reasoning, folded into the single collapsible block the + * transcript shows. [steps] are the reasoning parts that carry text, in the order + * the server sent them; a turn that reasons several times is therefore one entry + * rather than a stack of them. + */ +internal data class ReasoningTurn(val steps: List) { + val count: Int get() = steps.size + val empty: Boolean get() = steps.isEmpty() + + /** The turn's reasoning as the one expanded block reads it, steps in order. */ + val text: String get() = steps.joinToString("\n\n") +} + +/** + * The reasoning of a turn — every reasoning part with text, in order. The one + * fold the transcript and its tests share, so "one block per turn" is a single + * derivation rather than a rule each call site re-implements. + */ +internal fun turnReasoning(parts: List): ReasoningTurn = + ReasoningTurn( + parts.filter { it.type == ChatProtocol.PART_REASONING && it.text.isNotBlank() } + .map { it.text }, + ) + +/** The live label of a single-step turn's reasoning block while it streams. */ +private const val REASONING_STREAMING_LABEL = "Thinking…" + +/** The settled label of a single-step turn's reasoning block. */ +private const val REASONING_SETTLED_LABEL = "Reasoning" + +/** + * The collapsed thinking line's label. A turn that reasoned once keeps the plain + * one-block wording — a count of one is never shown — while a turn that reasoned + * several times reads as its step count, so the operator can tell before opening + * it how much thinking there is. + */ +internal fun reasoningLabel(count: Int, streaming: Boolean): String = when { + count > 1 && streaming -> "Thinking · $count steps" + count > 1 -> "Reasoning · $count steps" + streaming -> REASONING_STREAMING_LABEL + else -> REASONING_SETTLED_LABEL +} + +/** + * The elapsed time the server's own timing gives a settled turn: from the + * earliest start to the latest completion across the parts that carry a timing + * envelope (a tool call reports both). Null when the turn carries no usable + * timing, so the collapsed line shows a duration only when there is one to show + * rather than guessing one. + */ +internal fun turnElapsedMillis(parts: List): Long? { + val start = parts.mapNotNull { part -> + part.time?.let { if (it.ran > 0) it.ran else it.created }?.takeIf { it > 0 } + }.minOrNull() ?: return null + val end = parts.mapNotNull { it.time?.completed?.takeIf { it > 0 } }.maxOrNull() ?: return null + return (end - start).takeIf { it > 0 } +} /** Which action the composer's single primary control offers for a chat. */ enum class ComposerAction { Send, Stop } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt index 8eb37d9f..ddb3f115 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt @@ -184,6 +184,7 @@ internal fun ChatTranscript( message = message, reasoning = reasoning, streaming = message.id == streamingMessageId, + runningSince = thread.runningSince, onToggleReasoning = onToggleReasoning, ) } @@ -320,8 +321,20 @@ private fun MessageItem( message: ChatMessage, reasoning: ReasoningExpansion, streaming: Boolean, + runningSince: 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. + val elapsedMillis: Long? = if (streaming && runningSince > 0) { + val now = rememberElapsedNow(runningSince) + if (runningSince < now) now - runningSince else 0L + } else { + turnElapsedMillis(message.parts) + } val isUser = message.role == ChatProtocol.ROLE_USER Row( modifier = Modifier.fillMaxWidth(), @@ -346,6 +359,7 @@ private fun MessageItem( parts = message.parts, reasoning = reasoning, streaming = streaming, + elapsedMillis = elapsedMillis, onToggleReasoning = onToggleReasoning, ) } @@ -378,6 +392,11 @@ private fun UserParts(parts: List) { * 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( @@ -385,67 +404,75 @@ private fun AssistantParts( parts: List, 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) { - if (parts[index].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 - } else { - val part = parts[index] - MessagePart( - part = part, - reasoningKey = reasoningKey(messageId, part, index), - reasoning = reasoning, - streaming = streaming, - onToggleReasoning = onToggleReasoning, - ) - index++ + 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, - reasoningKey: String, - reasoning: ReasoningExpansion, - streaming: Boolean, - onToggleReasoning: (String) -> Unit, -) { +private fun MessagePart(part: ChatPart) { when (partRendering(part)) { PartRendering.MARKDOWN -> MarkdownText(part.text) - PartRendering.REASONING -> ReasoningBlock( - text = part.text, - expanded = reasoning.isExpanded(reasoningKey), - streaming = streaming, - onToggle = { onToggleReasoning(reasoningKey) }, - ) + // 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 } } /** - * Reasoning is visually secondary and collapsed by default: one compact, muted - * line per part (its spinner-free label names the state; the live label is - * `Thinking…`) that expands on tap to the full, still-muted text. The expansion - * state lives on the conversation, so it survives the transcript disposing the - * item while the operator scrolls and a streaming part keeps its state as - * deltas arrive. + * 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 + * timing is known — and expands on tap to the whole turn's reasoning in order, + * still muted so it stays secondary to the answer. The expansion state lives on + * the conversation keyed by the turn, so it survives the transcript disposing the + * item while the operator scrolls and a streaming turn keeps it as deltas arrive. */ @Composable private fun ReasoningBlock( - text: String, + turn: ReasoningTurn, expanded: Boolean, streaming: Boolean, + elapsedMillis: Long?, onToggle: () -> Unit, ) { - if (text.isBlank()) return - val label = if (streaming) REASONING_STREAMING_LABEL else REASONING_SETTLED_LABEL + if (turn.empty) return + val label = reasoningLabel(turn.count, streaming) + val duration = elapsedMillis?.let { formatDuration(it / 1_000) } Column(Modifier.fillMaxWidth()) { Row( verticalAlignment = Alignment.CenterVertically, @@ -463,7 +490,7 @@ private fun ReasoningBlock( modifier = Modifier.size(ICON_INLINE_DP), ) Text( - text = label, + text = if (duration != null) "$label · $duration" else label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), @@ -477,7 +504,7 @@ private fun ReasoningBlock( } if (expanded) { Text( - text = text, + text = turn.text, style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Default), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = ICON_INLINE_DP + CHAT_ITEM_GAP, bottom = CHAT_ITEM_GAP), @@ -485,7 +512,3 @@ private fun ReasoningBlock( } } } - -/** The live and settled labels of a reasoning part's one collapsed line. */ -private const val REASONING_STREAMING_LABEL = "Thinking…" -private const val REASONING_SETTLED_LABEL = "Reasoning" diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatReasoningTurnTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatReasoningTurnTest.kt new file mode 100644 index 00000000..f1fd4d4d --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatReasoningTurnTest.kt @@ -0,0 +1,128 @@ +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.ChatTime +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A turn's reasoning is one collapsible entry, not one per part: the fold into a + * single block, its ordered contents, its collapsed wording, the elapsed time the + * turn's own timing supplies, and a streaming turn that grows the block it has + * rather than adding another. All pure (or driven straight against [ChatStore] + * with an injected clock), so no device, server or Compose runtime is needed. + */ +class ChatReasoningTurnTest { + + private fun reasoning(id: String, text: String) = + ChatPart(type = ChatProtocol.PART_REASONING, id = id, text = text) + + private fun text(id: String, value: String) = ChatPart(type = ChatProtocol.PART_TEXT, id = id, text = value) + + @Test + fun everyReasoningPartOfATurnFoldsIntoExactlyOneEntryInOrder() { + // Three reasoning parts with an answer and a tool call between them are + // still one entry: the fold yields a single [ReasoningTurn]. + val parts = listOf( + reasoning("r1", "first thought"), + text("t1", "an answer"), + reasoning("r2", "second thought"), + ChatPart(type = ChatProtocol.PART_TOOL, id = "tool1", name = "read"), + reasoning("r3", "third thought"), + ) + + val turn = turnReasoning(parts) + assertFalse(turn.empty) + assertEquals(3, turn.count) + // The steps keep the server's order, regardless of the parts between them. + assertEquals(listOf("first thought", "second thought", "third thought"), turn.steps) + // Expanding shows them all, in order, as the one block's text. + assertEquals("first thought\n\nsecond thought\n\nthird thought", turn.text) + } + + @Test + fun aTurnThatReasonedOnceOrNotAtAllIsNotACountedEntry() { + // One part is a block, not a count of one. + assertEquals(1, turnReasoning(listOf(reasoning("r1", "only thought"))).count) + assertEquals("Thinking…", reasoningLabel(1, streaming = true)) + assertEquals("Reasoning", reasoningLabel(1, streaming = false)) + + // Several steps carry their count, live or settled. + assertEquals("Thinking · 6 steps", reasoningLabel(6, streaming = true)) + assertEquals("Reasoning · 6 steps", reasoningLabel(6, streaming = false)) + + // A turn with no reasoning is empty, so nothing is rendered. + assertTrue(turnReasoning(listOf(text("t1", "just an answer"))).empty) + // A reasoning part without text is not a step either. + assertTrue(turnReasoning(listOf(reasoning("r1", " "))).empty) + } + + @Test + fun theElapsedTimeComesFromTheTurnsOwnPartTimingOrIsAbsent() { + // A turn whose parts report a timing envelope has an elapsed time. + val timed = listOf( + ChatPart(type = ChatProtocol.PART_TOOL, id = "a", time = ChatTime(created = 1_000, ran = 1_000, completed = 2_500)), + ChatPart(type = ChatProtocol.PART_TOOL, id = "b", time = ChatTime(created = 2_000, ran = 2_000, completed = 4_000)), + ) + assertEquals(3_000L, turnElapsedMillis(timed)) + + // A turn with no timing at all shows no duration rather than a guessed one. + assertNull(turnElapsedMillis(listOf(reasoning("r1", "thought")))) + // A start but no completion is still unknown. + assertNull(turnElapsedMillis(listOf(ChatPart(type = ChatProtocol.PART_TOOL, id = "a", time = ChatTime(created = 1_000))))) + } + + @Test + fun aStreamingTurnGrowsTheSameEntryInsteadOfAddingAnother() { + val store = ChatStore() + store.open(ChatSession(id = "s", title = "s")) + store.history("s", emptyList()) + + // Two reasoning deltas to one part grow that part's text... + store.event(reasoningDelta("s", "m1", "r1", "thin")) + store.event(reasoningDelta("s", "m1", "r1", "king")) + val message = store.value.thread("s")!!.messages.single() + assertEquals(1, message.parts.size) + assertEquals("thinking", message.parts.single().text) + + // ...and a later reasoning part is folded into the same one entry, never a + // second. The turn still holds a single assistant message throughout. + store.event(reasoningDelta("s", "m1", "r2", "more")) + val threaded = store.value.thread("s")!!.messages.single() + assertEquals(2, threaded.parts.size) + val turn = turnReasoning(threaded.parts) + assertFalse(turn.empty) + assertEquals(2, turn.count) + assertEquals("thinking\n\nmore", turn.text) + } + + @Test + fun theExpandedStateIsKeyedByTheTurnAndSurvivesAsItGrows() { + // The expansion key is the turn, so a turn match survives the block + // growing: toggling before more parts arrive still reads as expanded after. + var reasoning = ReasoningExpansion() + val key = reasoningTurnKey("m1") + reasoning = reasoning.toggled(key) + assertTrue(reasoning.isExpanded(key)) + + // The same turn id used by the transcript for its message keeps that state. + assertTrue(reasoning.isExpanded(reasoningTurnKey("m1"))) + // A different turn is untouched. + assertFalse(reasoning.isExpanded(reasoningTurnKey("m2"))) + } + + private fun reasoningDelta(sessionId: String, messageId: String, partId: String, delta: String) = + ChatEventFrame( + sessionId = sessionId, + messageId = messageId, + kind = ChatProtocol.PART_REASONING, + delta = delta, + part = ChatPart(type = ChatProtocol.PART_REASONING, id = partId), + ) +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt index 43712b85..ce071d77 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt @@ -76,34 +76,33 @@ class ChatTranscriptTest { } @Test - fun reasoningStartsCollapsedAndKeepsItsExpansionPerPart() { + fun reasoningStartsCollapsedAndKeepsItsExpansionPerTurn() { var reasoning = ReasoningExpansion() - assertFalse(reasoning.isExpanded("m:r1")) - assertFalse(reasoning.isExpanded("m:r2")) + assertFalse(reasoning.isExpanded("m1")) + assertFalse(reasoning.isExpanded("m2")) - reasoning = reasoning.toggled("m:r1") - assertTrue(reasoning.isExpanded("m:r1")) - assertFalse(reasoning.isExpanded("m:r2")) + reasoning = reasoning.toggled("m1") + assertTrue(reasoning.isExpanded("m1")) + assertFalse(reasoning.isExpanded("m2")) - // Expanding a second part does not disturb the first. - reasoning = reasoning.toggled("m:r2") - assertTrue(reasoning.isExpanded("m:r1")) - assertTrue(reasoning.isExpanded("m:r2")) + // Expanding a second turn does not disturb the first. + reasoning = reasoning.toggled("m2") + assertTrue(reasoning.isExpanded("m1")) + assertTrue(reasoning.isExpanded("m2")) - // Collapsing brings only that part back. - reasoning = reasoning.toggled("m:r1") - assertFalse(reasoning.isExpanded("m:r1")) - assertTrue(reasoning.isExpanded("m:r2")) + // Collapsing brings only that turn back. + reasoning = reasoning.toggled("m1") + assertFalse(reasoning.isExpanded("m1")) + assertTrue(reasoning.isExpanded("m2")) - // A blank key is never a key: it can never expand every id-less part at once. + // A blank key is never a key: it can never expand every id-less turn at once. val untouched = ReasoningExpansion().toggled("") assertFalse(untouched.isExpanded("")) } @Test - fun reasoningKeyIsStableForAServerPartAndFallsBackToTheIndex() { - assertEquals("m:r1", reasoningKey("m", ChatPart(id = "r1"), 0)) - assertEquals("m:2", reasoningKey("m", ChatPart(id = ""), 2)) + fun theReasoningKeyIsTheTurnItself() { + assertEquals("m", reasoningTurnKey("m")) } @Test