diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index 284f038e..a565f4d6 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -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.") diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt index c3f8b35d..dcaa5b6a 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt @@ -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 diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt index 4817181b..8b738fcd 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt @@ -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? = null, ) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index 80f01734..e312f3de 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -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 load(target: MutableStateFlow>, block: suspend () -> T) { viewModelScope.launch { target.value = target.value.copy(loading = true, error = null) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index d50c87cc..e4a8e196 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -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 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt index e58ec9cf..4b9ab629 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatListPane.kt @@ -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(null) } + var closing by remember { mutableStateOf(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 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOverrides.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOverrides.kt index 52ebdafa..54b65ce3 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOverrides.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOverrides.kt @@ -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. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index a3d80f75..e81d3a38 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -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 = emptyList(), val loading: Boolean = false, val loaded: Boolean = false, @@ -225,6 +231,21 @@ data class ChatState( */ val filteredSessions: List 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 + 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 + 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) } diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt index ef8d96f4..f6590287 100644 --- a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt @@ -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? { diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatCloseTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatCloseTest.kt new file mode 100644 index 00000000..f673af4f --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatCloseTest.kt @@ -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")) + } +} diff --git a/docs/notes/chat-close.md b/docs/notes/chat-close.md new file mode 100644 index 00000000..be8942de --- /dev/null +++ b/docs/notes/chat-close.md @@ -0,0 +1,106 @@ +# Finishing a chat: a server-side close that keeps the history + +## What this item changed + +The Pipelines server and `android/`. Before this, the only way to get a chat out +of the list was the app's device-local hide (`ChatOverrides.hidden`): the session +stayed open on the server, other clients still showed it, and nothing recorded +that the operator had finished with it. + +- `internal/protocol/chat.go` adds the `chat_close` and `chat_reopen` request + types, a `ChatCloseResult` (`session_id`, `closed_at`, `interrupted`) and + additive `closed`/`closed_at` fields on the chat session; `internal/protocol/message.go` + carries `ChatClose` on the outcome envelope (the requests themselves ride on + `chat_query`, like `chat_messages`/`chat_interrupt`). +- `internal/server/chat_close.go` (new) handles both: `chat_close` stops a turn + in flight by reusing the broker interrupt the session's room owns (recording in + the reply that a turn was stopped, so a stream is never left running into + nothing), then sets `closed_at`; `chat_reopen` clears it. Both take a + `chat_query` and echo the session plus its registry row. A session id that is + not a recorded operator session — including a pipeline-owned run session — is + refused before anything is written. Nothing is deleted. +- `internal/server/chat_sessions.go` marks a listed session `closed`/`closed_at` + from the registry, so every client sees the same state and a closed session + stays listed. +- `internal/server/chat_room.go` gains `turnInFlight`, so close only interrupts a + session that actually has a turn running. +- `internal/pipeline/operator_sessions.go` adds `closed_at` to + `operator_sessions` (for a fresh database and by an idempotent + `addColumnIfMissing` migration for an existing one), plus + `CloseOperatorSession`, `ReopenOperatorSession` and `OperatorSession`, and + clears the closed state on record and on touch, so simply prompting a closed + session reopens it. +- `android/`: `data/protocol/Chat.kt`/`Message.kt` (closed fields, the two + requests), `PipelinesRepository.chatClose`/`chatReopen`, `ChatStore` (closed + state, a `closedSessions` grouping, `setQueued`/`sessionReopened`), + `ChatFormat` (a closed status label), `ChatListPane` (a `Closed` chip and + section, Close/Reopen actions, a confirmation stating that close stops a + running turn, marks the chat closed on every device and deletes nothing), + `AppViewModel` (the close/reopen actions), and the rename of the local action + to **Hide on this device** with a snackbar saying the chat stays on the server. +- Tests: `internal/protocol/chat_test.go`, `internal/server/chat_close_test.go`, + `internal/pipeline/operator_sessions_close_test.go`, + `android/.../ChatCloseTest.kt` and the closed-state cases in + `android/.../ChatProtocolTest.kt`. + +No new dependency (only the already-declared material-icons-extended), the +installer and the Docker files are untouched, and no run is started from the app. +State: committed locally only, not deployed; the on-device close/second-client/ +reopen check is deferred to visual review. + +## Shared documents this change makes stale + +The note is written here rather than edited in place; the `docs-fold` writer +should update these when it next folds notes. + +- `docs/cli.md:306` — the `## Chat sessions` bullet for `chat_sessions` lists each + session's `directory`, `tag` and recency and ends "A session is never marked + `busy`". It should add that a closed session is still listed, marked + `closed: true` with its `closed_at`, so a client groups or filters it as + history rather than losing it. +- `docs/cli.md:342` — after the `chat_adopt` bullet, add two bullets: + `chat_close` takes a `chat_query` (`session_id`), stops any in-flight turn + through the same interrupt `chat_interrupt` uses (the `chat_close` result's + `interrupted` flag records that a turn was stopped), then sets `closed_at` in + the operator-session registry; it answers with the closed session as + `chat_session`, its registry row in `chat_sessions` and the `chat_close` + result; an id that is not a recorded operator session — including a + pipeline-owned run session — is refused before anything is written, and + nothing is ever deleted. And `chat_reopen` clears the state again (the inverse, + same `chat_query`); prompting a closed session also clears it. +- `android/README.md:6326` — append a dated section recording the behaviour: the + server-side close and reopen, the session and transcript surviving a close, + the `Closed` chip/section and the `Closed` status line, the Close action and + its confirmation wording, the Reopen action, the two ways a session reopens, + and the rename of the local action to **Hide on this device** (device-only, + with a snackbar saying the chat stays on the server) so the two are never + confused. Include the verification evidence and the not-verified-on-device + boundary (implementation verification is the build and the unit tests; visual + review owns the device). +- `internal/author/skill/references/operations.md:268` — the "Brokered OpenCode + chat" preamble lists the declared `chat_*` surface; add `chat_close` and + `chat_reopen`. +- `internal/author/skill/references/operations.md:307` — the `chat_sessions` + paragraph describes the `operator_sessions` shape (`session_id`, `directory`, + `title`, `tag`, `created_at`, `last_used_at`); add `closed_at` and say that a + closed session stays in the list marked `closed`/`closed_at`. Add a paragraph + documenting `chat_close`/`chat_reopen` (interrupt a running turn, record the + closed state, refuse a non-operator session, keep listing as history, reopen + explicitly or by prompting), and add a dated evidence bullet naming + `internal/server/chat_close_test.go`, + `internal/pipeline/operator_sessions_close_test.go`, + `internal/protocol/chat_test.go` and the app's `ChatCloseTest`, marking the + on-device check as not run. + +## Not stale + +- No packaged template names the chat surface, so `internal/author/`'s templates + need no change. +- `internal/author/install.go`'s managed file inventory needs no change: this + item adds no reference file. +- `internal/author/skill/references/SKILL.md` stays a task-directed index; the + close/reopen detail belongs in `operations.md`. +- `android/AGENTS.md` already lists `ui/chat/` and its files, and + `internal/server/AGENTS.md` already points at `internal/server/chat_*.go` and + `internal/pipeline/`'s operator-session registry, so neither area map needs a + new entry. diff --git a/internal/pipeline/operator_sessions.go b/internal/pipeline/operator_sessions.go index 52d99d39..c4cb2b7f 100644 --- a/internal/pipeline/operator_sessions.go +++ b/internal/pipeline/operator_sessions.go @@ -2,6 +2,8 @@ package pipeline import ( "context" + "database/sql" + "errors" "time" ) @@ -23,6 +25,11 @@ type OperatorSession struct { Tag string CreatedAt int64 UpdatedAt int64 + // ClosedAt is the epoch-millisecond time the operator finished with the + // session, or 0 while it is open. It records the closed state on the server + // so every client sees the same thing; the session and its history are never + // deleted, and reopening clears it back to 0. + ClosedAt int64 } // initOperatorSessions creates the operator-session registry. It is a table of @@ -30,44 +37,96 @@ type OperatorSession struct { // ownership (run_session_owners, SessionOwner) is untouched and the two // vocabularies cannot be confused. session_id is the primary key, so lookups and // the upsert use the index; operator_sessions_recent serves the recency order. +// closed_at is added here for a fresh database and by migrateOperatorSessions for +// one created before the closed state existed. func (s *Store) initOperatorSessions() error { _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions ( session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', -tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL); +tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL, +closed_at INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`) - return err + if err != nil { + return err + } + return s.migrateOperatorSessions() +} + +// migrateOperatorSessions adds the closed_at column to a database created before +// the closed state existed. Adding a column with a default leaves every existing +// row valid and open (0), so an upgrade is idempotent across repeated Open calls +// and no session is silently reported as closed. +func (s *Store) migrateOperatorSessions() error { + return s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0") } // RecordOperatorSession upserts one operator chat session in a single statement: // a new id is inserted with its created_at and last_used_at set to now, and a // repeated id updates directory/title/tag and moves last_used_at to now while // preserving the original created_at. CreatedAt is therefore stable across -// re-records. +// re-records. Recording also clears any closed state: re-creating or adopting a +// session is use, so it is open again. func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error { now := time.Now().UnixMilli() - _, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at) -VALUES(?,?,?,?,?,?) -ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at`, + _, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at) +VALUES(?,?,?,?,?,?,0) +ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0`, sessionID, directory, title, tag, now, now) return err } // TouchOperatorSession records that an operator session was just used, in one -// UPDATE. A session id that is not an operator session updates no row and is not -// an error: the statement is itself the presence check, so no second read is +// UPDATE. It also clears the closed state, so simply prompting a closed session +// reopens it. A session id that is not an operator session updates no row and is +// not an error: the statement is itself the presence check, so no second read is // needed. func (s *Store) TouchOperatorSession(ctx context.Context, sessionID string) error { - _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET last_used_at=? WHERE session_id=?", time.Now().UnixMilli(), sessionID) + _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET last_used_at=?, closed_at=0 WHERE session_id=?", time.Now().UnixMilli(), sessionID) return err } +// CloseOperatorSession records that the operator finished with an operator +// session, in one UPDATE that sets closed_at to now. Nothing is deleted: the row, +// its history and the OpenCode session itself are untouched. A session id that is +// not an operator session (for example a pipeline-owned run session) updates no +// row and is not an error, so run sessions are never affected. +func (s *Store) CloseOperatorSession(ctx context.Context, sessionID string) error { + _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET closed_at=? WHERE session_id=?", time.Now().UnixMilli(), sessionID) + return err +} + +// ReopenOperatorSession clears the closed state of an operator session, in one +// UPDATE that sets closed_at back to 0. A session id that is not an operator +// session updates no row and is not an error. +func (s *Store) ReopenOperatorSession(ctx context.Context, sessionID string) error { + _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET closed_at=0 WHERE session_id=?", sessionID) + return err +} + +// OperatorSession returns one operator session by id. found is false when the id +// is not a recorded operator session (so a pipeline-owned run session is never +// returned). It is one indexed lookup and never mutates the row. +func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) { + var session OperatorSession + row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at +FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) + if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return OperatorSession{}, false, nil + } + return OperatorSession{}, false, err + } + return session, true, nil +} + // OperatorSessions reports the operator's chat sessions, most-recently-used // first (ties broken by session id for a deterministic order), capped at // operatorSessionListLimit. Rows with no tag are omitted: a session with no -// recorded tag is not an operator session and must never be listed. It is one -// bounded statement; recency is never mutated here. +// recorded tag is not an operator session and must never be listed. Closed +// sessions are included: the app groups or filters them as history, so the +// operator can still see and reopen what they finished. It is one bounded +// statement; recency is never mutated here. func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) { - rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at + rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at FROM operator_sessions WHERE tag <> '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit) if err != nil { return nil, err @@ -76,7 +135,7 @@ FROM operator_sessions WHERE tag <> '' ORDER BY last_used_at DESC, session_id LI sessions := []OperatorSession{} for rows.Next() { var session OperatorSession - if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt); err != nil { + if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil { return nil, err } sessions = append(sessions, session) diff --git a/internal/pipeline/operator_sessions_close_test.go b/internal/pipeline/operator_sessions_close_test.go new file mode 100644 index 00000000..959b26b4 --- /dev/null +++ b/internal/pipeline/operator_sessions_close_test.go @@ -0,0 +1,124 @@ +package pipeline + +import ( + "context" + "path/filepath" + "testing" +) + +// TestOperatorSessionsCloseReopenAndTouch proves the closed-state contract: a +// close records closed_at and the session is still listed as history, an explicit +// reopen clears it, a prompt (touch) clears it, re-recording clears it, and the +// session, its history and its created_at are never deleted or rewritten. +func TestOperatorSessionsCloseReopenAndTouch(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "close.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil { + t.Fatal(err) + } + before, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + + if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil { + t.Fatal(err) + } + closed, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(closed) != 1 || closed[0].ClosedAt <= 0 { + t.Fatalf("close did not record closed_at: %+v", closed) + } + if closed[0].ID != before[0].ID || closed[0].Directory != before[0].Directory || + closed[0].Title != before[0].Title || closed[0].Tag != before[0].Tag || closed[0].CreatedAt != before[0].CreatedAt { + t.Fatalf("close changed the session beyond closed_at:\nbefore %+v\nafter %+v", before[0], closed[0]) + } + one, found, err := store.OperatorSession(ctx, "ses_a") + if err != nil || !found || one.ClosedAt <= 0 { + t.Fatalf("OperatorSession = %+v found=%v err=%v", one, found, err) + } + if _, found, err := store.OperatorSession(ctx, "ses_run"); err != nil || found { + t.Fatalf("a non-operator session was reported found=%v err=%v", found, err) + } + + if err := store.ReopenOperatorSession(ctx, "ses_a"); err != nil { + t.Fatal(err) + } + if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt != 0 { + t.Fatalf("explicit reopen did not clear closed_at: %+v %v", rows, err) + } + + // Prompting (touch) reopens too. + if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil { + t.Fatal(err) + } + if err := store.TouchOperatorSession(ctx, "ses_a"); err != nil { + t.Fatal(err) + } + if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt != 0 { + t.Fatalf("touch did not clear closed_at: %+v %v", rows, err) + } + + // Re-recording (create/adopt) reopens too. + if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil { + t.Fatal(err) + } + if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil { + t.Fatal(err) + } + if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt != 0 { + t.Fatalf("re-record did not clear closed_at: %+v %v", rows, err) + } + + // Closing a session id that is not an operator session writes nothing. + if err := store.CloseOperatorSession(ctx, "ses_run"); err != nil { + t.Fatalf("closing a non-operator session errored: %v", err) + } +} + +// TestOperatorSessionsMigrationAddsClosedAt proves an existing database created +// before the closed state opens cleanly: the column is added with a default, so +// every existing session stays open and Close/Reopen work afterwards. +func TestOperatorSessionsMigrationAddsClosedAt(t *testing.T) { + ctx := context.Background() + path := filepath.Join(t.TempDir(), "migrate.db") + store, err := Open(path) + if err != nil { + t.Fatal(err) + } + if err := store.RecordOperatorSession(ctx, "ses_old", "/work/old", "Old", "operator"); err != nil { + t.Fatal(err) + } + // Simulate the pre-closed schema by dropping the column, then reopen. + if _, err := store.db.ExecContext(ctx, "ALTER TABLE operator_sessions DROP COLUMN closed_at"); err != nil { + t.Fatalf("drop closed_at: %v", err) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + + store, err = Open(path) + if err != nil { + t.Fatalf("Open after drop: %v", err) + } + defer store.Close() + rows, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0].ID != "ses_old" || rows[0].ClosedAt != 0 { + t.Fatalf("migrated rows = %+v, want the old session open", rows) + } + if err := store.CloseOperatorSession(ctx, "ses_old"); err != nil { + t.Fatal(err) + } + if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt <= 0 { + t.Fatalf("close after migration failed: %+v %v", rows, err) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index bd39f8f0..282c0da0 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -26,6 +26,16 @@ const ( ChatMessages = "chat_messages" ChatInterrupt = "chat_interrupt" ChatReply = "chat_reply" + // ChatClose finishes an operator session and records it as closed on the + // server: any in-flight turn is interrupted through the existing interrupt, + // nothing is deleted (the session, its transcript and its history survive) and + // the closed state is shared by every client because it lives in the + // operator-session registry. ChatReopen clears the closed state again, so a + // finished chat can be resumed. Both take a ChatQuery (the session id) and + // echo the updated session like chat_create/chat_adopt. Neither ever touches + // the pipeline-owned run sessions. + ChatClose = "chat_close" + ChatReopen = "chat_reopen" // ChatDirectories is the request/response type for the operator's directory // choices: the home directory plus the directories of previous operator // sessions, most recently used first, deduplicated and bounded. It is a @@ -116,6 +126,23 @@ type ChatSession struct { // of letting two clients silently write the same conversation. It is // additive and optional: older peers ignore it. Busy bool `json:"busy,omitempty"` + // Closed records that the operator finished with this session: the server + // keeps the session, its transcript and its history, but the closed state is + // shared by every client (it lives in the operator-session registry, not on + // one device). ClosedAt is the epoch-millisecond close time, 0 while open. + // Additive/omitempty so older peers ignore them. + Closed bool `json:"closed,omitempty"` + ClosedAt int64 `json:"closed_at,omitempty"` +} + +// ChatCloseResult reports the outcome of a chat_close: the session id, the +// epoch-millisecond time the closed state was recorded, and whether an +// in-flight turn was interrupted to stop it. It is the record that a running +// turn was stopped, so a stream is never left running into nothing. +type ChatCloseResult struct { + SessionID string `json:"session_id"` + ClosedAt int64 `json:"closed_at"` + Interrupted bool `json:"interrupted,omitempty"` } // ChatCreateRequest is the chat_create request body: a title and an optional diff --git a/internal/protocol/chat_test.go b/internal/protocol/chat_test.go index 5c02e6cc..15f27d29 100644 --- a/internal/protocol/chat_test.go +++ b/internal/protocol/chat_test.go @@ -22,6 +22,8 @@ func chatSamples() []struct { Directory: "/work", ParentID: "ses_0", Tag: ChatSessionTagOperator, CreatedAt: 1792112366711, UpdatedAt: 1792112367999, }}, {"session_busy", ChatSession{ID: "ses_2", Title: "held", Busy: true}}, + {"session_closed", ChatSession{ID: "ses_3", Title: "done", Closed: true, ClosedAt: 1792112367999}}, + {"close_result", ChatCloseResult{SessionID: "ses_3", ClosedAt: 1792112367999, Interrupted: true}}, {"create", ChatCreateRequest{Title: "demo", Directory: "/work"}}, {"adopt", ChatAdoptRequest{SessionID: "ses_1"}}, {"query", ChatQuery{SessionID: "ses_1", Limit: 50}}, @@ -166,6 +168,7 @@ func TestChatEnvelopeRoundTrip(t *testing.T) { }, ChatReply: &ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionReject}, ChatDirectories: []string{"/home/operator", "/work/project"}, + ChatClose: &ChatCloseResult{SessionID: "ses_1", ClosedAt: 1792112367999, Interrupted: true}, } encoded, err := json.Marshal(message) if err != nil { @@ -188,7 +191,8 @@ func TestChatEnvelopeRoundTrip(t *testing.T) { !reflect.DeepEqual(decoded.ChatEvent, message.ChatEvent) || !reflect.DeepEqual(decoded.ChatPermission, message.ChatPermission) || !reflect.DeepEqual(decoded.ChatReply, message.ChatReply) || - !reflect.DeepEqual(decoded.ChatDirectories, message.ChatDirectories) { + !reflect.DeepEqual(decoded.ChatDirectories, message.ChatDirectories) || + !reflect.DeepEqual(decoded.ChatClose, message.ChatClose) { t.Fatalf("chat payloads lost: %+v", decoded) } } @@ -198,7 +202,7 @@ func TestChatFieldsOmittedWhenUnused(t *testing.T) { if err != nil { t.Fatal(err) } - for _, absent := range []string{"chat_sessions", "chat_session", "chat_create", "chat_adopt", "chat_query", "chat_prompt", "chat_messages", "chat_event", "chat_permission", "chat_reply", "chat_directories"} { + for _, absent := range []string{"chat_sessions", "chat_session", "chat_create", "chat_adopt", "chat_query", "chat_prompt", "chat_messages", "chat_event", "chat_permission", "chat_reply", "chat_directories", "chat_close"} { if strings.Contains(string(minimal), absent) { t.Fatalf("absent %q must be omitted: %s", absent, minimal) } diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 0ca03db2..c9165a19 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -166,6 +166,10 @@ type Message struct { ChatEvent *ChatEventFrame `json:"chat_event,omitempty"` ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"` ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"` + // ChatClose carries the outcome of a chat_close; the close and reopen + // requests themselves ride on ChatQuery (the session id), matching + // chat_messages/chat_interrupt. + ChatClose *ChatCloseResult `json:"chat_close,omitempty"` // ChatDirectories carries the operator's directory choices on a // chat_directories response (home first, then recent operator-session // directories, deduplicated and bounded). Additive/omitempty so older peers diff --git a/internal/server/chat.go b/internal/server/chat.go index 6112c876..f46082fb 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -44,6 +44,15 @@ type operatorRegistry interface { TouchOperatorSession(ctx context.Context, sessionID string) error OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error) OperatorDirectories(ctx context.Context, limit int) ([]string, error) + // OperatorSession returns one recorded operator session by id (found false + // when the id is not an operator session), so chat_close/chat_reopen can echo + // the updated row and refuse a session that is not theirs. + OperatorSession(ctx context.Context, sessionID string) (pipeline.OperatorSession, bool, error) + // CloseOperatorSession records the closed state; ReopenOperatorSession clears + // it. Neither deletes anything, and neither touches a pipeline-owned run + // session (which has no operator_sessions row). + CloseOperatorSession(ctx context.Context, sessionID string) error + ReopenOperatorSession(ctx context.Context, sessionID string) error } // chatClientToken returns an unguessable per-connection identity. It attributes @@ -89,6 +98,12 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker case protocol.ChatDirectories: handleChatDirectories(ctx, request, registry, write) return true + case protocol.ChatClose: + handleChatClose(ctx, request, broker, hub, registry, write) + return true + case protocol.ChatReopen: + handleChatReopen(ctx, request, registry, write) + return true } return false } diff --git a/internal/server/chat_claims.go b/internal/server/chat_claims.go index ccc1792e..bd97b6ef 100644 --- a/internal/server/chat_claims.go +++ b/internal/server/chat_claims.go @@ -48,6 +48,17 @@ func (h *chatHub) busyForOther(sessionID, clientID string) bool { return ok && holder != clientID } +// active reports whether any client currently holds sessionID, so a turn may be +// running. chat_close uses it to decide whether to interrupt; the claim is +// released when the turn's stream drains, so it is never left set for a settled +// session. +func (h *chatHub) active(sessionID string) bool { + h.mu.Lock() + defer h.mu.Unlock() + _, ok := h.claims[sessionID] + return ok +} + // evictClaimsLocked drops the oldest claim when the cap is reached, keeping the // claim map bounded like the retained turns. Callers must hold h.mu. func (h *chatHub) evictClaimsLocked() { diff --git a/internal/server/chat_close.go b/internal/server/chat_close.go new file mode 100644 index 00000000..87a7933b --- /dev/null +++ b/internal/server/chat_close.go @@ -0,0 +1,143 @@ +package server + +import ( + "context" + "strings" + + "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// handleChatClose finishes an operator chat session and records it as closed on +// the server. It stops a turn that is running by reusing the existing interrupt +// (so a stream is never left running into nothing, and the result records that a +// turn was stopped), then sets the closed state in the operator-session +// registry. Nothing is deleted: the session, its transcript and its history +// survive, and every client sees the closed state because it lives in the +// registry, not on one device. A session id that is not a recorded operator +// session is refused before anything is written, so a pipeline-owned run session +// is never touched. +func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) { + if broker == nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) + return + } + if registry == nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"}) + return + } + query := request.ChatQuery + if query == nil || !opencode.ValidSessionID(query.SessionID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"}) + return + } + sessionID := query.SessionID + if _, found, err := registry.OperatorSession(ctx, sessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } else if !found { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is not an operator chat session"}) + return + } + // Stop a running turn first. A failed interrupt is surfaced and the close is + // not recorded, so the operator is never told a live turn was stopped when it + // was not. + interrupted := hub.active(sessionID) + if interrupted { + if err := broker.Interrupt(ctx, sessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " could not be stopped: " + err.Error()}) + return + } + } + if err := registry.CloseOperatorSession(ctx, sessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + session, found, err := registry.OperatorSession(ctx, sessionID) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + if !found { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " was closed but is no longer an operator session"}) + return + } + wire := chatSessionFromOperator(session) + response := protocol.Message{ + Type: protocol.ChatClose, + ID: request.ID, + ChatSession: &wire, + ChatClose: &protocol.ChatCloseResult{SessionID: sessionID, ClosedAt: session.ClosedAt, Interrupted: interrupted}, + } + // Echo the registry row on the list field so a client can splice it into + // chat_sessions without a re-list. + response.ChatSessions = []protocol.ChatSession{wire} + _ = write(response) +} + +// handleChatReopen clears the closed state of an operator chat session so it +// returns to the active list. Nothing is created or deleted; it is the inverse of +// chat_close. Prompting a closed session also reopens it (the store clears the +// closed state on touch), so both an explicit reopen and simply sending another +// message work. A session id that is not a recorded operator session is refused. +func handleChatReopen(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) { + if registry == nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"}) + return + } + query := request.ChatQuery + if query == nil || !opencode.ValidSessionID(query.SessionID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"}) + return + } + sessionID := query.SessionID + if _, found, err := registry.OperatorSession(ctx, sessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } else if !found { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is not an operator chat session"}) + return + } + if err := registry.ReopenOperatorSession(ctx, sessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + session, found, err := registry.OperatorSession(ctx, sessionID) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + if !found { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is no longer an operator session"}) + return + } + wire := chatSessionFromOperator(session) + response := protocol.Message{ + Type: protocol.ChatReopen, + ID: request.ID, + ChatSession: &wire, + } + response.ChatSessions = []protocol.ChatSession{wire} + _ = write(response) +} + +// chatSessionFromOperator projects one registry row to the wire ChatSession the +// app lists, so close/reopen and chat_sessions agree on the closed fields. The +// id is always set; title/directory/tag are copied verbatim, and the closed +// state comes from closed_at. +func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSession { + out := protocol.ChatSession{ + ID: session.ID, + Title: strings.TrimSpace(session.Title), + Directory: session.Directory, + Tag: session.Tag, + CreatedAt: session.CreatedAt, + UpdatedAt: session.UpdatedAt, + } + if session.ClosedAt > 0 { + out.Closed = true + out.ClosedAt = session.ClosedAt + } + return out +} diff --git a/internal/server/chat_close_test.go b/internal/server/chat_close_test.go new file mode 100644 index 00000000..a88924af --- /dev/null +++ b/internal/server/chat_close_test.go @@ -0,0 +1,313 @@ +package server + +import ( + "strings" + "testing" + + "github.com/coder/websocket/wsjson" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// TestChatCloseRecordsClosedState is the close-records-state evidence: a +// chat_close on a recorded operator session answers with the closed session, sets +// closed_at in the registry and leaves the session listed (as closed) by +// chat_sessions, so every client sees the same state. +func TestChatCloseRecordsClosedState(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + broker.sessions = []protocol.ChatSession{{ID: "ses_1", Title: "A", Directory: "/work/a"}} + ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatClose || response.ID != "cl1" { + t.Fatalf("chat_close response = %+v", response) + } + if response.ChatSession == nil || !response.ChatSession.Closed || response.ChatSession.ClosedAt <= 0 { + t.Fatalf("closed session not reported: %+v", response.ChatSession) + } + if response.ChatClose == nil || response.ChatClose.SessionID != "ses_1" || response.ChatClose.ClosedAt <= 0 { + t.Fatalf("chat_close result = %+v", response.ChatClose) + } + if response.ChatClose.Interrupted { + t.Fatalf("idle session reported an interrupted turn: %+v", response.ChatClose) + } + if _, interrupts, _ := broker.counts(); interrupts != 0 { + t.Fatalf("idle close interrupted a turn: %d", interrupts) + } + rows, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0].ClosedAt <= 0 { + t.Fatalf("registry did not record the closed state: %+v", rows) + } + + // The list still carries the session, marked closed, so it is reachable as + // history rather than disappearing. + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "l1"}); err != nil { + t.Fatal(err) + } + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 1 { + t.Fatalf("chat_sessions = %+v", response) + } + if !response.ChatSessions[0].Closed || response.ChatSessions[0].ClosedAt <= 0 { + t.Fatalf("closed session not listed as closed: %+v", response.ChatSessions[0]) + } +} + +// TestChatCloseStopsRunningTurn is the close-stops-a-running-turn evidence: a +// prompt holds the session (its stream is live), and chat_close from another +// connection interrupts it through the existing broker interrupt and reports that +// a turn was stopped. +func TestChatCloseStopsRunningTurn(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + broker.block = true + broker.started = make(chan struct{}) + broker.done = make(chan struct{}) + ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 2) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + // Start a long-running turn on the first connection. + if err := wsjson.Write(ctx, conns[0], protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "long running"}}); err != nil { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, conns[0], &ack); err != nil { + t.Fatal(err) + } + if ack.Type != protocol.ChatPrompt { + t.Fatalf("prompt ack = %+v", ack) + } + <-broker.started + + // Close from the second connection; it must interrupt the running turn. + if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conns[1], &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatClose || response.ID != "cl1" { + t.Fatalf("chat_close response = %+v", response) + } + if response.ChatClose == nil || !response.ChatClose.Interrupted { + t.Fatalf("close did not record a stopped turn: %+v", response.ChatClose) + } + if _, interrupts, _ := broker.counts(); interrupts != 1 { + t.Fatalf("interrupts = %d, want 1", interrupts) + } + rows, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0].ClosedAt <= 0 { + t.Fatalf("registry did not record the closed state: %+v", rows) + } +} + +// TestChatCloseKeepsSessionAndMessages pins that closing deletes nothing: the +// registry row survives (only its closed_at changes) and the session's history is +// still readable afterwards. +func TestChatCloseKeepsSessionAndMessages(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + broker.messages = []protocol.ChatMessage{{ID: "m1", SessionID: "ses_1", Role: protocol.ChatRoleUser}} + ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + before, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatClose { + t.Fatalf("close failed: %+v", response) + } + after, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(after) != 1 || after[0].ID != before[0].ID || after[0].Directory != before[0].Directory || + after[0].Title != before[0].Title || after[0].Tag != before[0].Tag || after[0].CreatedAt != before[0].CreatedAt { + t.Fatalf("close changed the session beyond closed_at:\nbefore %+v\nafter %+v", before[0], after[0]) + } + // The transcript is still readable. + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "ms1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatMessages || len(response.ChatMessages) != 1 || response.ChatMessages[0].ID != "m1" { + t.Fatalf("history lost after close: %+v", response) + } + if calls, _, _ := broker.messageQuery(); calls != 1 { + t.Fatalf("message reads = %d, want 1", calls) + } +} + +// TestChatReopenClearsClosedState pins that chat_reopen is the inverse of +// chat_close: the closed state is cleared and the session is listed as active +// again. +func TestChatReopenClearsClosedState(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + if err := store.CloseOperatorSession(ctx, "ses_1"); err != nil { + t.Fatal(err) + } + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReopen, ID: "op1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.ChatReopen || response.ID != "op1" || response.ChatSession == nil { + t.Fatalf("chat_reopen response = %+v", response) + } + if response.ChatSession.Closed || response.ChatSession.ClosedAt != 0 { + t.Fatalf("reopened session still closed: %+v", response.ChatSession) + } + rows, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0].ClosedAt != 0 { + t.Fatalf("registry still closed after reopen: %+v", rows) + } +} + +// TestChatPromptReopensClosedSession pins the second reopen path: simply +// prompting a closed session clears its closed state, so the operator never has +// to make an explicit reopen request. +func TestChatPromptReopensClosedSession(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + if err := store.CloseOperatorSession(ctx, "ses_1"); err != nil { + t.Fatal(err) + } + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "resume"}}); err != nil { + t.Fatal(err) + } + var ack protocol.Message + if err := wsjson.Read(ctx, conn, &ack); err != nil { + t.Fatal(err) + } + if ack.Type != protocol.ChatPrompt { + t.Fatalf("prompt ack = %+v", ack) + } + _ = readChatTurn(t, ctx, conn) + rows, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0].ClosedAt != 0 { + t.Fatalf("prompting did not clear the closed state: %+v", rows) + } +} + +// TestChatCloseRefusesNonOperatorSession pins that a pipeline-owned run session +// (which has no operator_sessions row) is refused and nothing is written, so the +// close never touches the sessions the pipelines own. +func TestChatCloseRefusesNonOperatorSession(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_run"}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || !strings.Contains(response.Error, "not an operator") { + t.Fatalf("non-operator session not refused: %+v", response) + } + if _, interrupts, _ := broker.counts(); interrupts != 0 { + t.Fatalf("refused close still interrupted: %d", interrupts) + } + rows, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(rows) != 0 { + t.Fatalf("refused close wrote a registry row: %+v", rows) + } +} + +// TestChatCloseRejectsInvalidInput pins that a missing/invalid session id and an +// unconfigured broker/registry are answered with an error before any write. +func TestChatCloseRejectsInvalidInput(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store}) + for _, query := range []*protocol.ChatQuery{nil, {}, {SessionID: "not-a-session"}} { + if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "bad", ChatQuery: query}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(ctx, conn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || response.ID != "bad" { + t.Fatalf("query %+v not rejected: %+v", query, response) + } + } + + // No registry configured: refuse rather than close nothing. + noRegCtx, cancelNoReg, noRegConn := dialChatOptions(t, Options{Chat: broker}) + defer cancelNoReg() + if err := wsjson.Write(noRegCtx, noRegConn, protocol.Message{Type: protocol.ChatClose, ID: "nr", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + var response protocol.Message + if err := wsjson.Read(noRegCtx, noRegConn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || !strings.Contains(response.Error, "registry") { + t.Fatalf("close without registry = %+v", response) + } + + // No broker configured: the existing "not configured" error. + noBrokerCtx, cancelNoBroker, noBrokerConn := dialChatOptions(t, Options{OperatorRegistry: store}) + defer cancelNoBroker() + if err := wsjson.Write(noBrokerCtx, noBrokerConn, protocol.Message{Type: protocol.ChatClose, ID: "nb", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil { + t.Fatal(err) + } + if err := wsjson.Read(noBrokerCtx, noBrokerConn, &response); err != nil { + t.Fatal(err) + } + if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") { + t.Fatalf("close without broker = %+v", response) + } +} diff --git a/internal/server/chat_sessions.go b/internal/server/chat_sessions.go index 4a0d034c..17efafbf 100644 --- a/internal/server/chat_sessions.go +++ b/internal/server/chat_sessions.go @@ -74,6 +74,11 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch session.Tag = operator.Tag session.CreatedAt = operator.CreatedAt session.UpdatedAt = operator.UpdatedAt + // The closed state comes from the registry, so every client sees the same + // thing; a closed session stays in the list (the app groups it as history) + // rather than disappearing. + session.Closed = operator.ClosedAt > 0 + session.ClosedAt = operator.ClosedAt session.Busy = hub.busyForOther(operator.ID, clientID) response.ChatSessions = append(response.ChatSessions, session) }