From 70270fa90eb196668a39e25874fa67423c8f2ac2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 17 Oct 2026 16:56:19 +0100 Subject: [PATCH] Split the chat conversation screen into files by concern Move ui/chat/ChatScreen.kt (1864 lines) into ten files by concern with no behaviour change: ChatScreen.kt keeps the destination and the shared chat geometry tokens (84 lines); ChatListPane, ChatCreatePane, ChatOpenStrip, ChatConversationPane, ChatTranscript, ChatComposer, ChatToolCalls, ChatDiffCard and ChatApprovalCard take the session list, new-chat picker, open-conversation strip, conversation header, transcript, composer, tool chips and the cards. Pure move: same package, same composable names and signatures, same call graph. The only substantive edits are per-file imports and private->internal widenings needed for the cross-file calls; review confirmed identical declaration sets and an equal line multiset. :app:assembleDebug and the full unit suite pass (545 tests, 0 failures, 0 skipped) and the built APK is byte-identical (same sha256) to the published artifact. Checked before committing: - Packaged templates: this repository carries no packaged template tree, so nothing to update. - Packaged authoring skill references (internal/author/skill/references/): none reference the chat UI internals; nothing to update. - android/README.md still cites ChatScreen.kt inner declarations (ChatScreen.MessagePart, rememberElapsedMillis, ChatConversationPane) that this move relocated; left unedited for the single documentation writer. --- .../pipelines/ui/chat/ChatApprovalCard.kt | 105 + .../awan/pipelines/ui/chat/ChatComposer.kt | 97 + .../pipelines/ui/chat/ChatConversationPane.kt | 255 +++ .../awan/pipelines/ui/chat/ChatCreatePane.kt | 184 ++ .../awan/pipelines/ui/chat/ChatDiffCard.kt | 89 + .../awan/pipelines/ui/chat/ChatListPane.kt | 424 ++++ .../awan/pipelines/ui/chat/ChatOpenStrip.kt | 116 ++ .../net/awan/pipelines/ui/chat/ChatScreen.kt | 1788 +---------------- .../awan/pipelines/ui/chat/ChatToolCalls.kt | 256 +++ .../awan/pipelines/ui/chat/ChatTranscript.kt | 491 +++++ 10 files changed, 2021 insertions(+), 1784 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatApprovalCard.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatComposer.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatConversationPane.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDiffCard.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOpenStrip.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatApprovalCard.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatApprovalCard.kt new file mode 100644 index 00000000..2df9cbfe --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatApprovalCard.kt @@ -0,0 +1,105 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Shield +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.ui.theme.HAIRLINE_DP +import net.awan.pipelines.ui.theme.ICON_LIST_DP +import net.awan.pipelines.ui.theme.ICON_STATUS_DP +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The approval card's amber review panel and pending-card border strengths, + * echoing the reference app's 10%-alpha amber `RISK REVIEW` box. + */ +private const val RISK_REVIEW_ALPHA = 0.12f +private const val APPROVAL_PENDING_BORDER_ALPHA = 0.5f + +/** + * One approval request as a card in the conversation (research §1.3 `_CodeRun` / + * risk review): the action being requested, the affected resources, the amber + * `RISK REVIEW` panel repeating the server's risk summary, and once/always/reject + * actions answered with `chat_reply`, so the server-held credentials and the tool + * never leave it. A card that is already answered or resolved keeps its place but + * drops the actions and states the outcome, so it can never offer a stale choice. + */ +@Composable +internal fun ApprovalCardItem(card: ApprovalCard, onDecision: (String) -> Unit) { + val amber = MaterialTheme.colorScheme.tertiary + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), + border = if (card.actionable) BorderStroke(HAIRLINE_DP, amber.copy(alpha = APPROVAL_PENDING_BORDER_ALPHA)) else null, + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_LIST_DP)) + Column(Modifier.weight(1f)) { + Text(card.headline, style = pipelinesText().cardTitle) + Text( + text = card.statusLine, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + if (card.resources.isNotEmpty()) { + Text( + text = card.resources.joinToString("\n"), + style = pipelinesText().mono, + maxLines = 6, + overflow = TextOverflow.Ellipsis, + ) + } + if (card.showRisk && card.risk.isNotBlank()) { + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(CHAT_ITEM_GAP)) + .background(amber.copy(alpha = RISK_REVIEW_ALPHA)) + .padding(CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_STATUS_DP)) + Text("RISK REVIEW", style = MaterialTheme.typography.labelSmall, color = amber) + } + Text(card.risk, style = MaterialTheme.typography.bodySmall) + } + } + if (card.actionable) { + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Button(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") } + TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always allow") } + TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Reject") } + } + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatComposer.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatComposer.kt new file mode 100644 index 00000000..f67967f1 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatComposer.kt @@ -0,0 +1,97 @@ +package net.awan.pipelines.ui.chat + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.AttachFile +import androidx.compose.material.icons.filled.Stop +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +@Composable +internal fun ChatComposer( + thread: ChatThread, + onDraft: (String) -> Unit, + onAttach: (List) -> Unit, + onRemoveAttachment: (String) -> Unit, + onSend: () -> Unit, + onStop: () -> Unit, +) { + val action = composerAction(thread) + val context = LocalContext.current + val scope = rememberCoroutineScope() + // The platform picker: the operator chooses files and they are only resolved + // into attachments here — nothing is sent until the message is. + val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> + if (uris.isNotEmpty()) { + scope.launch { + val resolved = withContext(Dispatchers.IO) { uris.map { resolveChatAttachment(context, it) } } + onAttach(resolved) + } + } + } + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) { + if (thread.readOnly) { + Text( + text = "Another client holds this session; it is read-only here.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = CHAT_ITEM_GAP), + ) + } + if (thread.attachments.isNotEmpty()) { + ChatAttachmentStrip(attachments = thread.attachments, onRemove = onRemoveAttachment) + } + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) { + IconButton( + onClick = { picker.launch(arrayOf("*/*")) }, + enabled = !thread.readOnly, + ) { + Icon(Icons.Default.AttachFile, contentDescription = "Attach file") + } + OutlinedTextField( + value = thread.draft, + onValueChange = onDraft, + enabled = !thread.readOnly, + placeholder = { Text("Message the agent…") }, + minLines = 1, + maxLines = 6, + keyboardActions = KeyboardActions( + onSend = { if (action == ComposerAction.Send && thread.canSend) onSend() }, + ), + modifier = Modifier.weight(1f), + ) + when (action) { + // While a turn is in flight the send control becomes the stop + // control, so it must interrupt rather than send the draft. + ComposerAction.Stop -> IconButton(onClick = onStop) { + Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error) + } + ComposerAction.Send -> IconButton(onClick = onSend, enabled = thread.canSend) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send") + } + } + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatConversationPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatConversationPane.kt new file mode 100644 index 00000000..7d51f576 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatConversationPane.kt @@ -0,0 +1,255 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.PanTool +import androidx.compose.material.icons.filled.Stop +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.launch +import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.components.EmptyState +import net.awan.pipelines.ui.components.ErrorState +import net.awan.pipelines.ui.components.LabelChip +import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.SPACING_XXS +import net.awan.pipelines.ui.theme.pipelinesText + +// ---- 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 +internal fun ChatConversationPane( + vm: AppViewModel, + state: ChatState, + thread: ChatThread, + modifier: Modifier, +) { + 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 + // The count of the transcript's items: the messages, 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 + (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 + // chatOpensAtNewest), so the current turn is never hunted for. + val savedScroll = remember(thread.sessionId) { thread.scroll } + // The list state is created the moment the conversation first has content, so + // its very first measure is already at the newest item rather than at the top: + // opening a chat must not show anything else first. It is still saveable, so a + // rotation or process death keeps the operator's position. + val listState = rememberSaveable(thread.sessionId, itemCount > 0, saver = LazyListState.Saver) { + val first = chatFirstScroll(savedScroll, itemCount) + LazyListState( + firstVisibleItemIndex = first.index, + firstVisibleItemScrollOffset = first.offset, + ) + } + // Persist the scroll position when the operator leaves this chat, so switching + // away and back returns them exactly where they were. Keyed on the list state, + // so the position saved is the one that was actually shown; a state that never + // held content (replaced when the conversation first loaded) saves nothing, + // leaving the conversation with no position of its own to open at its newest. + DisposableEffect(listState) { + onDispose { + if (listState.layoutInfo.totalItemsCount > 0) { + vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) + } + } + } + val scope = rememberCoroutineScope() + + Scaffold( + modifier = modifier, + 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 = header.title, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val meta = chatHeaderMeta(thread) + if (meta.isNotBlank()) { + Text( + text = meta, + style = pipelinesText().meta, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + navigationIcon = { + IconButton(onClick = vm::showChatList) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to chats") + } + }, + actions = { + if (awaiting) { + IconButton( + onClick = { + // The transcript's one scroll path, so a pending + // request is brought into view the same way new + // content is. + scope.launch { listState.scrollToEnd(itemCount, animated = true) } + }, + ) { + Icon( + Icons.Default.PanTool, + contentDescription = "Waiting for your approval", + tint = MaterialTheme.colorScheme.tertiary, + ) + } + } + if (thread.running) { + IconButton(onClick = { vm.stopChat(thread.sessionId) }) { + Icon(Icons.Default.Stop, contentDescription = "Stop") + } + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).imePadding()) { + 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…") + thread.error != null && !thread.loaded -> ErrorState( + message = thread.error, + onRetry = { vm.loadChatHistory(thread.sessionId) }, + ) + thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState( + message = if (thread.readOnly) { + "This chat is read-only while another client holds the session." + } else { + "This chat has no messages yet. Ask something below." + }, + ) + else -> ChatTranscript( + thread = thread, + listState = listState, + savedScroll = savedScroll, + itemCount = itemCount, + approval = approval, + showRunning = showRunning, + reasoning = reasoning, + onToggleReasoning = { reasoning = reasoning.toggled(it) }, + onDecision = { decision -> + approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) } + }, + ) + } + } + if (thread.error != null && thread.loaded) { + Text( + text = thread.error, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp), + ) + } + ChatComposer( + thread = thread, + onDraft = { vm.updateChatDraft(thread.sessionId, it) }, + onAttach = { vm.attachChatFiles(thread.sessionId, it) }, + onRemoveAttachment = { vm.removeChatAttachment(thread.sessionId, it) }, + onSend = { vm.sendChatPrompt(thread.sessionId) }, + onStop = { vm.stopChat(thread.sessionId) }, + ) + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt new file mode 100644 index 00000000..5e421c53 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt @@ -0,0 +1,184 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.components.ErrorState +import net.awan.pipelines.ui.components.ListRow +import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.theme.ICON_INLINE_DP +import net.awan.pipelines.ui.theme.pipelinesText + +// ---- The create flow: choose the directory, then create ---------------------- + +/** + * Where the operator starts a new chat: the server's directories, the home first + * and the recents after it, each with its full path. It is a normal pane of the + * chat stack — Back or its Cancel control leaves without creating anything — so + * starting a chat is a step in the flow rather than a modal dead end, and a + * session is never created wherever the server happens to run. + * + * The operator's home is the default; a recent is chosen with one tap, and the + * chat is created only when the operator confirms. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun NewChatPane( + vm: AppViewModel, + state: ChatState, + create: ChatCreateState, + modifier: Modifier, +) { + val choices = remember(state.directories) { directoryChoices(state.directories) } + val selected = remember(create.directory, choices) { + choices.firstOrNull { it.createDirectory == create.directory } ?: defaultDirectoryChoice(choices) + } + Scaffold( + modifier = modifier, + topBar = { + TopAppBar( + title = { Text("Start a chat") }, + navigationIcon = { + IconButton(onClick = vm::cancelNewChat) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel new chat") + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding)) { + when { + state.directoriesError != null && !state.directoriesLoaded -> + ErrorState(state.directoriesError, onRetry = vm::refreshChatDirectories) + !state.directoriesLoaded -> LoadingState("Loading directories…") + else -> { + Text( + text = "Where should this chat live?", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + LazyColumn(Modifier.weight(1f).fillMaxWidth()) { + items(choices, key = { it.createDirectory }) { choice -> + DirectoryRow( + choice = choice, + selected = choice.createDirectory == selected?.createDirectory, + onClick = { vm.selectChatDirectory(choice.createDirectory) }, + ) + } + } + if (state.directoriesError != null) { + Text( + text = state.directoriesError, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + } + create.error?.let { error -> + Text( + text = error, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + } + // The brokered server exposes no request for choosing a + // session's model: chat_prompt carries model/agent fields but + // the server does not forward them, and there is no catalogue + // request to offer a choice from. So the flow says so plainly + // rather than shipping a picker that would do nothing. The + // conversation header then shows whatever model the server + // reports for the created session. + Text( + text = "This server has no request for choosing a chat's model, so a new chat uses the server's default.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + NewChatActions( + directory = selected?.createDirectory ?: create.directory, + creating = create.creating, + onCreate = vm::createNewChat, + onCancel = vm::cancelNewChat, + ) + } + } + } + } +} + +/** One directory the new chat can live in: the home first, then the recents. */ +@Composable +private fun DirectoryRow(choice: ChatDirectoryChoice, selected: Boolean, onClick: () -> Unit) { + ListRow(selected = selected, onClick = onClick) { + Text( + text = choice.label, + style = pipelinesText().cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + // The home row's label is `~`, so its full path is shown beneath it; a + // recent's own label already is its full path. + choice.secondary?.let { path -> + Text(text = path, style = pipelinesText().meta, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +/** The create flow's footer: the chosen directory, its confirm and its cancel. */ +@Composable +private fun NewChatActions(directory: String, creating: Boolean, onCreate: () -> Unit, onCancel: () -> Unit) { + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP), + modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER), + ) { + Text( + text = "Start in $directory", + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onCancel, enabled = !creating) { Text("Cancel") } + Button(onClick = onCreate, enabled = !creating) { + if (creating) { + Box(contentAlignment = Alignment.Center) { + CircularProgressIndicator(Modifier.size(ICON_INLINE_DP), strokeWidth = 2.dp) + } + } else { + Text("New chat") + } + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDiffCard.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDiffCard.kt new file mode 100644 index 00000000..a91c1fb6 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDiffCard.kt @@ -0,0 +1,89 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT +import net.awan.pipelines.ui.components.RunState +import net.awan.pipelines.ui.components.RunStatusPalette +import net.awan.pipelines.ui.theme.pipelinesText + +/** The `+N -M` counts, green/red monospace, exactly as the reference diff stat. */ +@Composable +internal fun DiffStat(diff: ToolDiff) { + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Text( + text = "+${diff.added}", + style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace), + color = RunStatusPalette.of(RunState.Succeeded).color, + ) + Text( + text = "-${diff.removed}", + style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace), + color = RunStatusPalette.of(RunState.Failed).color, + ) + } +} + +/** + * The unified diff body of an edit card: line-by-line monospace with `+`/`-` + * gutter symbols and the app's success/failure hues, bounded so a long diff + * scrolls inside the card instead of pushing the transcript down. + */ +@Composable +internal fun DiffView(diff: ToolDiff) { + val added = RunStatusPalette.of(RunState.Succeeded).color + val removed = RunStatusPalette.of(RunState.Failed).color + val context = MaterialTheme.colorScheme.onSurfaceVariant + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = CODE_BLOCK_MAX_HEIGHT) + .verticalScroll(rememberScrollState()) + .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) { + if (diff.omitted > 0) { + // A very large edit is summarised rather than rendered in full, so + // the card stays short and readable on a phone. The note sits first + // so the truncation is visible without scrolling to the end. + Text( + text = "… ${diff.omitted} more changed " + + (if (diff.omitted == 1) "line" else "lines") + " not shown", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = CHAT_ITEM_GAP), + ) + } + diff.lines.forEach { line -> + val (symbol, color) = when (line.kind) { + DiffKind.ADD -> "+" to added + DiffKind.REMOVE -> "-" to removed + DiffKind.CONTEXT -> " " to context + } + Text( + text = "$symbol ${line.text}", + style = pipelinesText().mono, + color = color, + ) + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt new file mode 100644 index 00000000..2e17f36a --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt @@ -0,0 +1,424 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.components.EmptyState +import net.awan.pipelines.ui.components.ErrorState +import net.awan.pipelines.ui.components.FilterMenu +import net.awan.pipelines.ui.components.FilterSectionHeader +import net.awan.pipelines.ui.components.LabelChip +import net.awan.pipelines.ui.components.ListRow +import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.components.PaneIdentity +import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP +import net.awan.pipelines.ui.theme.ICON_INLINE_DP +import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XXS +import net.awan.pipelines.ui.theme.pipelinesText + +// ---- Pane 0: the server's session list --------------------------------------- + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun ChatListPane( + vm: AppViewModel, + state: ChatState, + connected: Boolean, + covered: Boolean, + modifier: Modifier, +) { + // A covered pane shows its compact identity only; the server list and the + // operator's own local changes are folded into the visible projection only + // for the pane actually drawn, never for the sliver behind a conversation. + if (covered) { + val count = state.visibleSessionCount + PaneIdentity( + title = "Chat", + subtitle = when { + state.open.isNotEmpty() -> "${state.open.size} open" + count > 0 -> "$count sessions" + else -> null + }, + modifier = modifier.fillMaxSize(), + ) + return + } + + // The server returns operator sessions only, with the operator's own local + // renames and removals applied on top; the app never guesses which session + // belongs to a run. The operator's search narrows that list without touching + // its order, and the survivors are grouped by directory when there is more + // than one so sessions in the same repository sit together. + val sessions = state.filteredSessions + val groups = groupChatSessionsByDirectory(sessions) + val query = state.sessionQuery + + // A removal is reported for what it is: a local, undoable change, never a + // pretend delete — the server is not asked to remove anything. + val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(state.lastRemoved) { + if (state.lastRemoved != null && + snackbarHostState.showSnackbar( + message = CHAT_REMOVED_MESSAGE, + actionLabel = "Undo", + duration = SnackbarDuration.Long, + ) == SnackbarResult.ActionPerformed + ) { + vm.undoRemoveChat() + } + } + var renaming by remember { mutableStateOf(null) } + + Scaffold( + modifier = modifier, + snackbarHost = { SnackbarHost(snackbarHostState) }, + topBar = { + TopAppBar( + title = { Text("Chat") }, + actions = { + ChatListSearchControl(query = query, onQuery = vm::setChatSessionQuery) + IconButton(onClick = vm::refreshChatSessions) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh chats") + } + // The create path stays one tap away while the list is + // narrowed: it is the same trailing action, never hidden. + IconButton(onClick = vm::startNewChat) { + Icon(Icons.Default.Add, contentDescription = "New chat") + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding)) { + if (state.open.isNotEmpty()) { + OpenChatStrip( + state = state, + onSelect = vm::activateChat, + onClose = vm::closeChat, + ) + } + if (!connected) { + NotConnectedNotice() + } + when { + state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…") + state.sessionsError != null && state.sessions.isEmpty() -> { + ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions) + } + sessions.isEmpty() && query.isNotBlank() -> EmptyState( + // A narrowing that matches nothing says so plainly and offers + // to clear it, the same empty-state pattern the other lists use. + message = "No chats match \"${query.trim()}\".", + actionLabel = "Clear search", + onAction = { vm.setChatSessionQuery("") }, + ) + sessions.isEmpty() -> EmptyState( + message = "No chat sessions on this server yet.", + actionLabel = "New chat", + onAction = vm::startNewChat, + ) + else -> LazyColumn(Modifier.fillMaxSize()) { + if (groups.size > 1) { + // More than one directory: one section per repository so + // same-directory chats sit together, each keeping the + // recency order inside it. + groups.forEach { group -> + item(key = "dir-" + group.directory) { DirectoryHeader(group.directory) } + items(group.sessions, key = { it.id }) { session -> + SessionListItem(state, session, vm, onRename = { renaming = it }) + } + } + } else { + items(sessions, key = { it.id }) { session -> + SessionListItem(state, session, vm, onRename = { renaming = it }) + } + } + if (state.sessionsError != null) { + item("error") { + Text( + text = state.sessionsError, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(CHAT_GUTTER), + ) + } + } + } + } + } + } + + renaming?.let { session -> + RenameChatDialog( + session = session, + onDismiss = { renaming = null }, + onConfirm = { title -> + vm.renameChat(session.id, title) + renaming = null + }, + ) + } +} + +/** + * The session-list search control: the same top-bar filter-menu pattern the other + * lists use, with one free-text field that narrows the list by title and directory + * as the operator types. The active-count badge and the reset action report and + * clear the narrowing, and the create action beside it is never hidden. + */ +@Composable +private fun ChatListSearchControl(query: String, onQuery: (String) -> Unit) { + FilterMenu( + activeCount = if (query.isBlank()) 0 else 1, + contentDescription = "Search chats", + resetLabel = "Clear search", + onReset = { onQuery("") }, + ) { + FilterSectionHeader("Search") + OutlinedTextField( + value = query, + onValueChange = onQuery, + label = { Text("Title or directory contains") }, + singleLine = true, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SPACING_M, vertical = SPACING_S), + ) + } +} + +/** + * One session of the list, whether it is rendered flat or inside a directory + * section: [SessionRow] fed from the live [state], so the activity marks, the open + * flag and the rename/remove actions are identical in both layouts. + */ +@Composable +private fun SessionListItem( + state: ChatState, + session: ChatSession, + vm: AppViewModel, + onRename: (ChatSession) -> Unit, +) { + val thread = state.thread(session.id) + SessionRow( + session = session, + open = thread != null, + running = thread?.running == true, + unseen = state.isUnseen(session), + active = state.activeId == session.id, + onClick = { vm.openChatSession(session) }, + onRename = { onRename(session) }, + onRemove = { vm.removeChat(session.id) }, + ) +} + +/** + * The heading of one directory section. The directory is shown here as well as on + * every row, so the grouping is legible even after a row scrolls out of view. + */ +@Composable +private fun DirectoryHeader(directory: String) { + Text( + text = directory.ifBlank { NO_DIRECTORY_LABEL }, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) +} + +/** The section heading for sessions the server reported without a directory. */ +private const val NO_DIRECTORY_LABEL = "No directory" + +@Composable +private fun SessionRow( + session: ChatSession, + open: Boolean, + running: Boolean, + unseen: Boolean, + active: Boolean, + onClick: () -> Unit, + onRename: () -> Unit, + onRemove: () -> Unit, +) { + val texts = pipelinesText() + val activity = sessionActivity(running, unseen) + ListRow(selected = active, onClick = onClick) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = sessionTitle(session), + style = texts.cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + // The kind chip names the session kind the server reported, so an + // operator chat is tellable from anything run-related at a glance. + sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) } + // The activity badge is the new-activity signal; the tag and the + // directory below are unchanged beside it. + SessionActivityBadge(activity, open) + SessionMenu(onRename = onRename, onRemove = onRemove) + } + val meta = buildList { + add(sessionStatusLabel(session, running)) + if (session.directory.isNotBlank()) add(session.directory) + if (session.model.isNotBlank()) add(session.model) + }.joinToString(" · ") + Text(text = meta, style = texts.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + +/** A session row's management actions: rename and remove from this device's list. */ +@Composable +private fun SessionMenu(onRename: () -> Unit, onRemove: () -> Unit) { + var expanded by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { expanded = true }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { + Icon( + Icons.Default.MoreVert, + contentDescription = "Chat actions", + modifier = Modifier.size(ICON_INLINE_DP), + ) + } + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + DropdownMenuItem( + text = { Text("Rename…") }, + onClick = { + expanded = false + onRename() + }, + ) + DropdownMenuItem( + text = { Text("Remove from list") }, + onClick = { + expanded = false + onRemove() + }, + ) + } + } +} + +/** + * The rename dialog. The brokered protocol has no rename for a chat session, so + * the dialog says plainly that the name is kept on this device rather than + * implying the server was told. + */ +@Composable +private fun RenameChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: (String) -> Unit) { + var title by remember(session.id) { mutableStateOf(sessionTitle(session)) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Rename chat") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + singleLine = true, + label = { Text("Name") }, + modifier = Modifier.fillMaxWidth(), + ) + Text( + text = "The server has no rename for a chat, so this name is kept on this device.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + confirmButton = { + TextButton(onClick = { onConfirm(title) }, enabled = title.isNotBlank()) { Text("Save") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** The removal report: what happened and how to undo it. */ +private const val CHAT_REMOVED_MESSAGE = "Removed from this list; the chat stays on the server." + +/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */ +@Composable +private fun SessionActivityBadge(activity: SessionActivity, open: Boolean) { + val label = when (activity) { + SessionActivity.STREAMING -> "Streaming" + SessionActivity.UNSEEN -> "New" + SessionActivity.IDLE -> if (open) "Open" else return + } + val color = when (activity) { + SessionActivity.STREAMING -> MaterialTheme.colorScheme.tertiary + SessionActivity.UNSEEN -> MaterialTheme.colorScheme.primary + SessionActivity.IDLE -> MaterialTheme.colorScheme.outline + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color)) + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun NotConnectedNotice() { + Surface( + color = MaterialTheme.colorScheme.errorContainer, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = "Not connected. Chats are served by the Pipelines server; connect in Settings.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOpenStrip.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOpenStrip.kt new file mode 100644 index 00000000..d2efd869 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOpenStrip.kt @@ -0,0 +1,116 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.PanTool +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.theme.CHAT_TITLE_MAX_WIDTH_DP +import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP +import net.awan.pipelines.ui.theme.ICON_STATUS_DP + +/** + * 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 +internal 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() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + threads.forEach { thread -> + val selected = state.activeId == thread.sessionId + Surface( + shape = RoundedCornerShape(50), + color = if (selected) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + modifier = Modifier + .selectable(selected = selected, role = Role.Tab, onClick = { onSelect(thread.sessionId) }), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.padding(start = CHAT_ITEM_GAP + 4.dp, end = 2.dp, top = 4.dp, bottom = 4.dp), + ) { + if (thread.running) { + Box( + Modifier.size(CHAT_STATUS_DOT).clip(CircleShape) + .background(MaterialTheme.colorScheme.tertiary), + ) + } + if (approvalCard(thread.permission, thread.permissionAnswer)?.actionable == true) { + // A request waiting on the operator is surfaced on the + // chat's own chip, so it is findable without opening it. + Icon( + Icons.Default.PanTool, + contentDescription = "Waiting for your approval", + tint = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.size(ICON_STATUS_DP), + ) + } + Text( + text = thread.title.ifBlank { thread.sessionId.take(12) }, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = CHAT_TITLE_MAX_WIDTH_DP), + ) + IconButton(onClick = { onClose(thread.sessionId) }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { + Icon( + Icons.Default.Close, + contentDescription = "Close chat ${thread.title}", + modifier = Modifier.size(16.dp), + ) + } + } + } + } + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) +} 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 ab0767f0..e7619e0e 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 @@ -1,175 +1,27 @@ package net.awan.pipelines.ui.chat -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.gestures.animateScrollBy -import androidx.compose.foundation.gestures.scrollBy -import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.interaction.DragInteraction -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material.icons.automirrored.filled.Send -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.AttachFile -import androidx.compose.material.icons.filled.Build -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.Edit -import androidx.compose.material.icons.filled.ErrorOutline -import androidx.compose.material.icons.filled.KeyboardArrowDown -import androidx.compose.material.icons.filled.KeyboardArrowUp -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material.icons.filled.PanTool -import androidx.compose.material.icons.filled.Psychology -import androidx.compose.material.icons.filled.Refresh -import androidx.compose.material.icons.filled.Stop -import androidx.compose.material.icons.outlined.Shield -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarDuration -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.SnackbarResult -import androidx.compose.material3.SmallFloatingActionButton -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.activity.compose.PredictiveBackHandler import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.key -import androidx.compose.runtime.mutableLongStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.IntRect -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Popup -import androidx.compose.ui.window.PopupPositionProvider -import androidx.compose.ui.window.PopupProperties -import androidx.compose.foundation.selection.selectable -import androidx.activity.compose.PredictiveBackHandler -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.compose.collectAsStateWithLifecycle -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -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 import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.ui.AppViewModel -import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT -import net.awan.pipelines.ui.components.CodeBlock -import net.awan.pipelines.ui.components.EmptyState -import net.awan.pipelines.ui.components.ErrorState -import net.awan.pipelines.ui.components.FilterMenu -import net.awan.pipelines.ui.components.FilterSectionHeader -import net.awan.pipelines.ui.components.LabelChip -import net.awan.pipelines.ui.components.ListRow -import net.awan.pipelines.ui.components.LoadingState -import net.awan.pipelines.ui.components.PaneIdentity -import net.awan.pipelines.ui.components.RunState -import net.awan.pipelines.ui.components.RunStatusPalette import net.awan.pipelines.ui.components.SlidingPaneStack -import net.awan.pipelines.ui.formatDuration -import net.awan.pipelines.ui.theme.CHAT_BUBBLE_MAX_WIDTH_DP -import net.awan.pipelines.ui.theme.CHAT_FOLLOW_THRESHOLD_DP -import net.awan.pipelines.ui.theme.CHAT_TITLE_MAX_WIDTH_DP -import net.awan.pipelines.ui.theme.HAIRLINE_DP -import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP -import net.awan.pipelines.ui.theme.ICON_INLINE_DP -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 /** * Geometry tokens for the chat surface. Every value is a named constant so no * screen body holds an ad-hoc number; Material's own minimum interactive size * governs touch targets. */ -private val CHAT_GUTTER = 16.dp +internal val CHAT_GUTTER = 16.dp internal val CHAT_ITEM_GAP = 8.dp -private val CHAT_COMPOSER_GAP = 12.dp -private val CHAT_STATUS_DOT = 8.dp - -/** - * The approval card's amber review panel and pending-card border strengths, - * echoing the reference app's 10%-alpha amber `RISK REVIEW` box. - */ -private const val RISK_REVIEW_ALPHA = 0.12f -private const val APPROVAL_PENDING_BORDER_ALPHA = 0.5f - -/** The tool panel floats over the transcript; these bound its width and offsets. */ - -private val TOOL_PANEL_GAP = 4.dp -private val TOOL_PANEL_MARGIN = 8.dp -private val TOOL_PANEL_ELEVATION = 12.dp - -/** The running indicator's elapsed time ticks once a second, never per frame. */ -private const val CHAT_ELAPSED_TICK_MILLIS = 1_000L +internal val CHAT_COMPOSER_GAP = 12.dp +internal val CHAT_STATUS_DOT = 8.dp /** * The Chat destination. It is the same adaptive [SlidingPaneStack] the Pipelines @@ -230,1635 +82,3 @@ fun ChatScreen(vm: AppViewModel, wide: Boolean, modifier: Modifier = Modifier) { } } } - -// ---- Pane 0: the server's session list --------------------------------------- - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun ChatListPane( - vm: AppViewModel, - state: ChatState, - connected: Boolean, - covered: Boolean, - modifier: Modifier, -) { - // A covered pane shows its compact identity only; the server list and the - // operator's own local changes are folded into the visible projection only - // for the pane actually drawn, never for the sliver behind a conversation. - if (covered) { - val count = state.visibleSessionCount - PaneIdentity( - title = "Chat", - subtitle = when { - state.open.isNotEmpty() -> "${state.open.size} open" - count > 0 -> "$count sessions" - else -> null - }, - modifier = modifier.fillMaxSize(), - ) - return - } - - // The server returns operator sessions only, with the operator's own local - // renames and removals applied on top; the app never guesses which session - // belongs to a run. The operator's search narrows that list without touching - // its order, and the survivors are grouped by directory when there is more - // than one so sessions in the same repository sit together. - val sessions = state.filteredSessions - val groups = groupChatSessionsByDirectory(sessions) - val query = state.sessionQuery - - // A removal is reported for what it is: a local, undoable change, never a - // pretend delete — the server is not asked to remove anything. - val snackbarHostState = remember { SnackbarHostState() } - LaunchedEffect(state.lastRemoved) { - if (state.lastRemoved != null && - snackbarHostState.showSnackbar( - message = CHAT_REMOVED_MESSAGE, - actionLabel = "Undo", - duration = SnackbarDuration.Long, - ) == SnackbarResult.ActionPerformed - ) { - vm.undoRemoveChat() - } - } - var renaming by remember { mutableStateOf(null) } - - Scaffold( - modifier = modifier, - snackbarHost = { SnackbarHost(snackbarHostState) }, - topBar = { - TopAppBar( - title = { Text("Chat") }, - actions = { - ChatListSearchControl(query = query, onQuery = vm::setChatSessionQuery) - IconButton(onClick = vm::refreshChatSessions) { - Icon(Icons.Default.Refresh, contentDescription = "Refresh chats") - } - // The create path stays one tap away while the list is - // narrowed: it is the same trailing action, never hidden. - IconButton(onClick = vm::startNewChat) { - Icon(Icons.Default.Add, contentDescription = "New chat") - } - }, - ) - }, - ) { padding -> - Column(Modifier.fillMaxSize().padding(padding)) { - if (state.open.isNotEmpty()) { - OpenChatStrip( - state = state, - onSelect = vm::activateChat, - onClose = vm::closeChat, - ) - } - if (!connected) { - NotConnectedNotice() - } - when { - state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…") - state.sessionsError != null && state.sessions.isEmpty() -> { - ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions) - } - sessions.isEmpty() && query.isNotBlank() -> EmptyState( - // A narrowing that matches nothing says so plainly and offers - // to clear it, the same empty-state pattern the other lists use. - message = "No chats match \"${query.trim()}\".", - actionLabel = "Clear search", - onAction = { vm.setChatSessionQuery("") }, - ) - sessions.isEmpty() -> EmptyState( - message = "No chat sessions on this server yet.", - actionLabel = "New chat", - onAction = vm::startNewChat, - ) - else -> LazyColumn(Modifier.fillMaxSize()) { - if (groups.size > 1) { - // More than one directory: one section per repository so - // same-directory chats sit together, each keeping the - // recency order inside it. - groups.forEach { group -> - item(key = "dir-" + group.directory) { DirectoryHeader(group.directory) } - items(group.sessions, key = { it.id }) { session -> - SessionListItem(state, session, vm, onRename = { renaming = it }) - } - } - } else { - items(sessions, key = { it.id }) { session -> - SessionListItem(state, session, vm, onRename = { renaming = it }) - } - } - if (state.sessionsError != null) { - item("error") { - Text( - text = state.sessionsError, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(CHAT_GUTTER), - ) - } - } - } - } - } - } - - renaming?.let { session -> - RenameChatDialog( - session = session, - onDismiss = { renaming = null }, - onConfirm = { title -> - vm.renameChat(session.id, title) - renaming = null - }, - ) - } -} - -/** - * The session-list search control: the same top-bar filter-menu pattern the other - * lists use, with one free-text field that narrows the list by title and directory - * as the operator types. The active-count badge and the reset action report and - * clear the narrowing, and the create action beside it is never hidden. - */ -@Composable -private fun ChatListSearchControl(query: String, onQuery: (String) -> Unit) { - FilterMenu( - activeCount = if (query.isBlank()) 0 else 1, - contentDescription = "Search chats", - resetLabel = "Clear search", - onReset = { onQuery("") }, - ) { - FilterSectionHeader("Search") - OutlinedTextField( - value = query, - onValueChange = onQuery, - label = { Text("Title or directory contains") }, - singleLine = true, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = SPACING_M, vertical = SPACING_S), - ) - } -} - -/** - * One session of the list, whether it is rendered flat or inside a directory - * section: [SessionRow] fed from the live [state], so the activity marks, the open - * flag and the rename/remove actions are identical in both layouts. - */ -@Composable -private fun SessionListItem( - state: ChatState, - session: ChatSession, - vm: AppViewModel, - onRename: (ChatSession) -> Unit, -) { - val thread = state.thread(session.id) - SessionRow( - session = session, - open = thread != null, - running = thread?.running == true, - unseen = state.isUnseen(session), - active = state.activeId == session.id, - onClick = { vm.openChatSession(session) }, - onRename = { onRename(session) }, - onRemove = { vm.removeChat(session.id) }, - ) -} - -/** - * The heading of one directory section. The directory is shown here as well as on - * every row, so the grouping is legible even after a row scrolls out of view. - */ -@Composable -private fun DirectoryHeader(directory: String) { - Text( - text = directory.ifBlank { NO_DIRECTORY_LABEL }, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) -} - -/** The section heading for sessions the server reported without a directory. */ -private const val NO_DIRECTORY_LABEL = "No directory" - -@Composable -private fun SessionRow( - session: ChatSession, - open: Boolean, - running: Boolean, - unseen: Boolean, - active: Boolean, - onClick: () -> Unit, - onRename: () -> Unit, - onRemove: () -> Unit, -) { - val texts = pipelinesText() - val activity = sessionActivity(running, unseen) - ListRow(selected = active, onClick = onClick) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - modifier = Modifier.fillMaxWidth(), - ) { - Text( - text = sessionTitle(session), - style = texts.cardTitle, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - // The kind chip names the session kind the server reported, so an - // operator chat is tellable from anything run-related at a glance. - sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) } - // The activity badge is the new-activity signal; the tag and the - // directory below are unchanged beside it. - SessionActivityBadge(activity, open) - SessionMenu(onRename = onRename, onRemove = onRemove) - } - val meta = buildList { - add(sessionStatusLabel(session, running)) - if (session.directory.isNotBlank()) add(session.directory) - if (session.model.isNotBlank()) add(session.model) - }.joinToString(" · ") - Text(text = meta, style = texts.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) - } -} - -/** A session row's management actions: rename and remove from this device's list. */ -@Composable -private fun SessionMenu(onRename: () -> Unit, onRemove: () -> Unit) { - var expanded by remember { mutableStateOf(false) } - Box { - IconButton(onClick = { expanded = true }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { - Icon( - Icons.Default.MoreVert, - contentDescription = "Chat actions", - modifier = Modifier.size(ICON_INLINE_DP), - ) - } - DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { - DropdownMenuItem( - text = { Text("Rename…") }, - onClick = { - expanded = false - onRename() - }, - ) - DropdownMenuItem( - text = { Text("Remove from list") }, - onClick = { - expanded = false - onRemove() - }, - ) - } - } -} - -/** - * The rename dialog. The brokered protocol has no rename for a chat session, so - * the dialog says plainly that the name is kept on this device rather than - * implying the server was told. - */ -@Composable -private fun RenameChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: (String) -> Unit) { - var title by remember(session.id) { mutableStateOf(sessionTitle(session)) } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Rename chat") }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - OutlinedTextField( - value = title, - onValueChange = { title = it }, - singleLine = true, - label = { Text("Name") }, - modifier = Modifier.fillMaxWidth(), - ) - Text( - text = "The server has no rename for a chat, so this name is kept on this device.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - }, - confirmButton = { - TextButton(onClick = { onConfirm(title) }, enabled = title.isNotBlank()) { Text("Save") } - }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} - -// ---- The create flow: choose the directory, then create ---------------------- - -/** - * Where the operator starts a new chat: the server's directories, the home first - * and the recents after it, each with its full path. It is a normal pane of the - * chat stack — Back or its Cancel control leaves without creating anything — so - * starting a chat is a step in the flow rather than a modal dead end, and a - * session is never created wherever the server happens to run. - * - * The operator's home is the default; a recent is chosen with one tap, and the - * chat is created only when the operator confirms. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun NewChatPane( - vm: AppViewModel, - state: ChatState, - create: ChatCreateState, - modifier: Modifier, -) { - val choices = remember(state.directories) { directoryChoices(state.directories) } - val selected = remember(create.directory, choices) { - choices.firstOrNull { it.createDirectory == create.directory } ?: defaultDirectoryChoice(choices) - } - Scaffold( - modifier = modifier, - topBar = { - TopAppBar( - title = { Text("Start a chat") }, - navigationIcon = { - IconButton(onClick = vm::cancelNewChat) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel new chat") - } - }, - ) - }, - ) { padding -> - Column(Modifier.fillMaxSize().padding(padding)) { - when { - state.directoriesError != null && !state.directoriesLoaded -> - ErrorState(state.directoriesError, onRetry = vm::refreshChatDirectories) - !state.directoriesLoaded -> LoadingState("Loading directories…") - else -> { - Text( - text = "Where should this chat live?", - style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) - LazyColumn(Modifier.weight(1f).fillMaxWidth()) { - items(choices, key = { it.createDirectory }) { choice -> - DirectoryRow( - choice = choice, - selected = choice.createDirectory == selected?.createDirectory, - onClick = { vm.selectChatDirectory(choice.createDirectory) }, - ) - } - } - if (state.directoriesError != null) { - Text( - text = state.directoriesError, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) - } - create.error?.let { error -> - Text( - text = error, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) - } - // The brokered server exposes no request for choosing a - // session's model: chat_prompt carries model/agent fields but - // the server does not forward them, and there is no catalogue - // request to offer a choice from. So the flow says so plainly - // rather than shipping a picker that would do nothing. The - // conversation header then shows whatever model the server - // reports for the created session. - Text( - text = "This server has no request for choosing a chat's model, so a new chat uses the server's default.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) - NewChatActions( - directory = selected?.createDirectory ?: create.directory, - creating = create.creating, - onCreate = vm::createNewChat, - onCancel = vm::cancelNewChat, - ) - } - } - } - } -} - -/** One directory the new chat can live in: the home first, then the recents. */ -@Composable -private fun DirectoryRow(choice: ChatDirectoryChoice, selected: Boolean, onClick: () -> Unit) { - ListRow(selected = selected, onClick = onClick) { - Text( - text = choice.label, - style = pipelinesText().cardTitle, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - // The home row's label is `~`, so its full path is shown beneath it; a - // recent's own label already is its full path. - choice.secondary?.let { path -> - Text(text = path, style = pipelinesText().meta, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } -} - -/** The create flow's footer: the chosen directory, its confirm and its cancel. */ -@Composable -private fun NewChatActions(directory: String, creating: Boolean, onCreate: () -> Unit, onCancel: () -> Unit) { - Surface(color = MaterialTheme.colorScheme.surfaceContainer) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP), - modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER), - ) { - Text( - text = "Start in $directory", - style = MaterialTheme.typography.bodyMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - TextButton(onClick = onCancel, enabled = !creating) { Text("Cancel") } - Button(onClick = onCreate, enabled = !creating) { - if (creating) { - Box(contentAlignment = Alignment.Center) { - CircularProgressIndicator(Modifier.size(ICON_INLINE_DP), strokeWidth = 2.dp) - } - } else { - Text("New chat") - } - } - } - } -} - -/** The removal report: what happened and how to undo it. */ -private const val CHAT_REMOVED_MESSAGE = "Removed from this list; the chat stays on the server." - -/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */ -@Composable -private fun SessionActivityBadge(activity: SessionActivity, open: Boolean) { - val label = when (activity) { - SessionActivity.STREAMING -> "Streaming" - SessionActivity.UNSEEN -> "New" - SessionActivity.IDLE -> if (open) "Open" else return - } - val color = when (activity) { - SessionActivity.STREAMING -> MaterialTheme.colorScheme.tertiary - SessionActivity.UNSEEN -> MaterialTheme.colorScheme.primary - SessionActivity.IDLE -> MaterialTheme.colorScheme.outline - } - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color)) - Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - } -} - -@Composable -private fun NotConnectedNotice() { - Surface( - color = MaterialTheme.colorScheme.errorContainer, - modifier = Modifier.fillMaxWidth(), - ) { - Text( - text = "Not connected. Chats are served by the Pipelines server; connect in Settings.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onErrorContainer, - modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) - } -} - -/** - * 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() - .horizontalScroll(rememberScrollState()) - .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - ) { - threads.forEach { thread -> - val selected = state.activeId == thread.sessionId - Surface( - shape = RoundedCornerShape(50), - color = if (selected) { - MaterialTheme.colorScheme.secondaryContainer - } else { - MaterialTheme.colorScheme.surfaceContainerHigh - }, - modifier = Modifier - .selectable(selected = selected, role = Role.Tab, onClick = { onSelect(thread.sessionId) }), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier.padding(start = CHAT_ITEM_GAP + 4.dp, end = 2.dp, top = 4.dp, bottom = 4.dp), - ) { - if (thread.running) { - Box( - Modifier.size(CHAT_STATUS_DOT).clip(CircleShape) - .background(MaterialTheme.colorScheme.tertiary), - ) - } - if (approvalCard(thread.permission, thread.permissionAnswer)?.actionable == true) { - // A request waiting on the operator is surfaced on the - // chat's own chip, so it is findable without opening it. - Icon( - Icons.Default.PanTool, - contentDescription = "Waiting for your approval", - tint = MaterialTheme.colorScheme.tertiary, - modifier = Modifier.size(ICON_STATUS_DP), - ) - } - Text( - text = thread.title.ifBlank { thread.sessionId.take(12) }, - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.widthIn(max = CHAT_TITLE_MAX_WIDTH_DP), - ) - IconButton(onClick = { onClose(thread.sessionId) }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { - Icon( - Icons.Default.Close, - contentDescription = "Close chat ${thread.title}", - modifier = Modifier.size(16.dp), - ) - } - } - } - } - } - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) -} - -// ---- 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( - vm: AppViewModel, - state: ChatState, - thread: ChatThread, - modifier: Modifier, -) { - 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 - // The count of the transcript's items: the messages, 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 + (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 - // chatOpensAtNewest), so the current turn is never hunted for. - val savedScroll = remember(thread.sessionId) { thread.scroll } - // The list state is created the moment the conversation first has content, so - // its very first measure is already at the newest item rather than at the top: - // opening a chat must not show anything else first. It is still saveable, so a - // rotation or process death keeps the operator's position. - val listState = rememberSaveable(thread.sessionId, itemCount > 0, saver = LazyListState.Saver) { - val first = chatFirstScroll(savedScroll, itemCount) - LazyListState( - firstVisibleItemIndex = first.index, - firstVisibleItemScrollOffset = first.offset, - ) - } - // Persist the scroll position when the operator leaves this chat, so switching - // away and back returns them exactly where they were. Keyed on the list state, - // so the position saved is the one that was actually shown; a state that never - // held content (replaced when the conversation first loaded) saves nothing, - // leaving the conversation with no position of its own to open at its newest. - DisposableEffect(listState) { - onDispose { - if (listState.layoutInfo.totalItemsCount > 0) { - vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) - } - } - } - val scope = rememberCoroutineScope() - - Scaffold( - modifier = modifier, - 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 = header.title, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - val meta = chatHeaderMeta(thread) - if (meta.isNotBlank()) { - Text( - text = meta, - style = pipelinesText().meta, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - }, - navigationIcon = { - IconButton(onClick = vm::showChatList) { - Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to chats") - } - }, - actions = { - if (awaiting) { - IconButton( - onClick = { - // The transcript's one scroll path, so a pending - // request is brought into view the same way new - // content is. - scope.launch { listState.scrollToEnd(itemCount, animated = true) } - }, - ) { - Icon( - Icons.Default.PanTool, - contentDescription = "Waiting for your approval", - tint = MaterialTheme.colorScheme.tertiary, - ) - } - } - if (thread.running) { - IconButton(onClick = { vm.stopChat(thread.sessionId) }) { - Icon(Icons.Default.Stop, contentDescription = "Stop") - } - } - }, - ) - }, - ) { padding -> - Column(Modifier.fillMaxSize().padding(padding).imePadding()) { - 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…") - thread.error != null && !thread.loaded -> ErrorState( - message = thread.error, - onRetry = { vm.loadChatHistory(thread.sessionId) }, - ) - thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState( - message = if (thread.readOnly) { - "This chat is read-only while another client holds the session." - } else { - "This chat has no messages yet. Ask something below." - }, - ) - else -> ChatTranscript( - thread = thread, - listState = listState, - savedScroll = savedScroll, - itemCount = itemCount, - approval = approval, - showRunning = showRunning, - reasoning = reasoning, - onToggleReasoning = { reasoning = reasoning.toggled(it) }, - onDecision = { decision -> - approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) } - }, - ) - } - } - if (thread.error != null && thread.loaded) { - Text( - text = thread.error, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp), - ) - } - ChatComposer( - thread = thread, - onDraft = { vm.updateChatDraft(thread.sessionId, it) }, - onAttach = { vm.attachChatFiles(thread.sessionId, it) }, - onRemoveAttachment = { vm.removeChatAttachment(thread.sessionId, it) }, - onSend = { vm.sendChatPrompt(thread.sessionId) }, - onStop = { vm.stopChat(thread.sessionId) }, - ) - } - } -} - -/** - * The bottom-anchored transcript: content is packed to the bottom (so a short or - * freshly opened chat sits against the composer) and the running indicator sits - * at the newest end while a turn is in flight. - * - * The transcript has one scroll path ([scrollToEnd] / [closeBottomGap]) and one - * decision for whether it follows new content. It opens at the newest message - * (placed by the pane's initial position, with any part of a last message taller - * than the viewport closed instantly here), and then — while the operator intends - * to read the newest part — every arrival (a message, a streamed delta, a tool - * chip, a grown composer or the appearing keyboard) is followed smoothly, so the - * newest content stays in view. An item that arrives entirely below the fold is - * brought in rather than left there. A freshly arrived approval card is followed - * the same way. Once the operator has scrolled up to read history nothing moves - * under them, and the jump-to-latest affordance is offered instead. - */ -@Composable -private fun ChatTranscript( - thread: ChatThread, - listState: LazyListState, - savedScroll: ChatScrollPosition?, - itemCount: Int, - approval: ApprovalCard?, - showRunning: Boolean, - reasoning: ReasoningExpansion, - onToggleReasoning: (String) -> Unit, - onDecision: (String) -> Unit, -) { - val scope = rememberCoroutineScope() - val density = LocalDensity.current - val thresholdPx = remember(density) { with(density) { CHAT_FOLLOW_THRESHOLD_DP.roundToPx() } } - // The transcript's item count, read at use time: the drag collector and the - // derived state below outlive any single recomposition, so a count captured - // when they were created would go stale as messages arrive and the follow - // would measure against how many items there used to be. - val currentItemCount by rememberUpdatedState(itemCount) - // Whether the operator wants the newest content kept in view. Only their own - // drag changes it — a programmatic scroll never touches the list's - // interactionSource, so it cannot un-stick the view — and a drag that settles - // at (or within the threshold of) the bottom resumes the follow. Its real - // value is settled once the transcript is placed, when the live distance to - // the bottom is known. - // Saved, so a rotation or process death while the operator is reading history - // restores "not following" too, rather than the restored transcript being - // yanked to the bottom by the placement the new composition would otherwise run. - var following by rememberSaveable(thread.sessionId) { mutableStateOf(true) } - LaunchedEffect(listState, thresholdPx) { - listState.interactionSource.interactions.collect { interaction -> - when (interaction) { - is DragInteraction.Start -> following = false - is DragInteraction.Stop, is DragInteraction.Cancel -> - following = chatFollowsAt( - distanceFromBottomPx = listState.bottomDistancePx(currentItemCount), - thresholdPx = thresholdPx, - itemCount = currentItemCount, - ) - else -> Unit - } - } - } - // The distance to the transcript's end, read through a derived state so the - // affordance's visibility is recomputed only when it actually changes rather - // than on every scrolled pixel. The item count is read through - // [currentItemCount] so the derived value also recomputes as content arrives. - val showJumpToLatest by remember(listState, thresholdPx) { - derivedStateOf { - chatShowJumpToLatest( - following = following, - distanceFromBottomPx = listState.bottomDistancePx(currentItemCount), - thresholdPx = thresholdPx, - itemCount = currentItemCount, - ) - } - } - // The transcript is placed once, when it first has content, and only after it - // has been measured; the viewport height is an input too, so a grown composer - // or the appearing keyboard re-follows rather than leaving the newest message - // hidden behind it. Placement itself is saved, so restoring a rotation does not - // re-place (and re-follow) a transcript the operator had scrolled up. - var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) } - val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } } - LaunchedEffect(thread.messages, thread.running, approval?.requestId, viewportHeight) { - if (itemCount <= 0) return@LaunchedEffect - if (!placed) { - // Wait for the first measure: placement run before it would no-op and - // leave the first display to the measured re-run, which animates, and - // the first display must not animate. - if (viewportHeight <= 0) return@LaunchedEffect - placed = true - if (chatOpensAtNewest(savedScroll)) { - // No position of the operator's own: bring the newest item fully - // into view, instantly — the first display must not animate — and - // through the same path the follow uses, so placement and follow - // cannot disagree about what the newest item is (a last message - // taller than the viewport has its below-the-fold part closed by - // the same call), then follow. - listState.scrollToEnd(itemCount, animated = false) - following = true - } else { - // A position the operator left: follow only if it was the bottom, so - // returning to a chat never yanks the view. - following = chatFollowsAt(listState.bottomDistancePx(itemCount), thresholdPx, itemCount) - } - return@LaunchedEffect - } - 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(), - 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, - onToggleReasoning = onToggleReasoning, - ) - } - if (showRunning) { - item(key = "pending") { RunningIndicator(thread) } - } - if (approval != null) { - // Keyed by request id so switching between requests swaps the card - // instead of reusing the previous one's state. - item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) } - } - } - // Offered only once the transcript is placed and the operator has left the - // bottom, so it never covers the newest content it would return to. - if (placed && showJumpToLatest) { - SmallFloatingActionButton( - onClick = { - following = true - scope.launch { listState.scrollToEnd(itemCount, animated = true) } - }, - modifier = Modifier.align(Alignment.BottomEnd).padding(CHAT_GUTTER), - ) { - Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Jump to latest") - } - } - } -} - -/** - * The transcript's one scroll path, shared by the first placement, the follow, - * the app-bar approval jump and the jump-to-latest affordance. The newest item is - * brought into view when it sits entirely below the fold — an item appended past - * the viewport's edge, so no pixel of it is on screen and the remaining distance - * cannot be measured — and any part of it still below the fold (a message taller - * than the viewport) is then closed by exactly that distance. An item that is - * already partly visible is only gap-closed, never moved up first. [animated] is - * false only for the first placement, which must not animate. - * - * [itemCount] is the transcript's *content* count, which can be ahead of the - * layout's: an appended item exists in the content before the recomposition that - * measures it, and the effect that follows it is dispatched ahead of that measure, - * so the layout still describes the previous items and its own last visible item - * reads as the end. Measuring against [itemCount] — see [bottomDistancePx] — is - * what stops an appended item from being mistaken for the already-visible end and - * left below the fold: it has no pixel on screen, so it is unknown-distance and is - * brought into view rather than gap-closed at zero. - */ -private suspend fun LazyListState.scrollToEnd(itemCount: Int, animated: Boolean) { - if (itemCount <= 0) return - if (bottomDistancePx(itemCount) == null) { - if (animated) animateScrollToItem(itemCount - 1) else scrollToItem(itemCount - 1) - } - closeBottomGap(itemCount, animated) -} - -/** - * Scrolls the transcript's end into view by exactly the distance it sits below - * the viewport, measured against the same [itemCount] the decisions above use. - */ -private suspend fun LazyListState.closeBottomGap(itemCount: Int, animated: Boolean) { - val remaining = bottomDistancePx(itemCount) ?: return - if (remaining <= 0) return - if (animated) animateScrollBy(remaining.toFloat()) else scrollBy(remaining.toFloat()) -} - -/** - * The distance from the transcript's end to the viewport's bottom, measured - * against [itemCount] — the transcript's *content* count, not the layout's. The - * two differ on the frame content arrives: the layout still describes the - * previous items, so its own last visible item reads as the end and the appended - * item's absence is invisible. Measuring against the content count makes the - * appended item read exactly as [chatBottomDistancePx] defines it — no pixel on - * screen — so the scroll path above brings it into view rather than trusting a - * stale layout's "already at the end". [itemCount] is what the transcript - * renders, so the two counts agree as soon as the layout catches up. - */ -private fun LazyListState.bottomDistancePx(itemCount: Int): Int? { - val info = layoutInfo - val last = info.visibleItemsInfo.lastOrNull() - return chatBottomDistancePx( - lastVisibleIndex = last?.index ?: -1, - lastVisibleEndPx = last?.let { it.offset + it.size } ?: 0, - itemCount = itemCount, - viewportEndPx = info.viewportEndOffset, - ) -} - -/** - * The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed - * time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]), - * so it keeps counting across a chat switch, and the tick loop stops the moment - * the turn settles. - */ -@Composable -private fun RunningIndicator(thread: ChatThread) { - val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince)) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), - ) { - CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) - Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text( - text = "· ${formatDuration(elapsedMillis / 1_000)}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -/** - * The wall clock, re-read once a second while a turn is in flight, so the - * indicator derives the elapsed time with [ChatThread.elapsedMillis] — the one - * derivation its unit test also shares — instead of subtracting the turn's start - * itself. Keyed on [runningSince] and only entered for a live turn, so a settled - * chat schedules nothing. - */ -@Composable -private fun rememberElapsedNow(runningSince: Long): Long { - var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) } - LaunchedEffect(runningSince) { - if (runningSince <= 0) return@LaunchedEffect - while (true) { - nowMillis = System.currentTimeMillis() - delay(CHAT_ELAPSED_TICK_MILLIS) - } - } - return nowMillis -} - -@Composable -private fun MessageItem( - message: ChatMessage, - reasoning: ReasoningExpansion, - streaming: Boolean, - onToggleReasoning: (String) -> Unit, -) { - val isUser = message.role == ChatProtocol.ROLE_USER - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start, - ) { - Surface( - shape = RoundedCornerShape(CHAT_GUTTER), - color = if (isUser) { - MaterialTheme.colorScheme.secondaryContainer - } else { - MaterialTheme.colorScheme.surfaceContainer - }, - modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP), - ) { - SelectionContainer { - Column(Modifier.padding(CHAT_GUTTER)) { - if (isUser) { - UserParts(message.parts) - } else { - AssistantParts( - messageId = message.id, - parts = message.parts, - reasoning = reasoning, - streaming = streaming, - onToggleReasoning = onToggleReasoning, - ) - } - } - } - } - } -} - -/** - * 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 - * sent message shows its file in the transcript through the one display path - * rather than a second attachment list under the bubble. - */ -@Composable -private fun UserParts(parts: List) { - val text = parts.filter { it.type == ChatProtocol.PART_TEXT || it.type.isBlank() } - .joinToString("\n") { it.text } - .trim() - val files = parts.filter { it.type == ChatProtocol.PART_FILE } - Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - if (text.isNotBlank()) Text(text, style = MaterialTheme.typography.bodyMedium) - files.forEach { FilePart(it) } - } -} - -/** - * 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. - */ -@Composable -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) { - 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++ - } - } -} - -@Composable -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 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, - expanded: Boolean, - streaming: Boolean, - onToggle: () -> Unit, -) { - if (text.isBlank()) return - 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 - * shows its name (or the edited file), its duration and a spinner while it runs, - * and the chips of the turn wrap together on as few lines as they fit instead of - * each taking a row. - * - * Tapping a chip opens its INPUT (pretty JSON) / OUTPUT (monospace) panel as an - * overlay anchored to that chip (research §1.3 `_buildPanel`), dismissed by its - * own X or by tapping outside. Because the panel is a popup and not part of the - * transcript layout, opening or closing it never re-flows the conversation nor - * moves its scroll position — the transcript stays exactly where the operator - * left it. - * - * An `edit`-family call expands to a diff card (research §1.3 `_CodeRun` / - * `_DiffView`): the `+N -M` stat on the chip and a green/red unified diff derived - * from the arguments, since the brokered protocol carries no diff field. An - * `error` call is visibly failed — an error-tinted chip and error icon — and its - * panel shows the error text. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun ToolCalls(parts: List) { - // One id at a time: the reference shows a single panel, and a focusable popup - // dismisses the previous one on open. No key is needed: an id that is no - // longer among the calls simply matches nothing, so a streaming rebuild keeps - // the panel the operator just opened without allocating a key list per frame. - var openId by remember { mutableStateOf(null) } - FlowRow( - modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - ) { - parts.forEach { part -> - ToolChip( - part = part, - expanded = openId == part.id, - onToggle = { openId = if (openId == part.id) null else part.id }, - onDismiss = { openId = null }, - ) - } - } -} - -/** A compact tool-call chip: kind icon, label, diff stat, duration and chevron. */ -@Composable -private fun ToolChip(part: ChatPart, expanded: Boolean, onToggle: () -> Unit, onDismiss: () -> Unit) { - val running = ChatProtocol.toolRunning(part.state) - val failed = toolFailed(part.state) - val diff = toolEditDiff(part.state?.input) - Box { - Surface( - shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp), - color = if (failed) { - MaterialTheme.colorScheme.errorContainer - } else { - MaterialTheme.colorScheme.surfaceContainerHigh - }, - modifier = Modifier.clickable(onClick = onToggle), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP), - ) { - if (running) { - CircularProgressIndicator(Modifier.size(ICON_STATUS_DP), strokeWidth = 2.dp) - } else { - Icon( - imageVector = when { - failed -> Icons.Default.ErrorOutline - diff != null -> Icons.Default.Edit - else -> Icons.Default.Build - }, - contentDescription = if (failed) "Failed tool call" else null, - modifier = Modifier.size(16.dp), - tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Text( - text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - diff?.let { DiffStat(it) } - toolDurationMillis(part)?.let { - Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - Icon( - imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, - contentDescription = if (expanded) "Collapse tool call" else "Expand tool call", - modifier = Modifier.size(ICON_INLINE_DP), - ) - } - } - if (expanded) { - Popup( - popupPositionProvider = rememberToolPanelPositionProvider(), - onDismissRequest = onDismiss, - properties = PopupProperties(focusable = true), - ) { - ToolPanel(part = part, onDismiss = onDismiss) - } - } - } -} - -/** - * Anchors the tool panel just below its chip, or above it when there is no room - * below, keeping it inside the window margins — the same flip the reference - * panel does. Resolved in px, so it is independent of the current density. - */ -internal class ToolPanelPositionProvider(private val gapPx: Int, private val marginPx: Int) : PopupPositionProvider { - override fun calculatePosition( - anchorBounds: IntRect, - windowSize: IntSize, - layoutDirection: LayoutDirection, - popupContentSize: IntSize, - ): IntOffset { - val maxX = (windowSize.width - popupContentSize.width - marginPx).coerceAtLeast(marginPx) - val x = anchorBounds.left.coerceIn(marginPx, maxX) - val below = anchorBounds.bottom + gapPx - val above = anchorBounds.top - popupContentSize.height - gapPx - val maxY = (windowSize.height - popupContentSize.height - marginPx).coerceAtLeast(marginPx) - val y = if (below <= maxY) below else above.coerceAtLeast(marginPx) - return IntOffset(x, y) - } -} - -@Composable -private fun rememberToolPanelPositionProvider(): PopupPositionProvider { - val density = LocalDensity.current - return remember(density) { - ToolPanelPositionProvider( - gapPx = with(density) { TOOL_PANEL_GAP.roundToPx() }, - marginPx = with(density) { TOOL_PANEL_MARGIN.roundToPx() }, - ) - } -} - -/** - * The expanded panel of one tool call, mirroring the reference panel - * (`_buildPanel`, research §1.3): a header naming the call and its duration with - * a close X, then the pretty-printed INPUT and the monospace OUTPUT (or the - * synthesised edit diff). Both content blocks carry the shared whole-block copy - * action from [CodeBlock]. A failed call always renders its error text in an - * ERROR block — even an edit-family call, whose diff is still shown alongside it. - */ -@Composable -private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier = Modifier) { - val diff = toolEditDiff(part.state?.input) - val failed = toolFailed(part.state) - Surface( - shape = RoundedCornerShape(CHAT_ITEM_GAP), - color = MaterialTheme.colorScheme.surfaceContainer, - shadowElevation = TOOL_PANEL_ELEVATION, - modifier = modifier.widthIn(max = TOOL_PANEL_MAX_WIDTH_DP).fillMaxWidth(), - ) { - Column( - verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - modifier = Modifier.fillMaxWidth().padding(CHAT_ITEM_GAP + 2.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - Icon( - imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build, - contentDescription = null, - modifier = Modifier.size(16.dp), - tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, - ) - Text( - text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), - style = MaterialTheme.typography.labelLarge, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - diff?.let { DiffStat(it) } - toolDurationMillis(part)?.let { - Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - IconButton(onClick = onDismiss, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { - Icon(Icons.Default.Close, contentDescription = "Close tool call", modifier = Modifier.size(16.dp)) - } - } - if (diff != null) { - DiffView(diff) - } else { - CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input)) - } - if (failed) { - CodeBlock(label = "ERROR", text = toolErrorText(part.state)) - } else if (diff == null) { - CodeBlock(label = "OUTPUT", text = toolOutputText(part.state)) - } - } - } -} - -/** The `+N -M` counts, green/red monospace, exactly as the reference diff stat. */ -@Composable -private fun DiffStat(diff: ToolDiff) { - Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - Text( - text = "+${diff.added}", - style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace), - color = RunStatusPalette.of(RunState.Succeeded).color, - ) - Text( - text = "-${diff.removed}", - style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace), - color = RunStatusPalette.of(RunState.Failed).color, - ) - } -} - -/** - * The unified diff body of an edit card: line-by-line monospace with `+`/`-` - * gutter symbols and the app's success/failure hues, bounded so a long diff - * scrolls inside the card instead of pushing the transcript down. - */ -@Composable -private fun DiffView(diff: ToolDiff) { - val added = RunStatusPalette.of(RunState.Succeeded).color - val removed = RunStatusPalette.of(RunState.Failed).color - val context = MaterialTheme.colorScheme.onSurfaceVariant - Card( - modifier = Modifier.fillMaxWidth(), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), - elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), - ) { - Column( - modifier = Modifier - .fillMaxWidth() - .heightIn(max = CODE_BLOCK_MAX_HEIGHT) - .verticalScroll(rememberScrollState()) - .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), - ) { - if (diff.omitted > 0) { - // A very large edit is summarised rather than rendered in full, so - // the card stays short and readable on a phone. The note sits first - // so the truncation is visible without scrolling to the end. - Text( - text = "… ${diff.omitted} more changed " + - (if (diff.omitted == 1) "line" else "lines") + " not shown", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(bottom = CHAT_ITEM_GAP), - ) - } - diff.lines.forEach { line -> - val (symbol, color) = when (line.kind) { - DiffKind.ADD -> "+" to added - DiffKind.REMOVE -> "-" to removed - DiffKind.CONTEXT -> " " to context - } - Text( - text = "$symbol ${line.text}", - style = pipelinesText().mono, - color = color, - ) - } - } - } -} - -@Composable -private fun ChatComposer( - thread: ChatThread, - onDraft: (String) -> Unit, - onAttach: (List) -> Unit, - onRemoveAttachment: (String) -> Unit, - onSend: () -> Unit, - onStop: () -> Unit, -) { - val action = composerAction(thread) - val context = LocalContext.current - val scope = rememberCoroutineScope() - // The platform picker: the operator chooses files and they are only resolved - // into attachments here — nothing is sent until the message is. - val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> - if (uris.isNotEmpty()) { - scope.launch { - val resolved = withContext(Dispatchers.IO) { uris.map { resolveChatAttachment(context, it) } } - onAttach(resolved) - } - } - } - Surface(color = MaterialTheme.colorScheme.surfaceContainer) { - Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) { - if (thread.readOnly) { - Text( - text = "Another client holds this session; it is read-only here.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(bottom = CHAT_ITEM_GAP), - ) - } - if (thread.attachments.isNotEmpty()) { - ChatAttachmentStrip(attachments = thread.attachments, onRemove = onRemoveAttachment) - } - Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) { - IconButton( - onClick = { picker.launch(arrayOf("*/*")) }, - enabled = !thread.readOnly, - ) { - Icon(Icons.Default.AttachFile, contentDescription = "Attach file") - } - OutlinedTextField( - value = thread.draft, - onValueChange = onDraft, - enabled = !thread.readOnly, - placeholder = { Text("Message the agent…") }, - minLines = 1, - maxLines = 6, - keyboardActions = KeyboardActions( - onSend = { if (action == ComposerAction.Send && thread.canSend) onSend() }, - ), - modifier = Modifier.weight(1f), - ) - when (action) { - // While a turn is in flight the send control becomes the stop - // control, so it must interrupt rather than send the draft. - ComposerAction.Stop -> IconButton(onClick = onStop) { - Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error) - } - ComposerAction.Send -> IconButton(onClick = onSend, enabled = thread.canSend) { - Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send") - } - } - } - } - } -} - -/** - * One approval request as a card in the conversation (research §1.3 `_CodeRun` / - * risk review): the action being requested, the affected resources, the amber - * `RISK REVIEW` panel repeating the server's risk summary, and once/always/reject - * actions answered with `chat_reply`, so the server-held credentials and the tool - * never leave it. A card that is already answered or resolved keeps its place but - * drops the actions and states the outcome, so it can never offer a stale choice. - */ -@Composable -private fun ApprovalCardItem(card: ApprovalCard, onDecision: (String) -> Unit) { - val amber = MaterialTheme.colorScheme.tertiary - Card( - modifier = Modifier.fillMaxWidth(), - colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh), - elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), - border = if (card.actionable) BorderStroke(HAIRLINE_DP, amber.copy(alpha = APPROVAL_PENDING_BORDER_ALPHA)) else null, - ) { - Column( - modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER), - verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_LIST_DP)) - Column(Modifier.weight(1f)) { - Text(card.headline, style = pipelinesText().cardTitle) - Text( - text = card.statusLine, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - if (card.resources.isNotEmpty()) { - Text( - text = card.resources.joinToString("\n"), - style = pipelinesText().mono, - maxLines = 6, - overflow = TextOverflow.Ellipsis, - ) - } - if (card.showRisk && card.risk.isNotBlank()) { - Column( - modifier = Modifier - .fillMaxWidth() - .clip(RoundedCornerShape(CHAT_ITEM_GAP)) - .background(amber.copy(alpha = RISK_REVIEW_ALPHA)) - .padding(CHAT_ITEM_GAP), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(ICON_STATUS_DP)) - Text("RISK REVIEW", style = MaterialTheme.typography.labelSmall, color = amber) - } - Text(card.risk, style = MaterialTheme.typography.bodySmall) - } - } - if (card.actionable) { - Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - Button(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") } - TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always allow") } - TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Reject") } - } - } - } - } -} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt new file mode 100644 index 00000000..ed9738cd --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatToolCalls.kt @@ -0,0 +1,256 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Build +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.ErrorOutline +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP +import net.awan.pipelines.ui.theme.ICON_INLINE_DP +import net.awan.pipelines.ui.theme.ICON_STATUS_DP +import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP + +/** The tool panel floats over the transcript; these bound its width and offsets. */ + +private val TOOL_PANEL_GAP = 4.dp +private val TOOL_PANEL_MARGIN = 8.dp +private val TOOL_PANEL_ELEVATION = 12.dp + +/** + * One turn's tool calls as a single group of compact chips, mirroring the + * reference transcript's `_ToolCalls`/`_ToolChip` (research §1.3): each call + * shows its name (or the edited file), its duration and a spinner while it runs, + * and the chips of the turn wrap together on as few lines as they fit instead of + * each taking a row. + * + * Tapping a chip opens its INPUT (pretty JSON) / OUTPUT (monospace) panel as an + * overlay anchored to that chip (research §1.3 `_buildPanel`), dismissed by its + * own X or by tapping outside. Because the panel is a popup and not part of the + * transcript layout, opening or closing it never re-flows the conversation nor + * moves its scroll position — the transcript stays exactly where the operator + * left it. + * + * An `edit`-family call expands to a diff card (research §1.3 `_CodeRun` / + * `_DiffView`): the `+N -M` stat on the chip and a green/red unified diff derived + * from the arguments, since the brokered protocol carries no diff field. An + * `error` call is visibly failed — an error-tinted chip and error icon — and its + * panel shows the error text. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun ToolCalls(parts: List) { + // One id at a time: the reference shows a single panel, and a focusable popup + // dismisses the previous one on open. No key is needed: an id that is no + // longer among the calls simply matches nothing, so a streaming rebuild keeps + // the panel the operator just opened without allocating a key list per frame. + var openId by remember { mutableStateOf(null) } + FlowRow( + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + parts.forEach { part -> + ToolChip( + part = part, + expanded = openId == part.id, + onToggle = { openId = if (openId == part.id) null else part.id }, + onDismiss = { openId = null }, + ) + } + } +} + +/** A compact tool-call chip: kind icon, label, diff stat, duration and chevron. */ +@Composable +private fun ToolChip(part: ChatPart, expanded: Boolean, onToggle: () -> Unit, onDismiss: () -> Unit) { + val running = ChatProtocol.toolRunning(part.state) + val failed = toolFailed(part.state) + val diff = toolEditDiff(part.state?.input) + Box { + Surface( + shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp), + color = if (failed) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + modifier = Modifier.clickable(onClick = onToggle), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP), + ) { + if (running) { + CircularProgressIndicator(Modifier.size(ICON_STATUS_DP), strokeWidth = 2.dp) + } else { + Icon( + imageVector = when { + failed -> Icons.Default.ErrorOutline + diff != null -> Icons.Default.Edit + else -> Icons.Default.Build + }, + contentDescription = if (failed) "Failed tool call" else null, + modifier = Modifier.size(16.dp), + tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Text( + text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + diff?.let { DiffStat(it) } + toolDurationMillis(part)?.let { + Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Icon( + imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, + contentDescription = if (expanded) "Collapse tool call" else "Expand tool call", + modifier = Modifier.size(ICON_INLINE_DP), + ) + } + } + if (expanded) { + Popup( + popupPositionProvider = rememberToolPanelPositionProvider(), + onDismissRequest = onDismiss, + properties = PopupProperties(focusable = true), + ) { + ToolPanel(part = part, onDismiss = onDismiss) + } + } + } +} + +/** + * Anchors the tool panel just below its chip, or above it when there is no room + * below, keeping it inside the window margins — the same flip the reference + * panel does. Resolved in px, so it is independent of the current density. + */ +internal class ToolPanelPositionProvider(private val gapPx: Int, private val marginPx: Int) : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val maxX = (windowSize.width - popupContentSize.width - marginPx).coerceAtLeast(marginPx) + val x = anchorBounds.left.coerceIn(marginPx, maxX) + val below = anchorBounds.bottom + gapPx + val above = anchorBounds.top - popupContentSize.height - gapPx + val maxY = (windowSize.height - popupContentSize.height - marginPx).coerceAtLeast(marginPx) + val y = if (below <= maxY) below else above.coerceAtLeast(marginPx) + return IntOffset(x, y) + } +} + +@Composable +private fun rememberToolPanelPositionProvider(): PopupPositionProvider { + val density = LocalDensity.current + return remember(density) { + ToolPanelPositionProvider( + gapPx = with(density) { TOOL_PANEL_GAP.roundToPx() }, + marginPx = with(density) { TOOL_PANEL_MARGIN.roundToPx() }, + ) + } +} + +/** + * The expanded panel of one tool call, mirroring the reference panel + * (`_buildPanel`, research §1.3): a header naming the call and its duration with + * a close X, then the pretty-printed INPUT and the monospace OUTPUT (or the + * synthesised edit diff). Both content blocks carry the shared whole-block copy + * action from [CodeBlock]. A failed call always renders its error text in an + * ERROR block — even an edit-family call, whose diff is still shown alongside it. + */ +@Composable +private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier = Modifier) { + val diff = toolEditDiff(part.state?.input) + val failed = toolFailed(part.state) + Surface( + shape = RoundedCornerShape(CHAT_ITEM_GAP), + color = MaterialTheme.colorScheme.surfaceContainer, + shadowElevation = TOOL_PANEL_ELEVATION, + modifier = modifier.widthIn(max = TOOL_PANEL_MAX_WIDTH_DP).fillMaxWidth(), + ) { + Column( + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth().padding(CHAT_ITEM_GAP + 2.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Icon( + imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build, + contentDescription = null, + modifier = Modifier.size(16.dp), + tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + ) + Text( + text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), + style = MaterialTheme.typography.labelLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + diff?.let { DiffStat(it) } + toolDurationMillis(part)?.let { + Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + IconButton(onClick = onDismiss, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { + Icon(Icons.Default.Close, contentDescription = "Close tool call", modifier = Modifier.size(16.dp)) + } + } + if (diff != null) { + DiffView(diff) + } else { + CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input)) + } + if (failed) { + CodeBlock(label = "ERROR", text = toolErrorText(part.state)) + } else if (diff == null) { + CodeBlock(label = "OUTPUT", text = toolOutputText(part.state)) + } + } + } +} 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 new file mode 100644 index 00000000..8eb37d9f --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatTranscript.kt @@ -0,0 +1,491 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.animateScrollBy +import androidx.compose.foundation.gestures.scrollBy +import androidx.compose.foundation.interaction.DragInteraction +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Psychology +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SmallFloatingActionButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +import net.awan.pipelines.data.protocol.ChatMessage +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.ui.formatDuration +import net.awan.pipelines.ui.theme.CHAT_BUBBLE_MAX_WIDTH_DP +import net.awan.pipelines.ui.theme.CHAT_FOLLOW_THRESHOLD_DP +import net.awan.pipelines.ui.theme.ICON_INLINE_DP +import net.awan.pipelines.ui.theme.SPACING_XS + +/** The running indicator's elapsed time ticks once a second, never per frame. */ +private const val CHAT_ELAPSED_TICK_MILLIS = 1_000L + +/** + * The bottom-anchored transcript: content is packed to the bottom (so a short or + * freshly opened chat sits against the composer) and the running indicator sits + * at the newest end while a turn is in flight. + * + * The transcript has one scroll path ([scrollToEnd] / [closeBottomGap]) and one + * decision for whether it follows new content. It opens at the newest message + * (placed by the pane's initial position, with any part of a last message taller + * than the viewport closed instantly here), and then — while the operator intends + * to read the newest part — every arrival (a message, a streamed delta, a tool + * chip, a grown composer or the appearing keyboard) is followed smoothly, so the + * newest content stays in view. An item that arrives entirely below the fold is + * brought in rather than left there. A freshly arrived approval card is followed + * the same way. Once the operator has scrolled up to read history nothing moves + * under them, and the jump-to-latest affordance is offered instead. + */ +@Composable +internal fun ChatTranscript( + thread: ChatThread, + listState: LazyListState, + savedScroll: ChatScrollPosition?, + itemCount: Int, + approval: ApprovalCard?, + showRunning: Boolean, + reasoning: ReasoningExpansion, + onToggleReasoning: (String) -> Unit, + onDecision: (String) -> Unit, +) { + val scope = rememberCoroutineScope() + val density = LocalDensity.current + val thresholdPx = remember(density) { with(density) { CHAT_FOLLOW_THRESHOLD_DP.roundToPx() } } + // The transcript's item count, read at use time: the drag collector and the + // derived state below outlive any single recomposition, so a count captured + // when they were created would go stale as messages arrive and the follow + // would measure against how many items there used to be. + val currentItemCount by rememberUpdatedState(itemCount) + // Whether the operator wants the newest content kept in view. Only their own + // drag changes it — a programmatic scroll never touches the list's + // interactionSource, so it cannot un-stick the view — and a drag that settles + // at (or within the threshold of) the bottom resumes the follow. Its real + // value is settled once the transcript is placed, when the live distance to + // the bottom is known. + // Saved, so a rotation or process death while the operator is reading history + // restores "not following" too, rather than the restored transcript being + // yanked to the bottom by the placement the new composition would otherwise run. + var following by rememberSaveable(thread.sessionId) { mutableStateOf(true) } + LaunchedEffect(listState, thresholdPx) { + listState.interactionSource.interactions.collect { interaction -> + when (interaction) { + is DragInteraction.Start -> following = false + is DragInteraction.Stop, is DragInteraction.Cancel -> + following = chatFollowsAt( + distanceFromBottomPx = listState.bottomDistancePx(currentItemCount), + thresholdPx = thresholdPx, + itemCount = currentItemCount, + ) + else -> Unit + } + } + } + // The distance to the transcript's end, read through a derived state so the + // affordance's visibility is recomputed only when it actually changes rather + // than on every scrolled pixel. The item count is read through + // [currentItemCount] so the derived value also recomputes as content arrives. + val showJumpToLatest by remember(listState, thresholdPx) { + derivedStateOf { + chatShowJumpToLatest( + following = following, + distanceFromBottomPx = listState.bottomDistancePx(currentItemCount), + thresholdPx = thresholdPx, + itemCount = currentItemCount, + ) + } + } + // The transcript is placed once, when it first has content, and only after it + // has been measured; the viewport height is an input too, so a grown composer + // or the appearing keyboard re-follows rather than leaving the newest message + // hidden behind it. Placement itself is saved, so restoring a rotation does not + // re-place (and re-follow) a transcript the operator had scrolled up. + var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) } + val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } } + LaunchedEffect(thread.messages, thread.running, approval?.requestId, viewportHeight) { + if (itemCount <= 0) return@LaunchedEffect + if (!placed) { + // Wait for the first measure: placement run before it would no-op and + // leave the first display to the measured re-run, which animates, and + // the first display must not animate. + if (viewportHeight <= 0) return@LaunchedEffect + placed = true + if (chatOpensAtNewest(savedScroll)) { + // No position of the operator's own: bring the newest item fully + // into view, instantly — the first display must not animate — and + // through the same path the follow uses, so placement and follow + // cannot disagree about what the newest item is (a last message + // taller than the viewport has its below-the-fold part closed by + // the same call), then follow. + listState.scrollToEnd(itemCount, animated = false) + following = true + } else { + // A position the operator left: follow only if it was the bottom, so + // returning to a chat never yanks the view. + following = chatFollowsAt(listState.bottomDistancePx(itemCount), thresholdPx, itemCount) + } + return@LaunchedEffect + } + 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(), + 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, + onToggleReasoning = onToggleReasoning, + ) + } + if (showRunning) { + item(key = "pending") { RunningIndicator(thread) } + } + if (approval != null) { + // Keyed by request id so switching between requests swaps the card + // instead of reusing the previous one's state. + item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) } + } + } + // Offered only once the transcript is placed and the operator has left the + // bottom, so it never covers the newest content it would return to. + if (placed && showJumpToLatest) { + SmallFloatingActionButton( + onClick = { + following = true + scope.launch { listState.scrollToEnd(itemCount, animated = true) } + }, + modifier = Modifier.align(Alignment.BottomEnd).padding(CHAT_GUTTER), + ) { + Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Jump to latest") + } + } + } +} + +/** + * The transcript's one scroll path, shared by the first placement, the follow, + * the app-bar approval jump and the jump-to-latest affordance. The newest item is + * brought into view when it sits entirely below the fold — an item appended past + * the viewport's edge, so no pixel of it is on screen and the remaining distance + * cannot be measured — and any part of it still below the fold (a message taller + * than the viewport) is then closed by exactly that distance. An item that is + * already partly visible is only gap-closed, never moved up first. [animated] is + * false only for the first placement, which must not animate. + * + * [itemCount] is the transcript's *content* count, which can be ahead of the + * layout's: an appended item exists in the content before the recomposition that + * measures it, and the effect that follows it is dispatched ahead of that measure, + * so the layout still describes the previous items and its own last visible item + * reads as the end. Measuring against [itemCount] — see [bottomDistancePx] — is + * what stops an appended item from being mistaken for the already-visible end and + * left below the fold: it has no pixel on screen, so it is unknown-distance and is + * brought into view rather than gap-closed at zero. + */ +internal suspend fun LazyListState.scrollToEnd(itemCount: Int, animated: Boolean) { + if (itemCount <= 0) return + if (bottomDistancePx(itemCount) == null) { + if (animated) animateScrollToItem(itemCount - 1) else scrollToItem(itemCount - 1) + } + closeBottomGap(itemCount, animated) +} + +/** + * Scrolls the transcript's end into view by exactly the distance it sits below + * the viewport, measured against the same [itemCount] the decisions above use. + */ +private suspend fun LazyListState.closeBottomGap(itemCount: Int, animated: Boolean) { + val remaining = bottomDistancePx(itemCount) ?: return + if (remaining <= 0) return + if (animated) animateScrollBy(remaining.toFloat()) else scrollBy(remaining.toFloat()) +} + +/** + * The distance from the transcript's end to the viewport's bottom, measured + * against [itemCount] — the transcript's *content* count, not the layout's. The + * two differ on the frame content arrives: the layout still describes the + * previous items, so its own last visible item reads as the end and the appended + * item's absence is invisible. Measuring against the content count makes the + * appended item read exactly as [chatBottomDistancePx] defines it — no pixel on + * screen — so the scroll path above brings it into view rather than trusting a + * stale layout's "already at the end". [itemCount] is what the transcript + * renders, so the two counts agree as soon as the layout catches up. + */ +private fun LazyListState.bottomDistancePx(itemCount: Int): Int? { + val info = layoutInfo + val last = info.visibleItemsInfo.lastOrNull() + return chatBottomDistancePx( + lastVisibleIndex = last?.index ?: -1, + lastVisibleEndPx = last?.let { it.offset + it.size } ?: 0, + itemCount = itemCount, + viewportEndPx = info.viewportEndOffset, + ) +} + +/** + * The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed + * time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]), + * so it keeps counting across a chat switch, and the tick loop stops the moment + * the turn settles. + */ +@Composable +private fun RunningIndicator(thread: ChatThread) { + val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + ) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + text = "· ${formatDuration(elapsedMillis / 1_000)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** + * The wall clock, re-read once a second while a turn is in flight, so the + * indicator derives the elapsed time with [ChatThread.elapsedMillis] — the one + * derivation its unit test also shares — instead of subtracting the turn's start + * itself. Keyed on [runningSince] and only entered for a live turn, so a settled + * chat schedules nothing. + */ +@Composable +private fun rememberElapsedNow(runningSince: Long): Long { + var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) } + LaunchedEffect(runningSince) { + if (runningSince <= 0) return@LaunchedEffect + while (true) { + nowMillis = System.currentTimeMillis() + delay(CHAT_ELAPSED_TICK_MILLIS) + } + } + return nowMillis +} + +@Composable +private fun MessageItem( + message: ChatMessage, + reasoning: ReasoningExpansion, + streaming: Boolean, + onToggleReasoning: (String) -> Unit, +) { + val isUser = message.role == ChatProtocol.ROLE_USER + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start, + ) { + Surface( + shape = RoundedCornerShape(CHAT_GUTTER), + color = if (isUser) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainer + }, + modifier = Modifier.widthIn(max = CHAT_BUBBLE_MAX_WIDTH_DP), + ) { + SelectionContainer { + Column(Modifier.padding(CHAT_GUTTER)) { + if (isUser) { + UserParts(message.parts) + } else { + AssistantParts( + messageId = message.id, + parts = message.parts, + reasoning = reasoning, + streaming = streaming, + onToggleReasoning = onToggleReasoning, + ) + } + } + } + } + } +} + +/** + * 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 + * sent message shows its file in the transcript through the one display path + * rather than a second attachment list under the bubble. + */ +@Composable +private fun UserParts(parts: List) { + val text = parts.filter { it.type == ChatProtocol.PART_TEXT || it.type.isBlank() } + .joinToString("\n") { it.text } + .trim() + val files = parts.filter { it.type == ChatProtocol.PART_FILE } + Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + if (text.isNotBlank()) Text(text, style = MaterialTheme.typography.bodyMedium) + files.forEach { FilePart(it) } + } +} + +/** + * 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. + */ +@Composable +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) { + 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++ + } + } +} + +@Composable +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 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, + expanded: Boolean, + streaming: Boolean, + onToggle: () -> Unit, +) { + if (text.isBlank()) return + 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"