Merge lane-chat4: keep the lane's reviewed work

Combine the reviewed chat work already on main (session model in the
header, agent mirroring, chatHeaderMeta, tagged-label intent) with the
incoming lane's "make the conversation readable" change (markdown/part
rendering, collapsed reasoning, one conversation identity,
openChatsBeside, ChatTranscriptTest) over merge base 5ac196c.

Both intents survive in every conflicted file: android/README.md,
ChatFormat.kt, ChatScreen.kt (session header and conversation header),
ChatStore.kt and the new ChatTranscriptTest.kt. No conflict markers or
duplicated blocks remain.

Verified on the merged tree (JDK 17, ANDROID_HOME=/Users/alan/Library/Android/sdk,
offline, no daemon, --rerun-tasks):
- gradle :app:assembleDebug -> BUILD SUCCESSFUL
- gradle :app:testDebugUnitTest -> BUILD SUCCESSFUL; JUnit XMLs total
  512 tests, 0 failures, 0 errors, 0 skipped (7 in ChatTranscriptTest).

Docs check: android/README.md already records the resolved change, and no
packaged template, README/topic doc or packaged authoring skill reference
describes the Android chat surface, so nothing there needed updating.
This commit is contained in:
2026-10-17 15:32:00 +01:00
5 changed files with 486 additions and 44 deletions
+65
View File
@@ -5861,3 +5861,68 @@ Not verified in this pass: the header meta on a device and the create-flow note
the brief keeps implementation verification to the build and the unit tests, and
visual review owns the operator's Pixel 9 Pro XL. No packaged skill reference was
touched: this is an app-UI change and no reference describes the chat surface.
## Conversation reading: markdown, collapsed reasoning, one identity (17 Oct 2026)
Making the conversation readable on a phone. `android/` only; no new dependency
(the declared `material-icons-extended` only), no Pipelines server/Go/installer/
Docker file touched and no run started from the app.
- **Markdown reaches the transcript (tested).** The assistant `text` part was
already rendered through `MarkdownText`, but the transcript's decision was
buried in a private composable. `ChatFormat.partRendering(part)` now names the
one decision the transcript makes (`MARKDOWN` / `REASONING` / `PLAIN` /
`HIDDEN`), `MessagePart` consumes it, and `ChatTranscriptTest` drives a sample
covering the whole documented subset (headings, paragraph, bullet and ordered
lists, quote, table, fenced code, rule, inline code/bold/italic/link) from a
`ChatPart` into `parseMarkdown`/`parseInline`. Text outside the subset (raw
HTML, `~~strike~~`) still parses to a paragraph and renders verbatim; an
unknown part kind still renders its text, never drops it.
- **Reasoning collapsed by default.** `ReasoningBlock` is now one compact,
muted line per part — a `Psychology` icon, a label (`Thinking…` while the
newest turn streams, `Reasoning` once settled) and a chevron — that expands on
tap to the full, still-muted text. Expansion is a pure
`ReasoningExpansion` set hoisted to the conversation pane (not the lazy
transcript), so a part keeps its state while the operator scrolls and its item
is disposed, and every part starts collapsed in a freshly opened chat. The
choice for a running turn: its streaming reasoning stays collapsed and keeps
following the stream under the live `Thinking…` label, so it signals progress
without competing with the answer.
- **One identity in the header.** `ChatFormat.conversationHeader(thread)` builds
the app-bar title plus the only extra context — the labelled kind chip
(`Operator`) from the server's own tag, the activity (`Running` /
`Busy · read-only` / `Idle`), the directory and the model — and the app bar and
context line read the same value. The conversation's active chip is omitted
from the open-chat strip (`openChatsBeside`), so the session's title is shown
once; every *other* open chat is still one tap away, and the session list is
unchanged.
Tests (`ChatTranscriptTest`, 7 cases, plus the existing `ChatFormatTest`): the
markdown subset reaches the renderer from a `ChatPart`; text outside the subset
and an unknown part kind still render; reasoning starts collapsed, toggles per
part and never expands on a blank key; the header names the session once with
only kind/activity/directory/model beside it; and the conversation strip offers
only the other open chats.
Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, `--no-daemon`,
`ANDROID_HOME=/Users/alan/Library/Android/sdk`):
- `gradle :app:assembleDebug --no-daemon --offline --rerun-tasks` → `BUILD
SUCCESSFUL` (35 tasks executed).
- `gradle :app:testDebugUnitTest --no-daemon --offline --rerun-tasks` →
`BUILD SUCCESSFUL`; the JUnit XMLs total **508 tests, 0 failures, 0 errors, 0
skipped** (7 new in `ChatTranscriptTest`).
- **APK publish.** `app-debug.apk` copied to this run's artifacts directory as
`pipelines-debug-wip-5ac196c.apk` (18,486,624 bytes, sha256
`0df6899429a8f5632ec568340dddb63a5617b1a04af19f52c6ebb793470a0b23`; `5ac196c`
is `git rev-parse --short HEAD`, the tree being uncommitted WIP on top of it).
It is served at
`http://10.0.0.75:8080/artifacts/274/1/pipelines-debug-wip-5ac196c.apk`
(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 18486624`).
Not verified in this pass: the conversation, the collapsed/expanded reasoning
and the header on a device — the brief keeps implementation verification to the
build and the unit tests, and visual review owns the operator's Pixel 9 Pro XL
(captures: headings/list/fenced code/table, reasoning collapsed then expanded,
and the header).
@@ -93,14 +93,16 @@ internal fun sessionTitle(session: ChatSession): String =
* session shows no chip. This only *labels*; the app never filters on the tag,
* because the server already lists operator sessions only.
*/
internal fun sessionTagLabel(session: ChatSession): String? = sessionTagLabel(session.tag)
internal fun sessionTagLabel(session: ChatSession): String? = tagLabel(session.tag)
/**
* The kind chip label for a session's own tag value (see [sessionTagLabel]).
* Kept as the single mapping so a session and the conversation it opens cannot
* label the same tag differently.
*/
internal fun sessionTagLabel(tag: String): String? = when {
internal fun sessionTagLabel(tag: String): String? = tagLabel(tag)
private fun tagLabel(tag: String): String? = when {
tag.isBlank() -> null
tag == ChatProtocol.TAG_OPERATOR -> OPERATOR_TAG_LABEL
else -> tag
@@ -131,9 +133,13 @@ private const val OPERATOR_TAG_LABEL = "Operator"
* `Running` and writable, never the read-only the server's own `busy` flag alone
* would imply.
*/
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String = when {
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String =
sessionStatusLabel(session.busy, runningLocally)
/** The status of a conversation from its own model flags (see [sessionStatusLabel]). */
internal fun sessionStatusLabel(busy: Boolean, runningLocally: Boolean): String = when {
runningLocally -> "Running"
session.busy -> "Busy · read-only"
busy -> "Busy · read-only"
else -> "Idle"
}
@@ -156,6 +162,73 @@ internal fun sessionActivity(running: Boolean, unseen: Boolean): SessionActivity
else -> SessionActivity.IDLE
}
/**
* The one identity a conversation header shows: the title is the session's
* name, and everything else is context that cannot be mistaken for a second
* name — the server's kind tag, the live activity and the directory/model.
* Kept pure so the header and its unit test agree that the title appears once.
*/
internal data class ConversationHeader(
val title: String,
val kind: String?,
val activity: String,
val directory: String,
val model: String,
) {
/** The extra identity context, in reading order, with blank fields omitted. */
val context: List<String> = listOf(directory, model).filter { it.isNotBlank() }
}
/** Builds the conversation header from the open thread's copied session fields. */
internal fun conversationHeader(thread: ChatThread): ConversationHeader = ConversationHeader(
title = sessionTitle(ChatSession(id = thread.sessionId, title = thread.title)),
kind = sessionTagLabel(thread.tag),
activity = sessionStatusLabel(thread.busy, thread.running),
directory = thread.directory,
model = thread.model,
)
/**
* The open chats a conversation still offers to switch to: every other open
* chat, never the active one, so its title is not repeated beside its own
* header. The session list keeps showing all open chats.
*/
internal fun openChatsBeside(open: List<ChatThread>, activeSessionId: String): List<ChatThread> =
open.filterNot { it.sessionId == activeSessionId }
/**
* 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
* text is plain, and an empty part renders nothing.
*/
internal enum class PartRendering { MARKDOWN, REASONING, PLAIN, HIDDEN }
internal fun partRendering(part: ChatPart): PartRendering = when {
part.type == ChatProtocol.PART_TEXT && part.text.isNotBlank() -> PartRendering.MARKDOWN
part.type == ChatProtocol.PART_REASONING && part.text.isNotBlank() -> PartRendering.REASONING
part.text.isNotBlank() -> PartRendering.PLAIN
else -> PartRendering.HIDDEN
}
/**
* 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.
*/
internal data class ReasoningExpansion(private val expanded: Set<String> = emptySet()) {
fun isExpanded(partKey: String): Boolean = partKey in expanded
fun toggled(partKey: String): ReasoningExpansion {
if (partKey.isBlank()) return this
return copy(expanded = if (partKey in expanded) expanded - partKey else expanded + partKey)
}
}
/** 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() }
/** Which action the composer's single primary control offers for a chat. */
enum class ComposerAction { Send, Stop }
@@ -70,6 +70,7 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
@@ -139,6 +140,7 @@ import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.pipelinesText
@@ -739,17 +741,26 @@ private fun NotConnectedNotice() {
}
/**
* The open-conversation switcher: one chip per conversation the operator has
* open, so several chats can be kept at once and switched between in one tap.
* A running chat carries a `Running` badge; the X closes that chat (optional
* close is provided).
* The open-conversation switcher: one chip per open conversation, so several
* chats can be kept at once and switched between in one tap. A running chat
* carries its live dot, a chat waiting on an approval carries its hand, and the
* X closes that chat (optional close is provided). [excludeSessionId] omits one
* chat — the conversation pane omits its own active one, whose title already
* stands in the app bar, while the session list shows every open chat.
*/
@Composable
private fun OpenChatStrip(
state: ChatState,
onSelect: (String) -> Unit,
onClose: (String) -> Unit,
excludeSessionId: String? = null,
) {
val threads = if (excludeSessionId == null) {
state.open
} else {
openChatsBeside(state.open, excludeSessionId)
}
if (threads.isEmpty()) return
Row(
modifier = Modifier
.fillMaxWidth()
@@ -757,7 +768,7 @@ private fun OpenChatStrip(
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
state.open.forEach { thread ->
threads.forEach { thread ->
val selected = state.activeId == thread.sessionId
Surface(
shape = RoundedCornerShape(50),
@@ -813,6 +824,41 @@ private fun OpenChatStrip(
// ---- Pane 1: the active conversation -----------------------------------------
/**
* The conversation's identity context, directly below the app bar that carries
* its title: the session kind (labelled, never a bare name), its activity and,
* when the server knows them, the directory and model. The title is not repeated
* here — this block adds only what the title cannot say.
*/
@Composable
private fun ConversationHeader(header: ConversationHeader) {
val texts = pipelinesText()
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
header.kind?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
Text(
text = header.activity,
style = texts.label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (header.context.isNotEmpty()) {
Text(
text = header.context.joinToString(" · "),
style = texts.meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ChatConversationPane(
@@ -823,6 +869,15 @@ private fun ChatConversationPane(
) {
val approval = approvalCard(thread.permission, thread.permissionAnswer)
val awaiting = approval?.actionable == true
// The header's one identity: the title, with the kind, activity, directory and
// model as context below it. It is built once so the app bar and the context
// line cannot disagree about the session's name.
val header = conversationHeader(thread)
// Reasoning expansion is hoisted here, not into the lazy transcript: a
// reasoning part keeps its open/closed state while the operator scrolls (and
// the item is disposed), and the state is per conversation, so a newly opened
// chat starts with every reasoning part collapsed.
var reasoning by remember(thread.sessionId) { mutableStateOf(ReasoningExpansion()) }
// 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
@@ -864,17 +919,18 @@ private fun ChatConversationPane(
topBar = {
TopAppBar(
title = {
// The one identity: the app bar carries the title (the value
// the context line below is built beside), and under it the
// model meta the server reports — its model, kind tag and
// directory — so what is answering is visible without leaving
// the conversation. Every part is server-reported; a blank one
// is simply omitted.
Column {
Text(
text = thread.title.ifBlank { sessionTitle(ChatSession(id = thread.sessionId)) },
text = header.title,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
// The model the server reports is answering this session,
// beside the session's kind tag and its directory, so what
// is replying is always visible without leaving the
// conversation. Every part is server-reported; a blank one
// is simply omitted.
val meta = chatHeaderMeta(thread)
if (meta.isNotBlank()) {
Text(
@@ -919,7 +975,15 @@ private fun ChatConversationPane(
},
) { padding ->
Column(Modifier.fillMaxSize().padding(padding).imePadding()) {
OpenChatStrip(state = state, onSelect = vm::activateChat, onClose = vm::closeChat)
ConversationHeader(header)
// Every *other* open chat is still one tap away; the active one is
// already named by the app bar, so it is not repeated here.
OpenChatStrip(
state = state,
onSelect = vm::activateChat,
onClose = vm::closeChat,
excludeSessionId = thread.sessionId,
)
Box(Modifier.weight(1f).fillMaxWidth()) {
when {
thread.loading && !thread.loaded -> LoadingState("Loading conversation…")
@@ -941,6 +1005,8 @@ private fun ChatConversationPane(
itemCount = itemCount,
approval = approval,
showRunning = showRunning,
reasoning = reasoning,
onToggleReasoning = { reasoning = reasoning.toggled(it) },
onDecision = { decision ->
approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) }
},
@@ -991,6 +1057,8 @@ private fun ChatTranscript(
itemCount: Int,
approval: ApprovalCard?,
showRunning: Boolean,
reasoning: ReasoningExpansion,
onToggleReasoning: (String) -> Unit,
onDecision: (String) -> Unit,
) {
val scope = rememberCoroutineScope()
@@ -1073,6 +1141,9 @@ private fun ChatTranscript(
if (following) listState.scrollToEnd(itemCount, animated = true)
}
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 }
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
@@ -1080,7 +1151,12 @@ private fun ChatTranscript(
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom),
) {
items(thread.messages, key = { it.id }) { message ->
MessageItem(message)
MessageItem(
message = message,
reasoning = reasoning,
streaming = message.id == streamingMessageId,
onToggleReasoning = onToggleReasoning,
)
}
if (showRunning) {
item(key = "pending") { RunningIndicator(thread) }
@@ -1211,7 +1287,12 @@ private fun rememberElapsedNow(runningSince: Long): Long {
}
@Composable
private fun MessageItem(message: ChatMessage) {
private fun MessageItem(
message: ChatMessage,
reasoning: ReasoningExpansion,
streaming: Boolean,
onToggleReasoning: (String) -> Unit,
) {
val isUser = message.role == ChatProtocol.ROLE_USER
Row(
modifier = Modifier.fillMaxWidth(),
@@ -1231,7 +1312,13 @@ private fun MessageItem(message: ChatMessage) {
if (isUser) {
UserParts(message.parts)
} else {
AssistantParts(message.parts)
AssistantParts(
messageId = message.id,
parts = message.parts,
reasoning = reasoning,
streaming = streaming,
onToggleReasoning = onToggleReasoning,
)
}
}
}
@@ -1264,7 +1351,13 @@ private fun UserParts(parts: List<ChatPart>) {
* as they fit, instead of each taking a row, so the transcript stays scannable.
*/
@Composable
private fun AssistantParts(parts: List<ChatPart>) {
private fun AssistantParts(
messageId: String,
parts: List<ChatPart>,
reasoning: ReasoningExpansion,
streaming: Boolean,
onToggleReasoning: (String) -> Unit,
) {
var index = 0
while (index < parts.size) {
if (parts[index].type == ChatProtocol.PART_TOOL) {
@@ -1273,42 +1366,101 @@ private fun AssistantParts(parts: List<ChatPart>) {
ToolCalls(parts.subList(index, end))
index = end
} else {
MessagePart(parts[index])
val part = parts[index]
MessagePart(
part = part,
reasoningKey = reasoningKey(messageId, part, index),
reasoning = reasoning,
streaming = streaming,
onToggleReasoning = onToggleReasoning,
)
index++
}
}
}
@Composable
private fun MessagePart(part: ChatPart) {
when (part.type) {
ChatProtocol.PART_TEXT -> if (part.text.isNotBlank()) {
MarkdownText(part.text)
}
ChatProtocol.PART_REASONING -> ReasoningBlock(part.text)
else -> if (part.text.isNotBlank()) Text(part.text, style = MaterialTheme.typography.bodyMedium)
private fun MessagePart(
part: ChatPart,
reasoningKey: String,
reasoning: ReasoningExpansion,
streaming: Boolean,
onToggleReasoning: (String) -> Unit,
) {
when (partRendering(part)) {
PartRendering.MARKDOWN -> MarkdownText(part.text)
PartRendering.REASONING -> ReasoningBlock(
text = part.text,
expanded = reasoning.isExpanded(reasoningKey),
streaming = streaming,
onToggle = { onToggleReasoning(reasoningKey) },
)
PartRendering.PLAIN -> Text(part.text, style = MaterialTheme.typography.bodyMedium)
PartRendering.HIDDEN -> Unit
}
}
/** Reasoning is visually secondary: a muted, bordered block, never body weight. */
/**
* 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.
*/
@Composable
private fun ReasoningBlock(text: String) {
private fun ReasoningBlock(
text: String,
expanded: Boolean,
streaming: Boolean,
onToggle: () -> Unit,
) {
if (text.isBlank()) return
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), modifier = Modifier.padding(vertical = 4.dp)) {
Icon(
Icons.Default.Psychology,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(16.dp),
)
Text(
text = text,
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Default),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
val label = if (streaming) REASONING_STREAMING_LABEL else REASONING_SETTLED_LABEL
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 = SPACING_XS),
) {
Icon(
Icons.Default.Psychology,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ICON_INLINE_DP),
)
Text(
text = label,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
Icon(
imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
contentDescription = if (expanded) "Hide reasoning" else "Show reasoning",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ICON_INLINE_DP),
)
}
if (expanded) {
Text(
text = 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),
)
}
}
}
/** 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"
/**
* One turn's tool calls as a single group of compact chips, mirroring the
* reference transcript's `_ToolCalls`/`_ToolChip` (research §1.3): each call
@@ -51,9 +51,9 @@ data class ChatThread(
val title: String = "",
val directory: String = "",
val model: String = "",
val agent: String = "",
/** The session's kind tag the server reported (see [ChatSession.tag]). */
val tag: String = "",
val agent: String = "",
val updatedAt: Long = 0,
/** The server reports another client (or an active run) holds this session. */
val busy: Boolean = false,
@@ -450,8 +450,8 @@ class ChatStore(
title = title,
directory = session.directory,
model = session.model,
agent = session.agent,
tag = session.tag,
agent = session.agent,
updatedAt = session.updatedAt,
busy = session.busy,
)
@@ -0,0 +1,152 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The conversation's reading decisions, all pure so they need no device: the
* markdown route out of the transcript, reasoning collapsed and remembering its
* expansion, and a header that names the session once with only context beside
* and below it.
*/
class ChatTranscriptTest {
@Test
fun assistantTextReachesTheMarkdownRendererWithTheDocumentedSubset() {
val sample = """
# Release notes
Intro with **bold**, *italic*, `inline code` and a [link](https://example.com/x).
- first
- second
1. one
2. two
> quoted line
| Name | Value |
| --- | --- |
| a | 1 |
```kotlin
val gap = 8.dp
```
---
""".trimIndent()
val part = ChatPart(type = ChatProtocol.PART_TEXT, id = "p1", text = sample)
// The transcript's own decision routes assistant text through markdown...
assertEquals(PartRendering.MARKDOWN, partRendering(part))
// ...and the whole documented subset parses into the renderer's blocks.
val blocks = parseMarkdown(part.text)
assertTrue(blocks.any { it is MdHeading })
assertTrue(blocks.any { it is MdParagraph })
assertTrue(blocks.any { it is MdListBlock })
assertTrue(blocks.any { it is MdQuote })
assertTrue(blocks.any { it is MdTableBlock })
assertTrue(blocks.any { it is MdCodeBlock })
assertTrue(blocks.contains(MdRule))
val spans = parseInline("**bold** *italic* `code` [link](https://example.com/x)")
assertTrue(spans.any { it is MdStrong })
assertTrue(spans.any { it is MdEmphasis })
assertTrue(spans.any { it is MdCodeSpan })
assertTrue(spans.any { it is MdLinkSpan })
}
@Test
fun textOutsideTheMarkdownSubsetStillRendersAsItsOwnText() {
val text = "~~struck~~ and <u>raw html</u>; \$_unclosed"
val part = ChatPart(type = ChatProtocol.PART_TEXT, id = "p1", text = text)
assertEquals(PartRendering.MARKDOWN, partRendering(part))
// Nothing in the subset matches, so the paragraph keeps the source verbatim.
assertEquals(listOf(MdParagraph(text)), parseMarkdown(text))
// A part kind the renderer does not know still shows its text, never drops it.
val unknown = ChatPart(type = "status", id = "p2", text = "connection restored")
assertEquals(PartRendering.PLAIN, partRendering(unknown))
assertEquals(PartRendering.HIDDEN, partRendering(ChatPart(type = ChatProtocol.PART_TEXT, id = "p3")))
}
@Test
fun reasoningStartsCollapsedAndKeepsItsExpansionPerPart() {
var reasoning = ReasoningExpansion()
assertFalse(reasoning.isExpanded("m:r1"))
assertFalse(reasoning.isExpanded("m:r2"))
reasoning = reasoning.toggled("m:r1")
assertTrue(reasoning.isExpanded("m:r1"))
assertFalse(reasoning.isExpanded("m:r2"))
// Expanding a second part does not disturb the first.
reasoning = reasoning.toggled("m:r2")
assertTrue(reasoning.isExpanded("m:r1"))
assertTrue(reasoning.isExpanded("m:r2"))
// Collapsing brings only that part back.
reasoning = reasoning.toggled("m:r1")
assertFalse(reasoning.isExpanded("m:r1"))
assertTrue(reasoning.isExpanded("m:r2"))
// A blank key is never a key: it can never expand every id-less part 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))
}
@Test
fun theHeaderNamesTheSessionOnceAndOnlyAddsContext() {
val header = conversationHeader(
ChatThread(
sessionId = "ses_1",
title = "Fix the parser",
directory = "/Users/alan/repos/pipelines",
model = "openai/gpt-5",
tag = ChatProtocol.TAG_OPERATOR,
running = true,
),
)
assertEquals("Fix the parser", header.title)
assertEquals("Operator", header.kind)
assertEquals("Running", header.activity)
assertEquals(listOf("/Users/alan/repos/pipelines", "openai/gpt-5"), header.context)
// The title is the only identity: the context never repeats it.
assertFalse(header.context.contains(header.title))
assertFalse(header.kind == header.title)
assertFalse(header.activity == header.title)
}
@Test
fun theHeaderFallsBackToTheIdAndOmitsUnknownContext() {
val header = conversationHeader(ChatThread(sessionId = "ses_untitled", running = false))
assertEquals("ses_untitled", header.title)
assertNull(header.kind)
assertEquals("Idle", header.activity)
assertEquals(emptyList<String>(), header.context)
}
@Test
fun theConversationOffersOnlyTheOtherOpenChatsToSwitchTo() {
val a = ChatThread(sessionId = "a", title = "Alpha")
val b = ChatThread(sessionId = "b", title = "Beta")
val open = listOf(a, b)
// The active chat is never repeated beside its own header...
assertEquals(listOf(b), openChatsBeside(open, "a"))
// ...and a single open chat leaves nothing to switch to.
assertEquals(emptyList<ChatThread>(), openChatsBeside(listOf(a), "a"))
}
}