diff --git a/android/README.md b/android/README.md index 44a598b7..0f2c3a10 100644 --- a/android/README.md +++ b/android/README.md @@ -5783,3 +5783,68 @@ Not verified in this pass: the search field, the directory sections and the empty state on a device, and the narrow/wide layouts — the brief keeps implementation verification to the build and the unit tests, and visual review owns the operator's Pixel 9 Pro XL. + +## 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). 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 56836c07..3f28436a 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 @@ -93,10 +93,15 @@ 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? = when { - session.tag.isBlank() -> null - session.tag == ChatProtocol.TAG_OPERATOR -> OPERATOR_TAG_LABEL - else -> session.tag +internal fun sessionTagLabel(session: ChatSession): String? = tagLabel(session.tag) + +/** The kind chip for a conversation's own tag (see [sessionTagLabel]). */ +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 } private const val OPERATOR_TAG_LABEL = "Operator" @@ -110,9 +115,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" } @@ -135,6 +144,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 = 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, activeSessionId: String): List = + 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 = 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 } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 189ecb1a..e392f8a4 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -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 @@ -726,17 +728,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() @@ -744,7 +755,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), @@ -800,6 +811,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( @@ -810,6 +856,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 @@ -852,7 +907,7 @@ private fun ChatConversationPane( TopAppBar( title = { Text( - text = thread.title.ifBlank { sessionTitle(ChatSession(id = thread.sessionId)) }, + text = header.title, maxLines = 1, overflow = TextOverflow.Ellipsis, ) @@ -889,7 +944,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…") @@ -911,6 +974,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) } }, @@ -961,6 +1026,8 @@ private fun ChatTranscript( itemCount: Int, approval: ApprovalCard?, showRunning: Boolean, + reasoning: ReasoningExpansion, + onToggleReasoning: (String) -> Unit, onDecision: (String) -> Unit, ) { val scope = rememberCoroutineScope() @@ -1043,6 +1110,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(), @@ -1050,7 +1120,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) } @@ -1181,7 +1256,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(), @@ -1201,7 +1281,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, + ) } } } @@ -1234,7 +1320,13 @@ private fun UserParts(parts: List) { * as they fit, instead of each taking a row, so the transcript stays scannable. */ @Composable -private fun AssistantParts(parts: List) { +private fun AssistantParts( + messageId: String, + parts: List, + reasoning: ReasoningExpansion, + streaming: Boolean, + onToggleReasoning: (String) -> Unit, +) { var index = 0 while (index < parts.size) { if (parts[index].type == ChatProtocol.PART_TOOL) { @@ -1243,42 +1335,101 @@ private fun AssistantParts(parts: List) { 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 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index 4a094e28..cdeb965b 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -51,6 +51,8 @@ data class ChatThread( val title: String = "", val directory: String = "", val model: String = "", + /** The server's stored session kind, copied so the conversation header can label it. */ + val tag: String = "", val agent: String = "", val updatedAt: Long = 0, /** The server reports another client (or an active run) holds this session. */ @@ -298,6 +300,8 @@ class ChatStore( thread.copy( title = renamed[thread.sessionId] ?: session.title.ifBlank { thread.title }, directory = session.directory.ifBlank { thread.directory }, + model = session.model.ifBlank { thread.model }, + tag = session.tag.ifBlank { thread.tag }, busy = session.busy, ) } @@ -445,6 +449,7 @@ class ChatStore( title = title, directory = session.directory, model = session.model, + tag = session.tag, agent = session.agent, updatedAt = session.updatedAt, busy = session.busy, @@ -455,6 +460,8 @@ class ChatStore( val merged = existing.copy( title = title.ifBlank { existing.title }, directory = session.directory.ifBlank { existing.directory }, + model = session.model.ifBlank { existing.model }, + tag = session.tag.ifBlank { existing.tag }, busy = session.busy, ) _state.value = _state.value.copy( @@ -720,6 +727,8 @@ class ChatStore( sessionId = sessionId, title = _state.value.overrides.titles[sessionId] ?: session?.title ?: "", directory = session?.directory ?: "", + model = session?.model ?: "", + tag = session?.tag ?: "", busy = session?.busy ?: false, ) _state.value = _state.value.copy(open = _state.value.open + placeholder) 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 new file mode 100644 index 00000000..43712b85 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt @@ -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 raw html; \$_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(), 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(), openChatsBeside(listOf(a), "a")) + } +}