Merge branch 'main' into lane-srv3

This commit is contained in:
2026-10-17 14:57:28 +01:00
10 changed files with 805 additions and 28 deletions
+142
View File
@@ -5641,3 +5641,145 @@ the counter and the kept file). The APK was republished for this stage as
at `http://10.0.0.75:8080/artifacts/249/3/pipelines-debug-wip-d1a859e.apk`
(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 18470240`).
## New activity in the session list (17 Oct 2026)
With several operator sessions open the list gave no sign of where a reply
arrived: an idle chat and one streaming a reply right now looked the same, so the
operator lost the conversation they were in. A row now signals a transcript the
operator has not read, and a turn streaming right now, distinctly from each other
and from an idle chat; opening a chat clears its mark; and the marks survive a
restart, not only a reconnect. The signal is derived from what the app already
receives — the sessions' own `updated_at` recency and the message ids/timestamps
of pushed chat events and history — so no server request is added for it.
`android/` only; nothing in the Pipelines server, its Go source, the installer or
the Docker files was touched, no dependency was added beyond the already-declared
material-icons-extended, and no run is started from the app.
- **Read state, persisted.** `ui/chat/ChatSeen.kt` adds `ChatSeenState`: a
per-session recency watermark (`seenAt`, the newest `updated_at` the operator
has read) plus the ids that moved on while the app was open (`unseen`). It is
stored as one opaque JSON preference (`SettingsRepository.chat_seen`, observed
by `AppViewModel.observeChatSeen`), exactly like `ChatSessionOverrides`, so a
mark is still there after a restart.
- **Unseen, derived not requested.** `ChatState.isUnseen` marks a session that is
not on screen and either carried a live mark (a pushed frame arrived for it
while it was backgrounded — `ChatStore.event`/`permission` mark any activity for
a chat that is not active) or, if it has never been opened on this device, is
newer than its stored watermark. First sight of a session is seeded to its
current recency (`ChatSeenState.seeded`), so a chat that predates the feature is
not reported as new; a reply that arrived while the app was closed is newer than
the watermark and reads as unseen after a restart. An **open** thread is judged
by its live mark alone, so a conversation the operator has been in is never
re-flagged by a later list refresh — only by activity after they leave it.
- **Opened means read.** `ChatStore.open`/`activate` advance the watermark to the
session's recency and clear its live mark; `history` for the active chat also
advances it to the newest message the server reports; `close` clears a live mark
because a chat the operator had open was read.
- **Three distinguishable states.** `ChatFormat.sessionActivity(running, unseen)`
is the one pure derivation (streaming outranks finished-unseen, which outranks
idle) and `SessionActivityBadge` renders it as a labelled dot: `Streaming`
(tertiary) while a turn is in flight, `New` (primary) once it settles unseen,
and the existing `Open` (outline) otherwise. The kind chip and the directory
line are unchanged beside it — this adds a signal, it does not replace them.
- **Ordering untouched.** The list is still the server's most-recently-used order;
nothing here reorders it.
Tests (`ChatActivityTest`, 5 cases): an unseen session is marked (a pushed frame
for a background chat, and a session newer than the stored watermark with no frame
at all), opening clears the mark from the persisted state too, the pure activity
derivation distinguishes streaming/finished-unseen/idle and the store agrees
across a background turn, and the seen state survives an encode/decode into a
fresh store.
Evidence (this run's implementer pass, macOS, Gradle 9.7.1 `--offline
--no-daemon`, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): `gradle --offline
--no-daemon :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the JUnit XMLs total **54
suites / 492 tests / 0 failures / 0 errors / 0 skipped** (5 new in
`ChatActivityTest`). `gradle --offline --no-daemon :app:assembleDebug` → `BUILD
SUCCESSFUL`; the APK was published to this run's artifacts directory as
`pipelines-debug-wip-5adc961.apk` (18,470,240 bytes, sha256
`0866b7c2c1cfbd51f55bd8a81e3550437553ff542a04de605d7f994060ee63ea`; `5adc961` is
`git rev-parse --short HEAD`, the tree being uncommitted WIP on top of it) and is
served at
`http://10.0.0.75:8080/artifacts/270/1/pipelines-debug-wip-5adc961.apk`
(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 18470240`).
Not verified in this pass: the badge on a device, the wide/narrow layouts, and a
mark surviving a real process restart — the brief keeps implementation
verification to the build and the unit tests, and visual review owns the operator's
Pixel 9 Pro XL. Known limitation: a reply streamed and watched while the chat was
active carries no wall-clock stamp on its pushed frames, so its exact recency is
only learned from the server's history/`updated_at` on a later read; if the app is
killed before that, a restart can conservatively re-flag that chat until it is
opened again. Opening always clears the mark.
## Finding a session among many: search and directory grouping (17 Oct 2026)
The chat list is the operator's own sessions in recency order, but as a day's work
accumulates it is a flat, unsearchable wall and the session that is wanted is the
one that cannot be found. The list can now be narrowed by typing over each chat's
title and directory, sessions of one repository are grouped together, and a
narrowing that matches nothing says so and offers to clear it.
`android/` only; no dependency was added beyond the already-declared
material-icons-extended, nothing in the Pipelines server, its Go source, the
installer or the Docker files was touched, and no run is started from the app.
- **The search control reuses the list-filter pattern.**
`ChatListSearchControl` is the shared `FilterMenu` (the same top-bar icon with
an active-count badge used by the pipelines and runs lists), carrying one
`OutlinedTextField` and a `Clear search` reset. It is not a new control: the
field narrows the list as the operator types and the menu stays open behind it,
exactly like the pipelines name filter.
- **The match rule is one pure derivation.** `ui/chat/ChatListFilter.kt`
adds `sessionMatchesQuery` / `filterChatSessions`: a case-insensitive substring
over the session's title (the local rename included, since it is applied to the
visible list first) and its directory. A blank or whitespace query narrows
nothing, and the survivors keep their incoming order — so the search composes
with the recency order rather than re-sorting it.
- **Same repository, together.** `groupChatSessionsByDirectory` groups the
narrowed sessions by directory, each group keeping the recency order inside it
and the groups ordered by their first (most recent) session, so the top of the
list still leads with the newest activity. The list pane renders a directory
heading per group only when there is more than one directory; a single directory
(or none) stays the flat list, which is already together. Every row still shows
its directory as before.
- **Empty result and the create path.** A narrowing that matches nothing renders
the shared `EmptyState` — `No chats match "<query>".` with a `Clear search`
action — the same empty-state pattern the other lists use. The trailing
`New chat` action is never hidden while the list is narrowed, so creating stays
one tap away.
- **State and marks untouched.** `ChatState.sessionQuery` (set through
`ChatStore.searchSessions` / `AppViewModel.setChatSessionQuery`) is a display
narrowing only: it never touches the server's list or an open conversation, and
the activity marks derive from the same session ids as before.
Tests (`ChatListFilterTest`, 9 cases): the match rule over title and directory
(case-insensitive, blank matches all, a miss is empty), that filtering preserves
the recency order, grouping by directory (order by the first session, order kept
inside a group, a single directory yields one group, a blank directory groups
too), and — through the store — that searching narrows `filteredSessions`,
clearing restores the full list, the server's list is untouched, and a filtered
session still reports its activity mark.
Evidence (this run's implementer pass, macOS, Gradle 8.11.1 at
`~/.gradle/wrapper/dists/gradle-8.11.1-bin/bpt9gzteqjrbo1mjrsomdt32c/gradle-8.11.1/bin/gradle`
with `JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"`
(JDK 17) and `ANDROID_HOME=/Users/alan/Library/Android/sdk`):
`gradle --offline --no-daemon :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the
JUnit XMLs total **55 suites / 501 tests / 0 failures / 0 errors / 0 skipped** (9
new in `ChatListFilterTest`). `gradle --offline --no-daemon :app:assembleDebug` →
`BUILD SUCCESSFUL`; the APK was published to this run's artifacts directory as
`pipelines-debug-wip-bb486ac.apk` (18,486,624 bytes, sha256
`d276f7be66501c7becdd83628e3407f955ec982552a87a6a5146d4f44cb5598d`; `bb486ac` is
`git rev-parse --short HEAD`, the tree being uncommitted WIP on top of it) and is
served at
`http://10.0.0.75:8080/artifacts/271/1/pipelines-debug-wip-bb486ac.apk`
(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 18486624`).
Not verified in this pass: the search field, the directory sections and the
empty state on a device, and the narrow/wide layouts — the brief keeps
implementation verification to the build and the unit tests, and visual review
owns the operator's Pixel 9 Pro XL.
@@ -59,6 +59,12 @@ class SettingsRepository(context: Context) {
private val _chatOverrides = MutableStateFlow(prefs.getString(KEY_CHAT_OVERRIDES, "").orEmpty())
val chatOverrides: StateFlow<String> = _chatOverrides.asStateFlow()
// What the operator has read of the chat session list, stored as one opaque
// JSON string the same way the overrides above are: the chat layer owns the
// shape, so this repository stays unaware of the chat model.
private val _chatSeen = MutableStateFlow(prefs.getString(KEY_CHAT_SEEN, "").orEmpty())
val chatSeen: StateFlow<String> = _chatSeen.asStateFlow()
fun setServerUrl(value: String) {
val trimmed = value.trim()
_serverUrl.value = trimmed
@@ -117,6 +123,12 @@ class SettingsRepository(context: Context) {
prefs.edit().putString(KEY_CHAT_OVERRIDES, value).apply()
}
fun setChatSeen(value: String) {
if (value == _chatSeen.value) return
_chatSeen.value = value
prefs.edit().putString(KEY_CHAT_SEEN, value).apply()
}
/** True only when the user has explicitly supplied both required values. */
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
@@ -132,5 +144,6 @@ class SettingsRepository(context: Context) {
const val KEY_PIPELINE_FILTER_RUN_STATUSES = "pipeline_filter_run_statuses"
const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name"
const val KEY_CHAT_OVERRIDES = "chat_overrides"
const val KEY_CHAT_SEEN = "chat_seen"
}
}
@@ -38,6 +38,7 @@ import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.data.transport.ServerUrl
import net.awan.pipelines.ui.chat.ChatAttachment
import net.awan.pipelines.ui.chat.ChatSessionOverrides
import net.awan.pipelines.ui.chat.ChatSeenState
import net.awan.pipelines.ui.chat.ChatState
import net.awan.pipelines.ui.chat.ChatStore
import net.awan.pipelines.ui.chat.attachmentFiles
@@ -134,7 +135,10 @@ class AppViewModel(
private val retryKeys = ConcurrentHashMap<Long, String>()
/** The multi-chat screen state (sessions, open conversations, drafts, scroll). */
private val chatStore = ChatStore(overrides = ChatSessionOverrides.decode(settings.chatOverrides.value))
private val chatStore = ChatStore(
overrides = ChatSessionOverrides.decode(settings.chatOverrides.value),
seen = ChatSeenState.decode(settings.chatSeen.value),
)
val chat: StateFlow<ChatState> = chatStore.state
// The live run subscription: the workspace currently watched, the job that
@@ -177,6 +181,7 @@ class AppViewModel(
observeRunEvents()
observeConnection()
observeChatOverrides()
observeChatSeen()
}
/**
@@ -475,6 +480,21 @@ class AppViewModel(
}
}
/**
* Persists what the operator has read of the session list (the recency
* watermarks and the live unread marks) as they change, so the marks a chat
* carries are still there after a restart, not only across a reconnect. Only a
* real change is written; the settings repository ignores a repeat, so the
* initial emission is a no-op.
*/
private fun observeChatSeen() {
viewModelScope.launch {
chatStore.state.map { it.seen }.distinctUntilChanged().collect {
settings.setChatSeen(it.encode())
}
}
}
fun updateServerUrlDraft(value: String) {
_serverUrlDraft.value = value
_urlError.value = null
@@ -819,6 +839,14 @@ class AppViewModel(
/** Shows the session list again while keeping every open conversation. */
fun showChatList() = chatStore.showList()
/**
* Narrows the session list to what matches [query] over each chat's title and
* directory, as the operator types. It is a display narrowing only, so no
* request is made and open conversations are untouched; a blank query clears
* it.
*/
fun setChatSessionQuery(query: String) = chatStore.searchSessions(query)
fun closeChat(sessionId: String) = chatStore.close(sessionId)
fun updateChatDraft(sessionId: String, text: String) = chatStore.draft(sessionId, text)
@@ -116,6 +116,25 @@ internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean):
else -> "Idle"
}
/**
* The activity a session row signals beyond its open/tag/directory state. An
* idle session has nothing extra; an unseen one finished since the operator last
* read it; a streaming one is producing a reply right now.
*/
enum class SessionActivity { IDLE, UNSEEN, STREAMING }
/**
* The one derivation of a row's activity, so the badge and its unit test cannot
* disagree: a turn streaming right now outranks a finished-but-unread
* transcript, which outranks an idle session. Kept pure (no Compose, no
* transport) like the other chat formatting.
*/
internal fun sessionActivity(running: Boolean, unseen: Boolean): SessionActivity = when {
running -> SessionActivity.STREAMING
unseen -> SessionActivity.UNSEEN
else -> SessionActivity.IDLE
}
/** Which action the composer's single primary control offers for a chat. */
enum class ComposerAction { Send, Stop }
@@ -0,0 +1,53 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatSession
/**
* The session-list narrowing: a case-insensitive substring the operator types to
* find a chat by what it is called or where it lives. Blank narrows nothing, and
* the list's own recency order is never touched — filtering keeps the order the
* server returned (and the operator's local overrides applied on top).
*
* Kept pure (no Compose, no transport) like the other chat formatting, so the
* match rule and its unit test share one derivation.
*/
internal fun sessionMatchesQuery(session: ChatSession, query: String): Boolean {
val needle = query.trim()
if (needle.isEmpty()) return true
return sessionTitle(session).contains(needle, ignoreCase = true) ||
session.directory.contains(needle, ignoreCase = true)
}
/**
* Narrows [sessions] to those matching [query] over their title and directory. A
* blank query changes nothing, and the surviving sessions keep their original
* relative order, so a narrowing composes with the recency order rather than
* re-sorting it.
*/
internal fun filterChatSessions(sessions: List<ChatSession>, query: String): List<ChatSession> =
if (query.isBlank()) sessions else sessions.filter { sessionMatchesQuery(it, query) }
/**
* One run of sessions sharing one directory, so sessions of the same repository
* can be placed together while each keeps its recency position inside the run.
*/
data class ChatSessionGroup(val directory: String, val sessions: List<ChatSession>)
/**
* Groups [sessions] by directory, so sessions in the same repository sit together.
* The sessions keep their incoming recency order (within each group), and the
* groups themselves are ordered by the first — most recent — session they contain,
* so the top of the list still leads with the newest activity. A blank directory is
* a group of its own, labelled by the row as usual.
*
* The caller renders the groups as sections only when there is more than one;
* with a single directory the flat list is already "together".
*/
internal fun groupChatSessionsByDirectory(sessions: List<ChatSession>): List<ChatSessionGroup> {
if (sessions.isEmpty()) return emptyList()
val order = LinkedHashMap<String, MutableList<ChatSession>>()
for (session in sessions) {
order.getOrPut(session.directory) { mutableListOf() }.add(session)
}
return order.map { (directory, grouped) -> ChatSessionGroup(directory, grouped) }
}
@@ -119,6 +119,8 @@ import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.FilterMenu
import net.awan.pipelines.ui.components.FilterSectionHeader
import net.awan.pipelines.ui.components.LabelChip
import net.awan.pipelines.ui.components.ListRow
import net.awan.pipelines.ui.components.LoadingState
@@ -136,6 +138,7 @@ import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.ICON_LIST_DP
import net.awan.pipelines.ui.theme.ICON_STATUS_DP
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP
import net.awan.pipelines.ui.theme.pipelinesText
@@ -256,8 +259,12 @@ private 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.
val sessions = state.visibleSessions
// belongs to a run. The operator's search narrows that list without touching
// its order, and the survivors are grouped by directory when there is more
// than one so sessions in the same repository sit together.
val sessions = state.filteredSessions
val groups = groupChatSessionsByDirectory(sessions)
val query = state.sessionQuery
// A removal is reported for what it is: a local, undoable change, never a
// pretend delete — the server is not asked to remove anything.
@@ -282,9 +289,12 @@ private fun ChatListPane(
TopAppBar(
title = { Text("Chat") },
actions = {
ChatListSearchControl(query = query, onQuery = vm::setChatSessionQuery)
IconButton(onClick = vm::refreshChatSessions) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh chats")
}
// The create path stays one tap away while the list is
// narrowed: it is the same trailing action, never hidden.
IconButton(onClick = vm::startNewChat) {
Icon(Icons.Default.Add, contentDescription = "New chat")
}
@@ -304,27 +314,37 @@ private fun ChatListPane(
NotConnectedNotice()
}
when {
state.sessionsLoading && sessions.isEmpty() -> LoadingState("Loading chats…")
state.sessionsError != null && sessions.isEmpty() -> {
state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…")
state.sessionsError != null && state.sessions.isEmpty() -> {
ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions)
}
sessions.isEmpty() && query.isNotBlank() -> EmptyState(
// A narrowing that matches nothing says so plainly and offers
// to clear it, the same empty-state pattern the other lists use.
message = "No chats match \"${query.trim()}\".",
actionLabel = "Clear search",
onAction = { vm.setChatSessionQuery("") },
)
sessions.isEmpty() -> EmptyState(
message = "No chat sessions on this server yet.",
actionLabel = "New chat",
onAction = vm::startNewChat,
)
else -> LazyColumn(Modifier.fillMaxSize()) {
items(sessions, key = { it.id }) { session ->
val thread = state.thread(session.id)
SessionRow(
session = session,
open = thread != null,
running = thread?.running == true,
active = state.activeId == session.id,
onClick = { vm.openChatSession(session) },
onRename = { renaming = session },
onRemove = { vm.removeChat(session.id) },
)
if (groups.size > 1) {
// More than one directory: one section per repository so
// same-directory chats sit together, each keeping the
// recency order inside it.
groups.forEach { group ->
item(key = "dir-" + group.directory) { DirectoryHeader(group.directory) }
items(group.sessions, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it })
}
}
} else {
items(sessions, key = { it.id }) { session ->
SessionListItem(state, session, vm, onRename = { renaming = it })
}
}
if (state.sessionsError != null) {
item("error") {
@@ -353,17 +373,92 @@ private fun ChatListPane(
}
}
/**
* The session-list search control: the same top-bar filter-menu pattern the other
* lists use, with one free-text field that narrows the list by title and directory
* as the operator types. The active-count badge and the reset action report and
* clear the narrowing, and the create action beside it is never hidden.
*/
@Composable
private fun ChatListSearchControl(query: String, onQuery: (String) -> Unit) {
FilterMenu(
activeCount = if (query.isBlank()) 0 else 1,
contentDescription = "Search chats",
resetLabel = "Clear search",
onReset = { onQuery("") },
) {
FilterSectionHeader("Search")
OutlinedTextField(
value = query,
onValueChange = onQuery,
label = { Text("Title or directory contains") },
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_M, vertical = SPACING_S),
)
}
}
/**
* One session of the list, whether it is rendered flat or inside a directory
* section: [SessionRow] fed from the live [state], so the activity marks, the open
* flag and the rename/remove actions are identical in both layouts.
*/
@Composable
private fun SessionListItem(
state: ChatState,
session: ChatSession,
vm: AppViewModel,
onRename: (ChatSession) -> Unit,
) {
val thread = state.thread(session.id)
SessionRow(
session = session,
open = thread != null,
running = thread?.running == true,
unseen = state.isUnseen(session),
active = state.activeId == session.id,
onClick = { vm.openChatSession(session) },
onRename = { onRename(session) },
onRemove = { vm.removeChat(session.id) },
)
}
/**
* The heading of one directory section. The directory is shown here as well as on
* every row, so the grouping is legible even after a row scrolls out of view.
*/
@Composable
private fun DirectoryHeader(directory: String) {
Text(
text = directory.ifBlank { NO_DIRECTORY_LABEL },
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
)
}
/** The section heading for sessions the server reported without a directory. */
private const val NO_DIRECTORY_LABEL = "No directory"
@Composable
private fun SessionRow(
session: ChatSession,
open: Boolean,
running: Boolean,
unseen: Boolean,
active: Boolean,
onClick: () -> Unit,
onRename: () -> Unit,
onRemove: () -> Unit,
) {
val texts = pipelinesText()
val activity = sessionActivity(running, unseen)
ListRow(selected = active, onClick = onClick) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -380,7 +475,9 @@ 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) }
if (open) SessionBadge("Open", running)
// The activity badge is the new-activity signal; the tag and the
// directory below are unchanged beside it.
SessionActivityBadge(activity, open)
SessionMenu(onRename = onRename, onRemove = onRemove)
}
val meta = buildList {
@@ -596,11 +693,16 @@ private const val CHAT_REMOVED_MESSAGE = "Removed from this list; the chat stays
/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */
@Composable
private fun SessionBadge(label: String, running: Boolean = false) {
val color = when {
running -> MaterialTheme.colorScheme.tertiary
label == "Open" -> MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.outline
private fun SessionActivityBadge(activity: SessionActivity, open: Boolean) {
val label = when (activity) {
SessionActivity.STREAMING -> "Streaming"
SessionActivity.UNSEEN -> "New"
SessionActivity.IDLE -> if (open) "Open" else return
}
val color = when (activity) {
SessionActivity.STREAMING -> MaterialTheme.colorScheme.tertiary
SessionActivity.UNSEEN -> MaterialTheme.colorScheme.primary
SessionActivity.IDLE -> MaterialTheme.colorScheme.outline
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color))
@@ -0,0 +1,78 @@
package net.awan.pipelines.ui.chat
import kotlinx.serialization.Serializable
import net.awan.pipelines.data.protocol.PipelinesJson
/**
* What the operator has already seen of the session list, derived from data the
* app already receives — the sessions' own `updated_at` recency and the message
* ids/timestamps of the pushed chat events and history — so no server request is
* added to tell a chat with new activity from an idle one.
*
* - [seenAt] is the recency watermark per session: the newest `updated_at` the
* operator has seen. A session the operator has never opened is compared
* against it, so a reply that arrived while the app was closed (a newer
* `updated_at`) still reads as unseen after a restart. First sight of a session
* is seeded, so a chat that predates this feature is not reported as new.
* - [unseen] is the session ids that moved on while the app was open (a pushed
* frame for a chat that is not on screen). It is kept explicitly because a
* live stream carries no wall-clock stamp to compare, and it is what survives a
* restart for a chat whose server recency has not been re-read yet.
*
* Kept as a serializable value so it survives a restart as one preference,
* exactly like the app's other stored chat state ([ChatSessionOverrides]).
*/
@Serializable
data class ChatSeenState(
val seenAt: Map<String, Long> = emptyMap(),
val unseen: Set<String> = emptySet(),
) {
/** The newest recency the operator has seen for [id], or 0 when never seen. */
fun watermark(id: String): Long = seenAt[id] ?: 0L
/** True when [updatedAt] is newer than everything seen for [id]. */
fun isNewer(id: String, updatedAt: Long): Boolean = updatedAt > watermark(id)
/**
* Records the first sight of [id] at [updatedAt]: its baseline recency, so a
* pre-existing chat is not reported as new activity. A session already known
* (or with no recency to record) is left untouched, and an explicit [unseen]
* mark is never cleared here — this only opens a baseline, it does not read.
*/
fun seeded(id: String, updatedAt: Long): ChatSeenState =
if (id.isBlank() || updatedAt <= 0 || watermark(id) != 0L) this
else copy(seenAt = seenAt + (id to updatedAt))
/**
* Records that [id] has been read up to [updatedAt]: its watermark advances
* (never rewinds, so a stale list cannot un-read it) and any [unseen] mark is
* cleared. Called when the operator opens a conversation.
*/
fun read(id: String, updatedAt: Long): ChatSeenState {
if (id.isBlank()) return this
val advanced = updatedAt > watermark(id)
if (!advanced && id !in unseen) return this
return copy(
seenAt = if (advanced) seenAt + (id to updatedAt) else seenAt,
unseen = unseen - id,
)
}
/** Marks [id] as having moved on while it was not on screen. */
fun unread(id: String): ChatSeenState =
if (id.isBlank() || id in unseen) this else copy(unseen = unseen + id)
/** The one-line JSON this value is stored as; never fails on our own value. */
fun encode(): String = PipelinesJson.encodeToString(serializer(), this)
companion object {
/** Decodes a stored value; anything unreadable falls back to nothing seen. */
fun decode(stored: String): ChatSeenState =
if (stored.isBlank()) {
ChatSeenState()
} else {
runCatching { PipelinesJson.decodeFromString(serializer(), stored) }
.getOrDefault(ChatSeenState())
}
}
}
@@ -157,11 +157,32 @@ data class ChatState(
val overrides: ChatSessionOverrides = ChatSessionOverrides(),
/** The id of the session most recently removed, while its removal can be undone. */
val lastRemoved: String? = null,
/** What the operator has read of the list (see [ChatSeenState]). */
val seen: ChatSeenState = ChatSeenState(),
/**
* The operator's search over the list: free text matched against each
* session's title and directory (see [sessionMatchesQuery]). Blank narrows
* nothing, so the default list is the server's order unchanged.
*/
val sessionQuery: String = "",
) {
val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId }
fun thread(sessionId: String): ChatThread? = open.firstOrNull { it.sessionId == sessionId }
/**
* Whether [session]'s transcript has moved on unseen: a session that is not
* on screen and either carried a live mark (a push arrived while it was
* backgrounded) or, if it has never been opened here, is newer than the
* recency watermark. An open thread is judged by its live mark alone, so a
* conversation the operator has been in is never re-marked by a later list
* refresh — only by new activity after they leave it.
*/
fun isUnseen(session: ChatSession): Boolean =
session.id != activeId &&
(session.id in seen.unseen ||
(thread(session.id) == null && seen.isNewer(session.id, session.updatedAt)))
/**
* The sessions the list shows: the server's list with the operator's own
* local changes applied — a removed chat is hidden and a renamed one shows its
@@ -193,6 +214,15 @@ data class ChatState(
val hiddenIds = overrides.hiddenIds
sessions.count { it.id !in hiddenIds }
}
/**
* The sessions the list shows after the operator's own changes and their
* search: [visibleSessions] narrowed by [sessionQuery], in the same order, so
* the search composes with the recency order instead of re-sorting it. The
* list pane groups the result by directory (see [groupChatSessionsByDirectory]).
*/
val filteredSessions: List<ChatSession>
get() = filterChatSessions(visibleSessions, sessionQuery)
}
/**
@@ -214,9 +244,10 @@ data class ChatState(
class ChatStore(
private val now: () -> Long = System::currentTimeMillis,
overrides: ChatSessionOverrides = ChatSessionOverrides(),
seen: ChatSeenState = ChatSeenState(),
) {
private val _state = MutableStateFlow(ChatState(overrides = overrides))
private val _state = MutableStateFlow(ChatState(overrides = overrides, seen = seen))
val state: StateFlow<ChatState> = _state.asStateFlow()
val value: ChatState get() = _state.value
@@ -242,6 +273,16 @@ class ChatStore(
_state.value = _state.value.copy(sessionsLoading = false, sessionsError = message)
}
/**
* Narrows the list by the operator's search text. It is a display narrowing
* only: the server's list and every open conversation are untouched, and a
* blank [query] restores the full, recency-ordered list.
*/
fun searchSessions(query: String) {
if (query == _state.value.sessionQuery) return
_state.value = _state.value.copy(sessionQuery = query)
}
/**
* Replaces the server's session list and folds its title/busy flags into any
* already-open thread, so a status change is reflected without dropping the
@@ -260,9 +301,22 @@ class ChatStore(
busy = session.busy,
)
}
// Fold the read state in: the active conversation is on screen, so its
// current recency is read; every session seen for the first time is seeded
// so a pre-existing chat is never reported as new activity. A session whose
// recency is now newer than its watermark stays unseen by the model, with
// no extra bookkeeping.
val activeId = _state.value.activeId
val seen = sessions.fold(_state.value.seen) { acc, session ->
when {
session.id == activeId -> acc.read(session.id, session.updatedAt)
else -> acc.seeded(session.id, session.updatedAt)
}
}
_state.value = _state.value.copy(
sessions = sessions,
open = open,
seen = seen,
sessionsLoading = false,
sessionsLoaded = true,
sessionsError = null,
@@ -382,6 +436,9 @@ class ChatStore(
// A local rename always wins over the server's title, whether the thread
// is new or already open.
val title = _state.value.overrides.titles[session.id] ?: session.title
// Opening reads the transcript: its current recency is seen and any
// unread mark is cleared, whether the thread is new or being returned to.
val seen = _state.value.seen.read(session.id, session.updatedAt)
if (existing == null) {
val thread = ChatThread(
sessionId = session.id,
@@ -392,7 +449,7 @@ class ChatStore(
updatedAt = session.updatedAt,
busy = session.busy,
)
_state.value = _state.value.copy(open = _state.value.open + thread, activeId = session.id)
_state.value = _state.value.copy(open = _state.value.open + thread, activeId = session.id, seen = seen)
return true
}
val merged = existing.copy(
@@ -403,6 +460,7 @@ class ChatStore(
_state.value = _state.value.copy(
open = _state.value.open.map { if (it.sessionId == session.id) merged else it },
activeId = session.id,
seen = seen,
)
return needsResync(merged)
}
@@ -414,14 +472,27 @@ class ChatStore(
*/
fun activate(sessionId: String): Boolean {
val thread = _state.value.thread(sessionId) ?: return false
_state.value = _state.value.copy(activeId = sessionId)
// Returning to a chat reads it, so a live unread mark clears; the
// watermark advances to the session's recency when the list knows it.
val session = _state.value.sessions.firstOrNull { it.id == sessionId }
val seen = _state.value.seen.read(sessionId, session?.updatedAt ?: 0L)
_state.value = _state.value.copy(activeId = sessionId, seen = seen)
return needsResync(thread)
}
fun close(sessionId: String) {
// Closing a chat the operator had open is still having read it, so a live
// unread mark clears rather than reappearing once the thread is gone.
val thread = _state.value.thread(sessionId)
val session = _state.value.sessions.firstOrNull { it.id == sessionId }
val seen = if (thread != null) {
_state.value.seen.read(sessionId, maxOf(thread.updatedAt, session?.updatedAt ?: 0L))
} else {
_state.value.seen
}
val open = _state.value.open.filterNot { it.sessionId == sessionId }
val active = if (_state.value.activeId == sessionId) open.lastOrNull()?.sessionId else _state.value.activeId
_state.value = _state.value.copy(open = open, activeId = active)
_state.value = _state.value.copy(open = open, activeId = active, seen = seen)
}
/**
@@ -498,8 +569,17 @@ class ChatStore(
* The running flag is left as-is: history alone cannot say whether a turn is
* still in flight.
*/
fun history(sessionId: String, messages: List<ChatMessage>) = update(sessionId) {
it.copy(messages = messages, loading = false, loaded = true, error = null)
fun history(sessionId: String, messages: List<ChatMessage>) {
update(sessionId) {
it.copy(messages = messages, loading = false, loaded = true, error = null)
}
// A conversation on screen is read as its history arrives: its recency
// watermark advances to the newest message the server reports (its own
// wall clock), so a later restart does not re-flag what was just watched.
if (sessionId == _state.value.activeId) {
val session = _state.value.sessions.firstOrNull { it.id == sessionId }
markRead(sessionId, maxOf(messages.lastOrNull()?.createdAt ?: 0L, session?.updatedAt ?: 0L))
}
}
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
@@ -554,6 +634,9 @@ class ChatStore(
permissionAnswer = if (sameRequest) it.permissionAnswer else "",
)
}
// A request waiting on the operator is activity they have not seen yet, so
// a background chat that raises one is marked just like a reply.
markUnread(frame.sessionId)
}
/**
@@ -614,6 +697,7 @@ class ChatStore(
fun event(frame: ChatEventFrame) {
if (frame.sessionId.isBlank()) return
ensureThread(frame.sessionId)
markUnread(frame.sessionId)
when (frame.kind) {
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
ChatProtocol.PART_TOOL -> applyTool(frame)
@@ -705,6 +789,23 @@ class ChatStore(
)
}
/** Advances the read watermark for [sessionId]; a no-op when nothing changed. */
private fun markRead(sessionId: String, updatedAt: Long) {
val seen = _state.value.seen.read(sessionId, updatedAt)
if (seen !== _state.value.seen) _state.value = _state.value.copy(seen = seen)
}
/**
* Marks a chat as having moved on while it was not on screen. Activity for the
* active conversation is skipped: the operator is looking at it, so it is read
* as it arrives.
*/
private fun markUnread(sessionId: String) {
if (sessionId == _state.value.activeId) return
val seen = _state.value.seen.unread(sessionId)
if (seen !== _state.value.seen) _state.value = _state.value.copy(seen = seen)
}
companion object {
const val LOCAL_MESSAGE_PREFIX = "local-"
}
@@ -0,0 +1,117 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatEventFrame
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import net.awan.pipelines.data.protocol.ChatStep
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Which session has new activity: a chat whose transcript the operator has not
* read is marked, opening it clears the mark, a chat streaming right now reads
* differently from one that just finished unseen, and the marks survive a restart
* (an encode/decode of the stored state into a fresh store). Driven directly
* against [ChatStore] with no device, server or Compose runtime.
*/
class ChatActivityTest {
private fun session(id: String, updatedAt: Long = 0) = ChatSession(id = id, title = id, updatedAt = updatedAt)
private fun delta(sessionId: String, messageId: String = "m1") = ChatEventFrame(
sessionId = sessionId,
messageId = messageId,
kind = ChatProtocol.PART_TEXT,
delta = "hello",
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "$messageId#0"),
)
private fun step(sessionId: String, status: String) = ChatEventFrame(
sessionId = sessionId,
kind = ChatProtocol.EVENT_STEP,
step = ChatStep(status = status),
)
@Test
fun anUnseenSessionIsMarked() {
val store = ChatStore()
val a = session("a", updatedAt = 100)
store.sessionsLoaded(listOf(a))
// The first sight of a pre-existing chat is a baseline, not new activity.
assertFalse(store.value.isUnseen(a))
// A pushed frame for the chat that is not on screen marks it unseen.
store.event(delta("a"))
assertTrue(store.value.isUnseen(a))
}
@Test
fun aSessionNewerThanWhatWasReadIsMarkedWithoutAnyFrame() {
// A reply that arrived while the app was closed: the server's recency moved
// past the stored watermark, and no frame was ever seen.
val stored = ChatSeenState().seeded("a", 100).encode()
val store = ChatStore(seen = ChatSeenState.decode(stored))
store.sessionsLoaded(listOf(session("a", updatedAt = 200)))
assertTrue(store.value.isUnseen(session("a", updatedAt = 200)))
}
@Test
fun openingASessionClearsItsMark() {
val store = ChatStore()
val a = session("a")
store.sessionsLoaded(listOf(a))
store.event(delta("a"))
assertTrue(store.value.isUnseen(a))
store.open(a)
assertFalse(store.value.isUnseen(a))
// The mark is gone from the state that gets persisted too, not just the row.
assertTrue(store.value.seen.unseen.isEmpty())
}
@Test
fun aStreamingSessionIsMarkedDifferentlyFromAFinishedUnseenOne() {
// The one activity derivation: streaming outranks unseen, which outranks idle.
assertEquals(SessionActivity.IDLE, sessionActivity(running = false, unseen = false))
assertEquals(SessionActivity.UNSEEN, sessionActivity(running = false, unseen = true))
assertEquals(SessionActivity.STREAMING, sessionActivity(running = true, unseen = false))
assertEquals(SessionActivity.STREAMING, sessionActivity(running = true, unseen = true))
// And the same distinction through the store: a background turn is
// streaming while it runs, then finished-unseen once it settles.
val store = ChatStore()
val a = session("a")
store.sessionsLoaded(listOf(a))
store.event(step("a", ChatProtocol.STEP_STARTED))
assertEquals(
SessionActivity.STREAMING,
sessionActivity(store.value.thread("a")!!.running, store.value.isUnseen(a)),
)
store.event(step("a", ChatProtocol.STEP_ENDED))
assertFalse(store.value.thread("a")!!.running)
assertEquals(
SessionActivity.UNSEEN,
sessionActivity(store.value.thread("a")!!.running, store.value.isUnseen(a)),
)
}
@Test
fun theSeenStateSurvivesAReload() {
val seen = ChatSeenState().seeded("a", 100).read("c", 200).unread("b")
assertEquals(seen, ChatSeenState.decode(seen.encode()))
// Nothing stored, or something unreadable, is simply nothing seen.
assertEquals(ChatSeenState(), ChatSeenState.decode(""))
assertEquals(ChatSeenState(), ChatSeenState.decode("{"))
// A fresh store built from the stored state still reports the unread chat
// and the chat whose server recency moved past what was read.
val store = ChatStore(seen = ChatSeenState.decode(seen.encode()))
store.sessionsLoaded(listOf(session("a", 300), session("b"), session("c", 200)))
assertTrue(store.value.isUnseen(session("a", 300)))
assertTrue(store.value.isUnseen(session("b")))
assertFalse(store.value.isUnseen(session("c", 200)))
}
}
@@ -0,0 +1,124 @@
package net.awan.pipelines.ui.chat
import net.awan.pipelines.data.protocol.ChatEventFrame
import net.awan.pipelines.data.protocol.ChatPart
import net.awan.pipelines.data.protocol.ChatProtocol
import net.awan.pipelines.data.protocol.ChatSession
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The session-list narrowing and grouping: the match rule over a chat's title and
* directory, that a narrowing keeps the recency order, and that sessions of one
* directory group together. Pure, so it needs no device, server or Compose.
*/
class ChatListFilterTest {
private fun session(
id: String,
title: String = id,
directory: String = "",
updatedAt: Long = 0,
) = ChatSession(id = id, title = title, directory = directory, updatedAt = updatedAt)
private fun delta(sessionId: String) = ChatEventFrame(
sessionId = sessionId,
messageId = "m1",
kind = ChatProtocol.PART_TEXT,
delta = "hello",
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "m1#0"),
)
private val deploy = session("a", title = "Deploy API", directory = "/repos/api")
private val webBug = session("b", title = "Fix login", directory = "/repos/web")
private val webDocs = session("c", title = "Write docs", directory = "/repos/web")
// --- the match rule: title and directory ------------------------------------
@Test
fun aBlankQueryMatchesEverySession() {
assertTrue(sessionMatchesQuery(deploy, ""))
assertTrue(sessionMatchesQuery(deploy, " "))
assertEquals(listOf(deploy, webBug, webDocs), filterChatSessions(listOf(deploy, webBug, webDocs), ""))
}
@Test
fun theQueryMatchesTheTitleOrTheDirectoryIgnoringCase() {
// Title, case-insensitively.
assertTrue(sessionMatchesQuery(deploy, "deploy"))
assertTrue(sessionMatchesQuery(deploy, "API"))
// Directory, case-insensitively.
assertTrue(sessionMatchesQuery(webBug, "REPOS/WEB"))
assertEquals(listOf(webBug, webDocs), filterChatSessions(listOf(deploy, webBug, webDocs), "web"))
}
@Test
fun aQueryThatMatchesNothingYieldsAnEmptyList() {
assertTrue(filterChatSessions(listOf(deploy, webBug), "no-such-chat").isEmpty())
}
// --- narrowing preserves the underlying order --------------------------------
@Test
fun filteringKeepsTheRecencyOrderOfTheSurvivors() {
val ordered = listOf(deploy, webBug, webDocs)
// Both web chats are kept in the order they were given, not re-sorted.
assertEquals(listOf("b", "c"), filterChatSessions(ordered, "web").map { it.id })
// A single hit is still just that hit.
assertEquals(listOf("a"), filterChatSessions(ordered, "deploy").map { it.id })
}
// --- grouping by directory --------------------------------------------------
@Test
fun sessionsOfTheSameDirectoryGroupTogetherKeepingTheirOrder() {
val groups = groupChatSessionsByDirectory(listOf(deploy, webBug, webDocs))
// The first group is the one whose most recent session comes first.
assertEquals(listOf("/repos/api", "/repos/web"), groups.map { it.directory })
assertEquals(listOf("b", "c"), groups[1].sessions.map { it.id })
}
@Test
fun aSingleDirectoryYieldsOneGroupSoTheFlatListIsAlreadyTogether() {
assertEquals(1, groupChatSessionsByDirectory(listOf(webBug, webDocs)).size)
assertTrue(groupChatSessionsByDirectory(emptyList()).isEmpty())
}
@Test
fun sessionsWithoutADirectoryGroupTogetherToo() {
val groups = groupChatSessionsByDirectory(listOf(session("a"), session("b", directory = "/repos/x")))
assertEquals(listOf("", "/repos/x"), groups.map { it.directory })
}
// --- through the store ------------------------------------------------------
@Test
fun searchNarrowsTheStoreListAndClearingRestoresIt() {
val store = ChatStore()
store.sessionsLoaded(listOf(deploy, webBug, webDocs))
assertEquals(listOf("a", "b", "c"), store.value.filteredSessions.map { it.id })
store.searchSessions("web")
// The list is narrowed but the order is untouched.
assertEquals(listOf("b", "c"), store.value.filteredSessions.map { it.id })
// The server's list itself is untouched.
assertEquals(3, store.value.sessions.size)
store.searchSessions("")
assertEquals(listOf("a", "b", "c"), store.value.filteredSessions.map { it.id })
}
@Test
fun theActivityMarkIsReportedForAFilteredSession() {
val store = ChatStore()
store.sessionsLoaded(listOf(deploy, webBug, webDocs))
// A pushed frame for a background chat marks it, whether or not it matches.
store.event(delta("b"))
store.searchSessions("web")
assertTrue(store.value.isUnseen(webBug))
val groups = groupChatSessionsByDirectory(store.value.filteredSessions)
assertEquals(1, groups.size)
assertEquals(listOf("b", "c"), groups.single().sessions.map { it.id })
}
}