Merge main into lane-pill: combine the pill overlay with main's chat-close, omni-search and status work

Brings the branch up to date with main's tip so it can be merged back without
conflict. Merged cleanly, with no conflicted path: git auto-merged
ui/PipelinesApp.kt, ui/chat/ChatListPane.kt and ui/screens/RunHistoryScreen.kt,
keeping main's changes (the omni-search panel, the one status colour, the chat
close/tool-work surfaces) alongside this item's pill overlay, its
LocalPillBottomInset clearance and the SettingsDestination templates stack.

android/README.md is main's version, not this item's: this item records its
documentation change in docs/notes/pill-overlay-and-position.md for the single
docs-fold writer instead of editing that shared document.

Checks re-run on the merged tree (macOS, JAVA_HOME=Android Studio jbr,
ANDROID_HOME=~/Library/Android/sdk, Gradle 8.11.1, --offline --no-daemon):
`gradle :app:assembleDebug :app:testDebugUnitTest` -> BUILD SUCCESSFUL, 67 result
XMLs aggregating to 627 tests, 0 failures, 0 errors, 0 skipped.
This commit is contained in:
2026-10-18 00:20:40 +01:00
68 changed files with 4782 additions and 709 deletions
@@ -1,5 +1,6 @@
package net.awan.pipelines.data
import android.os.Build
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.SharedFlow
@@ -27,6 +28,17 @@ import net.awan.pipelines.data.transport.PipelinesClient
import net.awan.pipelines.data.transport.ProtocolException
import net.awan.pipelines.data.transport.ServerUrl
/**
* The default label this device reports: its model name, so other clients can
* attribute a message to "Pixel 9 Pro XL". A build without a usable model (or a
* local unit test where the framework stub has none) falls back to a generic
* label rather than sending a blank one.
*/
private fun defaultClientLabel(): String {
val model = runCatching { Build.MODEL }.getOrNull()?.trim().orEmpty()
return model.ifBlank { "Android device" }
}
/** Run history plus the server's aggregate usage statistics. */
data class RunHistory(val runs: List<RunSummary>, val usage: UsageStats?)
@@ -38,6 +50,13 @@ data class RunHistory(val runs: List<RunSummary>, val usage: UsageStats?)
class PipelinesRepository(
private val client: PipelinesClient,
private val settings: SettingsRepository,
/**
* The label this device sends with its prompts and approval answers, so every
* other client can attribute a user message to the device that sent it and see
* which device answered an approval. Defaults to the device model; injectable
* so a unit test does not depend on the build.
*/
val clientLabel: String = defaultClientLabel(),
) {
val connectionState = client.state
@@ -155,13 +174,13 @@ class PipelinesRepository(
/**
* Sends one omni-search query over the shared transport and returns the raw
* reply envelope. The server command is still landing, so the reply is
* classified by its envelope type: [Protocol.SEARCH_RESULTS] is the accepted
* search, and any other type is an unexpected reply the caller reports rather
* than parsing. The typed result payload is added with the results item.
* reply envelope. [kind] narrows the server-side scan to one SearchKind (see
* SearchKindFilter); a blank kind searches every kind. The reply is classified
* by its envelope type: [Protocol.SEARCH_RESULTS] is the accepted search, and
* any other type is an unexpected reply the caller reports rather than parsing.
*/
suspend fun search(query: String): Message =
client.call(Message(type = Protocol.SEARCH, search = SearchRequest(query = query.trim())))
suspend fun search(query: String, kind: String = ""): Message =
client.call(Message(type = Protocol.SEARCH, search = SearchRequest(query = query.trim(), kind = kind)))
/** Fetches an artifact's bytes (image preview) over the shared HTTP client. */
suspend fun fetchArtifactBytes(url: String): ByteArray = client.fetchBytes(url)
@@ -241,9 +260,9 @@ class PipelinesRepository(
// directly and never holds its credentials. ----
/**
* Lists the sessions this server owns, with the `busy` flag the phone renders
* read-only. The server already returns operator sessions only, so the app
* never filters this list by ownership.
* Lists the sessions this server owns. The server already returns operator
* sessions only, so the app never filters this list by ownership; a session is
* never marked read-only.
*/
suspend fun chatSessions(): List<ChatSession> =
client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList()
@@ -284,15 +303,29 @@ class PipelinesRepository(
}
/**
* Sends one prompt with its attached file URIs; the server echoes an ack and
* then pushes chat_event frames. The attachments travel only here, with the
* prompt the operator actually sent — never on their own.
* Attaches this connection to [sessionId]'s shared live stream, so it sees
* every frame any client's turn produces — the other devices' prompts and the
* turn's streaming output — and can answer a shared approval. Best-effort: an
* older server that does not know `chat_subscribe` simply answers an error
* frame, which the caller ignores while history still loads.
*/
suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList()) {
suspend fun chatSubscribe(sessionId: String) {
if (sessionId.isBlank()) return
client.call(ChatProtocol.subscribeRequest(sessionId))
}
/**
* Sends one prompt with its attached file URIs; the server echoes an ack and
* then pushes chat_event frames. The prompt carries this device's label so the
* other clients can attribute it. The attachments travel only here, with the
* prompt the operator actually sent — never on their own. Returns true when the
* server queued the prompt behind an in-flight turn.
*/
suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList()): Boolean {
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(ChatProtocol.promptRequest(sessionId, trimmed, files))
return client.call(ChatProtocol.promptRequest(sessionId, trimmed, files, clientLabel)).chatQueued
}
suspend fun chatInterrupt(sessionId: String) {
@@ -300,11 +333,31 @@ class PipelinesRepository(
client.call(ChatProtocol.interruptRequest(sessionId))
}
/**
* Finishes a chat on the server: any running turn is stopped and the session
* is recorded closed, so every client sees it. Nothing is deleted. The
* server returns the closed session, which the caller folds into its list.
*/
suspend fun chatClose(sessionId: String): ChatSession {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val response = client.call(ChatProtocol.closeRequest(sessionId))
return response.chatSession
?: throw ProtocolException("The server did not return the closed chat session.")
}
/** Clears a closed chat's state so it returns to the active list. */
suspend fun chatReopen(sessionId: String): ChatSession {
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
val response = client.call(ChatProtocol.reopenRequest(sessionId))
return response.chatSession
?: throw ProtocolException("The server did not return the reopened chat session.")
}
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))
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message, clientLabel))
}
private fun requireConfigured() {
@@ -77,6 +77,13 @@ class SettingsRepository(context: Context) {
private val _notificationPermissionAsked =
MutableStateFlow(prefs.getBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, false))
val notificationPermissionAsked: StateFlow<Boolean> = _notificationPermissionAsked.asStateFlow()
// The omni-search kind narrowing (a server kind, "" = every kind) and the
// search order, stored as their stable values and resolved by the UI.
private val _searchFilterKind = MutableStateFlow(prefs.getString(KEY_SEARCH_FILTER_KIND, "").orEmpty())
val searchFilterKind: StateFlow<String> = _searchFilterKind.asStateFlow()
private val _searchSort = MutableStateFlow(prefs.getString(KEY_SEARCH_SORT, "").orEmpty())
val searchSort: StateFlow<String> = _searchSort.asStateFlow()
fun setServerUrl(value: String) {
val trimmed = value.trim()
@@ -155,6 +162,16 @@ class SettingsRepository(context: Context) {
prefs.edit().putBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, asked).apply()
}
fun setSearchFilterKind(value: String) {
_searchFilterKind.value = value
prefs.edit().putString(KEY_SEARCH_FILTER_KIND, value).apply()
}
fun setSearchSort(value: String) {
_searchSort.value = value
prefs.edit().putString(KEY_SEARCH_SORT, value).apply()
}
/** True only when the user has explicitly supplied both required values. */
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
@@ -173,5 +190,7 @@ class SettingsRepository(context: Context) {
const val KEY_CHAT_SEEN = "chat_seen"
const val KEY_ATTENTION = "attention"
const val KEY_NOTIFICATION_PERMISSION_ASKED = "notification_permission_asked"
const val KEY_SEARCH_FILTER_KIND = "search_filter_kind"
const val KEY_SEARCH_SORT = "search_sort"
}
}
@@ -30,9 +30,29 @@ data class ChatSession(
@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.
// run. Kept for wire compatibility; the server no longer sets it, and a
// session is never read-only for a client.
val busy: Boolean = false,
// The operator finished with this session: the server recorded it as closed,
// so every client sees the same state. The session, its transcript and its
// history are kept and the closed chat stays in the list (grouped as history),
// where it can be reopened. [closedAt] is the epoch-millisecond close time, 0
// while open. Additive/optional, so an older server simply never sets them.
val closed: Boolean = false,
@SerialName("closed_at") val closedAt: Long = 0,
)
/**
* The outcome of a `chat_close`, mirroring `internal/protocol/chat.go`
* ChatCloseResult: the closed session's id, the epoch-millisecond close time and
* whether an in-flight turn was interrupted to stop it. It is the record that a
* running turn was stopped.
*/
@Serializable
data class ChatCloseResult(
@SerialName("session_id") val sessionId: String = "",
@SerialName("closed_at") val closedAt: Long = 0,
val interrupted: Boolean = false,
)
@Serializable
@@ -55,6 +75,10 @@ data class ChatPromptRequest(
val model: String = "",
val agent: String = "",
val files: List<String> = emptyList(),
// The sending device's human-readable label (a device name), so every other
// client can attribute the message; the server sanitises it and falls back to
// a generic label when it is blank.
val client: String = "",
)
/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */
@@ -66,6 +90,9 @@ data class ChatMessage(
val model: String = "",
val agent: String = "",
@SerialName("created_at") val createdAt: Long = 0,
// The sending device's label on a user turn the server echoed, so a resumed
// transcript still says who sent the message. Empty on an assistant turn.
val client: String = "",
val parts: List<ChatPart> = emptyList(),
)
@@ -138,6 +165,9 @@ data class ChatEventFrame(
val part: ChatPart? = null,
val step: ChatStep? = null,
val usage: ChatUsage? = null,
// The sending device's label on a `user` frame (another client's prompt), so
// the transcript can say who sent it. Empty on the agent's own frames.
val client: String = "",
)
@Serializable
@@ -174,6 +204,9 @@ data class ChatPermissionFrame(
val message: String = "",
val resolved: Boolean = false,
val decision: String = "",
// The label of the client whose answer resolved the request, so every other
// client can show which device answered.
@SerialName("resolved_by") val resolvedBy: String = "",
)
@Serializable
@@ -189,6 +222,8 @@ data class ChatReplyRequest(
@SerialName("request_id") val requestId: String = "",
val decision: String = "",
val message: String = "",
// The answering device's label, recorded with the resolution.
val client: String = "",
)
/** Chat part/kind/state/reply constants, mirroring `internal/protocol/chat.go`. */
@@ -207,6 +242,13 @@ object ChatProtocol {
const val EVENT_STEP = "step"
const val EVENT_USAGE = "usage"
/**
* A prompt another client sent, echoed live to this client so it appears in
* the transcript attributed to the sending device. The sender never receives
* its own frame (it already has the message locally).
*/
const val EVENT_USER = "user"
const val STEP_STARTED = "started"
const val STEP_ENDED = "ended"
@@ -241,10 +283,21 @@ object ChatProtocol {
* shape a text-only prompt has always sent). Built here (not inline in the
* repository) so production and its unit test share the one wire shape.
*/
fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList()): Message =
fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList(), client: String = ""): Message =
Message(
type = Protocol.CHAT_PROMPT,
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files),
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files, client = client),
)
/**
* The `chat_subscribe` frame that attaches this connection to [sessionId]'s
* shared live stream, so the client sees every frame any client's turn
* produces. Built here so production and its unit test share the one shape.
*/
fun subscribeRequest(sessionId: String): Message =
Message(
type = Protocol.CHAT_SUBSCRIBE,
chatSubscribe = ChatQuery(sessionId = sessionId),
)
/**
@@ -255,13 +308,31 @@ object ChatProtocol {
fun interruptRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_close` frame that finishes [sessionId]: the server stops any
* running turn (through the same interrupt) and records the session closed on
* the server, sharing the state with every client. Nothing is deleted. Built
* here (not inline in the repository) so production and its unit test share
* the one wire shape.
*/
fun closeRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_CLOSE, chatQuery = ChatQuery(sessionId = sessionId))
/**
* The `chat_reopen` frame that clears a closed session's state so it returns
* to the active list; the inverse of [closeRequest]. Built here so production
* and its unit test share the one wire shape.
*/
fun reopenRequest(sessionId: String): Message =
Message(type = Protocol.CHAT_REOPEN, 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 =
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = "", client: String = ""): Message =
Message(
type = Protocol.CHAT_REPLY,
chatReply = ChatReplyRequest(
@@ -269,6 +340,7 @@ object ChatProtocol {
requestId = requestId,
decision = decision,
message = message,
client = client,
),
)
}
@@ -68,6 +68,14 @@ object Protocol {
const val CHAT_MESSAGES = "chat_messages"
const val CHAT_INTERRUPT = "chat_interrupt"
const val CHAT_REPLY = "chat_reply"
// Close/reopen an operator session on the server (its closed state is
// recorded so every client sees it). Both ride on chat_query like
// chat_interrupt; chat_close also carries a ChatCloseResult on the response.
const val CHAT_CLOSE = "chat_close"
const val CHAT_REOPEN = "chat_reopen"
// Attaches this connection to one session's shared live stream, so every
// client watching a session receives every frame any client's turn produces.
const val CHAT_SUBSCRIBE = "chat_subscribe"
// The operator's directory choices for a new chat (home first, then the
// directories of previous operator sessions, most recently used first).
const val CHAT_DIRECTORIES = "chat_directories"
@@ -676,9 +684,17 @@ data class Message(
@SerialName("chat_create") val chatCreate: ChatCreateRequest? = null,
@SerialName("chat_query") val chatQuery: ChatQuery? = null,
@SerialName("chat_prompt") val chatPrompt: ChatPromptRequest? = null,
// A chat_prompt response with this set was accepted into the session's queue
// because a turn is already in flight; the composer shows queued/steering
// instead of blocking input.
@SerialName("chat_queued") val chatQueued: Boolean = false,
@SerialName("chat_subscribe") val chatSubscribe: ChatQuery? = 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,
// The outcome of a chat_close (session id, closed_at, interrupted); the
// close/reopen requests themselves ride on chat_query like chat_interrupt.
@SerialName("chat_close") val chatClose: ChatCloseResult? = null,
@SerialName("chat_directories") val chatDirectories: List<String>? = null,
)
@@ -83,6 +83,10 @@ class AppViewModel(
val pipelineFilterRunStatuses: StateFlow<String> = settings.pipelineFilterRunStatuses
val pipelineFilterName: StateFlow<String> = settings.pipelineFilterName
/** The stored omni-search kind narrowing (a server kind, "" = every kind) and order. */
val searchKind: StateFlow<String> = settings.searchFilterKind
val searchSort: StateFlow<String> = settings.searchSort
private val _serverUrlDraft = MutableStateFlow(settings.serverUrl.value)
val serverUrlDraft: StateFlow<String> = _serverUrlDraft.asStateFlow()
@@ -685,6 +689,19 @@ class AppViewModel(
fun setPipelineFilterName(value: String) = settings.setPipelineFilterName(value)
/**
* Narrows the search to a server kind (see SearchKindFilter). The kind is a
* request parameter, so a narrowed search re-issues the live query at once
* rather than waiting for the next keystroke.
*/
fun setSearchKind(serverKind: String) {
settings.setSearchFilterKind(serverKind)
rerunSearchImmediately()
}
/** Records the search order; it orders the results already in hand, so no refetch. */
fun setSearchSort(storageKey: String) = settings.setSearchSort(storageKey)
private fun awaitConnected() {
viewModelScope.launch {
val connected = withTimeoutOrNull(CONNECT_TIMEOUT_MILLIS) {
@@ -803,7 +820,13 @@ class AppViewModel(
}
/** Runs the current query immediately (the IME's search action), skipping the debounce. */
fun searchNow() {
fun searchNow() = rerunSearchImmediately()
/**
* Re-issues the live query at once, cancelling any pending debounce: the IME
* search action and a kind-filter change both want the newest request now.
*/
private fun rerunSearchImmediately() {
val query = _search.value.query
if (query.isBlank()) return
val edit = searchSequencer.edit(query)
@@ -821,7 +844,10 @@ class AppViewModel(
private suspend fun runSearch(request: SentSearch) {
_search.value = _search.value.copy(loading = true, error = null)
try {
val reply = repository.search(request.query)
// The active kind filter is a request parameter; resolve it from the
// stored value (a blank/stale one falls back to every kind).
val kind = SearchKindFilter.fromStorage(settings.searchFilterKind.value).serverKind
val reply = repository.search(request.query, kind)
// A reply for a superseded query must never land: the sequencer only
// accepts the newest sent token.
if (!searchSequencer.accepts(request.token)) return
@@ -1078,6 +1104,10 @@ class AppViewModel(
fun loadChatHistory(sessionId: String) {
viewModelScope.launch {
// Watch the session's shared stream so frames from any client's turn
// arrive live. Best-effort: an older server answers an error frame,
// which must not stop the history from loading.
runCatching { repository.chatSubscribe(sessionId) }
chatStore.historyLoading(sessionId)
try {
chatStore.history(sessionId, repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT))
@@ -1107,7 +1137,14 @@ class AppViewModel(
chatStore.running(sessionId, true)
viewModelScope.launch {
try {
repository.chatPrompt(sessionId, text, attachmentFiles(attachments))
val queued = repository.chatPrompt(sessionId, text, attachmentFiles(attachments))
// The server accepted the prompt (queued or sent); a queued prompt
// is one waiting behind an in-flight turn, and the composer says so
// instead of blocking input.
chatStore.setQueued(sessionId, queued)
// Prompting a closed session reopens it on the server; clear the
// closed mark locally too so the list agrees without a re-fetch.
chatStore.sessionReopened(sessionId)
} catch (t: Throwable) {
if (t is CancellationException) throw t
val message = ErrorMessages.describe(t)
@@ -1115,6 +1152,7 @@ class AppViewModel(
chatStore.failed(sessionId, message)
chatStore.restoreAttachments(sessionId, attachments, message)
chatStore.running(sessionId, false)
chatStore.setQueued(sessionId, false)
}
}
}
@@ -1152,6 +1190,44 @@ class AppViewModel(
}
}
/**
* Finishes a chat on the server: any running turn is stopped (the server
* reuses its interrupt) and the session is recorded closed, so every client
* sees the same state. Nothing is deleted — the session and its history stay —
* and the chat is kept in the list as closed history. Errors are reported on
* the list, which is where the action lives.
*/
fun closeChatSession(sessionId: String) {
if (sessionId.isBlank()) return
viewModelScope.launch {
try {
val closed = repository.chatClose(sessionId)
chatStore.sessionClosed(sessionId, closed.closedAt)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.sessionsFailed(ErrorMessages.describe(t))
}
}
}
/**
* Reopens a closed chat so it returns to the active list. Sending another
* message also reopens it (the server clears the closed state on prompt), so
* this is the explicit path beside that one.
*/
fun reopenChatSession(sessionId: String) {
if (sessionId.isBlank()) return
viewModelScope.launch {
try {
repository.chatReopen(sessionId)
chatStore.sessionReopened(sessionId)
} catch (t: Throwable) {
if (t is CancellationException) throw t
chatStore.sessionsFailed(ErrorMessages.describe(t))
}
}
}
private fun <T> load(target: MutableStateFlow<LoadState<T>>, block: suspend () -> T) {
viewModelScope.launch {
target.value = target.value.copy(loading = true, error = null)
@@ -1,6 +1,15 @@
package net.awan.pipelines.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.automirrored.filled.Segment
import androidx.compose.material.icons.automirrored.filled.Subject
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Commit
import androidx.compose.material.icons.filled.History
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.vector.ImageVector
import java.time.OffsetDateTime
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.SearchArtifact
@@ -11,22 +20,50 @@ import net.awan.pipelines.data.protocol.SearchResult
import net.awan.pipelines.data.protocol.SearchRun
import net.awan.pipelines.data.protocol.SearchStep
import net.awan.pipelines.data.protocol.SearchVersion
import net.awan.pipelines.ui.graph.artifactIcon
import net.awan.pipelines.ui.graph.artifactKind
import net.awan.pipelines.ui.graph.artifactKindLabel
import net.awan.pipelines.ui.screens.runTimeline
// ---------------------------------------------------------------------------
// Row model: the badge, title and secondary line of one result. Pure (no
// Row model: the glyph, title and secondary line of one result. Pure (no
// Compose, no coroutines), so the mapping for every kind is unit-testable.
// ---------------------------------------------------------------------------
/** The short mixed-list type badge for a result kind. */
fun searchBadge(kind: String): String = when (kind) {
Protocol.SEARCH_KIND_PIPELINE, Protocol.SEARCH_KIND_VERSION -> "pipeline"
Protocol.SEARCH_KIND_RUN -> "run"
Protocol.SEARCH_KIND_STEP -> "step"
Protocol.SEARCH_KIND_ARTIFACT -> "artifact"
// A text ("field") match and an unknown kind both read as a generic match;
// the unknown one is additionally labelled read-only by [searchRow].
else -> "match"
/**
* The glyph that names one result's type at a glance: the result's kind, and for
* an artifact the file type its content resolves to. The artifact mapping is the
* gallery's own ([artifactKind]/[artifactIcon]) rather than a second copy, so the
* two surfaces can never disagree about a file. The payload decides the branch,
* exactly as [searchRow] does, so a known payload with an unknown kind string
* still gets the right glyph and an unrecognised result falls back to a neutral
* mark instead of vanishing.
*/
fun searchResultIcon(hit: SearchResult): ImageVector = when {
hit.pipeline != null -> Icons.Filled.AccountTree
hit.version != null -> Icons.Filled.Commit
hit.run != null -> Icons.Filled.History
hit.step != null -> Icons.AutoMirrored.Filled.Segment
hit.field != null -> Icons.AutoMirrored.Filled.Subject
hit.artifact != null -> artifactIcon(artifactKind(hit.artifact.contentType, hit.artifact.name))
else -> Icons.AutoMirrored.Filled.HelpOutline
}
/**
* The kind in words for a row's accessible description, so a screen reader hears
* what the row is even though the glyph alone carries no text. An artifact is
* named by its own content type ("Image artifact", "JSON artifact"), from the
* same gallery classification [searchResultIcon] uses.
*/
fun searchResultKindLabel(hit: SearchResult): String = when {
hit.pipeline != null -> "Pipeline"
hit.version != null -> "Pipeline version"
hit.run != null -> "Run"
hit.step != null -> "Step"
hit.field != null -> "Field"
hit.artifact != null ->
"${artifactKindLabel(artifactKind(hit.artifact.contentType, hit.artifact.name))} artifact"
else -> "Unrecognised result"
}
/**
@@ -38,13 +75,12 @@ fun searchBadge(kind: String): String = when (kind) {
data class SnippetSpan(val text: String, val matched: Boolean)
/**
* One rendered search row: its type badge, a title and a secondary line. [snippet]
* is non-null only for a text ("field") match and carries the snippet split so the
* matched span is distinguishable without colour.
* One rendered search row: its title and a secondary line. [snippet] is non-null
* only for a text ("field") match and carries the snippet split so the matched
* span is distinguishable without colour.
*/
@Immutable
data class SearchRow(
val badge: String,
val title: String,
val secondary: String,
val snippet: List<SnippetSpan>? = null,
@@ -56,7 +92,6 @@ data class SearchRow(
* renders its stable target (or a placeholder) and a `read-only` note.
*/
fun searchRow(hit: SearchResult, query: String): SearchRow {
val badge = searchBadge(hit.kind)
val pipeline: SearchPipeline? = hit.pipeline
val version: SearchVersion? = hit.version
val run: SearchRun? = hit.run
@@ -65,12 +100,10 @@ fun searchRow(hit: SearchResult, query: String): SearchRow {
val artifact: SearchArtifact? = hit.artifact
return when {
pipeline != null -> SearchRow(
badge,
pipeline.name.ifBlank { "pipeline ${pipeline.id}" },
"pipeline ${pipeline.id} · v${pipeline.version} · ${stageCountText(pipeline.stages)}",
)
version != null -> SearchRow(
badge,
"pipeline ${version.pipelineId} · v${version.version}",
listOfNotNull(
version.contentHash.takeIf { it.isNotBlank() }?.let { "content $it" },
@@ -78,7 +111,6 @@ fun searchRow(hit: SearchResult, query: String): SearchRow {
).joinToString(" · "),
)
run != null -> SearchRow(
badge,
"run #${run.id}" + run.pipelineName.takeIf { it.isNotBlank() }?.let { " · $it" }.orEmpty(),
listOfNotNull(
run.status.takeIf { it.isNotBlank() },
@@ -87,18 +119,15 @@ fun searchRow(hit: SearchResult, query: String): SearchRow {
).joinToString(" · "),
)
step != null -> SearchRow(
badge,
"run #${step.runId} · ${step.stage.ifBlank { "step" }} visit ${step.visit}",
stepSecondary(step),
)
field != null -> SearchRow(
badge,
"run #${field.runId} · step ${field.sequence} · ${field.field.ifBlank { "field" }}",
field.snippet,
snippetSpans(field.snippet, query),
)
artifact != null -> SearchRow(
badge,
artifact.name.ifBlank { "artifact" },
listOfNotNull(
"run #${artifact.runId}",
@@ -108,7 +137,6 @@ fun searchRow(hit: SearchResult, query: String): SearchRow {
).joinToString(" · "),
)
else -> SearchRow(
badge,
hit.target.ifBlank { "Unrecognised result" },
if (hit.kind.isBlank()) "read-only" else "kind \"${hit.kind}\" · read-only",
)
@@ -145,6 +173,92 @@ fun snippetSpans(snippet: String, query: String): List<SnippetSpan> {
}
}
// ---------------------------------------------------------------------------
// Narrowing and ordering: the filter/sort control's pure model. Pure (no
// Compose), so the kind narrowing and each order are unit-testable.
// ---------------------------------------------------------------------------
/**
* The kind narrowing the search filter control offers. [serverKind] is exactly the
* server's SearchRequest kind vocabulary (internal/protocol/search.go), sent and
* stored verbatim; [All] is the empty kind.
*
* There is deliberately no "prompts" entry: the server has no such kind (its
* kinds are pipeline, version, run, step, field and artifact), so a filter that
* could only ever match nothing is not offered.
*/
enum class SearchKindFilter(val label: String, val serverKind: String) {
All("All kinds", ""),
Pipelines("Pipelines", Protocol.SEARCH_KIND_PIPELINE),
Runs("Runs", Protocol.SEARCH_KIND_RUN),
Steps("Steps", Protocol.SEARCH_KIND_STEP),
Fields("Fields", Protocol.SEARCH_KIND_FIELD),
Artifacts("Artifacts", Protocol.SEARCH_KIND_ARTIFACT),
Versions("Versions", Protocol.SEARCH_KIND_VERSION);
companion object {
val Default = All
/** Resolves a stored kind, tolerating a blank/stale value by returning [Default]. */
fun fromStorage(value: String?): SearchKindFilter =
entries.firstOrNull { it.serverKind == value } ?: Default
}
}
/**
* The orders the search sort control offers. [Relevance] keeps the server's own
* ranking (score, then recency, then a stable kind/target tie-break). [Newest]
* and [Name] cannot be asked of the server - its search command takes only a
* query, an optional kind and a limit - so they order the results already in
* hand, and the control says so.
*/
enum class SearchSort(val label: String, val storageKey: String) {
Relevance("Relevance", "relevance"),
Newest("Newest first", "newest"),
Name("Name", "name");
companion object {
val Default = Relevance
/** Resolves a stored order, tolerating a blank/stale value by returning [Default]. */
fun fromStorage(value: String?): SearchSort =
entries.firstOrNull { it.storageKey == value } ?: Default
}
}
/** The one-line summary of the active filter and sort the collapsed control shows. */
fun searchControlsSummary(kind: SearchKindFilter, sort: SearchSort): String {
// Only Relevance is the server's own ranking; the other orders run on the
// results in hand, so the summary says so even when the menu is closed.
val reach = if (sort == SearchSort.Relevance) "" else " (in hand)"
return "${kind.label} · ${sort.label}$reach"
}
/**
* Narrows [results] to [filter]'s kind. The filter is also sent to the server
* (SearchRequest.kind), so this only re-narrows the results already in hand,
* keeping the panel honest while a narrowed request loads.
*/
fun filterSearchResults(results: List<SearchResult>, filter: SearchKindFilter): List<SearchResult> =
if (filter == SearchKindFilter.All) results else results.filter { it.kind == filter.serverKind }
/**
* Orders [results] by [sort]. [Relevance] leaves the server's ranking untouched;
* [Newest] and [Name] sort the results in hand (the server has no sort). The
* sorts are stable, so two results that tie keep the server's order rather than
* swapping arbitrarily.
*/
fun sortSearchResults(results: List<SearchResult>, sort: SearchSort): List<SearchResult> = when (sort) {
SearchSort.Relevance -> results
SearchSort.Newest -> results.sortedWith(
compareByDescending<SearchResult> { parseInstant(it.recency.orEmpty()) ?: OffsetDateTime.MIN },
)
SearchSort.Name -> results
.map { it to searchRow(it, "").title }
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.second })
.map { it.first }
}
// ---------------------------------------------------------------------------
// Navigation: the destination a result resolves to. Pure, so the mapping for
// every kind is unit-testable.
@@ -284,6 +398,22 @@ fun SearchUiState.loaded(response: SearchResponse): SearchUiState =
fun SearchUiState.failed(message: String?): SearchUiState =
copy(loading = false, error = message, loaded = true)
/** Whether the panel shows the explicit, query-naming empty state. */
fun SearchUiState.isEmptyResult(): Boolean =
error == null && !loading && loaded && results.isEmpty() && query.isNotBlank()
/**
* The empty-state line the panel shows when it has no rows to render for [query]
* under [kind], or null when it is showing rows, progress or nothing at all.
* [shown] is the filtered and sorted list actually displayed, so a filter that
* empties the list reports itself ("No runs match …") rather than the generic
* line. Pure, so the empty state is unit-testable without a device.
*/
fun searchPanelEmptyMessage(
state: SearchUiState,
shown: List<SearchResult>,
kind: SearchKindFilter,
): String? = when {
state.error != null -> null
shown.isNotEmpty() -> null
state.loading -> null
state.query.isBlank() -> null
kind == SearchKindFilter.All -> "No matches for \"${state.query}\"."
else -> "No ${kind.label.lowercase()} match \"${state.query}\"."
}
@@ -188,6 +188,8 @@ fun PipelinesApp(
// the chat list for the conversation.
val conversationOpen by vm.conversationOpen.collectAsStateWithLifecycle()
val pillVisible = destinationPillVisible(currentRoute, conversationOpen)
val searchKind by vm.searchKind.collectAsStateWithLifecycle()
val searchSort by vm.searchSort.collectAsStateWithLifecycle()
/** Back/scrim/close and a selection all dismiss the morph and clear the panel. */
val dismissSearch: () -> Unit = {
@@ -397,9 +399,13 @@ fun PipelinesApp(
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = destinationPillAlignment(wide),
) {
if (searchState.open && searchState.query.isNotBlank()) {
if (searchState.open) {
SearchResultsPanel(
state = search,
kind = SearchKindFilter.fromStorage(searchKind),
sort = SearchSort.fromStorage(searchSort),
onKind = { vm.setSearchKind(it.serverKind) },
onSort = { vm.setSearchSort(it.storageKey) },
onSelect = onSelectResult,
modifier = Modifier
.fillMaxWidth()
@@ -12,6 +12,7 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
@@ -30,31 +31,47 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.SearchResult
import net.awan.pipelines.ui.components.LabelChip
import net.awan.pipelines.ui.components.FilterCheckItem
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.SortMenu
import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.SEARCH_PROGRESS_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The omni-search results panel: one scrolling surface that sits above the search
* field. It renders the last accepted results, and while a newer query loads it
* keeps those results and adds a thin progress bar rather than blanking; a
* failure is reported without discarding what is already shown. Its height is
* bounded by the caller (the window's IME/navigation-bar insets), so it scrolls
* inside the remainder instead of running under the keyboard.
* field. It leads with the filter and sort controls (the same shared menu
* controls the runs list uses), then renders the last accepted results; while a
* newer query loads it keeps those results and adds a thin progress bar rather
* than blanking, and a failure is reported without discarding what is already
* shown. Its height is bounded by the caller (the window's IME/navigation-bar
* insets), so it scrolls inside the remainder instead of running under the
* keyboard.
*/
@Composable
internal fun SearchResultsPanel(
state: SearchUiState,
kind: SearchKindFilter,
sort: SearchSort,
onKind: (SearchKindFilter) -> Unit,
onSort: (SearchSort) -> Unit,
onSelect: (SearchResult) -> Unit,
modifier: Modifier = Modifier,
) {
val scheme = MaterialTheme.colorScheme
val error = state.error
// The filter and sort are applied to the results in hand as well as being sent
// to the server (the kind) or held client-side (the order), so the list always
// matches the active control, even for the moment a narrowed request loads.
val shown = remember(state.results, kind, sort) {
sortSearchResults(filterSearchResults(state.results, kind), sort)
}
Surface(
modifier = modifier,
shape = RoundedCornerShape(SPACING_XL),
@@ -63,6 +80,8 @@ internal fun SearchResultsPanel(
shadowElevation = 6.dp,
) {
Column(Modifier.fillMaxWidth()) {
SearchControls(kind = kind, sort = sort, onKind = onKind, onSort = onSort)
HorizontalDivider(color = scheme.outlineVariant)
// A refresh of an already-populated panel shows progress without
// replacing the results; the first load shows the searching row below.
if (state.loading && state.results.isNotEmpty()) {
@@ -70,14 +89,68 @@ internal fun SearchResultsPanel(
}
when {
error != null -> PanelMessage(error, isError = true)
state.isEmptyResult() -> PanelMessage("No matches for \"${state.query}\".", isError = false)
shown.isNotEmpty() -> SearchResultList(shown, state.query, onSelect)
state.loading && state.results.isEmpty() -> SearchingRow()
state.results.isNotEmpty() -> SearchResultList(state.results, state.query, onSelect)
else -> searchPanelEmptyMessage(state, shown, kind)?.let { PanelMessage(it, isError = false) }
}
}
}
}
/**
* The search surface's filter and sort control, the same shared [FilterMenu] and
* [SortMenu] the runs list uses rather than a new pattern, plus the one-line
* summary of the active choice so the collapsed controls are legible. The kind
* filter narrows server-side; the sort orders the results in hand.
*/
@Composable
private fun SearchControls(
kind: SearchKindFilter,
sort: SearchSort,
onKind: (SearchKindFilter) -> Unit,
onSort: (SearchSort) -> Unit,
) {
Row(
// The top inset leaves room for the filter badge, which is drawn above the
// icon button; without it the badge spills over the panel's rounded edge.
modifier = Modifier
.fillMaxWidth()
.padding(start = SPACING_S, end = SPACING_XS, top = SPACING_S, bottom = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
FilterMenu(
activeCount = if (kind == SearchKindFilter.All) 0 else 1,
contentDescription = "Filter results",
resetLabel = "Clear filter",
onReset = { onKind(SearchKindFilter.Default) },
) { dismiss ->
SearchKindFilter.entries.forEach { option ->
FilterCheckItem(option.label, option == kind) {
onKind(option)
dismiss()
}
}
}
SortMenu(
options = SearchSort.entries,
selected = sort,
label = { it.label },
header = "Sort results in hand",
contentDescription = "Sort results in hand",
onSelect = onSort,
onReset = { onSort(SearchSort.Default) },
)
Text(
text = searchControlsSummary(kind, sort),
style = pipelinesText().meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f).padding(start = SPACING_S),
)
}
}
@Composable
private fun PanelMessage(message: String, isError: Boolean) {
Text(
@@ -127,10 +200,12 @@ private fun SearchResultList(
}
/**
* One result row: its type badge, a title and a secondary line. A text match's
* secondary line is its snippet with the matched span rendered bold+underlined,
* so the match is distinguishable without relying on colour. A result with no
* navigation target (an unknown kind) is shown read-only and is not clickable.
* One result row: the type glyph (its kind, or an artifact's content type), a
* title and a secondary line. The glyph carries the kind in words as its
* content description, since the mark alone is not readable, and the matched span
* of a text match is rendered bold+underlined, so the match is distinguishable
* without relying on colour. A result with no navigation target (an unknown kind)
* is shown read-only and is not clickable.
*/
@Composable
private fun SearchResultRow(
@@ -151,9 +226,15 @@ private fun SearchResultRow(
},
)
.padding(horizontal = SPACING_L, vertical = SPACING_M),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
) {
LabelChip(row.badge, SPACING_S, SPACING_XXS)
Icon(
imageVector = searchResultIcon(hit),
contentDescription = searchResultKindLabel(hit),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(ICON_LIST_DP),
)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
@@ -51,9 +51,9 @@ internal fun ChatComposer(
}
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) {
if (thread.readOnly) {
if (thread.queued) {
Text(
text = "Another client holds this session; it is read-only here.",
text = "Queued — it will send when the current turn finishes.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
@@ -65,14 +65,12 @@ internal fun ChatComposer(
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) {
IconButton(
onClick = { picker.launch(arrayOf("*/*")) },
enabled = !thread.readOnly,
) {
Icon(Icons.Default.AttachFile, contentDescription = "Attach file")
}
OutlinedTextField(
value = thread.draft,
onValueChange = onDraft,
enabled = !thread.readOnly,
placeholder = { Text("Message the agent…") },
minLines = 1,
maxLines = 6,
@@ -213,11 +213,7 @@ internal fun ChatConversationPane(
onRetry = { vm.loadChatHistory(thread.sessionId) },
)
thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState(
message = if (thread.readOnly) {
"This chat is read-only while another client holds the session."
} else {
"This chat has no messages yet. Ask something below."
},
message = "This chat has no messages yet. Ask something below.",
)
else -> ChatTranscript(
thread = thread,
@@ -7,6 +7,7 @@ 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.ChatMessage
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatToolState
@@ -79,6 +80,126 @@ internal fun formatToolDuration(millis: Long): String = when {
/** The chip label for a tool call: its name, or a placeholder when unnamed. */
internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" }
/**
* The in-flight tool calls across a conversation's [messages], in transcript
* order, so the conversation's indicator and the session row read the same set
* and its order is stable from frame to frame (a chip is never re-ordered by a
* rebuild). A call drops out the moment it completes or errors, which is what
* clears the indicator, so nothing here ever invents a finish time.
*/
internal fun runningToolCalls(messages: List<ChatMessage>): List<ChatPart> =
messages.flatMap { it.parts }
.filter { it.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(it.state) }
/**
* The input keys, in preference order, that carry a human-facing command or a
* short description of what a tool call is doing. OpenCode's tools put the
* substance in different places (`command` for a shell, `description` for a task,
* a path or pattern for the file/search tools), so the first one present is shown
* rather than the raw arguments.
*/
private val TOOL_DETAIL_KEYS = listOf(
"description", "command", "filePath", "file_path", "path", "pattern", "query", "url",
)
/** How much of a command/description the phone shows before it is elided. */
private const val TOOL_DETAIL_MAX_LENGTH = 72
private val TOOL_DETAIL_WHITESPACE = Regex("\\s+")
/**
* A one-line command or short description for [part], taken from the input the
* part actually carries: the first of [TOOL_DETAIL_KEYS] present, collapsed to a
* single line and elided past [TOOL_DETAIL_MAX_LENGTH]. Null when the input
* carries no such key (a partial-JSON string while the call is still streaming,
* or a tool that reports none), so a caller shows the name alone rather than a
* fabricated summary.
*/
internal fun toolDetail(part: ChatPart): String? {
val obj = part.state?.input as? JsonObject ?: return null
for (key in TOOL_DETAIL_KEYS) {
val value = obj[key] as? JsonPrimitive ?: continue
if (!value.isString) continue
val text = value.content.trim().replace(TOOL_DETAIL_WHITESPACE, " ")
if (text.isBlank()) continue
return if (text.length <= TOOL_DETAIL_MAX_LENGTH) {
text
} else {
text.take(TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…"
}
}
return null
}
/**
* How long a running [part] has been going at [nowMillis]. The protocol's own
* timing wins whenever the part carries it (a running call from stored history
* has `time.ran`, the moment it started); otherwise the elapsed is measured
* locally from [startedAt] — the wall clock at which this client first saw the
* part running. Zero when neither is usable, so a caller never shows a time it
* cannot stand behind.
*/
internal fun runningToolElapsedMillis(part: ChatPart, startedAt: Long, nowMillis: Long): Long {
val protocolStart = part.time?.let { if (it.ran > 0) it.ran else it.created } ?: 0L
val start = if (protocolStart > 0) protocolStart else startedAt
return if (start in 1 until nowMillis) nowMillis - start else 0L
}
/**
* A tool call running longer than this reads as unusually long on the phone and
* is marked, so a genuinely stuck call is visible without a fabricated ETA. One
* minute: long enough that ordinary calls (a build, a search, a command) are not
* flagged, short enough that a hung call stands out while the operator is still
* wondering.
*/
internal const val TOOL_LONG_RUNNING_MILLIS: Long = 60_000L
/** Whether a running call has been going long enough to be marked as unusual. */
internal fun toolLongRunning(elapsedMillis: Long): Boolean = elapsedMillis >= TOOL_LONG_RUNNING_MILLIS
/**
* The running-tool start stamps after a thread's [messages] changed: every tool
* part in flight keeps the stamp it already had, or is stamped with [now] when it
* has just turned running, and a part that is no longer running loses its stamp.
* Kept free of Compose and of [ChatStore] so the bookkeeping and its unit test
* share one rule, and a stamp never moves forward while a call keeps running.
*/
internal fun runningToolStamps(
current: Map<String, Long>,
messages: List<ChatMessage>,
now: Long,
): Map<String, Long> {
val stamps = LinkedHashMap<String, Long>()
messages.forEach { message ->
message.parts.forEach { part ->
if (part.id.isNotEmpty() && part.type == ChatProtocol.PART_TOOL && ChatProtocol.toolRunning(part.state)) {
stamps[part.id] = current[part.id] ?: now
}
}
}
return stamps
}
/**
* The status a session row reports while a turn is in flight: it names the tool
* call it is parked on (or how many, when several run at once) so a working chat
* says what it is doing rather than just `Running`, and a chat only generating
* text still reads as plain `Running` — the two are never confused. A chat with
* nothing running falls back to the ordinary busy/idle label, so a session
* waiting on another client is never shown as idle.
*/
internal fun sessionWorkLabel(busy: Boolean, thread: ChatThread?): String = when {
thread?.running == true -> runningSessionLabel(thread.runningTools)
busy -> "Busy · read-only"
else -> "Idle"
}
private fun runningSessionLabel(tools: List<ChatPart>): String = when (tools.size) {
0 -> "Running"
1 -> "Running ${toolLabel(tools.single())}"
else -> "Running ${tools.size} tools"
}
/**
* A session's short title: the server title, or a truncated id when untitled, so
* a row never renders as a blank line.
@@ -125,21 +246,24 @@ internal fun chatHeaderMeta(thread: ChatThread): String = listOfNotNull(
private const val OPERATOR_TAG_LABEL = "Operator"
/**
* 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.
* The status a session row shows: `Running` while this client has a turn in
* flight, else `Idle`. A session is never reported `Busy` or read-only because
* another client is watching it — the server fans the stream out and accepts a
* prompt from any client, so the session stays writable everywhere.
*/
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String =
sessionStatusLabel(session.busy, runningLocally)
sessionStatusLabel(runningLocally, session.closed)
/** The status of a conversation from its own model flags (see [sessionStatusLabel]). */
internal fun sessionStatusLabel(busy: Boolean, runningLocally: Boolean): String = when {
/**
* The status of a conversation from its own flags (see [sessionStatusLabel]).
* A closed session reads `Closed` first: it is finished, whatever a stale local
* running mark says. A session is never reported `Busy` or read-only because
* another client is watching it — the server fans the stream out and accepts a
* prompt from any client, so the session stays writable everywhere.
*/
internal fun sessionStatusLabel(runningLocally: Boolean, closed: Boolean = false): String = when {
closed -> "Closed"
runningLocally -> "Running"
busy -> "Busy · read-only"
else -> "Idle"
}
@@ -183,7 +307,7 @@ internal data class ConversationHeader(
internal fun conversationHeader(thread: ChatThread): ConversationHeader = ConversationHeader(
title = sessionTitle(ChatSession(id = thread.sessionId, title = thread.title)),
kind = sessionTagLabel(thread.tag),
activity = sessionStatusLabel(thread.busy, thread.running),
activity = sessionStatusLabel(thread.running, thread.closed),
directory = thread.directory,
model = thread.model,
)
@@ -273,6 +397,19 @@ internal fun reasoningLabel(count: Int, streaming: Boolean): String = when {
else -> REASONING_SETTLED_LABEL
}
/**
* The close confirmation's body: it says exactly what closing does — stops a
* running turn, marks the chat closed on every device — and what it does not do:
* nothing is deleted, the chat and its history are kept and can be reopened. Kept
* pure so the confirmation wording and its unit test share one string instead of
* the copy drifting from the promise.
*/
internal fun closeChatConfirmation(title: String): String =
"Closes \"$title\" and marks it closed on every device. " +
"A turn that is running is stopped first. " +
"Nothing is deleted — the chat and its history are kept, " +
"and you can reopen it from the list."
/**
* The elapsed time the server's own timing gives a settled turn: from the
* earliest start to the latest completion across the parts that carry a timing
@@ -96,10 +96,12 @@ internal fun ChatListPane(
// The server returns operator sessions only, with the operator's own local
// renames and removals applied on top; the app never guesses which session
// belongs to a run. The operator's search narrows that list without touching
// its order, and the survivors are grouped by directory when there is more
// than one so sessions in the same repository sit together.
// its order. Active sessions are grouped by directory when there is more than
// one; the closed ones the operator finished with sit below them as history.
val sessions = state.filteredSessions
val groups = groupChatSessionsByDirectory(sessions)
val active = state.activeSessions
val closed = state.closedSessions
val groups = groupChatSessionsByDirectory(active)
val query = state.sessionQuery
// A removal is reported for what it is: a local, undoable change, never a
@@ -117,6 +119,7 @@ internal fun ChatListPane(
}
}
var renaming by remember { mutableStateOf<ChatSession?>(null) }
var closing by remember { mutableStateOf<ChatSession?>(null) }
Scaffold(
modifier = modifier,
@@ -182,12 +185,21 @@ internal fun ChatListPane(
groups.forEach { group ->
item(key = "dir-" + group.directory) { DirectoryHeader(group.directory) }
items(group.sessions, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it })
SessionListItem(state, session, vm, onRename = { renaming = it }, onClose = { closing = it })
}
}
} else {
items(sessions, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it })
items(active, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it }, onClose = { closing = it })
}
}
if (closed.isNotEmpty()) {
// Finished chats stay reachable as history: a clearly
// labelled section, in the same recency order, from which
// each one can be reopened.
item(key = "closed-header") { DirectoryHeader(CLOSED_SECTION_LABEL) }
items(closed, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it }, onClose = { closing = it })
}
}
if (state.sessionsError != null) {
@@ -216,6 +228,16 @@ internal fun ChatListPane(
},
)
}
closing?.let { session ->
CloseChatDialog(
session = session,
onDismiss = { closing = null },
onConfirm = {
vm.closeChatSession(session.id)
closing = null
},
)
}
}
/**
@@ -256,17 +278,20 @@ private fun SessionListItem(
session: ChatSession,
vm: AppViewModel,
onRename: (ChatSession) -> Unit,
onClose: (ChatSession) -> Unit,
) {
val thread = state.thread(session.id)
SessionRow(
session = session,
thread = thread,
open = thread != null,
running = thread?.running == true,
unseen = state.isUnseen(session),
unseen = !session.closed && state.isUnseen(session),
active = state.activeId == session.id,
onClick = { vm.openChatSession(session) },
onRename = { onRename(session) },
onRemove = { vm.removeChat(session.id) },
onClose = { onClose(session) },
onReopen = { vm.reopenChatSession(session.id) },
onHide = { vm.removeChat(session.id) },
)
}
@@ -294,15 +319,18 @@ private const val NO_DIRECTORY_LABEL = "No directory"
@Composable
private fun SessionRow(
session: ChatSession,
thread: ChatThread?,
open: Boolean,
running: Boolean,
unseen: Boolean,
active: Boolean,
onClick: () -> Unit,
onRename: () -> Unit,
onRemove: () -> Unit,
onClose: () -> Unit,
onReopen: () -> Unit,
onHide: () -> Unit,
) {
val texts = pipelinesText()
val running = thread?.running == true
val activity = sessionActivity(running, unseen)
ListRow(selected = active, onClick = onClick) {
Row(
@@ -320,13 +348,23 @@ private fun SessionRow(
// The kind chip names the session kind the server reported, so an
// operator chat is tellable from anything run-related at a glance.
sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
// A closed chat is named as such on the row itself, so it is never
// confused with a hide (which only affects this device) or with a
// still-open chat.
if (session.closed) LabelChip(CLOSED_CHIP_LABEL, SPACING_S, SPACING_XXS)
// The activity badge is the new-activity signal; the tag and the
// directory below are unchanged beside it.
SessionActivityBadge(activity, open)
SessionMenu(onRename = onRename, onRemove = onRemove)
SessionMenu(
closed = session.closed,
onRename = onRename,
onClose = onClose,
onReopen = onReopen,
onHide = onHide,
)
}
val meta = buildList {
add(sessionStatusLabel(session, running))
add(sessionWorkLabel(session.busy, thread))
if (session.directory.isNotBlank()) add(session.directory)
if (session.model.isNotBlank()) add(session.model)
}.joinToString(" · ")
@@ -334,9 +372,19 @@ private fun SessionRow(
}
}
/** A session row's management actions: rename and remove from this device's list. */
/**
* A session row's management actions. Closing is the real, server-side finish
* (shared by every device); hiding only affects this device and is named so the
* two cannot be confused. A closed chat offers Reopen instead of Close.
*/
@Composable
private fun SessionMenu(onRename: () -> Unit, onRemove: () -> Unit) {
private fun SessionMenu(
closed: Boolean,
onRename: () -> Unit,
onClose: () -> Unit,
onReopen: () -> Unit,
onHide: () -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { expanded = true }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) {
@@ -354,17 +402,52 @@ private fun SessionMenu(onRename: () -> Unit, onRemove: () -> Unit) {
onRename()
},
)
if (closed) {
DropdownMenuItem(
text = { Text("Reopen") },
onClick = {
expanded = false
onReopen()
},
)
} else {
DropdownMenuItem(
text = { Text("Close chat…") },
onClick = {
expanded = false
onClose()
},
)
}
DropdownMenuItem(
text = { Text("Remove from list") },
text = { Text("Hide on this device") },
onClick = {
expanded = false
onRemove()
onHide()
},
)
}
}
}
/**
* The close confirmation. It says exactly what closing does and does not do:
* stops any running turn, keeps the whole history, and marks the chat closed for
* every device — never a delete, and distinct from the local hide.
*/
@Composable
private fun CloseChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Close chat?") },
text = {
Text(closeChatConfirmation(sessionTitle(session)))
},
confirmButton = { TextButton(onClick = onConfirm) { Text("Close chat") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/**
* The rename dialog. The brokered protocol has no rename for a chat session, so
* the dialog says plainly that the name is kept on this device rather than
@@ -400,7 +483,13 @@ private fun RenameChatDialog(session: ChatSession, onDismiss: () -> Unit, onConf
}
/** The removal report: what happened and how to undo it. */
private const val CHAT_REMOVED_MESSAGE = "Removed from this list; the chat stays on the server."
private const val CHAT_REMOVED_MESSAGE = "Hidden on this device; the chat stays on the server."
/** The row chip and section heading for a chat the operator finished with. */
private const val CLOSED_CHIP_LABEL = "Closed"
/** The heading of the section that keeps closed chats reachable as history. */
private const val CLOSED_SECTION_LABEL = "Closed"
/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */
@Composable
@@ -5,16 +5,17 @@ import net.awan.pipelines.data.protocol.PipelinesJson
/**
* The operator's own changes to the session list, which the server has no
* request for: a chat cannot be renamed or deleted through the brokered
* protocol (there is no chat_rename/chat_delete type, and the OpenCode session
* endpoint is not exposed), so both are kept here, on the device, and applied
* over whatever the server lists.
* request for: a chat cannot be renamed through the brokered protocol (there is
* no chat_rename type), so it is kept here, on the device, and applied over
* whatever the server lists. Closing a chat and reopening it are *not* here: they
* are server-side (`chat_close`/`chat_reopen`) so every device sees them.
*
* - [titles] are local renames, keyed by session id; a renamed chat shows its
* local title and the server's title is left untouched.
* - [hidden] are sessions the operator removed from the list. Nothing is deleted
* on the server, so the removal is honest and reversible ([remove] can be
* undone with [restore]).
* - [hidden] are sessions the operator hid on this device. Nothing is deleted on
* the server, and no other device is affected, so the hide is honest and
* reversible ([remove] can be undone with [restore]). It is distinct from a
* server-side close, which marks the chat closed for every client.
*
* Kept as a serializable value so it survives a restart as one preference,
* exactly like the app's other stored settings.
@@ -57,6 +57,12 @@ data class ChatThread(
val updatedAt: Long = 0,
/** The server reports another client (or an active run) holds this session. */
val busy: Boolean = false,
/**
* The server reports this session closed: the operator finished with it. The
* conversation and its history are kept; the chat can be reopened, and sending
* another message reopens it too.
*/
val closed: Boolean = false,
val messages: List<ChatMessage> = emptyList(),
val loading: Boolean = false,
val loaded: Boolean = false,
@@ -70,6 +76,15 @@ data class ChatThread(
* the turn settles.
*/
val runningSince: Long = 0,
/**
* Wall-clock epoch millis each currently-running tool call was first seen
* running, keyed by the tool part's id. The brokered stream pushes a tool part
* with no timing envelope, so a running call's elapsed time is measured from
* here; a call that settles loses its stamp. Kept on the thread (not in the
* composable) so the elapsed time survives a chat switch, exactly like
* [runningSince] does for the turn.
*/
val toolStartedAt: Map<String, Long> = emptyMap(),
/** The unsent composer text for this chat. */
val draft: String = "",
/**
@@ -94,24 +109,26 @@ data class ChatThread(
* settle in place optimistically and survives a chat switch.
*/
val permissionAnswer: String = "",
/**
* The last prompt this client sent was accepted into the session's queue
* behind an in-flight turn (the server acknowledged it as queued), so the
* composer can say so instead of blocking. Cleared as soon as the turn's
* frames arrive or the thread settles.
*/
val queued: Boolean = false,
) {
/**
* 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.
* At least one attachment is flagged; the prompt must not be sent with it.
*/
val readOnly: Boolean get() = busy && !running
/** At least one attachment is flagged; the prompt must not be sent with it. */
val hasAttachmentErrors: Boolean get() = attachments.any { it.error != null }
/**
* Whether the composer's send action is allowed. A message with a flagged
* attachment is never sent: the operator must remove or re-attach it first,
* so the file is never silently dropped.
* Whether the composer's send action is allowed. A session is never read-only:
* another client may watch the same conversation without blocking this one. A
* message with a flagged attachment is never sent, so the file is never
* silently dropped.
*/
val canSend: Boolean get() = !readOnly && draft.isNotBlank() && !hasAttachmentErrors
val canSend: Boolean get() = draft.isNotBlank() && !hasAttachmentErrors
/**
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it
@@ -120,6 +137,22 @@ data class ChatThread(
*/
fun elapsedMillis(nowMillis: Long): Long =
if (running && runningSince in 1 until nowMillis) nowMillis - runningSince else 0
/**
* The tool calls still in flight for this session, in transcript order, so the
* conversation's in-flight indicator and the session row both read the same
* set. Empty once every call has completed or errored, which is what clears
* the indicator.
*/
val runningTools: List<ChatPart> get() = runningToolCalls(messages)
/**
* How long [part] has been running at [nowMillis]: the protocol's own timing
* when the part carries it, else the local start recorded in [toolStartedAt]
* (see [runningToolElapsedMillis]). Zero when neither is usable.
*/
fun toolElapsedMillis(part: ChatPart, nowMillis: Long): Long =
runningToolElapsedMillis(part, toolStartedAt[part.id] ?: 0L, nowMillis)
}
/**
@@ -225,6 +258,21 @@ data class ChatState(
*/
val filteredSessions: List<ChatSession>
get() = filterChatSessions(visibleSessions, sessionQuery)
/**
* The sessions still in play: [filteredSessions] without the closed ones, in
* the same recency order. The list shows these as the active conversations.
*/
val activeSessions: List<ChatSession>
get() = filteredSessions.filterNot { it.closed }
/**
* The finished sessions: [filteredSessions] the server reports as closed, in
* the same order. They are shown as history — nothing was deleted — and can be
* reopened from the list.
*/
val closedSessions: List<ChatSession>
get() = filteredSessions.filter { it.closed }
}
/**
@@ -304,6 +352,7 @@ class ChatStore(
agent = session.agent.ifBlank { thread.agent },
tag = session.tag.ifBlank { thread.tag },
busy = session.busy,
closed = session.closed,
)
}
// Fold the read state in: the active conversation is on screen, so its
@@ -405,9 +454,11 @@ class ChatStore(
}
/**
* Removes a session from the device's list and closes its conversation, if
* open. Nothing is deleted on the server — the session still exists there — so
* the removal is honest and reversible through [undoRemove].
* Hides a session on this device only and closes its conversation, if open.
* Nothing is deleted on the server — the session still exists there — and no
* other device is affected, so the hide is honest and reversible through
* [undoRemove]. It is deliberately not a "close": the server-side close (see
* [sessionClosed]) is shared by every client.
*/
fun remove(sessionId: String) {
if (sessionId.isBlank()) return
@@ -429,6 +480,44 @@ class ChatStore(
)
}
// ---- Closing and reopening (server-side, shared by every client) ---------
/**
* Records that the server closed [sessionId]: the row is marked closed with
* the server's [closedAt] and any in-flight turn is settled, because the
* server stopped it. The session is not removed from [ChatState.sessions] —
* closed chats stay listed as history.
*/
fun sessionClosed(sessionId: String, closedAt: Long) {
if (sessionId.isBlank()) return
val at = if (closedAt > 0) closedAt else now()
_state.value = _state.value.copy(
sessions = _state.value.sessions.map {
if (it.id == sessionId) it.copy(closed = true, closedAt = at) else it
},
open = _state.value.open.map {
if (it.sessionId == sessionId) setRunning(it.copy(closed = true), false) else it
},
)
}
/**
* Clears the closed state of [sessionId] — an explicit reopen, or a prompt
* that the server treated as reopening it — so the chat returns to the active
* list without a re-fetch.
*/
fun sessionReopened(sessionId: String) {
if (sessionId.isBlank()) return
_state.value = _state.value.copy(
sessions = _state.value.sessions.map {
if (it.id == sessionId) it.copy(closed = false, closedAt = 0) else it
},
open = _state.value.open.map {
if (it.sessionId == sessionId) it.copy(closed = false) else it
},
)
}
// ---- Opening / switching -------------------------------------------------
/**
@@ -454,6 +543,7 @@ class ChatStore(
agent = session.agent,
updatedAt = session.updatedAt,
busy = session.busy,
closed = session.closed,
)
_state.value = _state.value.copy(open = _state.value.open + thread, activeId = session.id, seen = seen)
return true
@@ -465,6 +555,7 @@ class ChatStore(
agent = session.agent.ifBlank { existing.agent },
tag = session.tag.ifBlank { existing.tag },
busy = session.busy,
closed = session.closed,
)
_state.value = _state.value.copy(
open = _state.value.open.map { if (it.sessionId == session.id) merged else it },
@@ -580,7 +671,16 @@ class ChatStore(
*/
fun history(sessionId: String, messages: List<ChatMessage>) {
update(sessionId) {
it.copy(messages = messages, loading = false, loaded = true, error = null)
it.copy(
messages = messages,
loading = false,
loaded = true,
error = null,
// A running call the history reports (a turn that started before
// this fetch) is stamped now, the best local measurement there is;
// a call that already settled drops its stamp.
toolStartedAt = runningToolStamps(it.toolStartedAt, messages, now()),
)
}
// A conversation on screen is read as its history arrives: its recency
// watermark advances to the newest message the server reports (its own
@@ -593,6 +693,13 @@ class ChatStore(
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
/**
* Records that the operator's last prompt was accepted into the session's
* queue (true) or sent immediately (false), so the composer can say "Queued"
* while it waits for the in-flight turn without blocking input.
*/
fun setQueued(sessionId: String, queued: Boolean) = update(sessionId) { it.copy(queued = queued) }
/**
* 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
@@ -605,7 +712,9 @@ class ChatStore(
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 },
open = _state.value.open.map {
if (it.running) it.copy(running = false, runningSince = 0, toolStartedAt = emptyMap()) else it
},
)
return ids
}
@@ -707,7 +816,11 @@ class ChatStore(
if (frame.sessionId.isBlank()) return
ensureThread(frame.sessionId)
markUnread(frame.sessionId)
// Any frame for the session means the turn has moved on, so a prompt we
// had queued is no longer waiting.
update(frame.sessionId) { if (it.queued) it.copy(queued = false) else it }
when (frame.kind) {
ChatProtocol.EVENT_USER -> applyRemoteUser(frame)
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
ChatProtocol.PART_TOOL -> applyTool(frame)
ChatProtocol.EVENT_STEP -> {
@@ -718,6 +831,28 @@ class ChatStore(
}
}
/**
* Folds a user turn another client sent into the transcript, in place, once.
* The server never echoes this client's own prompts, so the sender's own
* message is never duplicated; the [ChatMessage.client] label says which
* device sent it.
*/
private fun applyRemoteUser(frame: ChatEventFrame) {
val text = frame.part?.text.orEmpty()
if (frame.messageId.isEmpty() || text.isEmpty()) return
update(frame.sessionId) { thread ->
if (thread.messages.any { it.id == frame.messageId }) return@update thread
val message = ChatMessage(
id = frame.messageId,
sessionId = frame.sessionId,
role = ChatProtocol.ROLE_USER,
client = frame.client,
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)),
)
thread.copy(messages = thread.messages + message)
}
}
/**
* 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.
@@ -733,6 +868,7 @@ class ChatStore(
agent = session?.agent ?: "",
tag = session?.tag ?: "",
busy = session?.busy ?: false,
closed = session?.closed ?: false,
)
_state.value = _state.value.copy(open = _state.value.open + placeholder)
}
@@ -777,7 +913,8 @@ class ChatStore(
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)
val stamped = runningToolStamps(thread.toolStartedAt, messages, now())
setRunning(thread.copy(messages = messages, toolStartedAt = stamped), true)
}
}
@@ -790,7 +927,7 @@ class ChatStore(
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)
else -> thread.copy(running = false, runningSince = 0, toolStartedAt = emptyMap())
}
private fun update(sessionId: String, block: (ChatThread) -> ChatThread) {
@@ -20,6 +20,7 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Psychology
@@ -34,6 +35,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -46,6 +48,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
@@ -57,6 +60,7 @@ import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.theme.CHAT_BUBBLE_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.CHAT_FOLLOW_THRESHOLD_DP
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.SPACING_XS
/** The running indicator's elapsed time ticks once a second, never per frame. */
@@ -274,24 +278,90 @@ private fun LazyListState.bottomDistancePx(itemCount: Int): Int? {
/**
* The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed
* time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]),
* so it keeps counting across a chat switch, and the tick loop stops the moment
* the turn settles.
* time, then one compact line for each tool call in flight — its name, the
* command or description the part carries, and how long that call has been
* running. The elapsed values are derived from the turn's own start
* ([ChatThread.elapsedMillis]) and each call's own start
* ([ChatThread.toolElapsedMillis]), so they keep counting across a chat switch,
* and the tick loop stops the moment the turn settles. This is what makes the
* otherwise-silent part of a turn legible: the operator can tell `working on X`
* from `waiting on something` instead of watching a bare `Running`.
*/
@Composable
private fun RunningIndicator(thread: ChatThread) {
val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince))
val now = rememberElapsedNow(thread.runningSince)
val elapsedMillis = thread.elapsedMillis(now)
val tools = thread.runningTools
Column(
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(
text = "· ${formatDuration(elapsedMillis / 1_000)}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// One line per call in flight, in transcript order and keyed by the part,
// so several running at once read together rather than flickering between
// them; a call's line drops out the moment it completes or errors.
tools.forEach { part ->
key(part.id) { RunningToolLine(part, thread.toolElapsedMillis(part, now)) }
}
}
}
/**
* One tool call in flight: its name, the command or short description the part
* carries (when it carries one) and how long it has been running. A call that has
* been running past [TOOL_LONG_RUNNING_MILLIS] is tinted and labelled so a stuck
* call stands out. The elapsed time is the only progress signal; no percentage,
* ETA or progress bar is ever invented.
*/
@Composable
private fun RunningToolLine(part: ChatPart, elapsedMillis: Long) {
val long = toolLongRunning(elapsedMillis)
val tint = if (long) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant
val detail = toolDetail(part)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP),
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
modifier = Modifier.fillMaxWidth().padding(start = CHAT_GUTTER),
) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Icon(
Icons.Default.Build,
contentDescription = null,
tint = tint,
modifier = Modifier.size(ICON_STATUS_DP),
)
Text(
text = "· ${formatDuration(elapsedMillis / 1_000)}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
text = toolLabel(part),
style = MaterialTheme.typography.labelMedium,
color = tint,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (detail == null) Modifier.weight(1f) else Modifier,
)
if (detail != null) {
Text(
text = detail,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
}
Text(
text = formatDuration(elapsedMillis / 1_000) + if (long) " · long" else "",
style = MaterialTheme.typography.labelMedium,
color = tint,
)
}
}
@@ -352,6 +422,16 @@ private fun MessageItem(
SelectionContainer {
Column(Modifier.padding(CHAT_GUTTER)) {
if (isUser) {
// A user turn another device sent is attributed to it, so
// the transcript says who sent the message. Our own
// messages carry no label.
if (message.client.isNotBlank()) {
Text(
text = message.client,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
UserParts(message.parts)
} else {
AssistantParts(
@@ -179,7 +179,7 @@ fun FilterCheckItem(
)
}
/** A small section caption inside a filter menu (Status/Pipeline/Time range). */
/** A small section caption inside a menu (a filter facet or a sort's reach). */
@Composable
fun FilterSectionHeader(label: String) {
Text(
@@ -10,6 +10,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.DirectionsRun
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.CheckCircle
@@ -17,6 +18,7 @@ import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.FrontHand
import androidx.compose.material.icons.filled.PauseCircle
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -48,6 +50,8 @@ enum class RunState(val label: String) {
Failed("failed"),
Canceled("canceled"),
Interrupted("interrupted"),
Blocked("blocked"),
Skipped("skipped"),
Active("active"),
Unknown("unknown"),
}
@@ -67,6 +71,8 @@ fun runStateOf(status: String): RunState = when (status.trim().lowercase()) {
"failed", "error" -> RunState.Failed
"canceled", "cancelled" -> RunState.Canceled
"interrupted" -> RunState.Interrupted
"blocked" -> RunState.Blocked
"skipped" -> RunState.Skipped
else -> RunState.Unknown
}
@@ -86,6 +92,8 @@ fun runStateIcon(state: RunState): ImageVector = when (state) {
RunState.Failed -> Icons.Default.Error
RunState.Canceled -> Icons.Default.Cancel
RunState.Interrupted -> Icons.Default.PauseCircle
RunState.Blocked -> Icons.Default.Block
RunState.Skipped -> Icons.Default.SkipNext
RunState.Active -> Icons.Default.Bolt
RunState.Unknown -> Icons.AutoMirrored.Filled.HelpOutline
}
@@ -4,17 +4,20 @@ import androidx.compose.ui.graphics.Color
import net.awan.pipelines.ui.theme.DarkError
/**
* The app-owned run-status palette.
* The app-owned status palette, the single source of truth for the colour of a
* status or stage-outcome word.
*
* Run status is a *different vocabulary* from the graph's stage outcomes
* ([net.awan.pipelines.ui.graph.GraphPalette]): a run that is `running` is not a
* `skipped` stage, and a `succeeded` run is not the amber the theme uses for a
* positive *stage* outcome. Borrowing Material roles therefore put the wrong hue
* on the two states that matter most — `primary` (mint) made a *running* run read
* green and `tertiary` (amber) made a *succeeded* run read yellow.
* Borrowing Material roles put the wrong hue on the two states that matter most —
* `primary` (mint) made a *running* run read green and `tertiary` (amber) made a
* *succeeded* run read yellow — so every entry below is a deliberate, fixed
* colour with an explicit meaning. The stage outcomes that share a word with a
* run state (`success`/`done`→[Succeeded], `error`→[Failed], `blocked`,
* `skipped`, `waiting`) resolve here too, through [runStateOf], so the timeline,
* the graph, the runs list, the stage sheet and the peek all draw one word in one
* colour. Only genuinely graph-only flow outcomes (`approved`, `retry`, …) keep
* their own curated colour in [net.awan.pipelines.ui.graph.GraphPalette].
*
* Every entry below is instead a deliberate, fixed colour with an explicit
* meaning, tuned for the dark Pipelines surface (`DarkSurface 0xFF0E1513`,
* Every entry is tuned for the dark Pipelines surface (`DarkSurface 0xFF0E1513`,
* over which the chip label is drawn). The contrast of each colour against that
* surface is *measured* by `RunStatusPaletteTest`, never judged by eye. Status is
* never colour-only: every entry keeps its own material glyph ([runStateIcon])
@@ -29,6 +32,13 @@ internal object RunStatusPalette {
private val Running =
Entry(Color(0xFF7FB2F0), "blue: in progress; green would read as already finished")
/**
* Waiting for a person (a human decision): a distinct cyan, matching the TUI's
* accent for a paused run, so it is neither the running blue nor a failure.
*/
private val Waiting =
Entry(Color(0xFF8EDFF5), "cyan: paused for a person; distinct from running and from failure")
/** Finished well: the conventional green. Amber/tertiary would read as a warning. */
private val Succeeded =
Entry(Color(0xFF7FE0A8), "green: completed successfully; amber would read as a warning")
@@ -50,11 +60,18 @@ internal object RunStatusPalette {
Entry(Color(0xFF9AA6A2), "neutral grey: waiting, clearly not the in-progress blue")
/**
* Parked on a person: violet, distinct from the in-progress blue, the queued
* grey and the amber operator-stop, so a run needing a decision is unmistakable.
* Parked on a person (a human decision): distinct from the in-progress blue, the
* queued grey and the amber operator-stop, so a run needing a decision is
* unmistakable. Blocked and skipped are stage outcomes rather than run states:
* a stage that could not proceed is orange, and one deliberately not run is a
* quiet grey-blue - neither is a failure.
*/
private val Waiting =
Entry(Color(0xFFC0A3F5), "violet: parked for the operator's decision; not running, not a stop")
private val Blocked =
Entry(Color(0xFFF0A35E), "orange: a blocked stage could not proceed; not the failure red")
/** Skipped: a stage deliberately not run — a cool muted grey-blue, quiet and distinct. */
private val Skipped =
Entry(Color(0xFFA8B8C8), "muted grey-blue: a stage deliberately not run; quiet, not a status")
/** Unknown/blank status: the safe, low-key fallback. */
private val Unknown =
@@ -67,12 +84,14 @@ internal object RunStatusPalette {
*/
fun of(state: RunState): Entry = when (state) {
RunState.Running, RunState.Active -> Running
RunState.Waiting -> Waiting
RunState.Succeeded -> Succeeded
RunState.Failed -> Failed
RunState.Interrupted -> Interrupted
RunState.Canceled -> Canceled
RunState.Queued -> Queued
RunState.Waiting -> Waiting
RunState.Blocked -> Blocked
RunState.Skipped -> Skipped
RunState.Unknown -> Unknown
}
}
@@ -25,7 +25,9 @@ import androidx.compose.ui.Modifier
* icon and works at both window widths (it is not width-dependent geometry).
*
* [selected] draws a leading check on its row, so the active choice is conveyed
* by a glyph as well as by text, never by colour alone.
* by a glyph as well as by text, never by colour alone. An optional [header]
* captions the menu, e.g. to say that an order applies to the results in hand
* rather than server-side.
*/
@Composable
fun <T> SortMenu(
@@ -36,6 +38,7 @@ fun <T> SortMenu(
onSelect: (T) -> Unit,
onReset: () -> Unit,
modifier: Modifier = Modifier,
header: String? = null,
) {
var expanded by remember { mutableStateOf(false) }
Box(modifier) {
@@ -43,6 +46,7 @@ fun <T> SortMenu(
Icon(Icons.AutoMirrored.Filled.Sort, contentDescription = contentDescription)
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
header?.let { FilterSectionHeader(it) }
options.forEach { option ->
DropdownMenuItem(
text = { Text(label(option)) },
@@ -82,6 +82,26 @@ internal fun artifactIcon(kind: ArtifactKind): ImageVector = when (kind) {
ArtifactKind.Other -> Icons.AutoMirrored.Filled.InsertDriveFile
}
/**
* The word that names [kind] where a surface shows the type glyph but must also
* say the type in prose (a screen reader cannot read an icon). It is the same
* classification [artifactIcon] draws from, so the glyph and the word never
* disagree. Pure, so the mapping is unit-tested.
*/
internal fun artifactKindLabel(kind: ArtifactKind): String = when (kind) {
ArtifactKind.Image -> "Image"
ArtifactKind.Video -> "Video"
ArtifactKind.Audio -> "Audio"
ArtifactKind.Pdf -> "PDF"
ArtifactKind.Json -> "JSON"
ArtifactKind.Archive -> "Archive"
ArtifactKind.Spreadsheet -> "Spreadsheet"
ArtifactKind.Log -> "Log"
ArtifactKind.Code -> "Code"
ArtifactKind.Document -> "Document"
ArtifactKind.Other -> "File"
}
private val ARCHIVE_EXTENSIONS =
setOf("zip", "tar", "gz", "tgz", "bz2", "xz", "rar", "7z", "jar", "war")
@@ -8,9 +8,15 @@ import kotlin.math.min
import kotlin.math.pow
/**
* The curated graph colour palette.
* The curated palette for the graph-only flow outcomes.
*
* Every distinct outcome gets its own deliberate entry (no `hashCode() % 4`
* A stage outcome that is also a run state (`success`/`done`/`error`/`blocked`/
* `skipped`/`waiting`) is coloured from the one owned status palette
* ([net.awan.pipelines.ui.components.RunStatusPalette], through [outcomeColor]),
* so the graph, the timeline and the runs list never disagree. This palette
* covers only the words with no status meaning — the loop/choice outcomes a
* pipeline defines (`rejected`, `exhausted`, `retry`, `approved`, `fast`,
* `missing`) — giving each its own deliberate entry (no `hashCode() % 4`
* collisions): the mapping is pure and deterministic, so a given outcome name is
* the same colour across runs and recompositions, and an unknown/new name gets a
* stable reserved fallback colour instead of silently borrowing a known one.
@@ -19,46 +25,35 @@ import kotlin.math.pow
* over which the outcome label is drawn on a ~0.92-alpha chip). Every entry is
* bright enough to be legible both as a 3px edge stroke and as the small 11sp
* label text: contrast is *measured* by [GraphPaletteTest], not asserted by eye.
*
* The two terminal outcomes stay theme roles in [GraphColors] (`error`→error,
* `success`→tertiary) so their meaning is preserved; everything else uses
* [colors].
*/
internal object GraphPalette {
/**
* The fixed palette. Deliberately fixed (rather than scheme-derived) so an
* outcome is the same colour on every device; the two terminal roles above
* remain scheme roles.
* outcome is the same colour on every device.
*/
val colors: List<Color> = listOf(
Color(0xFF8FE0A0), // 0 blocked - green
Color(0xFFF5A3A3), // 1 rejected - red
Color(0xFF8FB4F5), // 2 skipped - blue
Color(0xFFF5B37A), // 3 exhausted - orange
Color(0xFF7FD4E8), // 4 retry - cyan
Color(0xFFC0A3F5), // 5 approved - violet
Color(0xFFF0E07A), // 6 fast - yellow
Color(0xFFF5A3D0), // 7 missing - pink
Color(0xFFD6B08C), // 8 done - sand
Color(0xFFF5A3A3), // 0 rejected - red
Color(0xFFF5B37A), // 1 exhausted - orange
Color(0xFF7FD4E8), // 2 retry - cyan
Color(0xFFC0A3F5), // 3 approved - violet
Color(0xFFF0E07A), // 4 fast - yellow
Color(0xFFF5A3D0), // 5 missing - pink
// Reserved fallback region for names not in [KNOWN], kept distinct from
// the known entries so an unknown outcome never borrows a known colour.
Color(0xFFD8C98A), // 9 fallback - khaki
Color(0xFF9FD8C0), // 10 fallback - sea
Color(0xFFD8A8C0), // 11 fallback - dusty rose
Color(0xFFD8C98A), // 6 fallback - khaki
Color(0xFF9FD8C0), // 7 fallback - sea
Color(0xFFD8A8C0), // 8 fallback - dusty rose
)
/** The known outcome names and their fixed palette index, in display order. */
/** The known graph-only outcome names and their fixed palette index, in display order. */
private val KNOWN: Map<String, Int> = linkedMapOf(
"blocked" to 0,
"rejected" to 1,
"skipped" to 2,
"exhausted" to 3,
"retry" to 4,
"approved" to 5,
"fast" to 6,
"missing" to 7,
"done" to 8,
"rejected" to 0,
"exhausted" to 1,
"retry" to 2,
"approved" to 3,
"fast" to 4,
"missing" to 5,
)
/** First palette index reserved for names that are not in [KNOWN]. */
@@ -67,8 +62,9 @@ internal object GraphPalette {
/**
* The palette index for [outcome]. Pure and deterministic for every input
* (including blank): known names get their curated slot, everything else a
* stable slot inside the reserved fallback region. `success`/`error` resolve
* to the theme roles in [outcomeColor] but still return a stable index here.
* stable slot inside the reserved fallback region. A word that resolves to a
* run state is coloured from the status palette by [outcomeColor] and does not
* reach this palette.
*/
fun outcomeColorIndex(outcome: String): Int {
KNOWN[outcome]?.let { return it }
@@ -85,8 +85,11 @@ import net.awan.pipelines.data.protocol.GraphSemantics
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.edges
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.hostResumed
import net.awan.pipelines.ui.components.rememberLiveNowMillis
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.secondsSince
import net.awan.pipelines.ui.theme.GRAPH_ACTIVE_HALO_GAP
@@ -534,44 +537,51 @@ internal class GraphColors(
/**
* The graph's colours for [scheme], built in one place so every surface that must
* agree with the graph (the graph itself and the timeline's step-outcome chips)
* uses the same palette. The two terminal roles stay scheme roles so their
* meaning is kept; every other outcome uses the one curated, legible
* [GraphPalette] for both a stroke and its label text.
* uses the same palette. The two terminal roles take the one owned run-status
* colour (success green, failure red) so they can never disagree with the runs
* list; every other status word is coloured by the status palette in
* [outcomeColor], and the remaining graph-only flow outcomes use the one curated,
* legible [GraphPalette] for both a stroke and its label text.
*
* Node and label surfaces are *tonal*: a raised surface tone ([scheme]'s
* `surfaceContainerHigh`/`surfaceContainerHighest`) blended with a subtle tint of
* the node's semantic colour (see [tonalFill]) rather than a flat fill, so a node
* reads as raised card, not a terminal cell.
*/
internal fun graphColors(scheme: ColorScheme): GraphColors = GraphColors(
// The two terminal roles stay scheme roles so their meaning is kept.
success = scheme.tertiary,
error = scheme.error,
// Every other outcome uses the one curated, legible palette for both its
// stroke and its label text, so a curve and its label always agree.
palette = GraphPalette.colors,
// Node fills differ by kind (see [GraphNodeKind]): model (neutral), ntfy
// (amber), other/custom (green), and the two terminals (success/error). Each
// is a tonal surface carrying a subtle tint of that kind's semantic hue.
nodeFill = tonalFill(scheme.surfaceContainerHigh, scheme.onSurfaceVariant, NEUTRAL_TINT),
nodeNtfyFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, KIND_TINT),
nodeCustomFill = tonalFill(scheme.surfaceContainerHigh, scheme.primary, KIND_TINT),
// A selected node inverts (light fill / dark text) plus a stronger border, so
// selection reads in either appearance and never relies on colour.
nodeFillActive = scheme.inverseSurface,
nodeTextActive = scheme.inverseOnSurface,
// The stage border is deliberately soft (a low-contrast outline variant), not
// the hard original outline; terminals carry their outcome hue instead.
nodeBorder = scheme.outlineVariant,
nodeBorderActive = scheme.primary,
nodeText = scheme.onSurface,
terminalFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, TERMINAL_TINT),
terminalErrorFill = tonalFill(scheme.surfaceContainerHigh, scheme.error, TERMINAL_TINT),
// Edge outcome labels sit on a tonal chip (drawn as a rounded rect) rather than
// raw text over the canvas.
labelBackground = scheme.surfaceContainerHighest,
labelText = scheme.onSurfaceVariant,
)
internal fun graphColors(scheme: ColorScheme): GraphColors {
// The two terminal outcomes take the shared run-status colours so the graph
// and the runs list can never disagree about success/failure.
val success = runStateColor(RunState.Succeeded)
val error = runStateColor(RunState.Failed)
return GraphColors(
success = success,
error = error,
// Every other graph-only outcome uses the one curated, legible palette for
// both its stroke and its label text, so a curve and its label always agree.
palette = GraphPalette.colors,
// Node fills differ by kind (see [GraphNodeKind]): model (neutral), ntfy
// (amber), other/custom (green), and the two terminals (success/error). Each
// is a tonal surface carrying a subtle tint of that kind's semantic hue.
nodeFill = tonalFill(scheme.surfaceContainerHigh, scheme.onSurfaceVariant, NEUTRAL_TINT),
nodeNtfyFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, KIND_TINT),
nodeCustomFill = tonalFill(scheme.surfaceContainerHigh, scheme.primary, KIND_TINT),
// A selected node inverts (light fill / dark text) plus a stronger border, so
// selection reads in either appearance and never relies on colour.
nodeFillActive = scheme.inverseSurface,
nodeTextActive = scheme.inverseOnSurface,
// The stage border is deliberately soft (a low-contrast outline variant), not
// the hard original outline; terminals carry their outcome hue instead.
nodeBorder = scheme.outlineVariant,
nodeBorderActive = scheme.primary,
nodeText = scheme.onSurface,
terminalFill = tonalFill(scheme.surfaceContainerHigh, success, TERMINAL_TINT),
terminalErrorFill = tonalFill(scheme.surfaceContainerHigh, error, TERMINAL_TINT),
// Edge outcome labels sit on a tonal chip (drawn as a rounded rect) rather than
// raw text over the canvas.
labelBackground = scheme.surfaceContainerHighest,
labelText = scheme.onSurfaceVariant,
)
}
/**
* [surface] blended with a [fraction] (0..1) of [accent], so a node/label fill
@@ -1602,17 +1612,19 @@ private fun DrawScope.drawActiveHalo(
}
/**
* The colour for an outcome: the theme error role for `error`, a clearly
* positive theme colour for `success`, and the curated [GraphPalette] entry for
* everything else. One colour is used for both the edge stroke and its label
* text (the palette is legible on the surface), so a curve and its label always
* agree. `success`/`error` are the terminal roles and are never colour-only
* signals (their labels name them). Pure and deterministic.
* The colour for an outcome or stage status, from the one owned source: a word
* that is a run state (`success`/`done`/`error`/`blocked`/`skipped`/`waiting`/
* `running`/…) takes the shared status colour the operator already learned from
* the runs list, so the same word is the same colour in the timeline, the graph,
* the stage sheet and the peek; a graph-only flow outcome (`approved`, `retry`, …)
* takes its curated [GraphPalette] entry. One colour serves both the edge stroke
* and its label text (the palette is legible on the surface), so a curve and its
* label always agree. Pure and deterministic.
*/
internal fun outcomeColor(outcome: String, colors: GraphColors): Color = when (outcome) {
"error" -> colors.error
"success" -> colors.success
else -> colors.palette[GraphPalette.outcomeColorIndex(outcome)]
internal fun outcomeColor(outcome: String, colors: GraphColors): Color {
val state = runStateOf(outcome)
if (state != RunState.Unknown) return runStateColor(state)
return colors.palette[GraphPalette.outcomeColorIndex(outcome)]
}
/**
@@ -46,13 +46,15 @@ enum class RunPresence(val label: String, val storageKey: String) {
/**
* The statuses a run filter can select. The server's own run vocabulary
* (internal/pipeline/runs.go: queued/running/succeeded/failed/canceled/
* interrupted); the app-only `active` usage bucket and the `unknown` fallback
* are deliberately not offered, so a status filter always names a real state.
* (internal/pipeline/runs.go: queued/running/waiting/succeeded/failed/canceled/
* interrupted); the app-only `active` usage bucket, the stage-outcome words
* (`blocked`/`skipped`) and the `unknown` fallback are deliberately not offered,
* so a status filter always names a real run state.
*/
internal val RUN_STATUS_FILTERS: List<RunState> = listOf(
RunState.Queued,
RunState.Running,
RunState.Waiting,
RunState.Succeeded,
RunState.Failed,
RunState.Canceled,
@@ -586,8 +586,10 @@ private fun RunRow(
Text(
run.diagnostic,
style = text.meta,
// The one status colour for a failure, never a scheme role that
// could drift from the chip above it.
color = if (state == RunState.Failed) {
MaterialTheme.colorScheme.error
runStateColor(RunState.Failed)
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
@@ -45,6 +45,45 @@ class ChatProtocolTest {
assertTrue(!sessions[1].busy)
}
@Test
fun chatMultiClientFieldsRoundTrip() {
// The client label the prompt carries, the queued acknowledgement, the
// subscribe request and the shared-answer fields of a permission frame.
val prompt = PipelinesJson.decodeFromString(
Message.serializer(),
"""{"type":"chat_prompt","chat_prompt":{"session_id":"ses_1","text":"hi","client":"Pixel 9 Pro XL"}}""",
)
assertEquals("Pixel 9 Pro XL", prompt.chatPrompt!!.client)
val ack = PipelinesJson.decodeFromString(
Message.serializer(),
"""{"type":"chat_prompt","id":"a1","chat_queued":true}""",
)
assertTrue(ack.chatQueued)
val subscribe = PipelinesJson.decodeFromString(
Message.serializer(),
"""{"type":"chat_subscribe","chat_subscribe":{"session_id":"ses_1"}}""",
)
assertEquals(Protocol.CHAT_SUBSCRIBE, subscribe.type)
assertEquals("ses_1", subscribe.chatSubscribe!!.sessionId)
val userFrame = PipelinesJson.decodeFromString(
Message.serializer(),
"""{"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"usr_1","kind":"user","client":"Pixel 10 Pro Fold","part":{"type":"text","text":"from the fold"}}}""",
)
assertEquals(ChatProtocol.EVENT_USER, userFrame.chatEvent!!.kind)
assertEquals("Pixel 10 Pro Fold", userFrame.chatEvent!!.client)
val resolved = PipelinesJson.decodeFromString(
Message.serializer(),
"""{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_1","resolved":true,"decision":"once","resolved_by":"Pixel 9"}}""",
)
assertTrue(resolved.chatPermission!!.resolved)
assertEquals("once", resolved.chatPermission!!.decision)
assertEquals("Pixel 9", resolved.chatPermission!!.resolvedBy)
}
@Test
fun chatMessagesParseTextReasoningAndToolParts() {
val json = """
@@ -311,6 +350,58 @@ class ChatProtocolTest {
assertNull(message.chatEvent)
assertNull(message.chatSessions)
assertNull(message.chatPermission)
assertNull(message.chatClose)
}
/**
* The session list carries the server's closed state: a closed session decodes
* with its flag and close time, and an open one stays open, so the app can
* group finished chats as history without a second request.
*/
@Test
fun chatSessionsParseTheClosedState() {
val json = """
{"type":"chat_sessions","chat_sessions":[
{"id":"ses_open","title":"Active"},
{"id":"ses_done","title":"Finished","closed":true,"closed_at":1792112367999}]}
""".trimIndent()
val sessions = PipelinesJson.decodeFromString(Message.serializer(), json).chatSessions!!
assertEquals(false, sessions[0].closed)
assertEquals(0L, sessions[0].closedAt)
assertTrue(sessions[1].closed)
assertEquals(1792112367999L, sessions[1].closedAt)
}
/**
* The close/reopen frames use the same builder the repository sends and carry
* only the session id; the close reply's result (closed_at, interrupted)
* round-trips, so the app can report that a turn was stopped.
*/
@Test
fun chatCloseAndReopenFramesRoundTrip() {
val close = ChatProtocol.closeRequest("ses_1")
assertEquals(Protocol.CHAT_CLOSE, close.type)
assertEquals("ses_1", close.chatQuery!!.sessionId)
val decodedClose = PipelinesJson.decodeFromString(
Message.serializer(),
PipelinesJson.encodeToString(Message.serializer(), close.copy(id = "android-1")),
)
assertEquals(Protocol.CHAT_CLOSE, decodedClose.type)
val reopen = ChatProtocol.reopenRequest("ses_1")
assertEquals(Protocol.CHAT_REOPEN, reopen.type)
assertEquals("ses_1", reopen.chatQuery!!.sessionId)
val reply = """
{"type":"chat_close","id":"android-1",
"chat_session":{"id":"ses_1","closed":true,"closed_at":1792112367999},
"chat_close":{"session_id":"ses_1","closed_at":1792112367999,"interrupted":true}}
""".trimIndent()
val decodedReply = PipelinesJson.decodeFromString(Message.serializer(), reply)
assertEquals(true, decodedReply.chatSession!!.closed)
assertEquals(1792112367999L, decodedReply.chatSession!!.closedAt)
assertTrue(decodedReply.chatClose!!.interrupted)
assertEquals(1792112367999L, decodedReply.chatClose!!.closedAt)
}
private fun toolDuration(part: ChatPart): Long? {
@@ -1,5 +1,19 @@
package net.awan.pipelines.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.HelpOutline
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.automirrored.filled.Segment
import androidx.compose.material.icons.automirrored.filled.Subject
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.Commit
import androidx.compose.material.icons.filled.DataObject
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.PictureAsPdf
import androidx.compose.ui.graphics.vector.ImageVector
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.SearchArtifact
@@ -10,6 +24,8 @@ import net.awan.pipelines.data.protocol.SearchResult
import net.awan.pipelines.data.protocol.SearchRun
import net.awan.pipelines.data.protocol.SearchStep
import net.awan.pipelines.data.protocol.SearchVersion
import net.awan.pipelines.ui.graph.artifactIcon
import net.awan.pipelines.ui.graph.artifactKind
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
@@ -19,26 +35,77 @@ import org.junit.Test
class OmniSearchResultsTest {
// ---- Badges and rows ---------------------------------------------------
// ---- Type glyphs and rows ----------------------------------------------
@Test
fun everyKindMapsToItsBadge() {
assertEquals("pipeline", searchBadge(Protocol.SEARCH_KIND_PIPELINE))
assertEquals("pipeline", searchBadge(Protocol.SEARCH_KIND_VERSION))
assertEquals("run", searchBadge(Protocol.SEARCH_KIND_RUN))
assertEquals("step", searchBadge(Protocol.SEARCH_KIND_STEP))
assertEquals("artifact", searchBadge(Protocol.SEARCH_KIND_ARTIFACT))
assertEquals("match", searchBadge(Protocol.SEARCH_KIND_FIELD))
// A kind the client does not know still gets a badge and is shown.
assertEquals("match", searchBadge("future_kind"))
assertEquals("match", searchBadge(""))
fun everyKindMapsToItsOwnGlyph() {
assertEquals(Icons.Filled.AccountTree, searchResultIcon(hit(Protocol.SEARCH_KIND_PIPELINE)))
assertEquals(Icons.Filled.Commit, searchResultIcon(hit(Protocol.SEARCH_KIND_VERSION)))
assertEquals(Icons.Filled.History, searchResultIcon(hit(Protocol.SEARCH_KIND_RUN)))
assertEquals(Icons.AutoMirrored.Filled.Segment, searchResultIcon(hit(Protocol.SEARCH_KIND_STEP)))
assertEquals(Icons.AutoMirrored.Filled.Subject, searchResultIcon(hit(Protocol.SEARCH_KIND_FIELD)))
// An artifact shows its content type's glyph; an unknown kind gets a neutral
// mark rather than none, and no two kinds share a glyph.
assertEquals(Icons.Filled.Description, searchResultIcon(hit(Protocol.SEARCH_KIND_ARTIFACT)))
assertEquals(Icons.AutoMirrored.Filled.HelpOutline, searchResultIcon(hit("future_kind")))
val glyphs = listOf(
Protocol.SEARCH_KIND_PIPELINE,
Protocol.SEARCH_KIND_VERSION,
Protocol.SEARCH_KIND_RUN,
Protocol.SEARCH_KIND_STEP,
Protocol.SEARCH_KIND_FIELD,
Protocol.SEARCH_KIND_ARTIFACT,
"future_kind",
).map { searchResultIcon(hit(it)) }
assertEquals(glyphs.size, glyphs.toSet().size)
}
@Test
fun eachRowCarriesABadgeTitleAndSecondaryLine() {
fun anArtifactGlyphIsTheGallerysContentTypeMapping() {
// Every artifact reuses artifactIcon(artifactKind(...)) rather than a second
// mapping, so the search surface and the gallery can never disagree.
val cases = listOf(
"image/png" to "shot.png",
"application/pdf" to "report.pdf",
"application/json" to "run.json",
"text/markdown" to "notes.md",
"application/xml" to "graph.xml",
"text/plain" to "readme.txt",
"application/octet-stream" to "blob",
)
cases.forEach { (contentType, name) ->
assertEquals(
"artifact $contentType",
artifactIcon(artifactKind(contentType, name)),
artifactGlyph(contentType, name),
)
}
// Spot-check the concrete glyphs the brief names.
assertEquals(Icons.Filled.Image, artifactGlyph("image/png", "shot.png"))
assertEquals(Icons.Filled.PictureAsPdf, artifactGlyph("application/pdf", "report.pdf"))
assertEquals(Icons.Filled.DataObject, artifactGlyph("application/json", "run.json"))
assertEquals(Icons.Filled.Code, artifactGlyph("application/xml", "graph.xml"))
assertEquals(Icons.Filled.Description, artifactGlyph("text/plain", "readme.txt"))
assertEquals(Icons.AutoMirrored.Filled.InsertDriveFile, artifactGlyph("application/octet-stream", "blob"))
}
@Test
fun everyKindCarriesItsKindInWords() {
assertEquals("Pipeline", searchResultKindLabel(hit(Protocol.SEARCH_KIND_PIPELINE)))
assertEquals("Pipeline version", searchResultKindLabel(hit(Protocol.SEARCH_KIND_VERSION)))
assertEquals("Run", searchResultKindLabel(hit(Protocol.SEARCH_KIND_RUN)))
assertEquals("Step", searchResultKindLabel(hit(Protocol.SEARCH_KIND_STEP)))
assertEquals("Field", searchResultKindLabel(hit(Protocol.SEARCH_KIND_FIELD)))
// The default artifact fixture is a markdown file; an image names itself.
assertEquals("Document artifact", searchResultKindLabel(hit(Protocol.SEARCH_KIND_ARTIFACT)))
assertEquals("Image artifact", searchResultKindLabel(artifactHit("image/png", "shot.png")))
assertEquals("Unrecognised result", searchResultKindLabel(hit("future_kind")))
}
@Test
fun eachRowCarriesATitleAndSecondaryLine() {
results().forEach { hit ->
val row = searchRow(hit, "release")
assertTrue("badge for ${hit.kind}", row.badge.isNotBlank())
assertTrue("title for ${hit.kind}", row.title.isNotBlank())
assertTrue("secondary for ${hit.kind}", row.secondary.isNotBlank())
}
@@ -62,6 +129,91 @@ class OmniSearchResultsTest {
assertNull("an unknown kind is not navigable", searchTarget(unknown))
}
// ---- Kind filter -------------------------------------------------------
@Test
fun everyFilterCarriesTheServerKindAndResolvesFromStorage() {
assertEquals("", SearchKindFilter.All.serverKind)
assertEquals(Protocol.SEARCH_KIND_PIPELINE, SearchKindFilter.Pipelines.serverKind)
assertEquals(Protocol.SEARCH_KIND_VERSION, SearchKindFilter.Versions.serverKind)
assertEquals(SearchKindFilter.All, SearchKindFilter.fromStorage(""))
assertEquals(SearchKindFilter.Runs, SearchKindFilter.fromStorage("run"))
// A stale/unknown stored value falls back to every kind; "prompts" is not a
// server kind, so it is deliberately not an option.
assertEquals(SearchKindFilter.All, SearchKindFilter.fromStorage("prompts"))
}
@Test
fun theKindFilterNarrowsTheListToThatKind() {
val mixed = listOf(
hit(Protocol.SEARCH_KIND_PIPELINE),
hit(Protocol.SEARCH_KIND_RUN),
hit(Protocol.SEARCH_KIND_STEP),
hit(Protocol.SEARCH_KIND_FIELD),
hit(Protocol.SEARCH_KIND_ARTIFACT),
hit(Protocol.SEARCH_KIND_VERSION),
)
assertEquals(mixed, filterSearchResults(mixed, SearchKindFilter.All))
assertEquals(listOf(hit(Protocol.SEARCH_KIND_RUN)), filterSearchResults(mixed, SearchKindFilter.Runs))
assertEquals(listOf(hit(Protocol.SEARCH_KIND_ARTIFACT)), filterSearchResults(mixed, SearchKindFilter.Artifacts))
assertEquals(
listOf(hit(Protocol.SEARCH_KIND_VERSION)),
filterSearchResults(mixed, SearchKindFilter.Versions),
)
}
// ---- Sort ordering -----------------------------------------------------
@Test
fun relevanceKeepsTheServersRanking() {
val ordered = listOf(
hitWithRecency(Protocol.SEARCH_KIND_RUN, "2026-01-01T00:00:00Z"),
hitWithRecency(Protocol.SEARCH_KIND_PIPELINE, "2026-03-01T00:00:00Z"),
)
assertEquals(ordered, sortSearchResults(ordered, SearchSort.Relevance))
}
@Test
fun newestFirstOrdersByRecencyDescending() {
val older = hitWithRecency(Protocol.SEARCH_KIND_RUN, "2026-01-01T00:00:00Z")
val newer = hitWithRecency(Protocol.SEARCH_KIND_PIPELINE, "2026-03-01T00:00:00Z")
assertEquals(listOf(newer, older), sortSearchResults(listOf(older, newer), SearchSort.Newest))
}
@Test
fun aRecencyTieKeepsTheServersOrder() {
val first = hitWithRecency(Protocol.SEARCH_KIND_RUN, "2026-01-01T00:00:00Z")
val second = hitWithRecency(Protocol.SEARCH_KIND_PIPELINE, "2026-01-01T00:00:00Z")
assertEquals(listOf(first, second), sortSearchResults(listOf(first, second), SearchSort.Newest))
}
@Test
fun aMissingRecencySortsLast() {
val dated = hitWithRecency(Protocol.SEARCH_KIND_RUN, "2026-01-01T00:00:00Z")
val undated = SearchResult(kind = Protocol.SEARCH_KIND_RUN, recency = null)
assertEquals(listOf(dated, undated), sortSearchResults(listOf(undated, dated), SearchSort.Newest))
}
@Test
fun nameOrdersByTheDisplayedTitleAndATieKeepsItsOrder() {
val alpha1 = SearchResult(kind = Protocol.SEARCH_KIND_PIPELINE, pipeline = SearchPipeline(id = 1, name = "alpha"))
val beta = SearchResult(kind = Protocol.SEARCH_KIND_PIPELINE, pipeline = SearchPipeline(id = 2, name = "beta"))
val alpha2 = SearchResult(kind = Protocol.SEARCH_KIND_PIPELINE, pipeline = SearchPipeline(id = 3, name = "alpha"))
// The two "alpha" rows tie and keep their input order; "beta" moves last.
assertEquals(listOf(alpha1, alpha2, beta), sortSearchResults(listOf(beta, alpha1, alpha2), SearchSort.Name))
}
@Test
fun theStoredSortAndTheControlSummaryResolve() {
assertEquals(SearchSort.Relevance, SearchSort.fromStorage(""))
assertEquals(SearchSort.Name, SearchSort.fromStorage("name"))
assertEquals(SearchSort.Relevance, SearchSort.fromStorage("bogus"))
assertEquals("All kinds · Relevance", searchControlsSummary(SearchKindFilter.All, SearchSort.Relevance))
// An order that runs on the fetched results says so in the collapsed summary.
assertEquals("Runs · Newest first (in hand)", searchControlsSummary(SearchKindFilter.Runs, SearchSort.Newest))
assertEquals("Fields · Name (in hand)", searchControlsSummary(SearchKindFilter.Fields, SearchSort.Name))
}
// ---- Snippet highlighting ---------------------------------------------
@Test
@@ -220,13 +372,25 @@ class OmniSearchResultsTest {
}
@Test
fun theEmptyStateNamesTheQueryAndOnlyAppearsWhenLoaded() {
fun theEmptyStateNamesTheQueryAndTheActiveFilter() {
val empty = SearchUiState(query = "release").loaded(SearchResponse(results = emptyList()))
assertTrue(empty.isEmptyResult())
// Still loading: not the empty state.
assertFalse(empty.editing("release2").isEmptyResult())
// A failure is an error, not an empty result.
assertFalse(SearchUiState(query = "release").failed("boom").isEmptyResult())
assertEquals(
"No matches for \"release\".",
searchPanelEmptyMessage(empty, emptyList(), SearchKindFilter.All),
)
// A filter that empties the list names itself rather than the generic line.
val pipelineOnly = empty.copy(results = listOf(hit(Protocol.SEARCH_KIND_PIPELINE)))
assertEquals(
"No runs match \"release\".",
searchPanelEmptyMessage(pipelineOnly, emptyList(), SearchKindFilter.Runs),
)
// Rows shown: no message. Still loading, blank query or an error: no message
// (the panel shows progress, nothing, or the error respectively).
val shown = listOf(hit(Protocol.SEARCH_KIND_RUN))
assertNull(searchPanelEmptyMessage(empty.copy(results = shown), shown, SearchKindFilter.All))
assertNull(searchPanelEmptyMessage(empty.editing("release2"), emptyList(), SearchKindFilter.All))
assertNull(searchPanelEmptyMessage(SearchUiState(query = ""), emptyList(), SearchKindFilter.All))
assertNull(searchPanelEmptyMessage(empty.failed("boom"), emptyList(), SearchKindFilter.All))
}
// ---- Fixtures ----------------------------------------------------------
@@ -265,6 +429,17 @@ class OmniSearchResultsTest {
else -> SearchResult(kind = kind, target = "")
}
private fun hitWithRecency(kind: String, recency: String?): SearchResult =
hit(kind).copy(recency = recency)
private fun artifactHit(contentType: String, name: String): SearchResult = SearchResult(
kind = Protocol.SEARCH_KIND_ARTIFACT,
artifact = SearchArtifact(name = name, contentType = contentType),
)
private fun artifactGlyph(contentType: String, name: String): ImageVector =
searchResultIcon(artifactHit(contentType, name))
private fun results(): List<SearchResult> = listOf(
Protocol.SEARCH_KIND_PIPELINE,
Protocol.SEARCH_KIND_VERSION,
@@ -0,0 +1,107 @@
package net.awan.pipelines.ui.chat
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.assertTrue
import org.junit.Test
/**
* Closing a chat: the server-side finish (shared by every client) marks the row
* closed, keeps it as history, settles a running turn, and can be reversed by a
* reopen or a prompt. Driven against [ChatStore] with no device or server.
*/
class ChatCloseTest {
private fun session(
id: String,
title: String = id,
closed: Boolean = false,
closedAt: Long = 0,
) = ChatSession(
id = id,
title = title,
tag = ChatProtocol.TAG_OPERATOR,
directory = "/home/op",
closed = closed,
closedAt = closedAt,
)
@Test
fun closingMarksTheRowClosedAndKeepsItAsHistory() {
val store = ChatStore()
store.sessionsLoaded(listOf(session("a"), session("b")))
store.sessionClosed("a", 1_700_000_000_000)
// Still in the server list (nothing deleted), but no longer active.
assertEquals(listOf("a", "b"), store.value.sessions.map { it.id })
assertEquals(listOf("b"), store.value.activeSessions.map { it.id })
val closed = store.value.closedSessions.single()
assertEquals("a", closed.id)
assertTrue(closed.closed)
assertEquals(1_700_000_000_000, closed.closedAt)
}
@Test
fun reopeningReturnsTheChatToTheActiveList() {
val store = ChatStore()
store.sessionsLoaded(listOf(session("a"), session("b")))
store.sessionClosed("a", 1_700_000_000_000)
store.sessionReopened("a")
assertEquals(listOf("a", "b"), store.value.activeSessions.map { it.id })
assertTrue(store.value.closedSessions.isEmpty())
assertFalse(store.value.sessions.first { it.id == "a" }.closed)
assertEquals(0, store.value.sessions.first { it.id == "a" }.closedAt)
}
@Test
fun closingSettlesARunningThreadAndMarksItClosed() {
val store = ChatStore()
store.sessionsLoaded(listOf(session("a")))
store.open(session("a"))
store.running("a", true)
store.sessionClosed("a", 1_700_000_000_000)
val thread = store.value.thread("a")!!
assertFalse("the stopped turn must not still read as running", thread.running)
assertTrue(thread.closed)
// The conversation is kept: its history is not deleted.
assertTrue(store.value.thread("a") != null)
}
@Test
fun aServerListRefreshCarriesTheClosedStateIntoTheStore() {
val store = ChatStore()
// The list arrives closed (the server is the source of truth).
store.sessionsLoaded(listOf(session("a", closed = true, closedAt = 5), session("b")))
assertEquals(listOf("b"), store.value.activeSessions.map { it.id })
assertEquals(listOf("a"), store.value.closedSessions.map { it.id })
}
@Test
fun aRefreshMarksAnAlreadyOpenThreadClosed() {
val store = ChatStore()
store.sessionsLoaded(listOf(session("a")))
store.open(session("a"))
assertFalse(store.value.thread("a")!!.closed)
store.sessionsLoaded(listOf(session("a", closed = true, closedAt = 5)))
assertTrue(store.value.thread("a")!!.closed)
}
@Test
fun theRowStatusReadsClosedAndTheConfirmationSaysWhatCloseDoes() {
assertEquals("Closed", sessionStatusLabel(session("a", closed = true), runningLocally = false))
val wording = closeChatConfirmation("Fix the parser")
assertTrue("names the stop of a running turn", wording.contains("running is stopped"))
assertTrue("says it affects every device", wording.contains("every device"))
assertTrue("says nothing is deleted", wording.contains("Nothing is deleted"))
assertTrue("says it can be reopened", wording.contains("reopen"))
assertTrue("names the chat", wording.contains("Fix the parser"))
}
}
@@ -65,12 +65,11 @@ class ChatFormatTest {
}
@Test
fun sessionStatusReportsRunningBusyAndIdle() {
fun sessionStatusIsRunningOrIdleNeverReadOnly() {
assertEquals("Running", sessionStatusLabel(ChatSession(id = "s"), runningLocally = true))
assertEquals(
"Busy · read-only",
sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false),
)
// The server no longer marks a session Busy for another client, and a
// session is never read-only: the stale flag cannot produce that label.
assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false))
assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s"), runningLocally = false))
}
@@ -0,0 +1,235 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
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.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatTime
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
/**
* The in-flight work a conversation and its session row show: a running tool with
* its name, the command or description the part carries, and a live elapsed time
* that grows from when the call turned running, uses the protocol's own timing
* when the part has it, and clears the moment the call completes or errors. All
* pure or driven against [ChatStore] with an injected clock, so no device, server
* or Compose runtime is needed.
*/
class ChatRunningWorkTest {
private fun tool(
id: String,
name: String,
status: String,
input: JsonObject? = null,
time: ChatTime? = null,
) = ChatPart(
type = ChatProtocol.PART_TOOL,
id = id,
name = name,
state = ChatToolState(status = status, input = input),
time = time,
)
private fun toolFrame(sessionId: String, messageId: String, part: ChatPart) =
ChatEventFrame(sessionId = sessionId, messageId = messageId, kind = ChatProtocol.PART_TOOL, part = part)
private fun input(vararg pairs: Pair<String, String>): JsonObject =
JsonObject(pairs.associate { (key, value) -> key to JsonPrimitive(value) })
private fun threadWith(vararg parts: ChatPart) = ChatThread(
sessionId = "s",
running = true,
messages = listOf(
ChatMessage(
id = "m1",
sessionId = "s",
role = ChatProtocol.ROLE_ASSISTANT,
parts = parts.toList(),
),
),
)
@Test
fun aRunningToolShowsItsNameDetailAndGrowingTime() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.history("s", emptyList())
store.event(
toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls -la"))),
)
val thread = store.value.thread("s")!!
assertTrue(thread.running)
val call = thread.runningTools.single()
assertEquals("shell", call.name)
assertEquals("ls -la", toolDetail(call))
// Elapsed is measured locally from when the call turned running, so it
// starts at zero and grows with the clock.
assertEquals(0L, thread.toolElapsedMillis(call, clock))
clock = 6_000L
val later = thread.toolElapsedMillis(call, clock)
assertEquals(5_000L, later)
assertTrue(later > 0L)
}
@Test
fun aToolWithProtocolTimingUsesItsOwnStart() {
val timed = tool("c1", "bash", ChatProtocol.TOOL_RUNNING, time = ChatTime(created = 900, ran = 1_000))
// The protocol's own `ran` wins over the local stamp, so the elapsed is
// its start to now.
assertEquals(4_000L, runningToolElapsedMillis(timed, startedAt = 0L, nowMillis = 5_000L))
// Neither a protocol start nor a local one: nothing to show, never a guess.
assertEquals(0L, runningToolElapsedMillis(tool("c2", "bash", ChatProtocol.TOOL_RUNNING), 0L, 5_000L))
}
@Test
fun aCompletedOrFailedCallLeavesTheRunningSetAndTheFailureIsVisible() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls"))))
assertEquals(1, store.value.thread("s")!!.runningTools.size)
// Completion clears the call from the in-flight set and drops its stamp.
clock = 2_000L
store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_COMPLETED, input("command" to "ls"))))
val done = store.value.thread("s")!!
assertTrue(done.runningTools.isEmpty())
assertTrue(done.toolStartedAt.isEmpty())
assertFalse(toolFailed(done.messages.last().parts.single().state))
// A failure is out of the running set too, and reads as failed on its chip.
store.event(toolFrame("s", "m1", tool("c2", "shell", ChatProtocol.TOOL_ERROR)))
val failed = store.value.thread("s")!!
assertTrue(failed.runningTools.isEmpty())
assertTrue(toolFailed(failed.messages.last().parts.first { it.id == "c2" }.state))
}
@Test
fun severalCallsRunTogetherInOrderWithStableStartStamps() {
var clock = 1_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
store.event(toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "build"))))
clock = 2_000L
store.event(toolFrame("s", "m1", tool("c2", "grep", ChatProtocol.TOOL_RUNNING, input("pattern" to "TODO"))))
val thread = store.value.thread("s")!!
// Both render, in transcript order, so the list does not flicker between them.
assertEquals(listOf("c1", "c2"), thread.runningTools.map { it.id })
// Each keeps the clock it first turned running on...
assertEquals(mapOf("c1" to 1_000L, "c2" to 2_000L), thread.toolStartedAt)
// ...so a later frame for the first call does not restart its timer.
clock = 3_000L
store.event(
toolFrame("s", "m1", tool("c1", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "build && test"))),
)
val updated = store.value.thread("s")!!
assertEquals(1_000L, updated.toolStartedAt["c1"])
clock = 11_000L
assertEquals(10_000L, updated.toolElapsedMillis(updated.runningTools.single { it.id == "c1" }, clock))
}
@Test
fun aCallWithoutADescriptionStillRendersNameStatusAndTime() {
var clock = 5_000L
val store = ChatStore(now = { clock })
store.open(ChatSession(id = "s", title = "s"))
// No input at all: the part carries no description to show.
store.event(toolFrame("s", "m1", tool("c1", "task", ChatProtocol.TOOL_RUNNING)))
val call = store.value.thread("s")!!.runningTools.single()
assertNull(toolDetail(call))
assertEquals("task", toolLabel(call))
assertTrue(ChatProtocol.toolRunning(call.state))
clock = 9_000L
assertEquals(4_000L, store.value.thread("s")!!.toolElapsedMillis(call, clock))
}
@Test
fun toolDetailPrefersDescriptionThenCommandAndIgnoresWhatItCannotRead() {
// A description wins over a command when both are present.
assertEquals(
"Summarise the diff",
toolDetail(
tool(
"c1", "task", ChatProtocol.TOOL_RUNNING,
input("description" to "Summarise the diff", "command" to "git diff"),
),
),
)
// A shell's command is next.
assertEquals(
"ls -la",
toolDetail(tool("c2", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "ls -la"))),
)
// A file tool's path is shown when nothing more descriptive exists.
assertEquals(
"/tmp/a.txt",
toolDetail(tool("c3", "read", ChatProtocol.TOOL_RUNNING, input("filePath" to "/tmp/a.txt"))),
)
// A multi-line command collapses to a single line.
assertEquals(
"run this",
toolDetail(tool("c4", "shell", ChatProtocol.TOOL_RUNNING, input("command" to "run\n this"))),
)
// A partial (not-yet-object) input, a missing state, and an input with no
// known key all show nothing rather than something invented.
assertNull(
toolDetail(
ChatPart(
type = ChatProtocol.PART_TOOL,
id = "c5",
name = "shell",
state = ChatToolState(status = ChatProtocol.TOOL_STREAMING, input = JsonPrimitive("{\"command\"")),
),
),
)
assertNull(toolDetail(ChatPart(type = ChatProtocol.PART_TOOL, id = "c6", name = "shell")))
assertNull(toolDetail(tool("c7", "shell", ChatProtocol.TOOL_RUNNING, input("foo" to "bar"))))
}
@Test
fun aCallRunningTooLongIsMarked() {
assertFalse(toolLongRunning(TOOL_LONG_RUNNING_MILLIS - 1))
assertTrue(toolLongRunning(TOOL_LONG_RUNNING_MILLIS))
}
@Test
fun theSessionRowReportsWhatIsRunning() {
assertEquals("Running shell", sessionWorkLabel(busy = false, threadWith(tool("c1", "shell", ChatProtocol.TOOL_RUNNING))))
assertEquals(
"Running 2 tools",
sessionWorkLabel(
busy = false,
threadWith(
tool("c1", "shell", ChatProtocol.TOOL_RUNNING),
tool("c2", "grep", ChatProtocol.TOOL_RUNNING),
),
),
)
// A turn running with no tool yet reads as plain Running, never idle, so a
// text stream and a parked tool call stay distinguishable.
assertEquals("Running", sessionWorkLabel(busy = false, ChatThread(sessionId = "s", running = true)))
assertEquals("Running", sessionWorkLabel(busy = true, ChatThread(sessionId = "s", running = true)))
// Nothing running falls back to the ordinary busy/idle label.
assertEquals("Busy · read-only", sessionWorkLabel(busy = true, thread = null))
assertEquals("Idle", sessionWorkLabel(busy = false, thread = null))
assertEquals("Idle", sessionWorkLabel(busy = false, ChatThread(sessionId = "s")))
}
}
@@ -113,19 +113,15 @@ class MultiChatStateTest {
}
@Test
fun busySessionIsReadOnlyAndCannotSend() {
fun busySessionStaysWritable() {
val store = ChatStore()
// Another client watching the session never makes it read-only: the
// server fans the stream out and accepts a prompt from any client.
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)
assertTrue(thread.canSend)
assertTrue(thread.busy)
}
@Test
@@ -192,10 +188,9 @@ class MultiChatStateTest {
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.
// A turn in flight (ours or another client's) keeps the session writable.
store.draft("a", "next prompt")
val thread = store.value.thread("a")!!
assertFalse(thread.readOnly)
assertTrue(thread.canSend)
}
@@ -229,4 +224,78 @@ class MultiChatStateTest {
assertFalse(store.value.open.any { it.sessionId == "a" })
assertTrue(store.value.open.any { it.sessionId == "b" })
}
@Test
fun remoteUserFrameIsFoldedOnceAndAttributed() {
val store = ChatStore()
store.open(session("a"))
// The operator's own message, appended locally when sent.
store.appendLocalUserMessage("a", "mine")
// Another client's prompt arrives live, attributed to that device.
val frame = ChatEventFrame(
sessionId = "a",
messageId = "usr_7",
kind = ChatProtocol.EVENT_USER,
client = "Pixel 10 Pro Fold",
part = ChatPart(type = ChatProtocol.PART_TEXT, text = "from the fold"),
)
store.event(frame)
val messages = store.value.thread("a")!!.messages
assertEquals(2, messages.size)
assertEquals("mine", messages[0].parts.single().text)
assertEquals(ChatProtocol.ROLE_USER, messages[1].role)
assertEquals("Pixel 10 Pro Fold", messages[1].client)
assertEquals("from the fold", messages[1].parts.single().text)
// A replayed frame (e.g. after a reconnect) is folded once, not twice.
store.event(frame)
assertEquals(2, store.value.thread("a")!!.messages.size)
}
@Test
fun remoteAnswerClearsTheApprovalCard() {
val store = ChatStore()
store.open(session("a"))
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "req_1", action = "bash"))
val open = approvalCard(store.value.thread("a")!!.permission, store.value.thread("a")!!.permissionAnswer)!!
assertTrue("the card is answerable while the request is open", open.actionable)
// Another client answered: the server pushes the resolved frame, which
// clears this client's card and shows the outcome without ever disabling
// it while the first answer was in flight.
store.permission(
ChatPermissionFrame(
sessionId = "a",
requestId = "req_1",
action = "bash",
resolved = true,
decision = ChatProtocol.DECISION_ONCE,
resolvedBy = "Pixel 9 Pro XL",
),
)
val thread = store.value.thread("a")!!
val cleared = approvalCard(thread.permission, thread.permissionAnswer)!!
assertFalse("a resolved request offers no controls", cleared.actionable)
assertEquals(ApprovalState.RESOLVED, cleared.state)
assertEquals(ChatProtocol.DECISION_ONCE, cleared.decision)
}
@Test
fun queuedPromptIsShownUntilTheTurnStreams() {
val store = ChatStore()
store.open(session("a"))
store.setQueued("a", true)
assertTrue(store.value.thread("a")!!.queued)
// The queued turn's first frame means it is running, so the marker clears.
store.event(
ChatEventFrame(
sessionId = "a",
messageId = "m1",
kind = ChatProtocol.PART_TEXT,
delta = "hi",
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "m1#0"),
),
)
assertFalse(store.value.thread("a")!!.queued)
}
}
@@ -11,14 +11,18 @@ class RunStatusTest {
assertEquals(RunState.Queued, runStateOf("queued"))
assertEquals(RunState.Waiting, runStateOf("waiting"))
assertEquals(RunState.Active, runStateOf("active"))
assertEquals(RunState.Waiting, runStateOf("waiting"))
assertEquals(RunState.Succeeded, runStateOf("succeeded"))
// Step/outcome words map onto the same states.
// Step/outcome words map onto the same states, so one word is one colour.
assertEquals(RunState.Succeeded, runStateOf("completed"))
assertEquals(RunState.Succeeded, runStateOf("success"))
assertEquals(RunState.Succeeded, runStateOf("done"))
assertEquals(RunState.Failed, runStateOf("failed"))
assertEquals(RunState.Failed, runStateOf("error"))
assertEquals(RunState.Canceled, runStateOf("canceled"))
assertEquals(RunState.Interrupted, runStateOf("interrupted"))
assertEquals(RunState.Blocked, runStateOf("blocked"))
assertEquals(RunState.Skipped, runStateOf("skipped"))
}
@Test
@@ -74,4 +74,17 @@ class ArtifactTypeTest {
val glyphs = ArtifactKind.entries.map { artifactIcon(it) }
assertEquals(ArtifactKind.entries.size, glyphs.toSet().size)
}
@Test
fun everyKindHasAWordThatNamesIt() {
// The search surface names an artifact by this word for a screen reader;
// it must exist for every kind and be distinct.
assertEquals("Image", artifactKindLabel(ArtifactKind.Image))
assertEquals("PDF", artifactKindLabel(ArtifactKind.Pdf))
assertEquals("JSON", artifactKindLabel(ArtifactKind.Json))
assertEquals("Document", artifactKindLabel(ArtifactKind.Document))
assertEquals("File", artifactKindLabel(ArtifactKind.Other))
val labels = ArtifactKind.entries.map { artifactKindLabel(it) }
assertEquals(ArtifactKind.entries.size, labels.toSet().size)
}
}
@@ -5,6 +5,9 @@ import net.awan.pipelines.data.protocol.GraphEdge
import net.awan.pipelines.data.protocol.GraphRoute
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -15,9 +18,9 @@ class GraphPaletteTest {
/** The dark Pipelines surface the outcome label chip is drawn on. */
private val darkSurface = Color(0xFF0E1513)
/** The two terminal roles as the dark scheme supplies them. */
private val successRole = Color(0xFFF2C879)
private val errorRole = Color(0xFFFFB4AB)
/** The two terminal roles are the shared run-status colours. */
private val successRole = runStateColor(RunState.Succeeded)
private val errorRole = runStateColor(RunState.Failed)
private fun colors() = GraphColors(
success = successRole,
@@ -43,11 +46,39 @@ class GraphPaletteTest {
"exhausted", "retry", "approved", "fast", "missing", "done",
)
/** The outcomes with no run-status meaning that the graph palette owns. */
private val graphOnlyOutcomes = listOf(
"rejected", "exhausted", "retry", "approved", "fast", "missing",
)
/**
* A word that is a run state resolves to exactly the colour the runs list
* draws for it: the graph factory and [outcomeColor] share one source.
*/
@Test
fun everyRealisticOutcomeGetsADistinctColour() {
fun statusOutcomesTakeTheSharedRunStatusColour() {
val colors = colors()
val mapped = realisticOutcomes.map { outcomeColor(it, colors) }
assertEquals(realisticOutcomes.size, mapped.toSet().size)
listOf(
"success", "completed", "done", "error", "failed",
"blocked", "skipped", "waiting", "running", "queued",
"canceled", "interrupted",
).forEach { word ->
assertEquals(
"outcomeColor($word) must equal the runs-list colour",
runStateColor(runStateOf(word)),
outcomeColor(word, colors),
)
}
}
/** The graph-only outcomes keep distinct curated colours, none a status colour. */
@Test
fun graphOnlyOutcomesGetDistinctColours() {
val colors = colors()
val mapped = graphOnlyOutcomes.map { outcomeColor(it, colors) }
assertEquals(graphOnlyOutcomes.size, mapped.toSet().size)
val statusColours = RunState.entries.map { runStateColor(it) }.toSet()
mapped.forEach { assertFalse("$it borrowed a run-status colour", it in statusColours) }
}
@Test
@@ -74,10 +105,8 @@ class GraphPaletteTest {
assertEquals(unknown, outcomeColor("something-brand-new", colors))
// A blank name is just another unknown: stable and non-throwing.
assertEquals(outcomeColor("", colors), outcomeColor("", colors))
// The fallback comes from the reserved region, not a known outcome slot.
val knownIndices = realisticOutcomes
.filter { it != "success" && it != "error" }
.map { GraphPalette.outcomeColorIndex(it) }
// The fallback comes from the reserved region, not a known graph-only slot.
val knownIndices = graphOnlyOutcomes.map { GraphPalette.outcomeColorIndex(it) }
assertFalse(GraphPalette.outcomeColorIndex("something-brand-new") in knownIndices)
}
@@ -0,0 +1,57 @@
package net.awan.pipelines.ui.graph
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.runStateColor
import net.awan.pipelines.ui.components.runStateOf
import net.awan.pipelines.ui.theme.PipelinesDarkColors
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* The one-colour contract behind the status brief: whatever draws a status or a
* stage outcome — the runs list, the timeline's step chips, the graph, the stage
* sheet — resolves a word through one owned source, so a word means one colour
* everywhere and never a second colour for the same meaning.
*/
class StatusColorConsistencyTest {
private val colors = graphColors(PipelinesDarkColors)
/**
* Every word the timeline can show that is a run state resolves, through the
* graph factory the timeline uses, to exactly the runs-list colour.
*/
@Test
fun theTimelineColourComesFromTheRunsListSource() {
listOf(
"success", "completed", "done", "error", "failed",
"blocked", "skipped", "waiting", "running", "queued",
"canceled", "cancelled", "interrupted", "active",
).forEach { word ->
assertEquals(
"timeline colour for '$word' must be the runs-list colour",
runStateColor(runStateOf(word)),
outcomeColor(word, colors),
)
}
}
/**
* Every state maps to exactly one colour: the lookup is deterministic, and no
* two states collide except the one deliberate alias (a live run and the
* server's `active` usage bucket are the same in-progress state).
*/
@Test
fun everyStateMapsToExactlyOneColour() {
RunState.entries.forEach { state ->
assertEquals(runStateColor(state), runStateColor(state))
}
val shared = RunState.entries
.groupBy { runStateColor(it) }
.filterValues { it.size > 1 }
.values
.map { it.toSet() }
.toSet()
assertEquals(setOf(setOf(RunState.Running, RunState.Active)), shared)
}
}