chat: close and reopen an operator session on the server, keeping its history

Add a server-side close for operator chats, so finishing with a chat takes it out
of the active list for every client without deleting anything. The brokered
protocol gains chat_close and chat_reopen; chat_close stops a running turn by
reusing the existing broker interrupt (its result carries an interrupted flag, so
a stream is never left running into nothing) and then sets closed_at on the
session's operator_sessions row. The session, its transcript and its history
survive, and because the closed state lives in the registry chat_sessions reports
it to every client, not just the one that asked. An id that is not a recorded
operator session, including a pipeline-owned run session, is refused before
anything is written. chat_reopen clears the state again, and simply prompting a
closed session also clears it (the store clears closed_at on touch).

The registry gains closed_at for a fresh database and an idempotent migration for
one created before it existed. The app renders closed sessions under a labelled
Closed section with a Closed chip, offers a Close action with a confirmation that
says it stops a running turn, marks the chat closed on every device and deletes
nothing, and a Reopen action on each closed row. The device-local hide is renamed
Hide on this device, with a snackbar saying the chat stays on the server, so it is
never confused with the real close. No new dependency, the installer and Docker
files are untouched, and no run is started from the app.

Checked before committing: the packaged templates carry no chat surface and need
no update, and internal/author/install.go's managed inventory needs none either
(this adds no reference file). The packaged authoring skill reference
internal/author/skill/references/operations.md and the shared docs/cli.md and
android/README.md are stale because of this change, but an item no longer edits a
shared document: what is stale and what should change there is recorded in
docs/notes/chat-close.md for the docs-fold writer, which is committed here with
the change.

Checks: gofmt clean, go build ./... and go vet ./... clean, and
go test ./internal/protocol/... ./internal/pipeline/... ./internal/server/...
./internal/author/... pass. The app side is verified with :app:assembleDebug and
:app:testDebugUnitTest (--offline --no-daemon, BUILD SUCCESSFUL); the on-device
close, second-client and reopen check is deferred to visual review.

Not deployed; deploying is the operator's step.
This commit is contained in:
2026-10-18 00:10:47 +01:00
parent 73284ff68c
commit 971e555ceb
21 changed files with 1293 additions and 44 deletions
@@ -300,6 +300,26 @@ 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.")
@@ -33,6 +33,26 @@ data class ChatSession(
// run: the phone shows it read-only instead of letting two clients write the
// same conversation.
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
@@ -255,6 +275,24 @@ 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
@@ -68,6 +68,11 @@ 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"
// 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"
@@ -680,5 +685,8 @@ data class Message(
@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,
)
@@ -1055,6 +1055,9 @@ class AppViewModel(
viewModelScope.launch {
try {
repository.chatPrompt(sessionId, text, attachmentFiles(attachments))
// 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)
@@ -1099,6 +1102,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)
@@ -134,10 +134,15 @@ private const val OPERATOR_TAG_LABEL = "Operator"
* would imply.
*/
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String =
sessionStatusLabel(session.busy, runningLocally)
sessionStatusLabel(session.busy, 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 model flags (see [sessionStatusLabel]).
* A closed session reads `Closed` first: it is finished, whatever the server's
* busy flag or a stale local running mark says.
*/
internal fun sessionStatusLabel(busy: Boolean, runningLocally: Boolean, closed: Boolean = false): String = when {
closed -> "Closed"
runningLocally -> "Running"
busy -> "Busy · read-only"
else -> "Idle"
@@ -183,7 +188,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.busy, thread.running, thread.closed),
directory = thread.directory,
model = thread.model,
)
@@ -273,6 +278,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
@@ -94,10 +94,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
@@ -115,6 +117,7 @@ internal fun ChatListPane(
}
}
var renaming by remember { mutableStateOf<ChatSession?>(null) }
var closing by remember { mutableStateOf<ChatSession?>(null) }
Scaffold(
modifier = modifier,
@@ -177,12 +180,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) {
@@ -211,6 +223,16 @@ internal fun ChatListPane(
},
)
}
closing?.let { session ->
CloseChatDialog(
session = session,
onDismiss = { closing = null },
onConfirm = {
vm.closeChatSession(session.id)
closing = null
},
)
}
}
/**
@@ -251,17 +273,20 @@ private fun SessionListItem(
session: ChatSession,
vm: AppViewModel,
onRename: (ChatSession) -> Unit,
onClose: (ChatSession) -> Unit,
) {
val thread = state.thread(session.id)
SessionRow(
session = session,
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) },
)
}
@@ -295,7 +320,9 @@ private fun SessionRow(
active: Boolean,
onClick: () -> Unit,
onRename: () -> Unit,
onRemove: () -> Unit,
onClose: () -> Unit,
onReopen: () -> Unit,
onHide: () -> Unit,
) {
val texts = pipelinesText()
val activity = sessionActivity(running, unseen)
@@ -315,10 +342,20 @@ 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))
@@ -329,9 +366,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)) {
@@ -349,17 +396,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
@@ -395,7 +477,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,
@@ -225,6 +231,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 +325,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 +427,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 +453,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 +516,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 +528,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 },
@@ -733,6 +797,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)
}
@@ -311,6 +311,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? {
@@ -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"))
}
}