Merge lane-app2: the chat experience and its multi-conversation state

Integrates eight commits of reviewed chat work: the Chat destination with
several conversations, markdown transcripts, tool-call chips with an expandable
INPUT/OUTPUT panel, edit diff cards, the composer's stop control, and approval
cards. The automated resolver failed on this merge repeatedly (its own stages kept
dying on the malformed-result defect), so it was integrated by hand.

Integration decisions:
- Pill geometry: main's tokens win. lane-app2 carried private duplicates of
  DESTINATION_ITEM_SIZE/GAP and a private DESTINATION_PILL_RESERVE, added before the
  geometry-token migration; those duplicates are dropped in favour of the theme
  tokens main already exports.
- IME mode: kept lane-app2's adjustResize for the window, because the chat composer
  and the search field both raise the keyboard and the chat UI was reviewed with it.
- Protocol and view-model constants: both sides' independent additions are kept.
- ChatScreen now passes the compactLabel main's SlidingPaneStack gained, and the
  literals lane-app2 introduced before the token discipline are converted to five
  new named tokens (HAIRLINE_DP, ICON_BUTTON_SMALL_DP, TOOL_PANEL_MAX_WIDTH_DP,
  CHAT_TITLE_MAX_WIDTH_DP, CHAT_BUBBLE_MAX_WIDTH_DP) rather than allow-listed.

Verified: assembleDebug plus the full Android unit suite (409 tests) pass,
including the geometry enforcement test.
This commit is contained in:
2026-10-16 22:27:30 +01:00
21 changed files with 4862 additions and 3 deletions
+1 -1
View File
@@ -32,7 +32,7 @@
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Pipelines"
android:windowSoftInputMode="adjustNothing">
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -2,8 +2,15 @@ package net.awan.pipelines.data
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.JsonElement
import net.awan.pipelines.data.protocol.ChatCreateRequest
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPromptRequest
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatQuery
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.PipelineSummary
@@ -32,6 +39,9 @@ class PipelinesRepository(
) {
val connectionState = client.state
/** Server-pushed chat frames (chat_event / chat_permission), with no request id. */
val events: SharedFlow<Message> = client.events
/** Opens the single shared connection to a validated server URL. */
fun connect(validated: ServerUrl.Validated) = client.connect(validated)
@@ -129,6 +139,62 @@ class PipelinesRepository(
Message(type = Protocol.RETRY_RUN, runId = id, requestKey = requestKey),
).runDetail ?: throw ProtocolException("The server returned no run detail.")
// ---- Brokered OpenCode chat (route B): the phone never speaks OpenCode
// directly and never holds its credentials. ----
/** Lists the sessions this server owns, with the `busy` flag the phone renders read-only. */
suspend fun chatSessions(): List<ChatSession> =
client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList()
/**
* Creates a session and returns it. The server currently answers this type
* with an explicit error when it does not broker creation; the caller
* surfaces that message rather than guessing at a session id.
*/
suspend fun chatCreate(title: String, directory: String): ChatSession {
val response = client.call(
Message(
type = Protocol.CHAT_CREATE,
chatCreate = ChatCreateRequest(title = title, directory = directory),
),
)
return response.chatSession
?: throw ProtocolException("The server did not return the new chat session.")
}
/** Loads a session's stored turns; the server prefers its retained live state. */
suspend fun chatMessages(sessionId: String, limit: Int = 0): List<ChatMessage> {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
return client.call(
Message(type = Protocol.CHAT_MESSAGES, chatQuery = ChatQuery(sessionId = sessionId, limit = limit)),
).chatMessages ?: emptyList()
}
/** Sends one prompt; the server echoes an ack and then pushes chat_event frames. */
suspend fun chatPrompt(sessionId: String, text: String) {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val trimmed = text.trim()
if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.")
client.call(
Message(
type = Protocol.CHAT_PROMPT,
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = trimmed),
),
)
}
suspend fun chatInterrupt(sessionId: String) {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
client.call(ChatProtocol.interruptRequest(sessionId))
}
suspend fun chatReply(sessionId: String, requestId: String, decision: String, message: String = "") {
if (sessionId.isBlank() || requestId.isBlank()) {
throw ProtocolException("A pending permission request is required.")
}
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message))
}
private fun requireConfigured() {
if (settings.serverUrl.value.isBlank()) {
throw NotConnectedException("Set the Pipelines server URL in Settings first.")
@@ -0,0 +1,233 @@
package net.awan.pipelines.data.protocol
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
/**
* Brokered OpenCode chat wire types (route B in the research report): the phone
* talks only to `/connect` and the server holds the OpenCode credentials,
* translating each type below. The field names and JSON tags mirror
* `internal/protocol/chat.go` exactly so the two cannot drift.
*
* Every list/field is optional with a default, so an older peer or a partial
* envelope never crashes the client.
*/
@Serializable
data class ChatSession(
val id: String = "",
val title: String = "",
val agent: String = "",
val model: String = "",
val directory: String = "",
@SerialName("parent_id") val parentId: String = "",
@SerialName("created_at") val createdAt: Long = 0,
@SerialName("updated_at") val updatedAt: Long = 0,
// Another client holds the session, or the server itself owns it as an active
// run: the phone shows it read-only instead of letting two clients write the
// same conversation.
val busy: Boolean = false,
)
@Serializable
data class ChatCreateRequest(
val title: String = "",
val directory: String = "",
)
/** The session-scoped request body for chat_messages and chat_interrupt. */
@Serializable
data class ChatQuery(
@SerialName("session_id") val sessionId: String = "",
val limit: Int = 0,
)
@Serializable
data class ChatPromptRequest(
@SerialName("session_id") val sessionId: String = "",
val text: String = "",
val model: String = "",
val agent: String = "",
val files: List<String> = emptyList(),
)
/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */
@Serializable
data class ChatMessage(
val id: String = "",
@SerialName("session_id") val sessionId: String = "",
val role: String = "",
val model: String = "",
val agent: String = "",
@SerialName("created_at") val createdAt: Long = 0,
val parts: List<ChatPart> = emptyList(),
)
/** One element of a [ChatMessage]; [type] selects which fields are meaningful. */
@Serializable
data class ChatPart(
val type: String = "",
val id: String = "",
val text: String = "",
val name: String = "",
val executed: Boolean = false,
val state: ChatToolState? = null,
val time: ChatTime? = null,
)
/** The lifecycle of a tool call; [input] is a partial-JSON string while streaming, an object afterwards. */
@Serializable
data class ChatToolState(
val status: String = "",
val input: JsonElement? = null,
val content: List<ChatToolContent> = emptyList(),
val metadata: JsonObject? = null,
val error: ChatError? = null,
)
@Serializable
data class ChatToolContent(
val type: String = "",
val text: String = "",
val uri: String = "",
val mime: String = "",
val name: String = "",
)
@Serializable
data class ChatError(
val type: String = "",
val message: String = "",
)
/** Epoch-millisecond timing envelope of a tool call. */
@Serializable
data class ChatTime(
val created: Long = 0,
val ran: Long = 0,
val completed: Long = 0,
)
/**
* A server-pushed chat_event frame. [kind] selects the payload: text/reasoning
* carry an incremental [delta] for the target [part], tool carries a full [part],
* step marks turn progress and usage reports the turn totals.
*/
@Serializable
data class ChatEventFrame(
@SerialName("session_id") val sessionId: String = "",
@SerialName("message_id") val messageId: String = "",
val kind: String = "",
val delta: String = "",
val part: ChatPart? = null,
val step: ChatStep? = null,
val usage: ChatUsage? = null,
)
@Serializable
data class ChatStep(
val status: String = "",
val index: Int = 0,
)
@Serializable
data class ChatUsage(
@SerialName("input_tokens") val inputTokens: Int = 0,
@SerialName("output_tokens") val outputTokens: Int = 0,
val cost: Double = 0.0,
)
/**
* One pending OpenCode approval request the phone answers with chat_reply.
*
* [resolved] and [decision] carry the server's outcome when it reports a request
* that is no longer open (another client answered it, or it expired): the phone
* then shows the verdict instead of live controls. They are additive and
* optional, so an older peer simply never sets them and every request stays
* pending.
*/
@Serializable
data class ChatPermissionFrame(
@SerialName("session_id") val sessionId: String = "",
@SerialName("request_id") val requestId: String = "",
val action: String = "",
val resources: List<String> = emptyList(),
val save: List<String> = emptyList(),
val metadata: JsonObject? = null,
val source: ChatPermissionSource? = null,
val message: String = "",
val resolved: Boolean = false,
val decision: String = "",
)
@Serializable
data class ChatPermissionSource(
val type: String = "",
@SerialName("message_id") val messageId: String = "",
val id: String = "",
)
@Serializable
data class ChatReplyRequest(
@SerialName("session_id") val sessionId: String = "",
@SerialName("request_id") val requestId: String = "",
val decision: String = "",
val message: String = "",
)
/** Chat part/kind/state/reply constants, mirroring `internal/protocol/chat.go`. */
object ChatProtocol {
const val PART_TEXT = "text"
const val PART_REASONING = "reasoning"
const val PART_TOOL = "tool"
const val EVENT_STEP = "step"
const val EVENT_USAGE = "usage"
const val STEP_STARTED = "started"
const val STEP_ENDED = "ended"
const val TOOL_STREAMING = "streaming"
const val TOOL_RUNNING = "running"
const val TOOL_COMPLETED = "completed"
const val TOOL_ERROR = "error"
const val ROLE_USER = "user"
const val ROLE_ASSISTANT = "assistant"
const val DECISION_ONCE = "once"
const val DECISION_ALWAYS = "always"
const val DECISION_REJECT = "reject"
/** A tool call still in flight (no result or error yet). */
fun toolRunning(state: ChatToolState?): Boolean = when (state?.status) {
TOOL_STREAMING, TOOL_RUNNING -> true
else -> false
}
/**
* The `chat_interrupt` frame the composer's stop control sends: the server
* aborts the in-flight turn for [sessionId]. Built here (not inline in the
* repository) so production and its unit test share the one wire shape.
*/
fun interruptRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_reply` frame that answers one permission request: [decision] is
* one of [DECISION_ONCE]/[DECISION_ALWAYS]/[DECISION_REJECT]. Built here (not
* inline in the repository) so the approval card's actions and their unit
* test share the one wire shape.
*/
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = ""): Message =
Message(
type = Protocol.CHAT_REPLY,
chatReply = ChatReplyRequest(
sessionId = sessionId,
requestId = requestId,
decision = decision,
message = message,
),
)
}
@@ -53,6 +53,16 @@ object Protocol {
const val SEARCH_KIND_STEP = "step"
const val SEARCH_KIND_FIELD = "field"
const val SEARCH_KIND_ARTIFACT = "artifact"
// chat.go (brokered OpenCode chat)
const val CHAT_SESSIONS = "chat_sessions"
const val CHAT_CREATE = "chat_create"
const val CHAT_PROMPT = "chat_prompt"
const val CHAT_MESSAGES = "chat_messages"
const val CHAT_INTERRUPT = "chat_interrupt"
const val CHAT_REPLY = "chat_reply"
// Server-pushed frames with no matching request.
const val CHAT_EVENT = "chat_event"
const val CHAT_PERMISSION = "chat_permission"
// terminals.go
const val SUCCESS_END = "#success"
@@ -562,4 +572,15 @@ data class Message(
@SerialName("write_paths") val writePaths: List<String>? = null,
@SerialName("request_key") val requestKey: String? = null,
val workspace: String? = null,
// Brokered chat traffic (see Chat.kt). Optional so an older server never
// breaks the existing envelope.
@SerialName("chat_sessions") val chatSessions: List<ChatSession>? = null,
@SerialName("chat_session") val chatSession: ChatSession? = null,
@SerialName("chat_create") val chatCreate: ChatCreateRequest? = null,
@SerialName("chat_query") val chatQuery: ChatQuery? = null,
@SerialName("chat_prompt") val chatPrompt: ChatPromptRequest? = null,
@SerialName("chat_messages") val chatMessages: List<ChatMessage>? = null,
@SerialName("chat_event") val chatEvent: ChatEventFrame? = null,
@SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null,
@SerialName("chat_reply") val chatReply: ChatReplyRequest? = null,
)
@@ -10,8 +10,11 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
@@ -53,6 +56,15 @@ class PipelinesClient(
private val _state = MutableStateFlow<ConnectionState>(ConnectionState.Idle)
val state: StateFlow<ConnectionState> = _state.asStateFlow()
// Unsolicited server frames (server-pushed chat_event / chat_permission /
// stream errors). Buffered and dropped-oldest so a slow collector can never
// block the socket read loop; chats re-sync from history after a gap anyway.
private val _events = MutableSharedFlow<Message>(
extraBufferCapacity = 256,
onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
)
val events: SharedFlow<Message> = _events.asSharedFlow()
private val sendLock = Mutex()
private val pending = ConcurrentHashMap<String, CompletableDeferred<Message>>()
private val sequence = AtomicLong(0)
@@ -190,9 +202,12 @@ class PipelinesClient(
val deferred = if (id != null) pending.remove(id) else null
if (deferred != null) {
deferred.complete(message)
} else {
// Unsolicited envelopes (the connection's initial pipeline_list,
// server-pushed chat frames, stream errors) carry no matching id:
// hand them to the event stream instead of dropping them.
_events.tryEmit(message)
}
// Unsolicited envelopes (for example the connection's initial
// pipeline_list) have no matching id and are intentionally dropped.
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
@@ -21,6 +21,7 @@ import net.awan.pipelines.data.PipelinesRepository
import net.awan.pipelines.data.RunHistory
import net.awan.pipelines.data.SettingsRepository
import net.awan.pipelines.data.protocol.BuildInfo
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.Protocol
@@ -29,6 +30,8 @@ import net.awan.pipelines.data.protocol.SearchResponse
import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.data.transport.ServerUrl
import net.awan.pipelines.ui.chat.ChatState
import net.awan.pipelines.ui.chat.ChatStore
/** Generic loading/empty/error/data state used by every screen. */
data class LoadState<T>(
@@ -110,6 +113,10 @@ class AppViewModel(
private val startKeys = ConcurrentHashMap<Long, String>()
private val retryKeys = ConcurrentHashMap<Long, String>()
/** The multi-chat screen state (sessions, open conversations, drafts, scroll). */
private val chatStore = ChatStore()
val chat: StateFlow<ChatState> = chatStore.state
init {
// Connect on launch when a server URL is already saved, reusing the shared
// client and its bounded backoff (no new client, DI or polling). init runs
@@ -120,6 +127,50 @@ class AppViewModel(
) {
reconnect()
}
observeChatEvents()
observeConnection()
}
/**
* Routes server-pushed chat frames into the per-chat state, wherever the
* frame's session sits in the open order. Frames for a chat that is not open
* create a placeholder in [ChatStore.event] so a running background chat
* keeps its stream; the operator sees it re-synced from history on return.
*/
private fun observeChatEvents() {
viewModelScope.launch {
repository.events.collect { message ->
message.chatEvent?.let { chatStore.event(it) }
// Never silently drop an approval request: it is held per chat and
// answered with chat_reply from the conversation's approval card.
message.chatPermission?.let { chatStore.permission(it) }
// An unsolicited server error has no request id to match, so it is
// the chat stream failing mid-turn: settle the running chat instead
// of leaving its indicator spinning forever.
if (message.id == null && message.type == Protocol.ERROR) {
chatStore.streamError(message.error?.takeIf { it.isNotBlank() } ?: "The chat stream failed.")
}
}
}
}
/**
* Re-syncs every open chat when the socket (re)connects: the frames sent
* during the gap are gone, so the conversation is re-fetched from history
* rather than trusted. A running chat is marked settled first and a still-live
* stream re-asserts it on its next frame, so a stale `Working…` never sticks.
*/
private fun observeConnection() {
viewModelScope.launch {
var connected = false
connectionState.collect { state ->
val isConnected = state is ConnectionState.Connected
if (isConnected && !connected) {
chatStore.streamResumed().forEach { loadChatHistory(it) }
}
connected = isConnected
}
}
}
fun updateServerUrlDraft(value: String) {
@@ -357,6 +408,125 @@ class AppViewModel(
}
}
// ---- Brokered chat -------------------------------------------------------
/** Refreshes the server's session list; never clears open conversations. */
fun refreshChatSessions() {
viewModelScope.launch {
chatStore.sessionsLoading()
try {
chatStore.sessionsLoaded(repository.chatSessions())
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.sessionsFailed(ErrorMessages.describe(t))
}
}
}
/**
* Opens [session] and makes it active. A brand-new chat always loads its
* history; a running one re-syncs from the server so a stale copy is never
* shown on return.
*/
fun openChatSession(session: ChatSession) {
val needsHistory = chatStore.open(session)
if (needsHistory) loadChatHistory(session.id)
}
/** Switches to an already-open chat, re-syncing it when it is running. */
fun activateChat(sessionId: String) {
if (chatStore.activate(sessionId)) loadChatHistory(sessionId)
}
/** Shows the session list again while keeping every open conversation. */
fun showChatList() = chatStore.showList()
fun closeChat(sessionId: String) = chatStore.close(sessionId)
fun updateChatDraft(sessionId: String, text: String) = chatStore.draft(sessionId, text)
fun saveChatScroll(sessionId: String, index: Int, offset: Int) = chatStore.scroll(sessionId, index, offset)
/** Creates a session on the server and opens it. Reports the server's own error on failure. */
fun newChat() {
viewModelScope.launch {
try {
val created = repository.chatCreate(title = "New chat", directory = settings.workspace.value)
chatStore.sessionsLoaded(chatStore.value.sessions + created)
chatStore.open(created)
chatStore.history(created.id, emptyList())
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.sessionsFailed(ErrorMessages.describe(t))
}
}
}
fun loadChatHistory(sessionId: String) {
viewModelScope.launch {
chatStore.historyLoading(sessionId)
try {
chatStore.history(sessionId, repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT))
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.failed(sessionId, ErrorMessages.describe(t))
}
}
}
/** Sends the active chat's draft. Read-only chats are never written to. */
fun sendChatPrompt(sessionId: String) {
val thread = chatStore.value.thread(sessionId) ?: return
if (thread.readOnly) return
val text = thread.draft.trim()
if (text.isEmpty()) return
chatStore.appendLocalUserMessage(sessionId, text)
chatStore.clearDraft(sessionId)
chatStore.running(sessionId, true)
viewModelScope.launch {
try {
repository.chatPrompt(sessionId, text)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.failed(sessionId, ErrorMessages.describe(t))
chatStore.running(sessionId, false)
}
}
}
/**
* Answers a pending approval. The card settles in place optimistically so a
* laggy round-trip over a tunnel never shows the old buttons again; a failed
* reply reopens the same request and reports why, so the operator can retry
* instead of trusting a decision the server never received.
*/
fun replyChatPermission(sessionId: String, requestId: String, decision: String) {
if (sessionId.isBlank() || requestId.isBlank()) return
chatStore.answerPermission(sessionId, requestId, decision)
viewModelScope.launch {
try {
repository.chatReply(sessionId, requestId, decision)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.permissionReplyFailed(sessionId, requestId)
chatStore.failed(sessionId, ErrorMessages.describe(t))
}
}
}
fun stopChat(sessionId: String) {
viewModelScope.launch {
try {
repository.chatInterrupt(sessionId)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.failed(sessionId, ErrorMessages.describe(t))
} finally {
chatStore.running(sessionId, false)
}
}
}
private fun <T> load(target: MutableStateFlow<LoadState<T>>, block: suspend () -> T) {
viewModelScope.launch {
target.value = target.value.copy(loading = true, error = null)
@@ -374,6 +544,8 @@ class AppViewModel(
/** How long the field waits after the last keystroke before issuing one request. */
const val SEARCH_DEBOUNCE_MILLIS = 250L
/** Bounds one history fetch; the server applies its own cap too. */
private const val CHAT_HISTORY_LIMIT = 200
fun factory(app: PipelinesApplication) = viewModelFactory {
initializer { AppViewModel(app.repository, app.settings) }
@@ -37,6 +37,7 @@ import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Chat
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.History
@@ -96,12 +97,14 @@ import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.chat.ChatScreen
private data class TopDestination(val route: String, val label: String, val icon: ImageVector)
private val destinations = listOf(
TopDestination("pipelines", "Pipelines", Icons.Default.AccountTree),
TopDestination("runs", "Runs", Icons.Default.History),
TopDestination("chat", "Chat", Icons.AutoMirrored.Filled.Chat),
TopDestination("settings", "Settings", Icons.Default.Settings),
)
@@ -263,6 +266,9 @@ fun PipelinesApp(vm: AppViewModel) {
listState = runListState,
)
}
composable("chat") {
ChatScreen(vm = vm, wide = wide)
}
composable("settings") {
SettingsScreen(vm)
}
@@ -0,0 +1,312 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatToolState
/**
* Pure chat formatting helpers shared by the session list and the conversation,
* so the same value is never spelled differently in two places. Kept free of
* Compose and of the transport so they are unit-testable.
*/
private val PRETTY_JSON = Json { prettyPrint = true; isLenient = true }
/**
* The INPUT section of a tool call: pretty-printed JSON once the arguments are
* an object/array, a partial-JSON string while still streaming, or the raw text
* when it cannot be parsed. Blank when there is nothing.
*/
internal fun prettyToolInput(input: JsonElement?): String = when (input) {
null -> ""
is JsonObject, is JsonArray -> PRETTY_JSON.encodeToString(JsonElement.serializer(), input)
is JsonPrimitive -> input.content
else -> input.toString()
}
/**
* The OUTPUT section of a tool call: the concatenated textual content, or the
* literal `(no output)` when the call returned nothing (mirroring jarvis), and
* an empty string while the call is still running.
*/
internal fun toolOutputText(state: ChatToolState?): String {
if (state == null) return ""
val text = state.content
.filter { it.type == "text" && it.text.isNotBlank() }
.joinToString("\n") { it.text }
if (text.isNotBlank()) return text
if (ChatProtocol.toolRunning(state)) return ""
return "(no output)"
}
/**
* The ERROR section of a failed tool call. The server's error message takes
* precedence over any partial output the call had already produced — a failed
* call can carry both, and the output text must not be labelled as the error —
* falling back to the output text so the block is never blank when the failure
* carries no message.
*/
internal fun toolErrorText(state: ChatToolState?): String {
val message = state?.error?.message
return if (!message.isNullOrBlank()) message else toolOutputText(state)
}
/** Wall-clock duration of a tool call, or null while it has no completion time. */
internal fun toolDurationMillis(part: ChatPart): Long? {
val time = part.time ?: return null
val start = if (time.ran > 0) time.ran else time.created
if (start <= 0 || time.completed <= 0 || time.completed < start) return null
return time.completed - start
}
/** True when a tool call ended in an error state. */
internal fun toolFailed(state: ChatToolState?): Boolean = state?.status == ChatProtocol.TOOL_ERROR
/** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */
internal fun formatToolDuration(millis: Long): String = when {
millis < 1_000 -> "${millis}ms"
millis < 60_000 -> String.format(java.util.Locale.US, "%.1fs", millis / 1000.0)
else -> "${millis / 60_000}m ${(millis % 60_000) / 1000}s"
}
/** The chip label for a tool call: its name, or a placeholder when unnamed. */
internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" }
/**
* A session's short title: the server title, or a truncated id when untitled, so
* a row never renders as a blank line.
*/
internal fun sessionTitle(session: ChatSession): String =
session.title.ifBlank { session.id.take(18).ifBlank { "Untitled chat" } }
/**
* The status a session row shows. A locally-running turn is reported as
* `Running`; otherwise the server's `busy` flag is `Busy · read-only` (another
* client holds it, so the composer is disabled), else `Idle`.
*
* This is the same precedence [ChatThread.readOnly] applies: a turn we started is
* `Running` and writable, never the read-only the server's own `busy` flag alone
* would imply.
*/
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String = when {
runningLocally -> "Running"
session.busy -> "Busy · read-only"
else -> "Idle"
}
/** Which action the composer's single primary control offers for a chat. */
enum class ComposerAction { Send, Stop }
/**
* The composer's primary control: while a turn is in flight the send control
* becomes the stop control (interrupt), otherwise it sends the draft. One
* derivation drives both the trailing button and the keyboard's send action, so
* a running turn can never be sent to from the other control.
*/
internal fun composerAction(thread: ChatThread): ComposerAction =
if (thread.running) ComposerAction.Stop else ComposerAction.Send
/**
* One line of a derived unified diff. [CONTEXT] lines are unchanged, [ADD] came
* from the edit's `newString` and [REMOVE] from its `oldString`.
*/
enum class DiffKind { CONTEXT, ADD, REMOVE }
data class DiffLine(val kind: DiffKind, val text: String)
/**
* A synthesised edit diff: the file, the true `+N -M` counts and the ordered
* lines. [omitted] is how many diff lines are not in [lines] because the edit was
* too large to render in full (0 when the whole diff is shown); the counts always
* describe the whole edit, never just the rendered prefix.
*/
data class ToolDiff(
val file: String,
val added: Int,
val removed: Int,
val lines: List<DiffLine>,
val omitted: Int = 0,
)
/**
* Derives a unified diff for an `edit`-family tool call from its
* `oldString`/`newString` arguments. The brokered protocol carries no diff field
* (research report §2.5), so the +/- view is synthesised here instead. A diff
* longer than [MAX_RENDERED_DIFF_LINES] is summarised — only that many lines are
* kept, with [ToolDiff.omitted] carrying the rest — so a very large edit cannot
* flood the transcript on a phone. Returns null for any other tool, so non-edit
* calls keep the INPUT/OUTPUT panel.
*/
internal fun toolEditDiff(input: JsonElement?): ToolDiff? {
val obj = input as? JsonObject ?: return null
val old = obj.stringOrNull("oldString", "old_string") ?: return null
val new = obj.stringOrNull("newString", "new_string") ?: return null
if (old.isEmpty() && new.isEmpty()) return null
val lines = lineDiff(old.split("\n"), new.split("\n"))
return ToolDiff(
file = obj.stringOrNull("filePath", "file_path", "file").orEmpty(),
added = lines.count { it.kind == DiffKind.ADD },
removed = lines.count { it.kind == DiffKind.REMOVE },
lines = lines.take(MAX_RENDERED_DIFF_LINES),
omitted = (lines.size - MAX_RENDERED_DIFF_LINES).coerceAtLeast(0),
)
}
private fun JsonObject.stringOrNull(vararg keys: String): String? {
for (key in keys) {
val value = this[key]
if (value is JsonPrimitive && value.isString) return value.content
}
return null
}
/**
* A minimal line diff (LCS) so only the changed lines are marked, not the whole
* block. A pathologically large edit falls back to a plain remove-then-add block
* to bound the quadratic table.
*/
private fun lineDiff(old: List<String>, new: List<String>): List<DiffLine> {
if (old.size > MAX_DIFF_LINES || new.size > MAX_DIFF_LINES) {
return old.map { DiffLine(DiffKind.REMOVE, it) } + new.map { DiffLine(DiffKind.ADD, it) }
}
val m = old.size
val n = new.size
val lcs = Array(m + 1) { IntArray(n + 1) }
for (i in m - 1 downTo 0) {
for (j in n - 1 downTo 0) {
lcs[i][j] = if (old[i] == new[j]) lcs[i + 1][j + 1] + 1
else maxOf(lcs[i + 1][j], lcs[i][j + 1])
}
}
val result = ArrayList<DiffLine>(m + n)
var i = 0
var j = 0
while (i < m && j < n) {
when {
old[i] == new[j] -> {
result.add(DiffLine(DiffKind.CONTEXT, old[i])); i++; j++
}
lcs[i + 1][j] >= lcs[i][j + 1] -> {
result.add(DiffLine(DiffKind.REMOVE, old[i])); i++
}
else -> {
result.add(DiffLine(DiffKind.ADD, new[j])); j++
}
}
}
while (i < m) { result.add(DiffLine(DiffKind.REMOVE, old[i])); i++ }
while (j < n) { result.add(DiffLine(DiffKind.ADD, new[j])); j++ }
return result
}
/**
* How many diff lines are rendered before the remainder is summarised. Small
* enough to stay readable on a phone, large enough that ordinary edits are
* always shown in full. [MAX_DIFF_LINES] is the larger algorithm guard that
* bounds the quadratic LCS table.
*/
internal const val MAX_RENDERED_DIFF_LINES = 200
private const val MAX_DIFF_LINES = 400
/**
* How one permission request stands: still waiting for the operator, answered
* here (optimistically, while the reply is in flight), or already settled by the
* server (another client answered it, or it expired).
*/
enum class ApprovalState { PENDING, ANSWERED, RESOLVED }
/**
* What the conversation renders for one permission request. Derived purely from
* the server's [ChatPermissionFrame] plus the operator's local answer, so the
* approval card and its unit test share one model instead of each reading the
* frame. [actionable] is true only while nothing has settled the request, which
* is what keeps a resolved request from offering stale once/always/reject
* controls.
*/
data class ApprovalCard(
val requestId: String,
val action: String,
val resources: List<String>,
val risk: String,
val state: ApprovalState,
val decision: String = "",
val note: String = "",
) {
/** The once/always/reject controls are live only while the request is open. */
val actionable: Boolean get() = state == ApprovalState.PENDING
/**
* The amber risk box is shown while the request is open and after the
* operator denies it (jarvis shows it while "pending/denied"), but not for a
* request the server already settled, whose note carries the outcome.
*/
val showRisk: Boolean
get() = state == ApprovalState.PENDING ||
(state == ApprovalState.ANSWERED && decision == ChatProtocol.DECISION_REJECT)
/** The card headline: what is being requested, or the verdict once settled. */
val headline: String
get() = when (state) {
ApprovalState.PENDING -> "Approve " + action.ifBlank { "tool call" }
ApprovalState.ANSWERED -> decisionLabel(decision)
ApprovalState.RESOLVED -> if (decision.isBlank()) "Already resolved" else decisionLabel(decision)
}
/** The one-line explanation under the headline. */
val statusLine: String
get() = when (state) {
ApprovalState.PENDING -> "Waiting for your response"
ApprovalState.ANSWERED -> "Waiting for the agent to continue…"
ApprovalState.RESOLVED -> note.ifBlank { "Another client already answered this request." }
}
}
/**
* The approval card for [permission], or null when there is no request to show.
* A request the server reports as settled wins over any local answer, so a stale
* tap can never reopen controls for a request that is already done.
*/
internal fun approvalCard(permission: ChatPermissionFrame?, answer: String): ApprovalCard? {
if (permission == null || permission.requestId.isBlank()) return null
val resolvedByServer = permission.resolved || permission.decision.isNotBlank()
val state = when {
resolvedByServer -> ApprovalState.RESOLVED
answer.isNotBlank() -> ApprovalState.ANSWERED
else -> ApprovalState.PENDING
}
return ApprovalCard(
requestId = permission.requestId,
action = permission.action,
resources = permission.resources.filter { it.isNotBlank() },
risk = permissionRiskText(permission),
state = state,
decision = if (resolvedByServer) permission.decision else answer,
note = if (resolvedByServer) permission.message else "",
)
}
/**
* The text in the amber risk-review box: the server's own summary when it carries
* one (jarvis shows the model's risk summary), otherwise a neutral sentence
* naming the action so the box is never blank.
*/
internal fun permissionRiskText(permission: ChatPermissionFrame): String {
if (permission.message.isNotBlank()) return permission.message
val what = permission.action.ifBlank { "a tool call" }
return "The agent is asking to run $what; review the request before allowing."
}
/** A human label for a once/always/reject decision, blank-safe. */
internal fun decisionLabel(decision: String): String = when (decision) {
ChatProtocol.DECISION_ONCE -> "Allowed once"
ChatProtocol.DECISION_ALWAYS -> "Always allowed"
ChatProtocol.DECISION_REJECT -> "Rejected"
else -> "Resolved"
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,429 @@
package net.awan.pipelines.ui.chat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import net.awan.pipelines.data.protocol.ChatEventFrame
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
/**
* A saved scroll position inside one conversation. Kept as Android-free
* primitives so it is part of the pure model and can survive a chat switch (the
* caller feeds it back into the list's state).
*/
data class ChatScrollPosition(val index: Int = 0, val offset: Int = 0)
/**
* One open conversation. The conversation itself, whether it is running, its
* unsent composer draft and its scroll position all live here, so switching to
* another chat and back can never lose any of them.
*/
data class ChatThread(
val sessionId: String,
val title: String = "",
val directory: String = "",
val model: String = "",
val agent: String = "",
val updatedAt: Long = 0,
/** The server reports another client (or an active run) holds this session. */
val busy: Boolean = false,
val messages: List<ChatMessage> = emptyList(),
val loading: Boolean = false,
val loaded: Boolean = false,
val error: String? = null,
/** A turn is in flight for this session; it keeps running when we switch away. */
val running: Boolean = false,
/**
* Wall-clock epoch millis the in-flight turn began, or 0 when it is not
* running. Stored on the thread (not in the composable) so the running
* indicator's elapsed time survives a chat switch, and cleared the moment
* the turn settles.
*/
val runningSince: Long = 0,
/** The unsent composer text for this chat. */
val draft: String = "",
val scroll: ChatScrollPosition = ChatScrollPosition(),
/** The server's pending approval for this session, answered with chat_reply. */
val permission: ChatPermissionFrame? = null,
/**
* The operator's local answer to [permission] (`once`/`always`/`reject`), or
* blank while it is still open. Held on the thread so the approval card can
* settle in place optimistically and survives a chat switch.
*/
val permissionAnswer: String = "",
) {
/**
* Read-only while another client holds the session: the composer must never
* write to it. A turn we started ourselves keeps the session writable even
* though the server reports it busy (the server owns it as our active run),
* so the one rule here agrees with [sessionStatusLabel]'s `Running` case.
*/
val readOnly: Boolean get() = busy && !running
/** Whether the composer's send action is allowed. */
val canSend: Boolean get() = !readOnly && draft.isNotBlank()
/**
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it
* has settled. Pure, so the running indicator and its unit test share the one
* derivation instead of each subtracting the start themselves.
*/
fun elapsedMillis(nowMillis: Long): Long =
if (running && runningSince in 1 until nowMillis) nowMillis - runningSince else 0
}
/**
* The multi-chat screen state. [sessions] is the server's list; [open] is the
* ordered set of conversations the operator has opened, each preserved
* independently; [activeId] is the one currently on screen.
*/
data class ChatState(
val sessions: List<ChatSession> = emptyList(),
val sessionsLoading: Boolean = false,
val sessionsLoaded: Boolean = false,
val sessionsError: String? = null,
val open: List<ChatThread> = emptyList(),
val activeId: String? = null,
) {
val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId }
fun thread(sessionId: String): ChatThread? = open.firstOrNull { it.sessionId == sessionId }
}
/**
* The multi-chat state model: a small, Android-free holder of [ChatState] with
* the transitions the chat surface needs. Keeping it free of Compose and of the
* transport makes the multi-chat guarantees (per-chat draft/scroll/conversation,
* running survives a switch and re-syncs on return) unit-testable without a
* device or a server.
*
* Method contracts that matter:
* - [open] and [activate] return true when the caller must (re-)fetch history;
* a running session must re-sync on return so a stale copy is never shown.
* - [event] applies a server frame to its session's thread whether or not that
* thread is on screen, so a background chat never loses its stream.
*
* [now] is injectable so the running indicator's elapsed time is testable without
* a device clock.
*/
class ChatStore(private val now: () -> Long = System::currentTimeMillis) {
private val _state = MutableStateFlow(ChatState())
val state: StateFlow<ChatState> = _state.asStateFlow()
val value: ChatState get() = _state.value
// ---- Session list --------------------------------------------------------
fun sessionsLoading() {
_state.value = _state.value.copy(sessionsLoading = true, sessionsError = null)
}
fun sessionsFailed(message: String) {
_state.value = _state.value.copy(sessionsLoading = false, sessionsError = message)
}
/**
* Replaces the server's session list and folds its title/busy flags into any
* already-open thread, so a status change is reflected without dropping the
* conversation. An open thread the server no longer lists is kept (its
* conversation is still the operator's).
*/
fun sessionsLoaded(sessions: List<ChatSession>) {
val byId = sessions.associateBy { it.id }
val open = _state.value.open.map { thread ->
val session = byId[thread.sessionId] ?: return@map thread
thread.copy(
title = session.title.ifBlank { thread.title },
directory = session.directory.ifBlank { thread.directory },
busy = session.busy,
)
}
_state.value = _state.value.copy(
sessions = sessions,
open = open,
sessionsLoading = false,
sessionsLoaded = true,
sessionsError = null,
)
}
// ---- Opening / switching -------------------------------------------------
/**
* Opens [session] (idempotently) and makes it active. Returns true when its
* history must be fetched: a brand-new thread always, and a re-opened one
* whose state may have moved on (it is running, or was never loaded).
*/
fun open(session: ChatSession): Boolean {
val existing = _state.value.thread(session.id)
if (existing == null) {
val thread = ChatThread(
sessionId = session.id,
title = session.title,
directory = session.directory,
model = session.model,
agent = session.agent,
updatedAt = session.updatedAt,
busy = session.busy,
)
_state.value = _state.value.copy(open = _state.value.open + thread, activeId = session.id)
return true
}
val merged = existing.copy(
title = session.title.ifBlank { existing.title },
directory = session.directory.ifBlank { existing.directory },
busy = session.busy,
)
_state.value = _state.value.copy(
open = _state.value.open.map { if (it.sessionId == session.id) merged else it },
activeId = session.id,
)
return needsResync(merged)
}
/**
* Makes an already-open thread active. Returns true when its history must be
* re-fetched first: a running session is re-synced from the server on return
* so the operator never sees a stale conversation.
*/
fun activate(sessionId: String): Boolean {
val thread = _state.value.thread(sessionId) ?: return false
_state.value = _state.value.copy(activeId = sessionId)
return needsResync(thread)
}
fun close(sessionId: String) {
val open = _state.value.open.filterNot { it.sessionId == sessionId }
val active = if (_state.value.activeId == sessionId) open.lastOrNull()?.sessionId else _state.value.activeId
_state.value = _state.value.copy(open = open, activeId = active)
}
/**
* Returns to the session list without closing any conversation: [activeId]
* becomes null while [ChatState.open] is untouched, so every open chat keeps
* its messages, draft and scroll.
*/
fun showList() {
if (_state.value.activeId != null) {
_state.value = _state.value.copy(activeId = null)
}
}
private fun needsResync(thread: ChatThread): Boolean = thread.running || !thread.loaded
// ---- Per-thread edits ----------------------------------------------------
fun draft(sessionId: String, text: String) = update(sessionId) { it.copy(draft = text) }
fun clearDraft(sessionId: String) = update(sessionId) { it.copy(draft = "") }
fun scroll(sessionId: String, index: Int, offset: Int) =
update(sessionId) { it.copy(scroll = ChatScrollPosition(index, offset)) }
fun historyLoading(sessionId: String) = update(sessionId) { it.copy(loading = true, error = null) }
fun failed(sessionId: String, message: String) =
update(sessionId) { it.copy(loading = false, error = message) }
/**
* Replaces a thread's conversation with the server's authoritative history.
* The running flag is left as-is: history alone cannot say whether a turn is
* still in flight.
*/
fun history(sessionId: String, messages: List<ChatMessage>) = update(sessionId) {
it.copy(messages = messages, loading = false, loaded = true, error = null)
}
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
/**
* The stream resumed (the socket reconnected): every frame that was feeding an
* in-flight turn is gone, so no thread keeps claiming to run until a fresh
* frame proves otherwise, and the caller re-fetches each open chat's history.
* Returning every open id (not only the running ones) means a gap that
* silently swallowed the end of a turn is repaired too. Re-fetching replaces
* the conversation wholesale, so a resync can neither duplicate nor drop text.
*/
fun streamResumed(): List<String> {
val ids = _state.value.open.map { it.sessionId }
if (ids.isEmpty()) return ids
_state.value = _state.value.copy(
open = _state.value.open.map { if (it.running) it.copy(running = false, runningSince = 0) else it },
)
return ids
}
/**
* A server-pushed stream error carries no session id (the brokered protocol
* cannot attribute it), so settle the one turn it can only have come from: the
* sole running chat, or the active one when several are in flight. With
* nothing running there is no turn to settle and it is ignored; the server's
* text is kept so the operator sees why the turn stopped.
*/
fun streamError(message: String) {
val running = _state.value.open.filter { it.running }
val target = when {
running.isEmpty() -> return
running.size == 1 -> running.single()
else -> running.firstOrNull { it.sessionId == _state.value.activeId } ?: return
}
update(target.sessionId) { setRunning(it.copy(error = message), false) }
}
/**
* The server pushed an approval request for this session, or reported one it
* has already settled. A frame for a *new* request replaces any leftover card
* from the previous one; a frame for the same request (for example a resolved
* re-push) keeps the local answer and applies the server's outcome.
*/
fun permission(frame: ChatPermissionFrame) {
if (frame.sessionId.isBlank()) return
ensureThread(frame.sessionId)
update(frame.sessionId) {
val sameRequest = it.permission?.requestId == frame.requestId && frame.requestId.isNotBlank()
it.copy(
permission = frame,
permissionAnswer = if (sameRequest) it.permissionAnswer else "",
)
}
}
/**
* The operator's decision on the pending request, recorded optimistically so
* the card settles in place before the round-trip: the buttons are never left
* offering a decision already made. A request that is no longer the one on
* screen is ignored.
*/
fun answerPermission(sessionId: String, requestId: String, decision: String) = update(sessionId) {
if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = decision)
}
/** The reply failed: reopen the same request so the operator can try again. */
fun permissionReplyFailed(sessionId: String, requestId: String) = update(sessionId) {
if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = "")
}
/**
* Appends the operator's just-sent prompt optimistically, so the bubble is
* visible before the ack and history round-trip. History later reconciles it.
*/
fun appendLocalUserMessage(sessionId: String, text: String) = update(sessionId) {
val message = ChatMessage(
id = LOCAL_MESSAGE_PREFIX + (it.messages.count { m -> m.id.startsWith(LOCAL_MESSAGE_PREFIX) } + 1),
sessionId = sessionId,
role = ChatProtocol.ROLE_USER,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)),
)
it.copy(messages = it.messages + message)
}
// ---- Streaming events ----------------------------------------------------
/**
* Folds one pushed [frame] into its session's thread, creating a placeholder
* thread when the frame arrives for a chat that is not open, so a background
* chat keeps its stream instead of dropping it.
*/
fun event(frame: ChatEventFrame) {
if (frame.sessionId.isBlank()) return
ensureThread(frame.sessionId)
when (frame.kind) {
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
ChatProtocol.PART_TOOL -> applyTool(frame)
ChatProtocol.EVENT_STEP -> {
val started = frame.step?.status != ChatProtocol.STEP_ENDED
update(frame.sessionId) { setRunning(it, started) }
}
else -> Unit
}
}
/**
* Creates a placeholder thread for a session that is not open, so a frame for
* a background chat is kept instead of dropped. A no-op when it already exists.
*/
private fun ensureThread(sessionId: String) {
if (_state.value.thread(sessionId) != null) return
val session = _state.value.sessions.firstOrNull { it.id == sessionId }
val placeholder = ChatThread(
sessionId = sessionId,
title = session?.title ?: "",
directory = session?.directory ?: "",
busy = session?.busy ?: false,
)
_state.value = _state.value.copy(open = _state.value.open + placeholder)
}
private fun applyDelta(frame: ChatEventFrame) {
val partId = frame.part?.id.orEmpty()
if (partId.isEmpty() || frame.delta.isEmpty()) return
upsertPart(frame, partId) { existing ->
existing?.copy(text = existing.text + frame.delta)
?: ChatPart(type = frame.kind, id = partId, text = frame.delta)
}
}
private fun applyTool(frame: ChatEventFrame) {
val part = frame.part ?: return
if (part.id.isEmpty()) return
upsertPart(frame, part.id) { part }
}
/**
* Finds or creates the assistant message [frame] targets and the part [partId]
* inside it, replacing it via [upsert] (the old part when it exists, else
* null), then marks the thread running. The text/reasoning delta and the tool
* upsert share this so the two cannot drift.
*/
private fun upsertPart(frame: ChatEventFrame, partId: String, upsert: (ChatPart?) -> ChatPart) {
update(frame.sessionId) { thread ->
val messages = thread.messages.toMutableList()
val index = messages.indexOfLast { it.id == frame.messageId }
val message = if (index >= 0) {
messages[index]
} else {
ChatMessage(
id = frame.messageId,
sessionId = frame.sessionId,
role = ChatProtocol.ROLE_ASSISTANT,
).also { messages.add(it) }
}
val resolvedIndex = if (index >= 0) index else messages.lastIndex
val parts = message.parts.toMutableList()
val partIndex = parts.indexOfFirst { it.id == partId }
val updated = upsert(if (partIndex >= 0) parts[partIndex] else null)
if (partIndex >= 0) parts[partIndex] = updated else parts.add(updated)
messages[resolvedIndex] = message.copy(parts = parts)
setRunning(thread.copy(messages = messages), true)
}
}
/**
* Applies a running transition: a turn that begins is stamped with the wall
* clock so the indicator can tick, a redundant `true` keeps the original
* stamp, and settling clears it. The one place `running` is set, so the two
* can never disagree.
*/
private fun setRunning(thread: ChatThread, running: Boolean): ChatThread = when {
running && !thread.running -> thread.copy(running = true, runningSince = now())
running -> thread
else -> thread.copy(running = false, runningSince = 0)
}
private fun update(sessionId: String, block: (ChatThread) -> ChatThread) {
val current = _state.value
if (current.open.none { it.sessionId == sessionId }) return
_state.value = current.copy(
open = current.open.map { if (it.sessionId == sessionId) block(it) else it },
)
}
companion object {
const val LOCAL_MESSAGE_PREFIX = "local-"
}
}
@@ -0,0 +1,463 @@
package net.awan.pipelines.ui.chat
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withLink
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.theme.HAIRLINE_DP
import net.awan.pipelines.ui.theme.pipelinesText
/**
* A small, dependency-free CommonMark subset for assistant prose. The brokered
* protocol carries assistant text as markdown and the reference experience renders
* it (research §1.2): body paragraphs, `#`..`######` headings, fenced code (the
* shared [CodeBlock], so the copy action comes for free), block quotes, bullet and
* ordered lists, `|` tables, thematic rules, and inline code / bold / italic /
* links. Anything outside the subset renders as plain text, never dropped.
*
* The parser is pure Kotlin (no Compose, no transport) so it is unit-testable; the
* composables below turn the same blocks into themed, selectable content.
*/
// ---- Parsed model ------------------------------------------------------------
internal sealed interface MdBlock
internal data class MdHeading(val level: Int, val text: String) : MdBlock
internal data class MdParagraph(val text: String) : MdBlock
internal data class MdCodeBlock(val language: String, val code: String) : MdBlock
internal data class MdQuote(val lines: List<String>) : MdBlock
internal data class MdListBlock(val ordered: Boolean, val items: List<String>) : MdBlock
internal data class MdTableBlock(val header: List<String>, val rows: List<List<String>>) : MdBlock
internal data object MdRule : MdBlock
internal sealed interface MdSpan
internal data class MdPlain(val text: String) : MdSpan
internal data class MdCodeSpan(val text: String) : MdSpan
internal data class MdStrong(val spans: List<MdSpan>) : MdSpan
internal data class MdEmphasis(val spans: List<MdSpan>) : MdSpan
internal data class MdLinkSpan(val spans: List<MdSpan>, val url: String) : MdSpan
// ---- Block parser ------------------------------------------------------------
/** Parses [source] into the block list the renderer walks. Never throws. */
internal fun parseMarkdown(source: String): List<MdBlock> {
val lines = source.replace("\r\n", "\n").replace('\r', '\n').split('\n')
val blocks = mutableListOf<MdBlock>()
var i = 0
while (i < lines.size) {
val line = lines[i]
val trimmed = line.trim()
when {
trimmed.isEmpty() -> i++
fenceRun(trimmed) != null -> {
val fence = fenceRun(trimmed)!!
val language = trimmed.removePrefix(fence).trim().substringBefore(' ')
val code = mutableListOf<String>()
i++
while (i < lines.size && fenceRun(lines[i].trim()) == null) {
code.add(lines[i])
i++
}
if (i < lines.size) i++ // consume the closing fence
blocks.add(MdCodeBlock(language, code.joinToString("\n")))
}
headingLevel(trimmed) > 0 -> {
val level = headingLevel(trimmed)
blocks.add(MdHeading(level, trimmed.drop(level).trim().trimEnd('#')))
i++
}
isRule(trimmed) -> {
blocks.add(MdRule)
i++
}
trimmed.startsWith(">") -> {
val quote = mutableListOf<String>()
while (i < lines.size && lines[i].trim().startsWith(">")) {
quote.add(lines[i].trim().removePrefix(">").removePrefix(" ").trimEnd())
i++
}
blocks.add(MdQuote(quote))
}
isTableStart(lines, i) -> {
val header = splitRow(lines[i])
i += 2 // header + delimiter row
val rows = mutableListOf<List<String>>()
while (i < lines.size && lines[i].contains('|') && lines[i].isNotBlank()) {
rows.add(fitRow(splitRow(lines[i]), header.size))
i++
}
blocks.add(MdTableBlock(header, rows))
}
listMarker(line) != null -> {
val ordered = listMarker(line)!!.first
val items = mutableListOf<String>()
while (i < lines.size && listMarker(lines[i])?.first == ordered) {
items.add(listMarker(lines[i])!!.second)
i++
}
blocks.add(MdListBlock(ordered, items))
}
else -> {
val paragraph = mutableListOf(line.trim())
i++
while (i < lines.size && lines[i].isNotBlank() && !startsBlock(lines, i)) {
paragraph.add(lines[i].trim())
i++
}
blocks.add(MdParagraph(paragraph.joinToString(" ")))
}
}
}
return blocks
}
/** The fence run (` ``` ` / `~~~`) a line opens or closes with, or null. */
private fun fenceRun(trimmed: String): String? {
val first = trimmed.firstOrNull() ?: return null
if (first != '`' && first != '~') return null
val run = trimmed.takeWhile { it == first }
return if (run.length >= 3) run else null
}
private fun headingLevel(trimmed: String): Int {
val hashes = trimmed.takeWhile { it == '#' }.length
if (hashes == 0 || hashes > 6) return 0
return if (trimmed.length == hashes || trimmed[hashes] == ' ') hashes else 0
}
private fun isRule(trimmed: String): Boolean =
trimmed.length >= 3 && trimmed.all { it == trimmed[0] } && trimmed[0] in "-*_"
/** True when [lines] at [index] is a table header followed by a `---` delimiter row. */
private fun isTableStart(lines: List<String>, index: Int): Boolean {
if (index + 1 >= lines.size || !lines[index].contains('|')) return false
val delimiter = splitRow(lines[index + 1])
if (delimiter.isEmpty() || splitRow(lines[index]).size < 2) return false
return delimiter.all { cell -> cell.isNotEmpty() && cell.all { it == '-' || it == ':' } && cell.contains('-') }
}
/** Splits a table row on unescaped `|`, dropping the leading/trailing empty cell. */
private fun splitRow(line: String): List<String> =
line.trim().removePrefix("|").removeSuffix("|").split('|').map { it.replace("\\|", "|").trim() }
private fun fitRow(row: List<String>, size: Int): List<String> =
List(size) { row.getOrElse(it) { "" } }
/** The ordered flag and item text of a list line, or null for a non-item line. */
private fun listMarker(line: String): Pair<Boolean, String>? {
val trimmed = line.trimStart()
val orderedMatch = ORDERED_ITEM.matchEntire(trimmed)
if (orderedMatch != null) return true to orderedMatch.groupValues[2]
val bulletMatch = BULLET_ITEM.matchEntire(trimmed)
if (bulletMatch != null) return false to bulletMatch.groupValues[2]
return null
}
/** True when [lines] at [index] begins a block that must interrupt a paragraph. */
private fun startsBlock(lines: List<String>, index: Int): Boolean {
val trimmed = lines[index].trim()
return fenceRun(trimmed) != null ||
headingLevel(trimmed) > 0 ||
isRule(trimmed) ||
trimmed.startsWith(">") ||
listMarker(lines[index]) != null ||
isTableStart(lines, index)
}
// ---- Inline parser -----------------------------------------------------------
/**
* Parses inline markup in [text] into a flat span tree. Handles `` `code` ``,
* `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
* `http(s)://` autolinks; everything else stays plain text. Underscore emphasis
* requires word boundaries so `snake_case` is never italicised.
*/
internal fun parseInline(text: String): List<MdSpan> {
val spans = mutableListOf<MdSpan>()
val buffer = StringBuilder()
var i = 0
fun flush() {
if (buffer.isNotEmpty()) {
spans.add(MdPlain(buffer.toString()))
buffer.clear()
}
}
while (i < text.length) {
val c = text[i]
when {
c == '`' -> {
val end = text.indexOf('`', i + 1)
if (end > i) {
flush()
spans.add(MdCodeSpan(text.substring(i + 1, end)))
i = end + 1
} else {
buffer.append(c); i++
}
}
c == '*' || c == '_' -> {
val doubled = i + 1 < text.length && text[i + 1] == c
val marker = if (doubled) "$c$c" else c.toString()
val boundOk = c != '_' || i == 0 || !text[i - 1].isLetterOrDigit()
val end = if (boundOk) text.indexOf(marker, i + marker.length) else -1
val closes = end > i + marker.length &&
(c != '_' || end + 1 >= text.length || !text[end + 1].isLetterOrDigit())
if (closes) {
flush()
val inner = parseInline(text.substring(i + marker.length, end))
spans.add(if (doubled) MdStrong(inner) else MdEmphasis(inner))
i = end + marker.length
} else {
buffer.append(c); i++
}
}
c == '[' -> {
val close = text.indexOf(']', i + 1)
if (close > i && close + 1 < text.length && text[close + 1] == '(') {
val urlEnd = text.indexOf(')', close + 2)
val url = if (urlEnd > close) text.substring(close + 2, urlEnd).trim() else ""
if (url.isNotEmpty()) {
flush()
spans.add(MdLinkSpan(parseInline(text.substring(i + 1, close)), url))
i = urlEnd + 1
} else {
buffer.append(c); i++
}
} else {
buffer.append(c); i++
}
}
else -> {
val url = autolinkAt(text, i)
if (url != null) {
flush()
spans.add(MdLinkSpan(listOf(MdPlain(url)), url))
i += url.length
} else {
buffer.append(c); i++
}
}
}
}
flush()
return spans
}
/** A bare `http(s)://` URL starting exactly at [index], trailing punctuation trimmed. */
private fun autolinkAt(text: String, index: Int): String? {
if (!text.startsWith("http://", index) && !text.startsWith("https://", index)) return null
var end = index
while (end < text.length && !text[end].isWhitespace() && text[end] !in "<>\"'") end++
var url = text.substring(index, end)
while (url.isNotEmpty() && url.last() in ".,;:!?)]}") url = url.dropLast(1)
return url.takeIf { it.length > "https://".length }
}
private val ORDERED_ITEM = Regex("""^(\d{1,9})[.)]\s+(.*)$""")
private val BULLET_ITEM = Regex("""^([-*+])\s+(.*)$""")
// ---- Renderers ---------------------------------------------------------------
private val MD_QUOTE_BAR = 3.dp
private val MD_TABLE_BORDER = HAIRLINE_DP
/**
* Renders [text] as markdown at the app's shared body style. The caller owns the
* selection container (a chat message is one selectable region), so this only
* lays out the blocks.
*/
@Composable
internal fun MarkdownText(text: String, modifier: Modifier = Modifier) {
val blocks = remember(text) { parseMarkdown(text) }
Column(modifier, verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
blocks.forEach { MarkdownBlock(it) }
}
}
@Composable
private fun MarkdownBlock(block: MdBlock) {
val texts = pipelinesText()
when (block) {
is MdHeading -> Text(
text = inline(block.text),
style = when (block.level) {
1 -> MaterialTheme.typography.titleLarge
2 -> MaterialTheme.typography.titleMedium
else -> texts.cardTitle
},
color = MaterialTheme.colorScheme.onSurface,
)
is MdParagraph -> Text(text = inline(block.text), style = texts.body)
is MdCodeBlock -> CodeBlock(label = block.language.ifBlank { "code" }, text = block.code)
MdRule -> HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
is MdQuote -> Row(Modifier.height(IntrinsicSize.Min)) {
Box(
Modifier
.width(MD_QUOTE_BAR)
.fillMaxHeight()
.background(MaterialTheme.colorScheme.outlineVariant),
)
Column(
modifier = Modifier.padding(start = CHAT_ITEM_GAP),
verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2),
) {
block.lines.forEach { line ->
if (line.isNotBlank()) {
Text(
text = inline(line),
style = texts.body,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
is MdListBlock -> Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2)) {
block.items.forEachIndexed { index, item ->
Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) {
Text(
text = if (block.ordered) "${index + 1}." else "•",
style = texts.body,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(text = inline(item), style = texts.body)
}
}
}
is MdTableBlock -> MarkdownTable(block)
}
}
@Composable
private fun MarkdownTable(table: MdTableBlock) {
val border = MaterialTheme.colorScheme.outlineVariant
val shape = RoundedCornerShape(CHAT_ITEM_GAP)
Column(
Modifier
.fillMaxWidth()
.clip(shape)
.border(MD_TABLE_BORDER, border, shape),
) {
TableRow(table.header, header = true, border = border)
table.rows.forEach { row ->
HorizontalDivider(color = border)
TableRow(row, header = false, border = border)
}
}
}
@Composable
private fun TableRow(cells: List<String>, header: Boolean, border: Color) {
val texts = pipelinesText()
Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
cells.forEachIndexed { index, cell ->
if (index > 0) {
Box(Modifier.width(MD_TABLE_BORDER).fillMaxHeight().background(border))
}
Text(
text = inline(cell),
style = if (header) texts.body.copy(fontWeight = FontWeight.Bold) else texts.body,
modifier = Modifier.weight(1f).padding(CHAT_ITEM_GAP),
maxLines = if (header) 1 else Int.MAX_VALUE,
overflow = TextOverflow.Ellipsis,
)
}
}
}
/** Inline text as one [AnnotatedString]; links are tappable and code is monospace. */
@Composable
private fun inline(text: String): AnnotatedString {
val linkColor = MaterialTheme.colorScheme.primary
val codeBackground = MaterialTheme.colorScheme.surfaceContainerHigh
val codeColor = MaterialTheme.colorScheme.onSurface
return remember(text, linkColor, codeBackground, codeColor) {
buildInline(parseInline(text), linkColor, codeBackground, codeColor)
}
}
private fun buildInline(
spans: List<MdSpan>,
linkColor: Color,
codeBackground: Color,
codeColor: Color,
): AnnotatedString = buildAnnotatedString { appendSpans(spans, linkColor, codeBackground, codeColor) }
private fun androidx.compose.ui.text.AnnotatedString.Builder.appendSpans(
spans: List<MdSpan>,
linkColor: Color,
codeBackground: Color,
codeColor: Color,
) {
for (span in spans) {
when (span) {
is MdPlain -> append(span.text)
is MdCodeSpan -> withStyle(
SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground, color = codeColor),
) { append(span.text) }
is MdStrong -> withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
appendSpans(span.spans, linkColor, codeBackground, codeColor)
}
is MdEmphasis -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
appendSpans(span.spans, linkColor, codeBackground, codeColor)
}
is MdLinkSpan -> withLink(
LinkAnnotation.Url(
span.url,
TextLinkStyles(style = SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)),
),
) { appendSpans(span.spans, linkColor, codeBackground, codeColor) }
}
}
}
@@ -212,3 +212,18 @@ internal val STAGE_CHIP_PAD_H = 10.dp
/** The omni-search panel's inline progress spinner. */
internal val SEARCH_PROGRESS_DP = 18.dp
/** The thinnest line the UI draws - a table border, a divider or a card outline. */
internal val HAIRLINE_DP = 1.dp
/** A small icon button: the session close action and the tool-panel dismiss. */
internal val ICON_BUTTON_SMALL_DP = 28.dp
/** The floating tool panel's maximum width; it floats over the transcript. */
internal val TOOL_PANEL_MAX_WIDTH_DP = 420.dp
/** A chat row's title column stops here so the close action keeps its place. */
internal val CHAT_TITLE_MAX_WIDTH_DP = 160.dp
/** A chat message bubble's maximum width, so long prose stays readable. */
internal val CHAT_BUBBLE_MAX_WIDTH_DP = 560.dp
@@ -0,0 +1,258 @@
package net.awan.pipelines.data.protocol
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class ChatProtocolTest {
@Test
fun chatSessionsParseWithBusyFlagAndFlattenedFields() {
val json = """
{
"type": "chat_sessions",
"id": "android-1",
"chat_sessions": [
{
"id": "ses_abc",
"title": "Fix the parser",
"agent": "build",
"model": "deepseek-v4.1-flash",
"directory": "/Users/alan/repos/pipelines",
"parent_id": "",
"created_at": 1792112366711,
"updated_at": 1792112367036,
"busy": true
},
{"id": "ses_def", "title": "Second chat"}
]
}
""".trimIndent()
val message = PipelinesJson.decodeFromString(Message.serializer(), json)
assertEquals(Protocol.CHAT_SESSIONS, message.type)
val sessions = message.chatSessions!!
assertEquals(2, sessions.size)
val first = sessions.first()
assertEquals("ses_abc", first.id)
assertEquals("Fix the parser", first.title)
assertEquals("/Users/alan/repos/pipelines", first.directory)
assertEquals(1792112366711L, first.createdAt)
assertTrue(first.busy)
// An absent busy key defaults to false, never a crash.
assertTrue(!sessions[1].busy)
}
@Test
fun chatMessagesParseTextReasoningAndToolParts() {
val json = """
{
"type": "chat_messages",
"chat_messages": [
{
"id": "msg_user",
"session_id": "ses_abc",
"role": "user",
"parts": [{"type": "text", "id": "p1", "text": "hello"}]
},
{
"id": "msg_asst",
"session_id": "ses_abc",
"role": "assistant",
"parts": [
{"type": "reasoning", "id": "r1", "text": "thinking"},
{"type": "text", "id": "t1", "text": "done"},
{
"type": "tool",
"id": "call_1",
"name": "shell",
"executed": false,
"state": {
"status": "completed",
"input": {"command": "ls"},
"content": [{"type": "text", "text": "a.txt"}],
"metadata": {"exit": 0},
"error": null
},
"time": {"created": 10, "ran": 12, "completed": 20}
}
]
}
]
}
""".trimIndent()
val messages = PipelinesJson.decodeFromString(Message.serializer(), json).chatMessages!!
assertEquals(2, messages.size)
assertEquals(ChatProtocol.ROLE_USER, messages[0].role)
assertEquals("hello", messages[0].parts.single().text)
val assistant = messages[1]
assertEquals(ChatProtocol.PART_REASONING, assistant.parts[0].type)
val tool = assistant.parts.first { it.type == ChatProtocol.PART_TOOL }
assertEquals("shell", tool.name)
assertEquals(ChatProtocol.TOOL_COMPLETED, tool.state!!.status)
assertTrue(tool.state!!.input is JsonObject)
assertEquals("a.txt", tool.state!!.content.single().text)
assertEquals(8L, toolDuration(tool))
}
/** The tool input is a partial-JSON string while streaming and an object afterwards. */
@Test
fun streamingToolInputIsAStringAndCompletedInputIsAnObject() {
val streaming = """
{"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"m1","kind":"tool",
"part":{"type":"tool","id":"c1","name":"edit","state":{"status":"streaming","input":"{\"old"}}}}
""".trimIndent()
val frame = PipelinesJson.decodeFromString(Message.serializer(), streaming).chatEvent!!
assertEquals(ChatProtocol.TOOL_STREAMING, frame.part!!.state!!.status)
assertEquals("{\"old", (frame.part!!.state!!.input as JsonPrimitive).content)
assertTrue(ChatProtocol.toolRunning(frame.part!!.state))
}
@Test
fun chatEventDeltaCarriesTheTargetPartAndText() {
val json = """
{"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"m1","kind":"text",
"delta":"wor","part":{"type":"text","id":"t1"}}}
""".trimIndent()
val frame = PipelinesJson.decodeFromString(Message.serializer(), json).chatEvent!!
assertEquals("ses_1", frame.sessionId)
assertEquals("m1", frame.messageId)
assertEquals(ChatProtocol.PART_TEXT, frame.kind)
assertEquals("wor", frame.delta)
assertEquals("t1", frame.part!!.id)
}
@Test
fun stepAndUsageFramesDecode() {
val step = """
{"type":"chat_event","chat_event":{"session_id":"s","kind":"step","step":{"status":"ended","index":3}}}
""".trimIndent()
val decodedStep = PipelinesJson.decodeFromString(Message.serializer(), step).chatEvent!!
assertEquals(ChatProtocol.EVENT_STEP, decodedStep.kind)
assertEquals(ChatProtocol.STEP_ENDED, decodedStep.step!!.status)
val usage = """
{"type":"chat_event","chat_event":{"session_id":"s","kind":"usage",
"usage":{"input_tokens":12,"output_tokens":34,"cost":0.002}}}
""".trimIndent()
val decodedUsage = PipelinesJson.decodeFromString(Message.serializer(), usage).chatEvent!!
assertEquals(12, decodedUsage.usage!!.inputTokens)
assertEquals(34, decodedUsage.usage!!.outputTokens)
assertEquals(0.002, decodedUsage.usage!!.cost, 0.0)
}
@Test
fun chatPermissionFrameDecodesTheRequestShape() {
val json = """
{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9",
"action":"edit","resources":["src/a.kt"],
"source":{"type":"tool","message_id":"m1","id":"c1"},
"message":"Allow this edit?"}}
""".trimIndent()
val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!!
assertEquals("req_9", permission.requestId)
assertEquals("edit", permission.action)
assertEquals("src/a.kt", permission.resources.single())
assertEquals("c1", permission.source!!.id)
// An open request defaults to unresolved; nothing is invented.
assertTrue(!permission.resolved)
assertEquals("", permission.decision)
}
/** A request the server reports as already settled carries the outcome. */
@Test
fun chatPermissionFrameCarriesTheServerResolution() {
val json = """
{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9",
"action":"edit","resolved":true,"decision":"reject","message":"another client rejected it"}}
""".trimIndent()
val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!!
assertTrue(permission.resolved)
assertEquals(ChatProtocol.DECISION_REJECT, permission.decision)
assertEquals("another client rejected it", permission.message)
}
@Test
fun chatRequestsRoundTripTheirBodies() {
val create = Message(
type = Protocol.CHAT_CREATE,
id = "android-1",
chatCreate = ChatCreateRequest(title = "New chat", directory = "/work"),
)
val createJson = PipelinesJson.encodeToString(Message.serializer(), create)
assertTrue(createJson.contains("\"chat_create\""))
val decodedCreate = PipelinesJson.decodeFromString(Message.serializer(), createJson)
assertEquals("New chat", decodedCreate.chatCreate!!.title)
val prompt = Message(
type = Protocol.CHAT_PROMPT,
id = "android-2",
chatPrompt = ChatPromptRequest(sessionId = "ses_1", text = "hi"),
)
val decodedPrompt = PipelinesJson.decodeFromString(
Message.serializer(),
PipelinesJson.encodeToString(Message.serializer(), prompt),
)
assertEquals("ses_1", decodedPrompt.chatPrompt!!.sessionId)
assertEquals("hi", decodedPrompt.chatPrompt!!.text)
val query = Message(type = Protocol.CHAT_MESSAGES, id = "android-3", chatQuery = ChatQuery("ses_1", 50))
val decodedQuery = PipelinesJson.decodeFromString(
Message.serializer(),
PipelinesJson.encodeToString(Message.serializer(), query),
)
assertEquals("ses_1", decodedQuery.chatQuery!!.sessionId)
assertEquals(50, decodedQuery.chatQuery!!.limit)
val reply = Message(
type = Protocol.CHAT_REPLY,
id = "android-4",
chatReply = ChatReplyRequest("ses_1", "req_9", ChatProtocol.DECISION_ONCE),
)
val decodedReply = PipelinesJson.decodeFromString(
Message.serializer(),
PipelinesJson.encodeToString(Message.serializer(), reply),
)
assertEquals(ChatProtocol.DECISION_ONCE, decodedReply.chatReply!!.decision)
}
/**
* The stop control's interrupt request: pressing it while a turn is in flight
* must send a `chat_interrupt` carrying the running session's id and nothing
* else, and the frame must survive the wire round-trip the client performs.
* Uses the same [ChatProtocol.interruptRequest] builder the repository sends,
* so this test cannot drift from the production frame.
*/
@Test
fun chatInterruptRequestCarriesTheRunningSession() {
val request = ChatProtocol.interruptRequest("ses_1")
assertEquals(Protocol.CHAT_INTERRUPT, request.type)
assertEquals("ses_1", request.chatQuery!!.sessionId)
val encoded = PipelinesJson.encodeToString(Message.serializer(), request.copy(id = "android-9"))
val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded)
assertEquals(Protocol.CHAT_INTERRUPT, decoded.type)
assertEquals("ses_1", decoded.chatQuery!!.sessionId)
assertNull(decoded.chatPrompt)
assertNull(decoded.chatReply)
}
/** A non-chat envelope leaves every chat field null, so the two never cross-talk. */
@Test
fun nonChatEnvelopeHasNoChatPayload() {
val message = PipelinesJson.decodeFromString(
Message.serializer(),
"""{"type":"pong"}""",
)
assertNull(message.chatEvent)
assertNull(message.chatSessions)
assertNull(message.chatPermission)
}
private fun toolDuration(part: ChatPart): Long? {
val time = part.time ?: return null
return time.completed - time.ran
}
}
@@ -0,0 +1,174 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.PipelinesJson
import net.awan.pipelines.data.protocol.Protocol
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The approval card the conversation shows for a pushed permission request: the
* request appears as a card, answering it updates the card in place with the
* decision the reply frame carries, and a request the server reports as already
* resolved offers no stale actions. Driven through [ChatStore] and the pure
* [approvalCard] the composable renders, so no device, server or Compose runtime
* is needed.
*/
class ChatApprovalTest {
private fun frame(
requestId: String = "req_9",
action: String = "edit",
resources: List<String> = listOf("src/a.kt"),
message: String = "This edits a file in your workspace.",
resolved: Boolean = false,
decision: String = "",
) = ChatPermissionFrame(
sessionId = "ses_1",
requestId = requestId,
action = action,
resources = resources,
message = message,
resolved = resolved,
decision = decision,
)
private fun storeWithPermission(permission: ChatPermissionFrame): ChatStore {
val store = ChatStore()
store.open(ChatSession(id = "ses_1", title = "Chat"))
store.permission(permission)
return store
}
private fun card(store: ChatStore): ApprovalCard {
val thread = store.value.thread("ses_1")!!
return approvalCard(thread.permission, thread.permissionAnswer)!!
}
@Test
fun permissionFrameShowsAPendingApprovalCard() {
val card = card(storeWithPermission(frame()))
assertEquals(ApprovalState.PENDING, card.state)
assertTrue(card.actionable)
assertEquals("Approve edit", card.headline)
assertEquals("Waiting for your response", card.statusLine)
assertEquals(listOf("src/a.kt"), card.resources)
assertEquals("This edits a file in your workspace.", card.risk)
assertTrue(card.showRisk)
}
@Test
fun onceAlwaysAndRejectSendTheRightDecision() {
// The same builder the repository sends, so the card's actions and this
// assertion cannot drift from the wire frame. Every decision goes through
// the identical encode/decode round trip, so none is asserted more weakly
// than another.
for (decision in listOf(
ChatProtocol.DECISION_ONCE,
ChatProtocol.DECISION_ALWAYS,
ChatProtocol.DECISION_REJECT,
)) {
val reply = ChatProtocol.replyRequest("ses_1", "req_9", decision)
assertEquals(Protocol.CHAT_REPLY, reply.type)
assertEquals("ses_1", reply.chatReply!!.sessionId)
assertEquals("req_9", reply.chatReply!!.requestId)
assertEquals(decision, reply.chatReply!!.decision)
val decoded = PipelinesJson.decodeFromString(
Message.serializer(),
PipelinesJson.encodeToString(Message.serializer(), reply.copy(id = "android-1")),
)
assertEquals(decision, decoded.chatReply!!.decision)
}
}
@Test
fun answeringOnceUpdatesTheCardInPlace() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
val settled = card(store)
assertEquals(ApprovalState.ANSWERED, settled.state)
assertFalse(settled.actionable)
assertEquals(ChatProtocol.DECISION_ONCE, settled.decision)
assertEquals("Allowed once", settled.headline)
// The request is still on screen, not removed: it just stopped asking.
assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId)
}
@Test
fun answeringAlwaysUpdatesTheCardInPlace() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ALWAYS)
val settled = card(store)
assertEquals(ApprovalState.ANSWERED, settled.state)
assertFalse(settled.actionable)
assertEquals(ChatProtocol.DECISION_ALWAYS, settled.decision)
assertEquals("Always allowed", settled.headline)
// The request stays visible but stops asking; only a denial keeps the
// amber review panel, so an allow-always retires it.
assertFalse(settled.showRisk)
assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId)
}
@Test
fun rejectingKeepsTheRiskReviewWhileItSettles() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_REJECT)
val settled = card(store)
assertEquals(ApprovalState.ANSWERED, settled.state)
assertEquals("Rejected", settled.headline)
assertTrue(settled.showRisk)
}
@Test
fun serverResolvedRequestOffersNoActions() {
val store = storeWithPermission(frame(resolved = true, message = "Another client already answered."))
val resolved = card(store)
assertEquals(ApprovalState.RESOLVED, resolved.state)
assertFalse(resolved.actionable)
assertEquals("Already resolved", resolved.headline)
assertEquals("Another client already answered.", resolved.statusLine)
}
@Test
fun serverResolvedDecisionIsNamed() {
val store = storeWithPermission(
frame(resolved = true, decision = ChatProtocol.DECISION_REJECT, message = ""),
)
assertEquals("Rejected", card(store).headline)
}
@Test
fun failedReplyReopensTheRequest() {
val store = storeWithPermission(frame())
store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE)
store.permissionReplyFailed("ses_1", "req_9")
assertTrue(card(store).actionable)
}
@Test
fun riskFallsBackToTheActionWhenTheServerSendsNoSummary() {
val store = storeWithPermission(frame(message = "", resources = emptyList()))
val card = card(store)
assertTrue(card.risk.contains("edit"))
assertEquals(emptyList<String>(), card.resources)
}
@Test
fun aRequestWithoutAnIdShowsNoCard() {
val store = storeWithPermission(frame(requestId = ""))
val thread = store.value.thread("ses_1")!!
assertNull(approvalCard(thread.permission, thread.permissionAnswer))
}
}
@@ -0,0 +1,155 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import net.awan.pipelines.data.protocol.ChatError
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatTime
import net.awan.pipelines.data.protocol.ChatToolContent
import net.awan.pipelines.data.protocol.ChatToolState
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class ChatFormatTest {
@Test
fun prettyToolInputPrintsObjectsAndPassesThroughPartialStrings() {
val obj = prettyToolInput(JsonObject(mapOf("command" to JsonPrimitive("ls"))))
assertTrue(obj.contains("\"command\""))
assertTrue(obj.contains("\n"))
assertEquals("{\"old", prettyToolInput(JsonPrimitive("{\"old")))
assertEquals("", prettyToolInput(null))
}
@Test
fun toolOutputFallsBackToNoOutput() {
val completed = ChatToolState(
status = ChatProtocol.TOOL_COMPLETED,
content = listOf(ChatToolContent(type = "text", text = "hello")),
)
assertEquals("hello", toolOutputText(completed))
assertEquals(
"(no output)",
toolOutputText(ChatToolState(status = ChatProtocol.TOOL_COMPLETED)),
)
// Still streaming -> nothing yet, never the "(no output)" claim.
assertEquals("", toolOutputText(ChatToolState(status = ChatProtocol.TOOL_RUNNING)))
}
@Test
fun toolErrorPrefersTheMessageOverPartialOutput() {
// A failed call can carry both output content and an error; the ERROR
// block must show the message, never the output text.
val failed = ChatToolState(
status = ChatProtocol.TOOL_ERROR,
content = listOf(ChatToolContent(type = "text", text = "partial output")),
error = ChatError(type = "boom", message = "exploded"),
)
assertEquals("exploded", toolErrorText(failed))
// A failure with no message still renders something rather than a blank block.
assertEquals("(no output)", toolErrorText(ChatToolState(status = ChatProtocol.TOOL_ERROR)))
}
@Test
fun toolDurationUsesRanToCompletedAndIsNullWhileRunning() {
val done = ChatPart(name = "shell", time = ChatTime(created = 5, ran = 10, completed = 35))
assertEquals(25L, toolDurationMillis(done))
assertNull(toolDurationMillis(ChatPart(name = "shell", time = ChatTime(created = 5))))
assertEquals("340ms", formatToolDuration(340))
assertEquals("1.5s", formatToolDuration(1500))
}
@Test
fun sessionStatusReportsRunningBusyAndIdle() {
assertEquals("Running", sessionStatusLabel(ChatSession(id = "s"), runningLocally = true))
assertEquals(
"Busy · read-only",
sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false),
)
assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s"), runningLocally = false))
}
@Test
fun composerControlIsStopWhileARunIsInFlightAndSendOtherwise() {
// While a turn is in flight the send control becomes the stop control:
// the phone's composer offers the interrupt, never a second send.
assertEquals(ComposerAction.Stop, composerAction(ChatThread(sessionId = "s", running = true)))
assertEquals(ComposerAction.Send, composerAction(ChatThread(sessionId = "s")))
}
@Test
fun toolEditDiffMarksOnlyChangedLinesAndCountsThem() {
val input = JsonObject(
mapOf(
"filePath" to JsonPrimitive("/tmp/a.txt"),
"oldString" to JsonPrimitive("one\ntwo\nthree"),
"newString" to JsonPrimitive("one\nTWO\nthree\nfour"),
),
)
val diff = toolEditDiff(input)!!
assertEquals("/tmp/a.txt", diff.file)
assertEquals(2, diff.added)
assertEquals(1, diff.removed)
// A small edit is shown whole, nothing summarised.
assertEquals(0, diff.omitted)
assertEquals(
listOf(
DiffLine(DiffKind.CONTEXT, "one"),
DiffLine(DiffKind.REMOVE, "two"),
DiffLine(DiffKind.ADD, "TWO"),
DiffLine(DiffKind.CONTEXT, "three"),
DiffLine(DiffKind.ADD, "four"),
),
diff.lines,
)
}
@Test
fun toolEditDiffSummarisesAnOversizedEditInsteadOfRenderingEveryLine() {
// Wholly disjoint old/new blocks: every line is a change, so the full diff
// is twice the block size — far past what a phone should render.
val changed = MAX_RENDERED_DIFF_LINES + 50
val old = (1..changed).joinToString("\n") { "old $it" }
val new = (1..changed).joinToString("\n") { "new $it" }
val diff = toolEditDiff(
JsonObject(
mapOf(
"filePath" to JsonPrimitive("/tmp/big.txt"),
"oldString" to JsonPrimitive(old),
"newString" to JsonPrimitive(new),
),
),
)!!
// The stat still describes the whole edit...
assertEquals(changed, diff.added)
assertEquals(changed, diff.removed)
// ...but only a readable prefix is rendered, the rest counted as omitted.
assertEquals(MAX_RENDERED_DIFF_LINES, diff.lines.size)
assertEquals(2 * changed - MAX_RENDERED_DIFF_LINES, diff.omitted)
}
@Test
fun toolEditDiffIsNullForNonEdits() {
assertNull(toolEditDiff(null))
assertNull(toolEditDiff(JsonObject(mapOf("command" to JsonPrimitive("ls")))))
}
@Test
fun toolFailedOnlyForTheErrorStatus() {
assertTrue(toolFailed(ChatToolState(status = ChatProtocol.TOOL_ERROR)))
assertFalse(toolFailed(ChatToolState(status = ChatProtocol.TOOL_COMPLETED)))
assertFalse(toolFailed(ChatToolState(status = ChatProtocol.TOOL_RUNNING)))
assertFalse(toolFailed(null))
}
@Test
fun sessionTitleNeverBlank() {
assertEquals("Named", sessionTitle(ChatSession(id = "ses_1", title = "Named")))
assertEquals("ses_abcdefghijklmn", sessionTitle(ChatSession(id = "ses_abcdefghijklmnop")))
}
}
@@ -0,0 +1,133 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatEventFrame
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatStep
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The streaming guarantees: a sequence of text deltas grows the rendered
* conversation and the running indicator toggles on and off, the elapsed time is
* derived from the turn's own start, a reconnect settles the indicator before the
* history re-fetch, and a mid-stream failure settles it with the server's text.
* Driven directly against [ChatStore] with an injected clock, so no device,
* server or Compose runtime is needed.
*/
class ChatStreamTest {
private fun session(id: String) = ChatSession(id = id, title = id)
private fun step(status: String) = ChatEventFrame(
sessionId = "s",
kind = ChatProtocol.EVENT_STEP,
step = ChatStep(status = status),
)
private fun delta(sessionId: String, messageId: String, partId: String, text: String) = ChatEventFrame(
sessionId = sessionId,
messageId = messageId,
kind = ChatProtocol.PART_TEXT,
delta = text,
part = ChatPart(type = ChatProtocol.PART_TEXT, id = partId),
)
/** The text of the single assistant message, exactly what the transcript renders. */
private fun renderedText(store: ChatStore, sessionId: String): String =
store.value.thread(sessionId)!!.messages.last().parts.single().text
@Test
fun deltaSequenceGrowsRenderedTextAndTogglesRunning() {
val store = ChatStore()
store.open(session("s"))
store.history("s", emptyList())
assertFalse(store.value.thread("s")!!.running)
// A step starting the turn raises the running indicator.
store.event(step(ChatProtocol.STEP_STARTED))
assertTrue(store.value.thread("s")!!.running)
// Each delta appends to the same part: the rendered text is the exact
// concatenation and strictly grows, never resets.
val chunks = listOf("Hel", "lo ", "wor", "ld")
val lengths = mutableListOf<Int>()
chunks.forEachIndexed { index, chunk ->
store.event(delta("s", "m1", "m1#0", chunk))
assertEquals(chunks.take(index + 1).joinToString(""), renderedText(store, "s"))
lengths += renderedText(store, "s").length
}
assertTrue(lengths.zipWithNext().all { (before, after) -> after > before })
// The step ending the turn lowers the indicator and clears its start.
store.event(step(ChatProtocol.STEP_ENDED))
assertFalse(store.value.thread("s")!!.running)
assertEquals(0L, store.value.thread("s")!!.runningSince)
assertEquals("Hello world", renderedText(store, "s"))
}
@Test
fun elapsedTimeComesFromTheTurnStartAndSurvivesARepeatedStart() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(session("s"))
store.event(step(ChatProtocol.STEP_STARTED))
assertEquals(1_000L, store.value.thread("s")!!.runningSince)
clock = 6_500L
assertEquals(5_500L, store.value.thread("s")!!.elapsedMillis(clock))
// A second start for the same turn must not move the clock forward.
store.event(step(ChatProtocol.STEP_STARTED))
assertEquals(1_000L, store.value.thread("s")!!.runningSince)
assertEquals(5_500L, store.value.thread("s")!!.elapsedMillis(clock))
// Settling drops the elapsed to 0 whatever the clock reads.
store.event(step(ChatProtocol.STEP_ENDED))
assertEquals(0L, store.value.thread("s")!!.elapsedMillis(clock))
}
@Test
fun streamResumedSettlesRunningAndReturnsEveryOpenChat() {
val store = ChatStore()
store.open(session("a"))
store.history("a", emptyList())
store.open(session("b"))
store.history("b", emptyList())
store.running("a", true)
// A reconnect names every open chat so the caller re-fetches each, and no
// thread keeps claiming to run until a fresh frame proves it.
assertEquals(listOf("a", "b"), store.streamResumed())
assertFalse(store.value.thread("a")!!.running)
// A delta after the resync re-asserts the running indicator.
store.event(delta("a", "m1", "m1#0", "still going"))
assertTrue(store.value.thread("a")!!.running)
assertEquals("still going", renderedText(store, "a"))
}
@Test
fun streamErrorSettlesTheRunningTurnAndKeepsTheServerText() {
val store = ChatStore()
store.open(session("s"))
store.running("s", true)
store.streamError("chat stream: boom")
val thread = store.value.thread("s")!!
assertFalse(thread.running)
assertEquals("chat stream: boom", thread.error)
}
@Test
fun streamErrorWithNothingRunningIsIgnored() {
val store = ChatStore()
store.open(session("s"))
store.streamError("chat stream: boom")
assertEquals(null, store.value.thread("s")!!.error)
}
}
@@ -0,0 +1,95 @@
package net.awan.pipelines.ui.chat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class MarkdownTest {
@Test
fun fencedCodeKeepsTheLanguageAndBody() {
val blocks = parseMarkdown(
"""
Intro text.
```kotlin
val gap = 8.dp
println(gap)
```
""".trimIndent(),
)
assertEquals(MdParagraph("Intro text."), blocks[0])
val code = blocks[1] as MdCodeBlock
assertEquals("kotlin", code.language)
assertEquals("val gap = 8.dp\nprintln(gap)", code.code)
}
@Test
fun anUnterminatedFenceStillYieldsItsCode() {
val blocks = parseMarkdown("```\nline one\nline two")
val code = blocks.single() as MdCodeBlock
assertEquals("", code.language)
assertEquals("line one\nline two", code.code)
}
@Test
fun softWrappedParagraphLinesJoinWithASpace() {
assertEquals(listOf(MdParagraph("one two three")), parseMarkdown("one\ntwo\nthree"))
assertEquals(listOf(MdParagraph("one"), MdParagraph("two")), parseMarkdown("one\n\ntwo"))
}
@Test
fun headingsAndThematicRulesParseByLevel() {
val blocks = parseMarkdown("# Title\n\n## Section\n\n---")
assertEquals(MdHeading(1, "Title"), blocks[0])
assertEquals(MdHeading(2, "Section"), blocks[1])
assertEquals(MdRule, blocks[2])
}
@Test
fun bulletAndOrderedListsKeepTheirOrder() {
val bullets = parseMarkdown("- one\n- two").single() as MdListBlock
assertEquals(false, bullets.ordered)
assertEquals(listOf("one", "two"), bullets.items)
val ordered = parseMarkdown("1. first\n2. second").single() as MdListBlock
assertEquals(true, ordered.ordered)
assertEquals(listOf("first", "second"), ordered.items)
}
@Test
fun aPipeTableParsesHeaderAndRows() {
val blocks = parseMarkdown("| Name | Value |\n| --- | ---: |\n| a | 1 |\n| b | 2 |")
val table = blocks.single() as MdTableBlock
assertEquals(listOf("Name", "Value"), table.header)
assertEquals(listOf(listOf("a", "1"), listOf("b", "2")), table.rows)
}
@Test
fun inlineCodeBoldItalicAndLinksBecomeSpans() {
val spans = parseInline("Use `CodeBlock` and **bold** and *italic* and [docs](https://example.com/x).")
assertTrue(spans.any { it is MdCodeSpan && it.text == "CodeBlock" })
assertTrue(spans.any { it is MdStrong })
assertTrue(spans.any { it is MdEmphasis })
val link = spans.filterIsInstance<MdLinkSpan>().single()
assertEquals("https://example.com/x", link.url)
}
@Test
fun bareUrlsAutolinkAndTrimTrailingPunctuation() {
val spans = parseInline("See https://example.com/a, then stop.")
val link = spans.filterIsInstance<MdLinkSpan>().single()
assertEquals("https://example.com/a", link.url)
}
@Test
fun underscoresInsideAWordAreNotEmphasis() {
assertEquals(listOf(MdPlain("snake_case_name")), parseInline("snake_case_name"))
}
@Test
fun anEmptySourceParsesToNoBlocks() {
assertEquals(emptyList<MdBlock>(), parseMarkdown(""))
assertEquals(emptyList<MdBlock>(), parseMarkdown("\n\n"))
}
}
@@ -0,0 +1,227 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatEventFrame
import net.awan.pipelines.data.protocol.ChatMessage
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatPermissionFrame
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The multi-chat state guarantees: each open chat preserves its own conversation,
* a running session re-syncs when the operator returns to it, and the draft and
* scroll position are per chat. Driven directly against [ChatStore], with no
* device, server or Compose runtime.
*/
class MultiChatStateTest {
private fun session(id: String, title: String = id, busy: Boolean = false) =
ChatSession(id = id, title = title, busy = busy)
private fun text(id: String, role: String, body: String) = ChatMessage(
id = id,
sessionId = "",
role = role,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "$id-p", text = body)),
)
@Test
fun switchingPreservesEachConversation() {
val store = ChatStore()
assertTrue(store.open(session("a", "Chat A")))
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "first"), text("a2", ChatProtocol.ROLE_ASSISTANT, "reply A")))
assertTrue(store.open(session("b", "Chat B")))
store.history("b", listOf(text("b1", ChatProtocol.ROLE_USER, "different")))
// Returning to A shows A's conversation, untouched by B. A loaded,
// settled chat needs no re-sync.
assertFalse(store.activate("a"))
assertEquals(listOf("a1", "a2"), store.value.thread("a")!!.messages.map { it.id })
assertEquals("a", store.value.activeId)
assertFalse(store.activate("b"))
assertEquals(listOf("b1"), store.value.thread("b")!!.messages.map { it.id })
}
@Test
fun runningSessionResyncsOnReturn() {
val store = ChatStore()
store.open(session("a"))
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "prompt")))
store.running("a", true)
store.open(session("b"))
store.history("b", emptyList())
// Switching to B must not cancel A's running turn.
store.activate("b")
assertTrue(store.value.thread("a")!!.running)
// Returning to the running chat reports that it must be re-synced.
assertTrue(store.activate("a"))
// The re-sync replaces the conversation with the server's copy and keeps running.
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "prompt"), text("a2", ChatProtocol.ROLE_ASSISTANT, "live")))
val resynced = store.value.thread("a")!!
assertTrue(resynced.running)
assertEquals("live", resynced.messages.last().parts.single().text)
// Once it settles, a later return does not force another re-sync.
store.running("a", false)
store.activate("b")
assertFalse(store.activate("a"))
}
@Test
fun draftsArePerChat() {
val store = ChatStore()
store.open(session("a"))
store.open(session("b"))
store.draft("a", "hello from A")
store.draft("b", "typed in B")
store.activate("a")
assertEquals("hello from A", store.value.thread("a")!!.draft)
store.activate("b")
assertEquals("typed in B", store.value.thread("b")!!.draft)
// Clearing one chat's draft never touches the other's.
store.clearDraft("b")
assertEquals("", store.value.thread("b")!!.draft)
assertEquals("hello from A", store.value.thread("a")!!.draft)
}
@Test
fun scrollPositionIsPerChat() {
val store = ChatStore()
store.open(session("a"))
store.open(session("b"))
store.scroll("a", 7, 12)
store.scroll("b", 1, 0)
assertEquals(ChatScrollPosition(7, 12), store.value.thread("a")!!.scroll)
assertEquals(ChatScrollPosition(1, 0), store.value.thread("b")!!.scroll)
}
@Test
fun busySessionIsReadOnlyAndCannotSend() {
val store = ChatStore()
store.open(session("a", busy = true))
store.draft("a", "unsent")
val thread = store.value.thread("a")!!
assertTrue(thread.readOnly)
assertFalse(thread.canSend)
// The server can clear busy later; the chat then becomes writable again.
store.sessionsLoaded(listOf(session("a", busy = false)))
store.draft("a", "unsent")
assertFalse(store.value.thread("a")!!.readOnly)
assertTrue(store.value.thread("a")!!.canSend)
}
@Test
fun sessionsLoadedMergesStatusWithoutDroppingOpenConversations() {
val store = ChatStore()
store.open(session("a", "Chat A"))
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "keep me")))
// The server now reports A busy and adds a new session B.
store.sessionsLoaded(listOf(session("a", "Chat A renamed", busy = true), session("b", "Chat B")))
val thread = store.value.thread("a")!!
assertEquals("Chat A renamed", thread.title)
assertTrue(thread.busy)
assertEquals(listOf("a1"), thread.messages.map { it.id })
assertEquals(2, store.value.sessions.size)
}
@Test
fun backgroundEventsApplyToTheirChatAndCreateAPlaceholder() {
val store = ChatStore()
store.open(session("a"))
store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "go")))
store.open(session("b")) // B is active
// A delta for the background chat A lands on A, not on B, and B stays active.
store.event(
ChatEventFrame(
sessionId = "a",
messageId = "a2",
kind = ChatProtocol.PART_TEXT,
delta = "streaming",
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "a2-p"),
),
)
assertEquals("streaming", store.value.thread("a")!!.messages.last().parts.single().text)
assertEquals("b", store.value.activeId)
// A frame for a chat that was never opened creates a placeholder thread.
store.event(
ChatEventFrame(
sessionId = "c",
messageId = "c1",
kind = ChatProtocol.PART_TEXT,
delta = "hi",
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "c1-p"),
),
)
assertNotNull(store.value.thread("c"))
assertEquals("hi", store.value.thread("c")!!.messages.single().parts.single().text)
}
@Test
fun stepFramesTrackRunningState() {
val store = ChatStore()
store.open(session("a"))
store.event(ChatEventFrame(sessionId = "a", kind = ChatProtocol.EVENT_STEP, step = net.awan.pipelines.data.protocol.ChatStep(status = ChatProtocol.STEP_STARTED)))
assertTrue(store.value.thread("a")!!.running)
store.event(ChatEventFrame(sessionId = "a", kind = ChatProtocol.EVENT_STEP, step = net.awan.pipelines.data.protocol.ChatStep(status = ChatProtocol.STEP_ENDED)))
assertFalse(store.value.thread("a")!!.running)
}
@Test
fun locallyRunningBusyChatStaysWritable() {
val store = ChatStore()
store.open(session("a", busy = true))
store.running("a", true)
// Our own turn keeps the session writable even though the server reports it busy.
store.draft("a", "next prompt")
val thread = store.value.thread("a")!!
assertFalse(thread.readOnly)
assertTrue(thread.canSend)
}
@Test
fun permissionIsStoredAndAnsweredInPlace() {
val store = ChatStore()
store.open(session("a"))
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r1", action = "edit"))
assertEquals("r1", store.value.thread("a")!!.permission!!.requestId)
store.answerPermission("a", "r1", ChatProtocol.DECISION_ONCE)
assertEquals(ChatProtocol.DECISION_ONCE, store.value.thread("a")!!.permissionAnswer)
// A different request replaces the settled card and drops the old answer.
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r2", action = "bash"))
assertEquals("r2", store.value.thread("a")!!.permission!!.requestId)
assertEquals("", store.value.thread("a")!!.permissionAnswer)
// A failed reply reopens the request it answers.
store.answerPermission("a", "r2", ChatProtocol.DECISION_REJECT)
store.permissionReplyFailed("a", "r2")
assertEquals("", store.value.thread("a")!!.permissionAnswer)
}
@Test
fun closeRemovesOnlyThatChat() {
val store = ChatStore()
store.open(session("a"))
store.open(session("b"))
store.close("a")
assertFalse(store.value.open.any { it.sessionId == "a" })
assertTrue(store.value.open.any { it.sessionId == "b" })
}
}
@@ -0,0 +1,42 @@
package net.awan.pipelines.ui.chat
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 org.junit.Assert.assertEquals
import org.junit.Test
/**
* The tool panel's placement: below the chip when it fits, flipped above when it
* does not, and always kept inside the window margins. Driven directly against
* the provider, so it needs no device or Compose runtime.
*/
class ToolPanelPositionProviderTest {
private val provider = ToolPanelPositionProvider(gapPx = 4, marginPx = 8)
private val window = IntSize(width = 1000, height = 2000)
private fun place(anchor: IntRect, content: IntSize): IntOffset =
provider.calculatePosition(anchor, window, LayoutDirection.Ltr, content)
@Test
fun placesBelowTheChipWhenItFits() {
val anchor = IntRect(left = 40, top = 100, right = 340, bottom = 160)
assertEquals(IntOffset(40, 164), place(anchor, IntSize(400, 500)))
}
@Test
fun flipsAboveWhenThereIsNoRoomBelow() {
val anchor = IntRect(left = 40, top = 1800, right = 340, bottom = 1860)
// 1860 + 4 + 500 > 2000 - 8, so it goes above: 1800 - 500 - 4 = 1296.
assertEquals(IntOffset(40, 1296), place(anchor, IntSize(400, 500)))
}
@Test
fun clampsToTheRightAndTopMargins() {
val anchor = IntRect(left = 950, top = 20, right = 990, bottom = 60)
// Width 400 cannot start at 950; it is pulled in to the right margin.
assertEquals(IntOffset(592, 64), place(anchor, IntSize(400, 500)))
}
}