From 971e555ceb770314b39df884bedcc3df8bca62ad Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 18 Oct 2026 00:10:47 +0100 Subject: [PATCH 1/2] 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. --- .../pipelines/data/PipelinesRepository.kt | 20 ++ .../net/awan/pipelines/data/protocol/Chat.kt | 38 +++ .../awan/pipelines/data/protocol/Message.kt | 8 + .../net/awan/pipelines/ui/AppViewModel.kt | 41 +++ .../net/awan/pipelines/ui/chat/ChatFormat.kt | 26 +- .../awan/pipelines/ui/chat/ChatListPane.kt | 118 ++++++- .../awan/pipelines/ui/chat/ChatOverrides.kt | 15 +- .../net/awan/pipelines/ui/chat/ChatStore.kt | 71 +++- .../data/protocol/ChatProtocolTest.kt | 52 +++ .../awan/pipelines/ui/chat/ChatCloseTest.kt | 107 ++++++ docs/notes/chat-close.md | 106 ++++++ internal/pipeline/operator_sessions.go | 85 ++++- .../pipeline/operator_sessions_close_test.go | 124 +++++++ internal/protocol/chat.go | 27 ++ internal/protocol/chat_test.go | 8 +- internal/protocol/message.go | 4 + internal/server/chat.go | 15 + internal/server/chat_claims.go | 11 + internal/server/chat_close.go | 143 ++++++++ internal/server/chat_close_test.go | 313 ++++++++++++++++++ internal/server/chat_sessions.go | 5 + 21 files changed, 1293 insertions(+), 44 deletions(-) create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/ChatCloseTest.kt create mode 100644 docs/notes/chat-close.md create mode 100644 internal/pipeline/operator_sessions_close_test.go create mode 100644 internal/server/chat_close.go create mode 100644 internal/server/chat_close_test.go 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) } From 5a44ff1568beb9ad9bc081fba5198a6507a45e47 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 18 Oct 2026 00:18:40 +0100 Subject: [PATCH 2/2] android: make the destinations pill a true overlay, centred narrow and right when wide The floating destination pill no longer takes layout space: it is drawn in the bottom overlay layer above the content, horizontally centred on a narrow window and anchored to the bottom-right corner on a wide one. Templates leaves the pill for a Templates row on the Settings page. - PipelinesApp: the content Column's pill reservation is gone; contentPillPadding (pillVisible) is the named zero and a unit test pins both states. The pill and the attention chip stay in their own bottom-anchored overlay Column, a sibling of the content in the Box, so nothing positions the content. The one placement rule is destinationPillAlignment(wide) (CenterHorizontally narrow, End wide); the corner margin is the named SPACING_L, so no new number. The attention chip keeps its own bottom-right place at every width via Modifier.align(End). - Trailing clearance moves into each scrollable's own content: pillScrollInset (DESTINATION_PILL_RESERVE + ATTENTION_CHIP_RESERVE while drawn, zero while hidden) is published through the new LocalPillBottomInset (components/PillInset.kt) and applied with pillContentPadding / Modifier.pillBottomPadding in every list, grid and scrolling detail, stage and settings body. The container keeps its full height, a hidden pill leaves no empty band, and the last row still scrolls clear of the pill. - Templates is no longer a pill destination: TemplatesDestination.kt is deleted and destinations is pipelines/runs/chat/settings. The new SettingsDestination sliding stack (pane 0 SettingsScreen, 1 TemplateGalleryScreen, 2 TemplateDetailScreen) with the pure, Bundle-able SettingsSelection model gives the gallery the shared covered-pane strip and one-level Back; SettingsScreen gains the Templates row that opens it. This re-lands the intent of a2043f9, which never reached main. - Dimens: the two reserve tokens' docs now describe the scroll-content clearance and the chip's share of it; no new token and no hardcoded geometry. Checked where the change belongs: no packaged template (examples/*.md) and no packaged authoring skill reference (internal/author/skill/references/*) describes the Android pill, its destinations or the Templates gallery, so none needs updating and internal/author/install.go's inventory is unchanged. android/README.md does document the surfaces this item changed, so it is now stale: this item does not edit that shared document - docs/notes/pill-overlay-and-position.md records the two places that need it (the Templates bullet and the dated section to append) for the single docs-fold writer. Tests: at a297fb6 with these working changes the build and unit suite were green (593 tests, 0 failures); no device command was run and the geometry stays token-derived. Visual rendering of the centred/right pill needs the device and was not verified here. --- .../net/awan/pipelines/ui/PipelinesApp.kt | 231 +++++++++++------- .../awan/pipelines/ui/SettingsDestination.kt | 89 +++++++ .../awan/pipelines/ui/SettingsSelection.kt | 86 +++++++ .../awan/pipelines/ui/TemplatesDestination.kt | 70 ------ .../awan/pipelines/ui/chat/ChatCreatePane.kt | 7 +- .../awan/pipelines/ui/chat/ChatListPane.kt | 7 +- .../awan/pipelines/ui/components/PillInset.kt | 53 ++++ .../net/awan/pipelines/ui/graph/SourceView.kt | 3 +- .../pipelines/ui/graph/StageDetailPane.kt | 7 +- .../ui/screens/PipelineDetailScreen.kt | 5 +- .../ui/screens/PipelineListScreen.kt | 3 +- .../pipelines/ui/screens/RunEvidenceTab.kt | 3 +- .../ui/screens/RunFieldSectionsTab.kt | 3 +- .../awan/pipelines/ui/screens/RunGraphTab.kt | 3 +- .../pipelines/ui/screens/RunHistoryScreen.kt | 3 +- .../pipelines/ui/screens/RunSummaryTab.kt | 3 +- .../pipelines/ui/screens/RunTimelineTab.kt | 3 +- .../pipelines/ui/screens/SettingsScreen.kt | 85 ++++++- .../ui/screens/TemplateDetailScreen.kt | 5 +- .../ui/screens/TemplateGalleryScreen.kt | 3 +- .../net/awan/pipelines/ui/theme/Dimens.kt | 14 +- .../net/awan/pipelines/ui/PipelinesNavTest.kt | 67 ++++- .../pipelines/ui/SettingsSelectionTest.kt | 74 ++++++ docs/notes/pill-overlay-and-position.md | 148 +++++++++++ 24 files changed, 777 insertions(+), 198 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/SettingsDestination.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/SettingsSelection.kt delete mode 100644 android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/components/PillInset.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/SettingsSelectionTest.kt create mode 100644 docs/notes/pill-overlay-and-position.md diff --git a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt index ae1a60d1..382a14e8 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt @@ -32,6 +32,7 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -60,19 +61,27 @@ import net.awan.pipelines.ui.chat.ChatScreen import net.awan.pipelines.ui.components.AttentionIndicator import net.awan.pipelines.ui.components.AttentionSheet import net.awan.pipelines.ui.components.ConnectionBanner +import net.awan.pipelines.ui.components.LocalPillBottomInset import net.awan.pipelines.ui.components.MotionStandard import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.components.spec -import net.awan.pipelines.ui.screens.SettingsScreen import net.awan.pipelines.ui.theme.ATTENTION_CHIP_RESERVE import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE +import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_S +/** One destination the floating pill holds: its nav [route], the accessible [label] and its glyph. */ internal data class TopDestination(val route: String, val label: String, val icon: ImageVector) -private val destinations = listOf( +/** + * The pill's destinations, in display order. Templates is deliberately absent: it + * is configuration, reached from the Settings page instead, so the pill holds only + * the surfaces a person moves between constantly. The pill's width derives from + * this list (its icon row), never a fixed value, so removing a destination only + * narrows it. + */ +internal val destinations = listOf( TopDestination("pipelines", "Pipelines", Icons.Default.AccountTree), - TopDestination("templates", "Templates", TemplatesIcon), TopDestination("runs", "Runs", Icons.Default.History), TopDestination("chat", "Chat", Icons.AutoMirrored.Filled.Chat), TopDestination("settings", "Settings", Icons.Default.Settings), @@ -270,74 +279,78 @@ fun PipelinesApp( // screens' app bars (a Material 3 TopAppBar applies the top safe-area inset), // which removed the duplicate top band. The bottom is owned by each screen's // Scaffold, and the floating pill explicitly clears the safe area (system - // bars, cutout, gesture area and IME) via windowInsetsPadding. The Column - // reserves DESTINATION_PILL_RESERVE at the bottom so no scrollable content is - // permanently hidden behind the pill; while the pill is hidden (an open - // conversation, see [destinationPillVisible]) that reservation is dropped too, - // so the composer sits at the true bottom instead of over an empty band. + // bars, cutout, gesture area and IME) via windowInsetsPadding. + // + // The pill is a true overlay: it is drawn in its own bottom-anchored layer over + // the content and never takes layout space, so the content keeps its full + // height. Nothing is positioned by the pill; its bottom clearance + // ([pillScrollInset], published through [LocalPillBottomInset]) is applied + // inside each scrollable screen's own scroll content, so scrolling to the end + // still reveals the last row clear of the pill, and while the pill is hidden + // (an open conversation, see [destinationPillVisible]) that clearance is zero + // so a hidden pill leaves no empty band. See [contentPillPadding]. val bannerVisible = connectionState !is ConnectionState.Connected Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0)) { padding -> Box(Modifier.fillMaxSize().padding(padding)) { - Column(Modifier.fillMaxSize().padding(bottom = destinationPillReserve(pillVisible) + ATTENTION_CHIP_RESERVE)) { - ConnectionBanner( - state = connectionState, - configuredUrl = configuredUrl, - onReconnect = vm::reconnect, - ) - NavHost( - navController = navController, - startDestination = "pipelines", - // While the banner is visible it owns the status-bar inset, so - // the inner app bars below must not apply it a second time. - modifier = Modifier - .weight(1f) - .then( - if (bannerVisible) { - Modifier.consumeWindowInsets( - paneSafeArea().only(WindowInsetsSides.Top), - ) - } else { - Modifier - }, - ), - ) { - composable("pipelines") { - PipelineDestination( - vm = vm, - wide = wide, - selection = pipelineSelection, - onSelectionChange = { pipelineSelection = it }, - listState = pipelineListState, - onOpenRun = { runId -> - runSelection = PaneSelection( - pane = MasterPane.Detail, - itemId = runId, - ) - navController.navigate("runs") { launchSingleTop = true } - }, - ) - } - composable("runs") { - RunsDestination( - vm = vm, - wide = wide, - selection = runSelection, - onSelectionChange = { runSelection = it }, - pendingNav = runSearchNav, - onPendingNavResolved = { runSearchNav = null }, - listState = runListState, - decisionRequest = decisionRequest, - onDecisionRequestHandled = { decisionRequest = null }, - ) - } - composable("chat") { - ChatScreen(vm = vm, wide = wide) - } - composable("templates") { - TemplatesDestination(vm = vm, wide = wide, listState = templateListState) - } - composable("settings") { - SettingsScreen(vm, wide = wide) + CompositionLocalProvider(LocalPillBottomInset provides pillScrollInset(pillVisible)) { + Column(Modifier.fillMaxSize().padding(bottom = contentPillPadding(pillVisible))) { + ConnectionBanner( + state = connectionState, + configuredUrl = configuredUrl, + onReconnect = vm::reconnect, + ) + NavHost( + navController = navController, + startDestination = "pipelines", + // While the banner is visible it owns the status-bar inset, so + // the inner app bars below must not apply it a second time. + modifier = Modifier + .weight(1f) + .then( + if (bannerVisible) { + Modifier.consumeWindowInsets( + paneSafeArea().only(WindowInsetsSides.Top), + ) + } else { + Modifier + }, + ), + ) { + composable("pipelines") { + PipelineDestination( + vm = vm, + wide = wide, + selection = pipelineSelection, + onSelectionChange = { pipelineSelection = it }, + listState = pipelineListState, + onOpenRun = { runId -> + runSelection = PaneSelection( + pane = MasterPane.Detail, + itemId = runId, + ) + navController.navigate("runs") { launchSingleTop = true } + }, + ) + } + composable("runs") { + RunsDestination( + vm = vm, + wide = wide, + selection = runSelection, + onSelectionChange = { runSelection = it }, + pendingNav = runSearchNav, + onPendingNavResolved = { runSearchNav = null }, + listState = runListState, + decisionRequest = decisionRequest, + onDecisionRequestHandled = { decisionRequest = null }, + ) + } + composable("chat") { + ChatScreen(vm = vm, wide = wide) + } + composable("settings") { + SettingsDestination(vm = vm, wide = wide, listState = templateListState) + } } } } @@ -360,21 +373,29 @@ fun PipelinesApp( // Composed after the NavHost, so while the field is open Back (button // or gesture) dismisses the morph before any pane's own Back handler. BackHandler(enabled = searchState.open) { dismissSearch() } - // The results panel and the destination bar share one bottom-anchored, - // inset-clearing column. `paneSafeArea` (WindowInsets.safeDrawing) is - // applied once here: the panel then takes exactly the height the IME and - // navigation bar leave (weight, `fill = false` so a short panel wraps) - // and scrolls inside it, and the input always sits directly below the - // panel and above the keyboard. The activity declares `adjustResize` - // and the app is edge-to-edge, so the Compose window inset is the only - // source of the IME geometry and it is applied once, here. + // The results panel, the attention chip and the destination bar share + // one bottom-anchored, inset-clearing column — the overlay layer, drawn + // above the content and never part of its layout. `paneSafeArea` + // (WindowInsets.safeDrawing) is applied once here, so the pill clears the + // system bars, cutout, gesture area and IME: the panel then takes exactly + // the height the IME and navigation bar leave (weight, `fill = false` so + // a short panel wraps) and scrolls inside it, and the input always sits + // directly below the panel and above the keyboard. The activity declares + // `adjustResize` and the app is edge-to-edge, so the Compose window inset + // is the only source of the IME geometry and it is applied once, here. + // + // The overlay's resting place is the window width's in [destinationPillAlignment]: + // horizontally centred on a narrow window, anchored to the bottom-right + // corner on a wide one. Its margin comes from the named [SPACING_L], so the + // corner placement adds no new number. That rule positions the pill; the + // attention chip above it keeps its own bottom-right place at every width. Column( modifier = Modifier .fillMaxSize() .windowInsetsPadding(paneSafeArea()) - .padding(end = 16.dp, bottom = 16.dp), + .padding(end = if (wide) SPACING_L else 0.dp, bottom = SPACING_L), verticalArrangement = Arrangement.Bottom, - horizontalAlignment = Alignment.End, + horizontalAlignment = destinationPillAlignment(wide), ) { if (searchState.open && searchState.query.isNotBlank()) { SearchResultsPanel( @@ -383,13 +404,17 @@ fun PipelinesApp( modifier = Modifier .fillMaxWidth() .weight(1f, fill = false) - .padding(bottom = 16.dp), + .padding(bottom = SPACING_L), ) } + // The attention chip is not part of the pill's placement rule: it + // keeps its own bottom-right resting place at every width (as it + // had before the pill became width-dependent), so only the pill + // follows [destinationPillAlignment]. AttentionIndicator( entries = attention, onClick = { attentionOpen = true }, - modifier = Modifier.padding(bottom = SPACING_S), + modifier = Modifier.align(Alignment.End).padding(bottom = SPACING_S), ) // The pill stands down while a conversation is open; the search // field it morphs into is unreachable there anyway (the field opens @@ -463,14 +488,40 @@ internal fun destinationPillVisible(currentRoute: String?, conversationOpen: Boo !(currentRoute == CHAT_ROUTE && conversationOpen) /** - * The bottom space the content reserves for the pill: the named - * [DESTINATION_PILL_RESERVE] while the pill is drawn, and none while it is - * hidden, so a hidden pill leaves no empty band at the end of scrollable content - * and the composer sits at the true bottom. Derived from [pillVisible] alone, so - * the reservation and the drawn pill can never disagree into a frame with a - * drawn pill over content it does not clear, or a reserved gap behind a hidden - * one — which is what keeps the content from jumping as the pill appears and - * disappears. + * Where the bottom overlay — the destination pill and the attention chip above it + * — rests in the window: horizontally centred on a **narrow** window and anchored + * to the bottom-right **corner** on a **wide** one. The overlay is drawn above the + * content and never takes layout space either way, so this is purely where it + * sits. A pure function of the window width, so the one arrangement rule is + * unit-testable and no screen hardcodes a width. */ -internal fun destinationPillReserve(pillVisible: Boolean): Dp = - if (pillVisible) DESTINATION_PILL_RESERVE else 0.dp +internal fun destinationPillAlignment(wide: Boolean): Alignment.Horizontal = + if (wide) Alignment.End else Alignment.CenterHorizontally + +/** + * The bottom padding the app's content column applies for the pill: none, whether + * the pill is [pillVisible] or not. The pill is an overlay drawn above the + * content, so it must never size or offset it — the content keeps its own full + * height and the pill's clearance lives in each scrollable's own scroll content + * (see [pillScrollInset]). The value is a function of the drawn state (both of + * which the unit test pins at zero) rather than left implicit in an absent + * modifier, so a later change that reintroduces a reserved band here fails the + * test. + */ +internal fun contentPillPadding(pillVisible: Boolean): Dp = 0.dp + +/** + * The trailing bottom space a scrollable screen keeps so its last row scrolls clear + * of the floating bottom stack — the destination pill and the attention chip above + * it — built from the named [DESTINATION_PILL_RESERVE] and [ATTENTION_CHIP_RESERVE] + * while the pill is drawn, and none while it is hidden (an open conversation, see + * [destinationPillVisible]) so a hidden pill leaves no empty band at the end of a + * list. Published to the content through `LocalPillBottomInset` and applied inside + * each scrollable's own scroll content, never as layout padding on the content. It + * is derived from [pillVisible] alone, so the clearance and the drawn pill can + * never disagree into a frame with a drawn pill over content it does not clear, or + * a reserved gap behind a hidden one — which is what keeps a list from jumping as + * the pill appears and disappears. + */ +internal fun pillScrollInset(pillVisible: Boolean): Dp = + if (pillVisible) DESTINATION_PILL_RESERVE + ATTENTION_CHIP_RESERVE else 0.dp diff --git a/android/app/src/main/java/net/awan/pipelines/ui/SettingsDestination.kt b/android/app/src/main/java/net/awan/pipelines/ui/SettingsDestination.kt new file mode 100644 index 00000000..ff1d6b5a --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/SettingsDestination.kt @@ -0,0 +1,89 @@ +package net.awan.pipelines.ui + +import androidx.activity.compose.PredictiveBackHandler +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Settings +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import kotlinx.coroutines.flow.collect +import net.awan.pipelines.ui.components.SlidingPaneStack +import net.awan.pipelines.ui.components.rememberPaneContent +import net.awan.pipelines.ui.screens.SettingsScreen +import net.awan.pipelines.ui.screens.TemplateDetailScreen +import net.awan.pipelines.ui.screens.TemplateGalleryScreen + +/** + * The Settings destination: the same shared pane stack the other destinations + * use, with the settings page as pane 0 and the templates gallery it opens from + * its Templates row as pane 1 and the selected template's detail as pane 2. + * Templates is configuration, so it is one of the settings destinations rather + * than a floating-pill entry; the gallery is the existing [TemplateGalleryScreen] + * (and its detail the existing [TemplateDetailScreen]), so no second templates + * surface is built. Its selection is saved state, so it survives rotation, + * configuration change and process death; the covered-pane strip, the back gesture + * and the pane's own back control all step exactly one level via [settingsBack]. + * Nothing here starts a run. + */ +@Composable +internal fun SettingsDestination( + vm: AppViewModel, + wide: Boolean, + listState: LazyListState, +) { + var selection by rememberSaveable(stateSaver = SettingsSelectionSaver) { + mutableStateOf(SettingsSelection()) + } + val depth = selection.depth + val onBack: () -> Unit = { selection = settingsBack(selection) } + + PredictiveBackHandler(enabled = depth >= 1) { progress -> + // Consume the gesture; on completion perform exactly one Back step. + progress.collect { } + onBack() + } + + SlidingPaneStack( + depth = depth, + wide = wide, + onPopTo = { level -> selection = settingsPopTo(selection, level) }, + compactLabel = "Settings", + compactIcon = Icons.Filled.Settings, + backContentDescription = { level -> + if (level == 0) "Back to settings" else "Back to templates" + }, + pane = { level, covered, paneModifier -> + when (level) { + 0 -> SettingsScreen( + vm = vm, + onOpenTemplates = { selection = openTemplatesGallery(selection) }, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + 1 -> TemplateGalleryScreen( + vm = vm, + wide = wide, + onOpen = { key -> selection = openTemplateDetail(selection, key) }, + listState = listState, + modifier = paneModifier, + covered = covered, + ) + 2 -> rememberPaneContent(selection.templateKey)?.let { key -> + TemplateDetailScreen( + vm = vm, + templateKey = key, + onBack = onBack, + wide = wide, + modifier = paneModifier, + covered = covered, + ) + } + } + }, + ) +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/SettingsSelection.kt b/android/app/src/main/java/net/awan/pipelines/ui/SettingsSelection.kt new file mode 100644 index 00000000..b1dc081d --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/SettingsSelection.kt @@ -0,0 +1,86 @@ +package net.awan.pipelines.ui + +import androidx.compose.runtime.saveable.Saver + +/** + * Which pane of the Settings destination's sliding stack is rightmost: the + * settings page itself (level 0), the templates gallery opened from its Templates + * row (level 1) or the selected template's detail (level 2). Templates is + * configuration, so it is one of the settings destinations reached from the + * Settings page rather than an entry in the floating destination pill; modelling + * the stack here is what gives the gallery the same covered-pane strip and + * one-level Back step the other destinations use. + */ +internal enum class SettingsPane(val level: Int) { + Settings(0), + Gallery(1), + Template(2), +} + +/** + * The Settings destination's saved pane selection. The only state beyond the + * rightmost pane is the open template's key, so the whole selection is + * Bundle-able primitives and survives rotation, configuration change and process + * death. Geometry (peek widths, insets) is deliberately not part of the model; it + * is derived from layout by the shared stack. + */ +internal data class SettingsSelection( + val pane: SettingsPane = SettingsPane.Settings, + val templateKey: String? = null, +) { + /** How many panes are stacked: 0 settings, 1 gallery, 2 template detail. */ + val depth: Int + get() = pane.level +} + +/** The Settings page's Templates row opens the gallery as its own pane. */ +internal fun openTemplatesGallery(selection: SettingsSelection): SettingsSelection = + selection.copy(pane = SettingsPane.Gallery, templateKey = null) + +/** A gallery card opens the selected template's detail as the next pane. */ +internal fun openTemplateDetail(selection: SettingsSelection, key: String): SettingsSelection = + selection.copy(pane = SettingsPane.Template, templateKey = key) + +/** + * Exactly one pane level of Back, so the back gesture, the covered strip's tap and + * the detail's own back control all step the same single level: detail → gallery → + * settings. At settings there is nothing to close and the selection is unchanged, + * so the caller lets Back leave the destination. + */ +internal fun settingsBack(selection: SettingsSelection): SettingsSelection = when (selection.pane) { + SettingsPane.Settings -> selection + SettingsPane.Gallery -> selection.copy(pane = SettingsPane.Settings, templateKey = null) + SettingsPane.Template -> selection.copy(pane = SettingsPane.Gallery, templateKey = null) +} + +/** + * The selection after tapping a covered pane's strip at [level]: every pane to its + * right is closed. Level 0 closes back to the settings page, level 1 closes the + * template detail back to the gallery, and a [level] at or beyond the current + * depth is a no-op. Peeks exist only on a wide window; narrow windows use + * Back/gesture for the same one-level step. + */ +internal fun settingsPopTo(selection: SettingsSelection, level: Int): SettingsSelection = when { + level <= 0 -> SettingsSelection() + level == 1 -> selection.copy(pane = SettingsPane.Gallery, templateKey = null) + else -> selection +} + +/** + * Encodes a [SettingsSelection] as Bundle-able primitives. Paired with + * [decodeSettingsSelection]. + */ +internal fun encodeSettingsSelection(selection: SettingsSelection): List = + listOf(selection.pane.name, selection.templateKey ?: "") + +/** Restores a [SettingsSelection] encoded by [encodeSettingsSelection]. */ +internal fun decodeSettingsSelection(encoded: List): SettingsSelection = SettingsSelection( + pane = SettingsPane.valueOf(encoded[0] as String), + templateKey = (encoded[1] as String).takeIf { it.isNotEmpty() }, +) + +/** Saves/restores a [SettingsSelection] across configuration change and process death. */ +internal val SettingsSelectionSaver: Saver> = Saver( + save = { encodeSettingsSelection(it) }, + restore = { decodeSettingsSelection(it) }, +) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt b/android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt deleted file mode 100644 index 6b97587d..00000000 --- a/android/app/src/main/java/net/awan/pipelines/ui/TemplatesDestination.kt +++ /dev/null @@ -1,70 +0,0 @@ -package net.awan.pipelines.ui - -import androidx.activity.compose.PredictiveBackHandler -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import kotlinx.coroutines.flow.collect -import net.awan.pipelines.ui.components.SlidingPaneStack -import net.awan.pipelines.ui.components.rememberPaneContent -import net.awan.pipelines.ui.screens.TemplateDetailScreen -import net.awan.pipelines.ui.screens.TemplateGalleryScreen - -/** - * The Templates destination: the same shared pane stack, with the template - * gallery as pane 0 and the selected template's detail as pane 1. The selected - * template key is the saved state, so it survives rotation, configuration change - * and process death; Back/the peek pop one level. Nothing here starts a run. - */ -@Composable -internal fun TemplatesDestination( - vm: AppViewModel, - wide: Boolean, - listState: LazyListState, -) { - var selectedKey by rememberSaveable { mutableStateOf(null) } - val depth = if (selectedKey == null) 0 else 1 - val onBack: () -> Unit = { selectedKey = null } - - PredictiveBackHandler(enabled = depth >= 1) { progress -> - progress.collect { } - onBack() - } - - SlidingPaneStack( - depth = depth, - wide = wide, - onPopTo = { level -> if (level <= 0) selectedKey = null }, - compactLabel = "Templates", - compactIcon = TemplatesIcon, - backContentDescription = { level -> - if (level == 0) "Back to templates" else "Back to template" - }, - pane = { level, covered, paneModifier -> - when (level) { - 0 -> TemplateGalleryScreen( - vm = vm, - wide = wide, - onOpen = { key -> selectedKey = key }, - listState = listState, - modifier = paneModifier, - covered = covered, - ) - 1 -> rememberPaneContent(selectedKey)?.let { key -> - TemplateDetailScreen( - vm = vm, - templateKey = key, - onBack = onBack, - wide = wide, - modifier = paneModifier, - covered = covered, - ) - } - } - }, - ) -} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt index 5e421c53..874c9709 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatCreatePane.kt @@ -3,6 +3,7 @@ package net.awan.pipelines.ui.chat import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -33,6 +34,7 @@ import net.awan.pipelines.ui.AppViewModel import net.awan.pipelines.ui.components.ErrorState import net.awan.pipelines.ui.components.ListRow import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.pipelinesText @@ -85,7 +87,10 @@ internal fun NewChatPane( color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), ) - LazyColumn(Modifier.weight(1f).fillMaxWidth()) { + LazyColumn( + modifier = Modifier.weight(1f).fillMaxWidth(), + contentPadding = pillContentPadding(PaddingValues()), + ) { items(choices, key = { it.createDirectory }) { choice -> DirectoryRow( choice = choice, 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..0850d837 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 @@ -4,6 +4,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -55,6 +56,7 @@ import net.awan.pipelines.ui.components.LabelChip import net.awan.pipelines.ui.components.ListRow import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.theme.ICON_BUTTON_SMALL_DP import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.SPACING_M @@ -169,7 +171,10 @@ internal fun ChatListPane( // drift hundreds of pixels from its title, the same constraint the // other lists and detail bodies use; narrow windows fill as before. else -> DetailTabBody(wide, Modifier.fillMaxSize()) { listModifier -> - LazyColumn(listModifier) { + LazyColumn( + modifier = listModifier, + contentPadding = pillContentPadding(PaddingValues()), + ) { if (groups.size > 1) { // More than one directory: one section per repository so // same-directory chats sit together, each keeping the diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/PillInset.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/PillInset.kt new file mode 100644 index 00000000..71e8e67d --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/PillInset.kt @@ -0,0 +1,53 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + +/** + * The floating destination pill's clearance at the bottom of the content, as the + * app shell computes it for the current window and route (see + * `pillScrollInset`). It is published around the content so a scrollable screen + * can add it to its own scroll content's bottom padding and let its last row + * scroll clear of the pill, without the pill ever taking or positioning layout + * space. Defaults to zero, so a screen composed outside the app shell (a preview, + * a test) keeps exactly its own padding. + */ +internal val LocalPillBottomInset = compositionLocalOf { 0.dp } + +/** + * [base] with the floating pill's clearance added at the bottom, for a scroll + * container's `contentPadding`. It adds the clearance **inside** the scroll + * content, so the container keeps its full height and its last row can still be + * scrolled into view above the pill; it is deliberately not a layout padding on + * the container, which would shrink the viewport and hide the row behind the pill + * instead. Returns [base] unchanged when no pill is drawn. + */ +@Composable +internal fun pillContentPadding(base: PaddingValues): PaddingValues { + val inset = LocalPillBottomInset.current + if (inset == 0.dp) return base + val direction = LocalLayoutDirection.current + return PaddingValues( + start = base.calculateLeftPadding(direction), + top = base.calculateTopPadding(), + end = base.calculateRightPadding(direction), + bottom = base.calculateBottomPadding() + inset, + ) +} + +/** + * Adds the floating pill's clearance as bottom padding on a scrollable's **own + * content** (a `Column` inside `verticalScroll`, or any content whose end must + * clear the pill), for the cases a `LazyColumn`'s `contentPadding` cannot reach. + * Like [pillContentPadding] it is content padding, not a layout inset, so the + * container keeps its full height and only its last content scrolls clear of the + * pill. A no-op when no pill is drawn. + */ +@Composable +internal fun Modifier.pillBottomPadding(): Modifier = padding(bottom = LocalPillBottomInset.current) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/SourceView.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/SourceView.kt index aa75cea3..8926a20f 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/SourceView.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/SourceView.kt @@ -32,6 +32,7 @@ import net.awan.pipelines.data.protocol.Graph import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.collapsibleSection import net.awan.pipelines.ui.components.copyText +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.rememberSectionExpansion import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.SPACING_L @@ -71,7 +72,7 @@ internal fun PipelineSourceView( LazyColumn( modifier = modifier.fillMaxSize(), - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "source-actions") { Row( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt index 30dd8dfc..8faaf0cc 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt @@ -48,6 +48,7 @@ import net.awan.pipelines.ui.components.KeyValueRow import net.awan.pipelines.ui.components.PaneIdentity import net.awan.pipelines.ui.components.SectionHeader import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillBottomPadding import net.awan.pipelines.ui.STAGE_RUN_LABEL_LINES import net.awan.pipelines.ui.displayMap import net.awan.pipelines.ui.fileChangeLine @@ -520,7 +521,8 @@ private fun StageDetailBody( Column( modifier = columnModifier .verticalScroll(rememberScrollState()) - .padding(horizontal = SPACING_L, vertical = SPACING_S), + .padding(horizontal = SPACING_L, vertical = SPACING_S) + .pillBottomPadding(), verticalArrangement = Arrangement.spacedBy(SPACING_XS), ) { // A run parked on this stage surfaces its decision here, at the top of @@ -755,7 +757,8 @@ private fun StageSectionBody( Column( modifier = columnModifier .verticalScroll(rememberScrollState()) - .padding(horizontal = SPACING_L, vertical = SPACING_L), + .padding(horizontal = SPACING_L, vertical = SPACING_L) + .pillBottomPadding(), verticalArrangement = Arrangement.spacedBy(SPACING_XS), ) { KeyValueRow("Stage", GraphSemantics.nodeLabel(stageKey)) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt index 293ea3ed..f90dab63 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineDetailScreen.kt @@ -52,6 +52,7 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.collapsibleSection import net.awan.pipelines.ui.components.detailLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.pipelineDetailTabs import net.awan.pipelines.ui.components.rememberPaneContent import net.awan.pipelines.ui.formatLocalTimestamp @@ -200,7 +201,7 @@ private fun PipelineSummaryTab(detail: PipelineDetail, wide: Boolean, modifier: DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "pipeline-summary") { Column( @@ -256,7 +257,7 @@ private fun PipelineGraphTab( val text = pipelinesText() LazyColumn( modifier = modifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "pipeline-graph") { Column( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt index 55f99758..eb25df10 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/PipelineListScreen.kt @@ -55,6 +55,7 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.animateListItem import net.awan.pipelines.ui.components.listLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.rememberLiveNowMillis import net.awan.pipelines.ui.formatLocalTimestamp import net.awan.pipelines.ui.stageCountText @@ -227,7 +228,7 @@ fun PipelineListScreen( LazyColumn( state = listState, modifier = listModifier, - contentPadding = PaddingValues(vertical = SPACING_S), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_S)), ) { items(items, key = { it.id }) { pipeline -> PipelineRow( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt index 2dda6065..130c12eb 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunEvidenceTab.kt @@ -20,6 +20,7 @@ import net.awan.pipelines.ui.LoadState import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.rememberSectionExpansion import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_S @@ -45,7 +46,7 @@ internal fun RunEvidenceTab( DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "evidence-reload") { Row( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt index be3e685a..63cabfb7 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunFieldSectionsTab.kt @@ -10,6 +10,7 @@ import kotlinx.serialization.json.JsonElement import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.collapsibleSection +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.rememberSectionExpansion import net.awan.pipelines.ui.displayText import net.awan.pipelines.ui.theme.SPACING_L @@ -35,7 +36,7 @@ internal fun RunFieldSectionsTab( DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { if (entries.isEmpty()) { item(key = "$keyPrefix-empty") { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt index faea05ac..1d2898c2 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunGraphTab.kt @@ -12,6 +12,7 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.RunGraphState +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.graph.WorkflowGraph import net.awan.pipelines.ui.theme.SPACING_L import net.awan.pipelines.ui.theme.SPACING_S @@ -39,7 +40,7 @@ internal fun RunGraphTab( val timeline = remember(run.steps) { runTimeline(run.steps) } LazyColumn( modifier = modifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "run-graph") { Column( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt index ffd14a14..cea8b110 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt @@ -68,6 +68,7 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.animateListItem import net.awan.pipelines.ui.components.listLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.rememberLiveNowMillis import net.awan.pipelines.ui.components.runStateColor import net.awan.pipelines.ui.components.runStateOf @@ -330,7 +331,7 @@ private fun RunHistoryContent( LazyColumn( state = listState, modifier = listModifier, - contentPadding = PaddingValues(bottom = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(bottom = SPACING_L)), ) { entries.forEach { entry -> when (entry) { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt index 802a5fc5..559a7029 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt @@ -20,6 +20,7 @@ import net.awan.pipelines.ui.RUN_VIEW_TITLE_LINES import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.KeyValueRow +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.StatusChip import net.awan.pipelines.ui.components.collapsibleSection import net.awan.pipelines.ui.components.rememberLiveNowMillis @@ -68,7 +69,7 @@ internal fun RunSummaryTab( DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { // The artifacts gallery still leads the summary, but inside one // collapsed section: its header alone carries the run's capture diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt index 2b06b6b2..168ac84b 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunTimelineTab.kt @@ -27,6 +27,7 @@ import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.ui.components.ColoredChip import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.RunStatusIcon +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.runStateIcon import net.awan.pipelines.ui.components.runStateOf import net.awan.pipelines.ui.graph.graphColors @@ -60,7 +61,7 @@ internal fun RunTimelineTab( DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { if (timeline.entries.isEmpty()) { item(key = "timeline-empty") { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/SettingsScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/SettingsScreen.kt index b918a2ae..09c31c44 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/SettingsScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/SettingsScreen.kt @@ -1,9 +1,11 @@ package net.awan.pipelines.ui.screens +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding @@ -11,6 +13,8 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.WarningAmber import androidx.compose.material3.Button import androidx.compose.material3.Card @@ -26,18 +30,32 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.TemplatesIcon import net.awan.pipelines.ui.components.DetailTabBody +import net.awan.pipelines.ui.components.PaneIdentity import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillBottomPadding +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_XS @OptIn(ExperimentalMaterial3Api::class) @Composable -fun SettingsScreen(vm: AppViewModel, modifier: Modifier = Modifier, wide: Boolean = false) { +fun SettingsScreen( + vm: AppViewModel, + onOpenTemplates: () -> Unit, + modifier: Modifier = Modifier, + wide: Boolean = false, + covered: Boolean = false, +) { val serverUrl by vm.serverUrlDraft.collectAsStateWithLifecycle() val workspace by vm.workspaceDraft.collectAsStateWithLifecycle() val urlError by vm.urlError.collectAsStateWithLifecycle() @@ -47,6 +65,17 @@ fun SettingsScreen(vm: AppViewModel, modifier: Modifier = Modifier, wide: Boolea val configuredWorkspace by vm.configuredWorkspace.collectAsStateWithLifecycle() val workspaceError by vm.workspaceError.collectAsStateWithLifecycle() + if (covered) { + // A covered pane shows only its compact identity, never its fields + // squeezed into the peek strip (the same rule as the other destinations). + PaneIdentity( + title = "Settings", + icon = Icons.Filled.Settings, + modifier = modifier.fillMaxSize(), + ) + return + } + Scaffold( modifier = modifier, contentWindowInsets = paneSafeArea(), @@ -75,6 +104,7 @@ fun SettingsScreen(vm: AppViewModel, modifier: Modifier = Modifier, wide: Boolea onDisconnect = vm::disconnect, onReconnect = vm::reconnect, onSaveWorkspace = vm::saveWorkspace, + onOpenTemplates = onOpenTemplates, ) } } @@ -98,15 +128,19 @@ private fun SettingsContent( onDisconnect: () -> Unit, onReconnect: () -> Unit, onSaveWorkspace: () -> Unit, + onOpenTemplates: () -> Unit, ) { // The settings body keeps the app's comfortable reading width on a wide // window (centred) instead of letting a helper line run the whole 2000px. + // The floating pill is an overlay, so the scrolled body adds its clearance to + // its own scroll content and its last control scrolls clear of the pill. DetailTabBody(wide, padding) { columnModifier -> Column( modifier = columnModifier .verticalScroll(rememberScrollState()) - .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), + .padding(SPACING_L) + .pillBottomPadding(), + verticalArrangement = Arrangement.spacedBy(SPACING_M), ) { Text("Connection", style = MaterialTheme.typography.titleMedium) @@ -163,6 +197,51 @@ private fun SettingsContent( ) Button(onClick = onSaveWorkspace, enabled = workspaceError == null) { Text("Save workspace") } Text("Saved workspace: ${configuredWorkspace.ifBlank { "(none)" }}") + + Text("Templates", style = MaterialTheme.typography.titleMedium) + + // The templates gallery is configuration, so it lives here rather than in + // the floating pill. The row is the settings page's idiom: a section + // label followed by a card, with a leading glyph and a forward chevron. + Card( + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, + ), + modifier = Modifier + .fillMaxWidth() + .clickable( + role = Role.Button, + onClickLabel = "Open templates", + onClick = onOpenTemplates, + ), + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(SPACING_L), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_M), + ) { + Icon( + imageVector = TemplatesIcon, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + Text("Browse templates", style = MaterialTheme.typography.bodyLarge) + Text( + text = "Reusable pipeline definitions offered by the server.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + ) + } + } } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateDetailScreen.kt index f78c81da..9bba9396 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateDetailScreen.kt @@ -50,6 +50,7 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.clampTabIndex import net.awan.pipelines.ui.components.detailLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.components.pipelineDetailTabs import net.awan.pipelines.ui.graph.PipelineSourceView import net.awan.pipelines.ui.graph.WorkflowGraph @@ -161,7 +162,7 @@ private fun TemplateSummaryTab(entry: TemplateEntry, wide: Boolean, modifier: Mo DetailTabBody(wide, modifier) { columnModifier -> LazyColumn( modifier = columnModifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "template-summary") { Column( @@ -232,7 +233,7 @@ private fun TemplateGraphTab(entry: TemplateEntry, modifier: Modifier) { } LazyColumn( modifier = modifier, - contentPadding = PaddingValues(vertical = SPACING_L), + contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)), ) { item(key = "template-graph") { Column( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateGalleryScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateGalleryScreen.kt index 93016a19..8b2ce05c 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateGalleryScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/TemplateGalleryScreen.kt @@ -49,6 +49,7 @@ import net.awan.pipelines.ui.components.StateCrossfade import net.awan.pipelines.ui.components.animateListItem import net.awan.pipelines.ui.components.listLoadPhase import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.components.pillContentPadding import net.awan.pipelines.ui.templateCard import net.awan.pipelines.ui.templateGridColumns import net.awan.pipelines.ui.templateStageCountLabel @@ -151,7 +152,7 @@ private fun TemplateGrid( LazyColumn( state = listState, modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(SPACING_L), + contentPadding = pillContentPadding(PaddingValues(SPACING_L)), verticalArrangement = Arrangement.spacedBy(SPACING_S), ) { items(rows, key = { it.first().key }) { row -> diff --git a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt index a1e2c969..f3fd5eb2 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt @@ -76,17 +76,21 @@ internal val MIN_COVERED_PANE_WIDTH_DP = 112.dp // ---- Destination pill (ui/PipelinesApp.kt) --------------------------------- /** - * Bottom space reserved by the floating destination pill, so content is never - * permanently hidden behind it (pill height + its margins + a small gap). + * The trailing bottom space a scrollable screen keeps at the end of its own scroll + * content so its last row is never permanently hidden behind the floating + * destination pill (pill height + its margins + a small gap). The pill itself is + * an overlay and takes no layout space; this is clearance inside the scroll + * content, applied through `LocalPillBottomInset`. */ internal val DESTINATION_PILL_RESERVE = 88.dp /** * Bottom space the floating attention chip occupies above the destination pill: * the chip's own height (its single label line plus its vertical padding) plus the - * gap below it. Reserved at the bottom of the content whether or not a chip is - * present, so the chip can never be laid out over a row, a field or a button and - * the content does not jump as it appears and clears. + * gap below it. Added to a scrollable's trailing space alongside + * [DESTINATION_PILL_RESERVE] while the pill is drawn, so the chip can never be laid + * out over a row, a field or a button and the content does not jump as it appears + * and clears. */ internal val ATTENTION_CHIP_RESERVE = SPACING_XXL + SPACING_M diff --git a/android/app/src/test/java/net/awan/pipelines/ui/PipelinesNavTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/PipelinesNavTest.kt index 9589b0c8..beb119ac 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/PipelinesNavTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/PipelinesNavTest.kt @@ -1,6 +1,8 @@ package net.awan.pipelines.ui +import androidx.compose.ui.Alignment import androidx.compose.ui.unit.Dp +import net.awan.pipelines.ui.theme.ATTENTION_CHIP_RESERVE import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -9,6 +11,31 @@ import org.junit.Test class PipelinesNavTest { + @Test + fun thePillDoesNotHoldTemplates() { + // Templates is configuration and moved to the Settings page; the pill keeps + // only the surfaces a person moves between constantly. + assertFalse(destinations.any { it.route == "templates" }) + } + + @Test + fun thePillKeepsItsRemainingDestinationsInOrder() { + // The pill's width derives from exactly this list, so removing a + // destination only narrows it. + assertEquals( + listOf("pipelines", "runs", "chat", "settings"), + destinations.map { it.route }, + ) + } + + @Test + fun thePillIsCentredOnANarrowWindowAndOnTheRightCornerOnAWideOne() { + // The overlay is bottom-anchored; only its horizontal arrangement follows + // the window width: centred when narrow, the right corner when wide. + assertEquals(Alignment.CenterHorizontally, destinationPillAlignment(wide = false)) + assertEquals(Alignment.End, destinationPillAlignment(wide = true)) + } + @Test fun listRoutesSelectTheirOwnDestination() { assertTrue(destinationSelected("pipelines", "pipelines")) @@ -59,7 +86,7 @@ class PipelinesNavTest { // the chat list keeps it, and so does every other destination. assertFalse(destinationPillVisible("chat", conversationOpen = true)) assertTrue(destinationPillVisible("chat", conversationOpen = false)) - for (route in listOf("pipelines", "templates", "runs", "settings", null)) { + for (route in listOf("pipelines", "runs", "settings", null)) { assertTrue(destinationPillVisible(route, conversationOpen = false)) } // A conversation only exists on the chat route; even if the flag were set @@ -68,24 +95,38 @@ class PipelinesNavTest { } @Test - fun theReserveTracksTheDrawnPillSoContentNeitherJumpsNorLeavesAGap() { - // Drawn: content reserves the named pill space and clears it. Hidden: no - // reservation, so there is no empty band where the pill used to be. - assertDp(DESTINATION_PILL_RESERVE.value, destinationPillReserve(pillVisible = true)) - assertDp(0f, destinationPillReserve(pillVisible = false)) - // One predicate drives both, so the space can never disagree with the - // pill: reserved exactly when drawn, gone exactly when hidden. + fun theContentKeepsItsOwnHeightBecauseThePillIsAnOverlay() { + // The pill floats above the content and never takes layout space, so the + // content column's own bottom padding for it is zero — whether the pill is + // drawn or hidden — and a scrollable list's last row scrolls under the pill + // rather than the whole content being shortened by it. + assertDp(0f, contentPillPadding(pillVisible = true)) + assertDp(0f, contentPillPadding(pillVisible = false)) + } + + @Test + fun theScrollInsetTracksTheDrawnPillSoAListNeitherJumpsNorHidesItsLastRow() { + // Drawn: a scrollable keeps the named pill + attention-chip space at the + // end of its own scroll content and its last row scrolls clear of the whole + // floating bottom stack. Hidden: no clearance, so there is no empty band + // where the pill used to be. + val drawnInset = DESTINATION_PILL_RESERVE + ATTENTION_CHIP_RESERVE + assertDp(drawnInset.value, pillScrollInset(pillVisible = true)) + assertDp(0f, pillScrollInset(pillVisible = false)) + // One predicate drives both the drawing and the clearance, so the space can + // never disagree with the pill: cleared exactly when drawn, gone exactly + // when hidden. for (route in listOf("pipelines", "chat", "runs", "settings", null)) { for (open in listOf(false, true)) { val drawn = destinationPillVisible(route, open) - val reserve = destinationPillReserve(drawn) + val inset = pillScrollInset(drawn) assertTrue( - "reserve held behind a hidden pill on $route (open=$open)", - drawn || reserve.value == 0f, + "scroll clearance held behind a hidden pill on $route (open=$open)", + drawn || inset.value == 0f, ) assertTrue( - "content not cleared of a drawn pill on $route (open=$open)", - !drawn || reserve.value == DESTINATION_PILL_RESERVE.value, + "list not cleared of a drawn pill on $route (open=$open)", + !drawn || inset.value == drawnInset.value, ) } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/SettingsSelectionTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/SettingsSelectionTest.kt new file mode 100644 index 00000000..0d3e18e1 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/SettingsSelectionTest.kt @@ -0,0 +1,74 @@ +package net.awan.pipelines.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The Settings destination's one-level navigation: its Templates row opens the + * gallery as its own pane, a gallery card opens the template detail as the next + * pane, and Back (the gesture, the covered strip's tap and the detail's own back + * control) steps exactly one pane at a time — detail → gallery → settings. Pure, + * so none of this needs a device. + */ +class SettingsSelectionTest { + + @Test + fun theTemplatesRowOpensTheGalleryAsItsOwnPane() { + val opened = openTemplatesGallery(SettingsSelection()) + assertEquals(SettingsPane.Gallery, opened.pane) + assertEquals(1, opened.depth) + assertNull(opened.templateKey) + } + + @Test + fun aGalleryCardOpensTheSelectedTemplatesDetailPane() { + val opened = openTemplateDetail(openTemplatesGallery(SettingsSelection()), "three-stage") + assertEquals(SettingsPane.Template, opened.pane) + assertEquals(2, opened.depth) + assertEquals("three-stage", opened.templateKey) + } + + @Test + fun backStepsExactlyOnePaneAndClearsTheTemplateKey() { + val detail = openTemplateDetail(openTemplatesGallery(SettingsSelection()), "three-stage") + + val gallery = settingsBack(detail) + assertEquals(SettingsPane.Gallery, gallery.pane) + assertEquals(1, gallery.depth) + assertNull(gallery.templateKey) + + val settings = settingsBack(gallery) + assertEquals(SettingsPane.Settings, settings.pane) + assertEquals(0, settings.depth) + } + + @Test + fun backAtSettingsLeavesTheSelectionSoBackCanLeaveTheDestination() { + assertEquals(SettingsSelection(), settingsBack(SettingsSelection())) + } + + @Test + fun tappingACoveredStripPopsEveryPaneToItsRight() { + val detail = openTemplateDetail(openTemplatesGallery(SettingsSelection()), "three-stage") + // The settings strip closes everything back to the settings page. + assertEquals(SettingsSelection(), settingsPopTo(detail, level = 0)) + // The gallery strip closes only the template detail above it. + assertEquals( + SettingsSelection(pane = SettingsPane.Gallery), + settingsPopTo(detail, level = 1), + ) + // A strip at or beyond the current depth has nothing to its right. + assertEquals(detail, settingsPopTo(detail, level = 2)) + } + + @Test + fun theSelectionSurvivesThroughItsSaverPayload() { + val detail = openTemplateDetail(openTemplatesGallery(SettingsSelection()), "three-stage") + assertEquals(detail, decodeSettingsSelection(encodeSettingsSelection(detail))) + assertEquals( + SettingsSelection(), + decodeSettingsSelection(encodeSettingsSelection(SettingsSelection())), + ) + } +} diff --git a/docs/notes/pill-overlay-and-position.md b/docs/notes/pill-overlay-and-position.md new file mode 100644 index 00000000..28fa1ce3 --- /dev/null +++ b/docs/notes/pill-overlay-and-position.md @@ -0,0 +1,148 @@ +# The destinations pill: a true overlay, centred narrow and right when wide + +## What this item changed + +`android/` only, the app shell's floating destination pill and where Templates lives. + +- `ui/PipelinesApp.kt` — the pill is a true overlay. The content `Column` no longer + reserves the pill's height (`destinationPillReserve` and the `ATTENTION_CHIP_RESERVE` + padding on it are gone); `contentPillPadding(pillVisible)` is the named zero it applies, + zero whether the pill is drawn or hidden. The pill and the attention chip stay in their + own bottom-anchored overlay `Column`, already a sibling of the content in the `Box`, so + nothing positions the content. The one placement rule is + `destinationPillAlignment(wide)` — `Alignment.CenterHorizontally` on a narrow window, + `Alignment.End` on a wide one — with the corner margin from the named `SPACING_L`; the + attention chip keeps its own bottom-right place at every width via + `Modifier.align(Alignment.End)`. `destinations` is now pipelines/runs/chat/settings + (Templates removed), and the `settings` route is `SettingsDestination`. +- `ui/components/PillInset.kt` (new) — `LocalPillBottomInset` plus `pillContentPadding` + (for a scroll container's `contentPadding`) and `Modifier.pillBottomPadding` (for a + scrollable `Column`'s own content). They add `pillScrollInset(pillVisible)` — the named + `DESTINATION_PILL_RESERVE` + `ATTENTION_CHIP_RESERVE` while the pill is drawn, zero while + it is hidden — **inside** the scroll content, never as layout padding on the container, + so the content keeps its full height, a hidden pill leaves no empty band, and the last row + still scrolls clear of the pill. Applied in the lists, the graph/source/stage panes, the + chat list and create panes, the run tabs and history, the pipeline list/detail and the + template gallery/detail. +- `ui/SettingsDestination.kt` (new) — the Settings destination as the shared + `SlidingPaneStack`: pane 0 `SettingsScreen`, pane 1 the existing `TemplateGalleryScreen`, + pane 2 the existing `TemplateDetailScreen`, with `PredictiveBackHandler`. +- `ui/SettingsSelection.kt` (new) — the pure, Bundle-able pane model + (`SettingsPane`/`SettingsSelection`, `openTemplatesGallery`, `openTemplateDetail`, + `settingsBack`, `settingsPopTo`, `encodeSettingsSelection`/`decodeSettingsSelection` and + the saver): one-level Back (detail → gallery → settings) and a covered-pane pop. +- `ui/screens/SettingsScreen.kt` — gains the Templates row (section label, card with the + `TemplatesIcon` glyph, title, description and a forward chevron) that opens the gallery; + the screen's own body takes `pillBottomPadding()`. +- `ui/TemplatesDestination.kt` — deleted (its gallery is now the settings stack's pane 1). +- `ui/theme/Dimens.kt` — the docs of `DESTINATION_PILL_RESERVE` and + `ATTENTION_CHIP_RESERVE` now describe scroll-content clearance rather than a reserved + layout band. No new token, no new hardcoded dimension. +- Tests — `PipelinesNavTest` (the pill holds no `templates` route, the remaining + destinations and their order, the narrow/wide alignment, the content's padding is zero + and the scroll inset tracks the drawn pill) and `SettingsSelectionTest` (the Templates + row opens the gallery, a card opens the detail, Back steps one pane, a covered strip pops, + the saver round-trips). This re-lands the intent of `a2043f9` ("move Templates from the + floating pill to Settings"), whose commit never reached main. + +## Shared documents this change makes stale + +`android/README.md` documents the app's surfaces this item changed. The note is written here +rather than edited in place; the `docs-fold` writer should update it. + +- `android/README.md:107` — the bullet "A **Templates** destination (its own top-level pill + between Pipelines and Runs, with its own gallery glyph rather than the Pipelines workflow + tree): a measured gallery of cards…" should read "The **Templates** gallery, reached from + a **Templates** row on the Settings page (not a floating-pill destination — it is + configuration, so it lives with the other settings; its own gallery glyph rather than the + Pipelines workflow tree): a measured gallery of cards…". The rest of the bullet (the + cards, the stage count, the column count, the detail pane) is still true. +- `android/README.md` — append the dated section below at the end of the file, after the + last record (`## Run title readability: whole in the run view, two lines in the list + (17 Oct 2026)`). Insert it verbatim; its build counts and the APK name are that run's + dated evidence, not current values. + +```markdown +## The destinations pill: a true overlay, centred narrow and right when wide (18 Oct 2026) + +The floating destination pill no longer takes layout space. It is drawn in the +bottom overlay above the content and its resting place follows the window width: +horizontally centred at the bottom on a **narrow** window, anchored to the +**bottom-right corner** on a **wide** one. Templates leaves the pill for the +Settings page. `android/` only; no new dependency (still only the declared +`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched +and no run started from the app; the build and unit tests only, no device command +run. + +- **An overlay, not a layout band.** `PipelinesApp`'s content `Column` no longer + reserves the pill's height (`destinationPillReserve` and its + `ATTENTION_CHIP_RESERVE` padding are gone). The pill and the attention chip stay + in their own bottom-anchored overlay `Column` — already a sibling of the content + in the `Box`, so nothing about them positions the content. `contentPillPadding(pillVisible)` + is the named zero it applies (zero whether the pill is drawn or hidden); a unit + test pins both states. +- **Trailing space moves into each scrollable.** A hidden pill must leave no empty + band, but scrolling to the end must still reveal the last row clear of the pill. + `pillScrollInset(pillVisible)` (the named `DESTINATION_PILL_RESERVE` + + `ATTENTION_CHIP_RESERVE` while drawn, zero while hidden) is published around the + content through the new `LocalPillBottomInset`, and `pillContentPadding` / + `Modifier.pillBottomPadding` add it to a screen's **own scroll content** (every + list, grid and scrolling detail/stage/settings body), never as layout padding on + the container — so the content keeps its full height and only its end clears the + pill. +- **Centred narrow, right corner when wide.** `destinationPillAlignment(wide)` is + the one pure rule (`Alignment.CenterHorizontally` narrow, `Alignment.End` wide); + the corner margin is the named `SPACING_L`, so no new number is introduced. The + pill still clears the safe area (system bars, cutout, gesture area and IME) via + `windowInsetsPadding(paneSafeArea())`, so it never covers the keyboard or an open + composer, and it still stands down while a conversation is open. +- **Templates leaves the pill for Settings.** `destinations` is now + pipelines/runs/chat/settings, so the pill's width (its icon row) simply narrows. + The `settings` route is the shared `SlidingPaneStack` (`SettingsDestination`): + pane 0 the Settings page, pane 1 the existing `TemplateGalleryScreen`, pane 2 the + existing `TemplateDetailScreen`. `SettingsSelection` is the pure, Bundle-able + pane model with one-level Back (detail → gallery → settings) and a + covered-pane pop. `SettingsScreen` gains a Templates row (section label + card + with the `TemplatesIcon` glyph, title, description and forward chevron). This + re-lands the intent of `a2043f9` ("move Templates from the floating pill to + Settings"), whose commit never reached main. + +Tests: the 64 result XMLs (plus Gradle's `binary` results directory) aggregate to +**593 tests, 0 failures, 0 errors, 0 skipped**. New/updated pure tests — +`PipelinesNavTest` (11, incl. the pill holds no `templates` route, the remaining +destinations and their order, the narrow/wide alignment, the content's padding is +zero, and the scroll inset tracks the drawn pill) and `SettingsSelectionTest` (6, +the Templates row opens the gallery, a card opens the detail, Back steps one pane, +a covered strip pops and the saver round-trips). + +Evidence (macOS, `JAVA_HOME=/Applications/Android Studio.app/Contents/jbr/Contents/Home`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`, Gradle 8.11.1, `--offline`, +`--no-daemon`, built at `a297fb6` = `main`'s tip with this item's working changes): + +- ` --offline --no-daemon :app:assembleDebug :app:testDebugUnitTest` → + `BUILD SUCCESSFUL`; the 64 result XMLs aggregate to 593 tests, 0 failures, 0 + errors, 0 skipped; `app-debug.apk` 18,657,246 bytes, sha256 + `c60f9b269368b51d4bc1f43b95b0970210d803e4fe0dc4add8db39e3b3821f51`. +- **APK publish.** Copied to this run's artifacts directory as + `pipelines-debug-wip-a297fb6.apk`, served at + `http://10.0.0.75:8080/artifacts/327/3/pipelines-debug-wip-a297fb6.apk` + (`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, the + downloaded bytes sha256-matching the local file). + +Not verified in this pass: how the centred/right pill actually renders and that a +scrolled list's last row clears it — that needs the device, which this +build-and-unit-test pass did not use; visual review owns the operator's Pixel 9 +Pro XL. +``` + +## Not stale + +- No packaged OpenCode skill reference documents this app surface. The references in + `internal/author/skill/references/` describe the server, the CLI and the pipeline + authoring model; none names the app's destination pill, its destinations or the + templates gallery. +- No packaged template (`examples/*.md`) and no `internal/author/` managed file names + them either, so `internal/author/install.go`'s inventory needs no change. +- `android/AGENTS.md` already describes `ui/PipelinesApp.kt` as "the app shell: + destinations, the floating pill, the omni-search morph" and lists `ui/screens/`, so + it needs no change.