chat: mark new activity in the session list
With several operator sessions 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. Add a per-session read state that the session list derives from data it already receives, and render it as a three-state activity badge: - ChatSeenState (ui/chat/ChatSeen.kt) keeps a per-session recency watermark (the newest updated_at the operator has read) plus the ids that moved on while the app was open. It is persisted as one opaque JSON preference (SettingsRepository chat_seen, observed by AppViewModel.observeChatSeen), the same way ChatSessionOverrides is, so the marks survive a restart and not only a reconnect. - ChatState.isUnseen marks a background session that carried a live mark (a pushed chat_event/permission frame) or, if never opened here, is newer than its stored watermark; first sight of a session is seeded to its current recency so a pre-existing chat is not reported as new. Opening, activating and closing a conversation reads it and clears the mark; history for the active chat advances the watermark to the newest server message. No server request is added. - ChatFormat.sessionActivity(running, unseen) is the one pure derivation (streaming outranks finished-unseen, which outranks idle) and SessionActivityBadge renders it as Streaming/New/Open beside the unchanged kind chip and directory line. Most-recently-used order is untouched. Tests (ChatActivityTest): unseen is marked, opening clears it including in the persisted state, the derivation distinguishes streaming/finished-unseen/ idle, and the seen state survives an encode/decode into a fresh store. Checked before commit: android/README.md was updated in this change with the behaviour, tests and evidence. The packaged authoring skill references (internal/author/skill/references/) describe the Pipelines server and its chat_* protocol surface, neither of which changed - this is a client-side derivation over existing frames - so none needed updating, and the internal/author/install.go managed reference inventory is unchanged. No repository template or root/topic doc describes the Android session list, so none was stale. android/ only; no dependency added; no run is started from the app.
This commit is contained in:
@@ -5641,3 +5641,76 @@ 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`
|
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`,
|
(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||||
`Content-Length: 18470240`).
|
`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.
|
||||||
|
|||||||
@@ -59,6 +59,12 @@ class SettingsRepository(context: Context) {
|
|||||||
private val _chatOverrides = MutableStateFlow(prefs.getString(KEY_CHAT_OVERRIDES, "").orEmpty())
|
private val _chatOverrides = MutableStateFlow(prefs.getString(KEY_CHAT_OVERRIDES, "").orEmpty())
|
||||||
val chatOverrides: StateFlow<String> = _chatOverrides.asStateFlow()
|
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) {
|
fun setServerUrl(value: String) {
|
||||||
val trimmed = value.trim()
|
val trimmed = value.trim()
|
||||||
_serverUrl.value = trimmed
|
_serverUrl.value = trimmed
|
||||||
@@ -117,6 +123,12 @@ class SettingsRepository(context: Context) {
|
|||||||
prefs.edit().putString(KEY_CHAT_OVERRIDES, value).apply()
|
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. */
|
/** True only when the user has explicitly supplied both required values. */
|
||||||
fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank()
|
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_RUN_STATUSES = "pipeline_filter_run_statuses"
|
||||||
const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name"
|
const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name"
|
||||||
const val KEY_CHAT_OVERRIDES = "chat_overrides"
|
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.data.transport.ServerUrl
|
||||||
import net.awan.pipelines.ui.chat.ChatAttachment
|
import net.awan.pipelines.ui.chat.ChatAttachment
|
||||||
import net.awan.pipelines.ui.chat.ChatSessionOverrides
|
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.ChatState
|
||||||
import net.awan.pipelines.ui.chat.ChatStore
|
import net.awan.pipelines.ui.chat.ChatStore
|
||||||
import net.awan.pipelines.ui.chat.attachmentFiles
|
import net.awan.pipelines.ui.chat.attachmentFiles
|
||||||
@@ -134,7 +135,10 @@ class AppViewModel(
|
|||||||
private val retryKeys = ConcurrentHashMap<Long, String>()
|
private val retryKeys = ConcurrentHashMap<Long, String>()
|
||||||
|
|
||||||
/** The multi-chat screen state (sessions, open conversations, drafts, scroll). */
|
/** 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
|
val chat: StateFlow<ChatState> = chatStore.state
|
||||||
|
|
||||||
// The live run subscription: the workspace currently watched, the job that
|
// The live run subscription: the workspace currently watched, the job that
|
||||||
@@ -177,6 +181,7 @@ class AppViewModel(
|
|||||||
observeRunEvents()
|
observeRunEvents()
|
||||||
observeConnection()
|
observeConnection()
|
||||||
observeChatOverrides()
|
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) {
|
fun updateServerUrlDraft(value: String) {
|
||||||
_serverUrlDraft.value = value
|
_serverUrlDraft.value = value
|
||||||
_urlError.value = null
|
_urlError.value = null
|
||||||
|
|||||||
@@ -116,6 +116,25 @@ internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean):
|
|||||||
else -> "Idle"
|
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. */
|
/** Which action the composer's single primary control offers for a chat. */
|
||||||
enum class ComposerAction { Send, Stop }
|
enum class ComposerAction { Send, Stop }
|
||||||
|
|
||||||
|
|||||||
@@ -320,6 +320,7 @@ private fun ChatListPane(
|
|||||||
session = session,
|
session = session,
|
||||||
open = thread != null,
|
open = thread != null,
|
||||||
running = thread?.running == true,
|
running = thread?.running == true,
|
||||||
|
unseen = state.isUnseen(session),
|
||||||
active = state.activeId == session.id,
|
active = state.activeId == session.id,
|
||||||
onClick = { vm.openChatSession(session) },
|
onClick = { vm.openChatSession(session) },
|
||||||
onRename = { renaming = session },
|
onRename = { renaming = session },
|
||||||
@@ -358,12 +359,14 @@ private fun SessionRow(
|
|||||||
session: ChatSession,
|
session: ChatSession,
|
||||||
open: Boolean,
|
open: Boolean,
|
||||||
running: Boolean,
|
running: Boolean,
|
||||||
|
unseen: Boolean,
|
||||||
active: Boolean,
|
active: Boolean,
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
onRename: () -> Unit,
|
onRename: () -> Unit,
|
||||||
onRemove: () -> Unit,
|
onRemove: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val texts = pipelinesText()
|
val texts = pipelinesText()
|
||||||
|
val activity = sessionActivity(running, unseen)
|
||||||
ListRow(selected = active, onClick = onClick) {
|
ListRow(selected = active, onClick = onClick) {
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
@@ -380,7 +383,9 @@ private fun SessionRow(
|
|||||||
// The kind chip names the session kind the server reported, so an
|
// The kind chip names the session kind the server reported, so an
|
||||||
// operator chat is tellable from anything run-related at a glance.
|
// operator chat is tellable from anything run-related at a glance.
|
||||||
sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) }
|
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)
|
SessionMenu(onRename = onRename, onRemove = onRemove)
|
||||||
}
|
}
|
||||||
val meta = buildList {
|
val meta = buildList {
|
||||||
@@ -596,11 +601,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. */
|
/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun SessionBadge(label: String, running: Boolean = false) {
|
private fun SessionActivityBadge(activity: SessionActivity, open: Boolean) {
|
||||||
val color = when {
|
val label = when (activity) {
|
||||||
running -> MaterialTheme.colorScheme.tertiary
|
SessionActivity.STREAMING -> "Streaming"
|
||||||
label == "Open" -> MaterialTheme.colorScheme.primary
|
SessionActivity.UNSEEN -> "New"
|
||||||
else -> MaterialTheme.colorScheme.outline
|
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)) {
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color))
|
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,26 @@ data class ChatState(
|
|||||||
val overrides: ChatSessionOverrides = ChatSessionOverrides(),
|
val overrides: ChatSessionOverrides = ChatSessionOverrides(),
|
||||||
/** The id of the session most recently removed, while its removal can be undone. */
|
/** The id of the session most recently removed, while its removal can be undone. */
|
||||||
val lastRemoved: String? = null,
|
val lastRemoved: String? = null,
|
||||||
|
/** What the operator has read of the list (see [ChatSeenState]). */
|
||||||
|
val seen: ChatSeenState = ChatSeenState(),
|
||||||
) {
|
) {
|
||||||
val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId }
|
val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId }
|
||||||
|
|
||||||
fun thread(sessionId: String): ChatThread? = open.firstOrNull { it.sessionId == sessionId }
|
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
|
* 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
|
* local changes applied — a removed chat is hidden and a renamed one shows its
|
||||||
@@ -214,9 +229,10 @@ data class ChatState(
|
|||||||
class ChatStore(
|
class ChatStore(
|
||||||
private val now: () -> Long = System::currentTimeMillis,
|
private val now: () -> Long = System::currentTimeMillis,
|
||||||
overrides: ChatSessionOverrides = ChatSessionOverrides(),
|
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 state: StateFlow<ChatState> = _state.asStateFlow()
|
||||||
|
|
||||||
val value: ChatState get() = _state.value
|
val value: ChatState get() = _state.value
|
||||||
@@ -260,9 +276,22 @@ class ChatStore(
|
|||||||
busy = session.busy,
|
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(
|
_state.value = _state.value.copy(
|
||||||
sessions = sessions,
|
sessions = sessions,
|
||||||
open = open,
|
open = open,
|
||||||
|
seen = seen,
|
||||||
sessionsLoading = false,
|
sessionsLoading = false,
|
||||||
sessionsLoaded = true,
|
sessionsLoaded = true,
|
||||||
sessionsError = null,
|
sessionsError = null,
|
||||||
@@ -382,6 +411,9 @@ class ChatStore(
|
|||||||
// A local rename always wins over the server's title, whether the thread
|
// A local rename always wins over the server's title, whether the thread
|
||||||
// is new or already open.
|
// is new or already open.
|
||||||
val title = _state.value.overrides.titles[session.id] ?: session.title
|
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) {
|
if (existing == null) {
|
||||||
val thread = ChatThread(
|
val thread = ChatThread(
|
||||||
sessionId = session.id,
|
sessionId = session.id,
|
||||||
@@ -392,7 +424,7 @@ class ChatStore(
|
|||||||
updatedAt = session.updatedAt,
|
updatedAt = session.updatedAt,
|
||||||
busy = session.busy,
|
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
|
return true
|
||||||
}
|
}
|
||||||
val merged = existing.copy(
|
val merged = existing.copy(
|
||||||
@@ -403,6 +435,7 @@ class ChatStore(
|
|||||||
_state.value = _state.value.copy(
|
_state.value = _state.value.copy(
|
||||||
open = _state.value.open.map { if (it.sessionId == session.id) merged else it },
|
open = _state.value.open.map { if (it.sessionId == session.id) merged else it },
|
||||||
activeId = session.id,
|
activeId = session.id,
|
||||||
|
seen = seen,
|
||||||
)
|
)
|
||||||
return needsResync(merged)
|
return needsResync(merged)
|
||||||
}
|
}
|
||||||
@@ -414,14 +447,27 @@ class ChatStore(
|
|||||||
*/
|
*/
|
||||||
fun activate(sessionId: String): Boolean {
|
fun activate(sessionId: String): Boolean {
|
||||||
val thread = _state.value.thread(sessionId) ?: return false
|
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)
|
return needsResync(thread)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun close(sessionId: String) {
|
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 open = _state.value.open.filterNot { it.sessionId == sessionId }
|
||||||
val active = if (_state.value.activeId == sessionId) open.lastOrNull()?.sessionId else _state.value.activeId
|
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 +544,17 @@ class ChatStore(
|
|||||||
* The running flag is left as-is: history alone cannot say whether a turn is
|
* The running flag is left as-is: history alone cannot say whether a turn is
|
||||||
* still in flight.
|
* still in flight.
|
||||||
*/
|
*/
|
||||||
fun history(sessionId: String, messages: List<ChatMessage>) = update(sessionId) {
|
fun history(sessionId: String, messages: List<ChatMessage>) {
|
||||||
it.copy(messages = messages, loading = false, loaded = true, error = null)
|
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) }
|
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
|
||||||
@@ -554,6 +609,9 @@ class ChatStore(
|
|||||||
permissionAnswer = if (sameRequest) it.permissionAnswer else "",
|
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 +672,7 @@ class ChatStore(
|
|||||||
fun event(frame: ChatEventFrame) {
|
fun event(frame: ChatEventFrame) {
|
||||||
if (frame.sessionId.isBlank()) return
|
if (frame.sessionId.isBlank()) return
|
||||||
ensureThread(frame.sessionId)
|
ensureThread(frame.sessionId)
|
||||||
|
markUnread(frame.sessionId)
|
||||||
when (frame.kind) {
|
when (frame.kind) {
|
||||||
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
|
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
|
||||||
ChatProtocol.PART_TOOL -> applyTool(frame)
|
ChatProtocol.PART_TOOL -> applyTool(frame)
|
||||||
@@ -705,6 +764,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 {
|
companion object {
|
||||||
const val LOCAL_MESSAGE_PREFIX = "local-"
|
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)))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user