diff --git a/android/README.md b/android/README.md index 22e209a6..dee0e785 100644 --- a/android/README.md +++ b/android/README.md @@ -5353,3 +5353,65 @@ owns the operator's Pixel 9 Pro XL): the on-device status change with no refresh and the live/reconnecting badge rendering. The captures and the phone's main-revision restore are that stage's evidence. +## Operator chat sessions: choose the directory, list only your own (17 Oct 2026) + +The Chat destination now starts a chat by asking where it should live, and its +list is the operator's own sessions only. Before this change "New chat" created a +session with no directory of its own choosing (it passed the workspace, so the +session landed wherever the server happened to be) and the list was whatever +`chat_sessions` returned with no way to tell an operator chat from anything +run-related. The server change this builds on (operator sessions tagged +`operator`, `chat_sessions` returning exactly those with their directory and +recency, and a `chat_directories` request) is already in this revision; nothing in +the Pipelines server, its Go source, the installer or the Docker files was +touched, no dependency was added beyond the already-declared +material-icons-extended, and no run is started from the app. + +- **Starting a chat asks where first.** `ChatScreen`'s level-1 pane is now the + directory picker while a create is in flight: the server's + `chat_directories` reply (the operator's home first, then the directories of + previous operator sessions, most recently used first) rendered through the + shared `ListRow`, each with its full path, home shown as `Home (~)` with its + absolute path beneath it. It is a normal pane of the chat stack, so Back, the + app bar's back control, the footer's Cancel and the predictive-back gesture all + leave it without creating anything — not a modal dead end. +- **The directory is always sent.** The picker starts on the operator's home + (`directoryChoices`/`defaultDirectoryChoice`) and `chat_create` is sent the + chosen directory — `~` for home, the absolute path for a recent — so a session + is never created in the server's own working directory. The server resolves or + rejects it, and its error is shown in the pane. +- **The list is the server's, and says so.** The list renders + `ChatState.visibleSessions`: exactly the server's `chat_sessions` (operator + sessions only — the app never guesses which session belongs to a run) with the + operator's own local changes applied. Each row carries its directory and the + kind chip derived from the server's own tag (`sessionTagLabel`, `operator` → + `Operator`), so an operator chat is tellable at a glance. +- **Managing a session, honestly.** The brokered protocol has no rename and no + delete for a chat session (there is no `chat_rename`/`chat_delete` type and the + native session endpoint is not exposed), so both are the operator's own, + device-local changes, persisted with the other settings + (`SettingsRepository.chat_overrides`, `ChatSessionOverrides`): rename stores a + local title that wins over the server's on every later list load, and "Remove + from list" hides the row and closes its conversation while a snackbar reports + it as a local, undoable change ("Removed from this list; the chat stays on the + server.") with an Undo action. Nothing is deleted on the server, and a refresh + cannot bring a removed row back. +- **Everything else is unchanged.** Multi-chat drafts/scroll/running, streaming, + tool chips, diff cards, approval cards, stop and the reconnect path are + untouched; the picker only reuses the stack's second level the conversation + already used. + +Tests (`app/src/test`): `ChatDirectoriesTest` (home first and the default, the +recents' order and their full-path create value, an empty/blank reply still +yielding home), `ChatSessionManagementTest` (the chip from the server's tag, the +create flow's home default and chosen directory, rename winning over the server +title and surviving a refresh, removal hiding until undone and leaving the +server's list intact, the override encode/decode round trip) and the new +`ChatProtocolTest` cases for the `tag` field and the `chat_directories` +request/reply. + +Not verified in this pass: the on-device picker, the tagged list and a session +open in a chosen directory — the brief keeps implementation verification to the +build and the unit tests, and visual review owns the device. The chip, menu and +dialog are Compose UI, which this module has no unit harness for; they are +covered by compilation only. 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 07265731..40d8af02 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 @@ -210,14 +210,29 @@ class PipelinesRepository( // ---- Brokered OpenCode chat (route B): the phone never speaks OpenCode // directly and never holds its credentials. ---- - /** Lists the sessions this server owns, with the `busy` flag the phone renders read-only. */ + /** + * Lists the sessions this server owns, with the `busy` flag the phone renders + * read-only. The server already returns operator sessions only, so the app + * never filters this list by ownership. + */ suspend fun chatSessions(): List = client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList() /** - * Creates a session and returns it. The server currently answers this type - * with an explicit error when it does not broker creation; the caller - * surfaces that message rather than guessing at a session id. + * The directories a new chat can be started in: the operator's home first, + * then the directories of previous operator sessions, most recently used + * first. The server is the only source of these choices — the app never + * invents one. + */ + suspend fun chatDirectories(): List = + client.call(Message(type = Protocol.CHAT_DIRECTORIES)).chatDirectories ?: emptyList() + + /** + * Creates a session in an explicit [directory] and returns it. The directory + * is always sent (the server resolves `~` to the operator's home), so a chat + * is never created in whatever directory the server happens to be running in. + * The server reports its own error when it does not broker creation; the + * caller surfaces that message rather than guessing at a session id. */ suspend fun chatCreate(title: String, directory: String): ChatSession { val response = client.call( diff --git a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt index 8f4a8c7b..48bdc9c8 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/SettingsRepository.kt @@ -6,7 +6,8 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow /** - * Persists the explicitly configured server URL and workspace path as plain, + * Persists the explicitly configured server URL and workspace path, the list + * sort/filter choices and the operator's local chat-session changes as plain, * non-secret preferences. No credentials or tokens are ever stored, because the * server has no authentication. */ @@ -52,6 +53,12 @@ class SettingsRepository(context: Context) { private val _pipelineFilterName = MutableStateFlow(prefs.getString(KEY_PIPELINE_FILTER_NAME, "").orEmpty()) val pipelineFilterName: StateFlow = _pipelineFilterName.asStateFlow() + // The operator's local chat-session changes (renames and removals), stored as + // one opaque JSON string: the chat layer owns the shape, so this repository + // stays unaware of the chat model, exactly like the sort/filter keys above. + private val _chatOverrides = MutableStateFlow(prefs.getString(KEY_CHAT_OVERRIDES, "").orEmpty()) + val chatOverrides: StateFlow = _chatOverrides.asStateFlow() + fun setServerUrl(value: String) { val trimmed = value.trim() _serverUrl.value = trimmed @@ -104,6 +111,12 @@ class SettingsRepository(context: Context) { prefs.edit().putString(KEY_PIPELINE_FILTER_NAME, value).apply() } + fun setChatOverrides(value: String) { + if (value == _chatOverrides.value) return + _chatOverrides.value = value + prefs.edit().putString(KEY_CHAT_OVERRIDES, value).apply() + } + /** True only when the user has explicitly supplied both required values. */ fun isConfigured(): Boolean = _serverUrl.value.isNotBlank() && _workspace.value.isNotBlank() @@ -118,5 +131,6 @@ class SettingsRepository(context: Context) { const val KEY_PIPELINE_FILTER_PRESENCE = "pipeline_filter_presence" const val KEY_PIPELINE_FILTER_RUN_STATUSES = "pipeline_filter_run_statuses" const val KEY_PIPELINE_FILTER_NAME = "pipeline_filter_name" + const val KEY_CHAT_OVERRIDES = "chat_overrides" } } 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 f4b8a747..d6b3f6d9 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 @@ -22,6 +22,11 @@ data class ChatSession( val model: String = "", val directory: String = "", @SerialName("parent_id") val parentId: String = "", + // The stored session kind. The only value the server records is "operator" + // (a chat the person created); a pipeline stage session is never tagged and + // is never listed by chat_sessions. Additive/optional, so an older server + // simply omits it and the client shows no kind chip. + val tag: String = "", @SerialName("created_at") val createdAt: Long = 0, @SerialName("updated_at") val updatedAt: Long = 0, // Another client holds the session, or the server itself owns it as an active @@ -200,6 +205,13 @@ object ChatProtocol { const val DECISION_ALWAYS = "always" const val DECISION_REJECT = "reject" + /** + * The only stored [ChatSession.tag] value, mirroring `internal/protocol/ + * chat.go`: a session the operator created. The display label (`Operator`) is + * derived from it by the UI rather than carried as a second field. + */ + const val TAG_OPERATOR = "operator" + /** A tool call still in flight (no result or error yet). */ fun toolRunning(state: ChatToolState?): Boolean = when (state?.status) { TOOL_STREAMING, TOOL_RUNNING -> true 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 fb4a586d..b83db794 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 @@ -65,6 +65,9 @@ object Protocol { const val CHAT_MESSAGES = "chat_messages" const val CHAT_INTERRUPT = "chat_interrupt" const val CHAT_REPLY = "chat_reply" + // 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" // Server-pushed frames with no matching request. const val CHAT_EVENT = "chat_event" const val CHAT_PERMISSION = "chat_permission" @@ -635,4 +638,5 @@ data class Message( @SerialName("chat_event") val chatEvent: ChatEventFrame? = null, @SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null, @SerialName("chat_reply") val chatReply: ChatReplyRequest? = 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 95c97523..35ac97de 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 @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import net.awan.pipelines.PipelinesApplication @@ -35,6 +36,7 @@ import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.protocol.Template import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.data.transport.ServerUrl +import net.awan.pipelines.ui.chat.ChatSessionOverrides import net.awan.pipelines.ui.chat.ChatState import net.awan.pipelines.ui.chat.ChatStore @@ -130,7 +132,7 @@ class AppViewModel( private val retryKeys = ConcurrentHashMap() /** The multi-chat screen state (sessions, open conversations, drafts, scroll). */ - private val chatStore = ChatStore() + private val chatStore = ChatStore(overrides = ChatSessionOverrides.decode(settings.chatOverrides.value)) val chat: StateFlow = chatStore.state // The live run subscription: the workspace currently watched, the job that @@ -172,6 +174,7 @@ class AppViewModel( observeChatEvents() observeRunEvents() observeConnection() + observeChatOverrides() } /** @@ -457,6 +460,19 @@ class AppViewModel( if (subscribedWorkspace != null) _runStream.value = RunStreamState.Connecting } + /** + * Persists the operator's local chat changes (renames and removals) as they + * happen, so a managed list survives a restart. Only a real change is written; + * the settings repository ignores a repeat, so the initial emission is a no-op. + */ + private fun observeChatOverrides() { + viewModelScope.launch { + chatStore.state.map { it.overrides }.distinctUntilChanged().collect { + settings.setChatOverrides(it.encode()) + } + } + } + fun updateServerUrlDraft(value: String) { _serverUrlDraft.value = value _urlError.value = null @@ -766,6 +782,23 @@ class AppViewModel( } } + /** + * Refreshes the directories a new chat can start in (the operator's home first, + * then the recents). The server is the only source, so a failed load reports + * its error rather than inventing a choice. + */ + fun refreshChatDirectories() { + viewModelScope.launch { + chatStore.directoriesLoading() + try { + chatStore.directoriesLoaded(repository.chatDirectories()) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.directoriesFailed(ErrorMessages.describe(t)) + } + } + } + /** * Opens [session] and makes it active. A brand-new chat always loads its * history; a running one re-syncs from the server so a stale copy is never @@ -790,21 +823,63 @@ class AppViewModel( fun saveChatScroll(sessionId: String, index: Int, offset: Int) = chatStore.scroll(sessionId, index, offset) - /** Creates a session on the server and opens it. Reports the server's own error on failure. */ - fun newChat() { + // ---- Directory choices and starting a new chat --------------------------- + + /** + * Opens the directory picker for a new chat and refreshes its choices. The + * chat is not created until a directory is confirmed, so "New chat" can never + * create a session wherever the server happens to be. + */ + fun startNewChat() { + chatStore.createOpened() + refreshChatDirectories() + } + + /** Picks the directory the new chat will be created in. */ + fun selectChatDirectory(directory: String) = chatStore.createDirectoryChosen(directory) + + /** Leaves the create flow without creating anything. */ + fun cancelNewChat() = chatStore.createCancelled() + + /** + * Creates the chat in the chosen directory and opens it. The directory is + * always sent, so the server resolves it (or rejects it) instead of falling + * back to its own working directory. + */ + fun createNewChat() { + val create = chatStore.value.create ?: return + if (create.creating) return + chatStore.creating() viewModelScope.launch { try { - val created = repository.chatCreate(title = "New chat", directory = settings.workspace.value) - chatStore.sessionsLoaded(chatStore.value.sessions + created) - chatStore.open(created) + val created = repository.chatCreate(title = "New chat", directory = create.directory) + chatStore.createSucceeded(created) chatStore.history(created.id, emptyList()) } catch (t: Throwable) { if (t is CancellationException) throw t - chatStore.sessionsFailed(ErrorMessages.describe(t)) + chatStore.createFailed(ErrorMessages.describe(t)) } } } + // ---- Managing a session -------------------------------------------------- + + /** + * Renames a session. The brokered protocol has no rename, so the title is kept + * on this device (persisted with the other settings) and shown in place of the + * server's own; nothing is sent to the server. + */ + fun renameChat(sessionId: String, title: String) = chatStore.rename(sessionId, title) + + /** + * Removes a session from this device's list. The server is not asked to delete + * anything — it exposes no delete for an OpenCode session — so the removal is + * local and can be undone from the message that reports it. + */ + fun removeChat(sessionId: String) = chatStore.remove(sessionId) + + fun undoRemoveChat() = chatStore.undoRemove() + fun loadChatHistory(sessionId: String) { viewModelScope.launch { chatStore.historyLoading(sessionId) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDirectories.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDirectories.kt new file mode 100644 index 00000000..5af8ac43 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatDirectories.kt @@ -0,0 +1,56 @@ +package net.awan.pipelines.ui.chat + +/** + * The value chat_create uses for the operator's home directory. It is the one + * literal the server documents (`~`, `~/...` and an omitted/empty value all + * resolve to the operator's home), so the home choice is sent exactly as the + * server defines it instead of relying on a locally known absolute path. + */ +const val HOME_DIRECTORY = "~" + +/** + * One directory the operator can start a new chat in, derived from the server's + * `chat_directories` reply (the operator's home first, then the directories of + * previous operator sessions, most recently used first). + * + * [label] is what the row shows; [path] is the full directory, always shown so + * the operator can tell two directories apart. [createDirectory] is what + * chat_create sends: the home choice goes as [HOME_DIRECTORY] and a recent as + * its absolute path. + */ +data class ChatDirectoryChoice( + val label: String, + val path: String, + val home: Boolean, +) { + val createDirectory: String get() = if (home) HOME_DIRECTORY else path + + /** The full path shown beneath the home row; a recent's own label is its path. */ + val secondary: String? get() = if (home) path else null +} + +/** + * The picker's choices from the server's reported directories. The first entry is + * the operator's home — the one entry the server always returns first and never + * dedupes away — and the rest keep the server's most-recently-used order. A blank + * entry is dropped, and a reply with nothing in it still yields the home choice, + * so the picker is never empty. + */ +fun directoryChoices(directories: List): List { + val cleaned = directories.filter { it.isNotBlank() } + val home = cleaned.firstOrNull() ?: HOME_DIRECTORY + return buildList { + add(ChatDirectoryChoice(label = HOME_TEXT, path = home, home = true)) + cleaned.drop(1).forEach { add(ChatDirectoryChoice(label = it, path = it, home = false)) } + } +} + +/** + * The choice a freshly opened picker starts on: the operator's home, first. The + * operator has to touch the picker only to change the directory, never to accept + * the default. + */ +fun defaultDirectoryChoice(choices: List): ChatDirectoryChoice? = choices.firstOrNull() + +/** The home row's label; the `~` the server accepts, named so the flow reads. */ +private const val HOME_TEXT = "Home ($HOME_DIRECTORY)" 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 2a14bf87..629262f7 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 @@ -85,6 +85,21 @@ internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" } internal fun sessionTitle(session: ChatSession): String = session.title.ifBlank { session.id.take(18).ifBlank { "Untitled chat" } } +/** + * The kind chip a session row shows, derived from the server's own tag: a session + * the server tagged `operator` reads `Operator`. Any other tag is shown verbatim + * (a kind this client does not know is never silently dropped) and an untagged + * session shows no chip. This only *labels*; the app never filters on the tag, + * because the server already lists operator sessions only. + */ +internal fun sessionTagLabel(session: ChatSession): String? = when { + session.tag.isBlank() -> null + session.tag == ChatProtocol.TAG_OPERATOR -> OPERATOR_TAG_LABEL + else -> session.tag +} + +private const val OPERATOR_TAG_LABEL = "Operator" + /** * The status a session row shows. A locally-running turn is reported as * `Running`; otherwise the server's `busy` flag is `Busy · read-only` (another 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 new file mode 100644 index 00000000..52ebdafa --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatOverrides.kt @@ -0,0 +1,58 @@ +package net.awan.pipelines.ui.chat + +import kotlinx.serialization.Serializable +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. + * + * - [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]). + * + * Kept as a serializable value so it survives a restart as one preference, + * exactly like the app's other stored settings. + */ +@Serializable +data class ChatSessionOverrides( + val titles: Map = emptyMap(), + val hidden: List = emptyList(), +) { + /** The hidden ids as a set, so membership checks on the list are O(1). */ + val hiddenIds: Set get() = hidden.toSet() + + /** Records a local rename for [id]; a blank id or title is ignored. */ + fun renamed(id: String, title: String): ChatSessionOverrides { + val trimmed = title.trim() + if (id.isBlank() || trimmed.isEmpty()) return this + return copy(titles = titles + (id to trimmed)) + } + + /** Hides [id] from the list; a blank id or an already-hidden one changes nothing. */ + fun hide(id: String): ChatSessionOverrides = + if (id.isBlank() || id in hidden) this else copy(hidden = hidden + id) + + /** Restores a hidden [id] to the list, undoing [hide]. */ + fun restore(id: String): ChatSessionOverrides = + if (id !in hidden) this else copy(hidden = hidden - id) + + /** The one-line JSON this value is stored as; never fails on our own value. */ + fun encode(): String = PipelinesJson.encodeToString(serializer(), this) + + companion object { + /** Decodes a stored value; anything unreadable falls back to no overrides. */ + fun decode(stored: String): ChatSessionOverrides = + if (stored.isBlank()) { + ChatSessionOverrides() + } else { + runCatching { PipelinesJson.decodeFromString(serializer(), stored) } + .getOrDefault(ChatSessionOverrides()) + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 0581f19a..bbe89ac5 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -38,15 +38,19 @@ import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.PanTool import androidx.compose.material.icons.filled.Psychology import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Stop import androidx.compose.material.icons.outlined.Shield +import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -54,6 +58,10 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -99,6 +107,7 @@ import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.EmptyState import net.awan.pipelines.ui.components.ErrorState +import net.awan.pipelines.ui.components.LabelChip import net.awan.pipelines.ui.components.ListRow import net.awan.pipelines.ui.components.LoadingState import net.awan.pipelines.ui.components.PaneIdentity @@ -113,6 +122,8 @@ 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.ICON_LIST_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XXS import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP import net.awan.pipelines.ui.theme.pipelinesText @@ -157,21 +168,25 @@ fun ChatScreen(vm: AppViewModel, wide: Boolean, modifier: Modifier = Modifier) { val state by vm.chat.collectAsStateWithLifecycle() val connection by vm.connectionState.collectAsStateWithLifecycle() val active = state.active + val create = state.create // Fetch the server's session list once when the Chat destination opens. LaunchedEffect(Unit) { vm.refreshChatSessions() } - // Back inside a conversation returns to the session list before leaving the - // destination, exactly one level (the same rule the other destinations use). - PredictiveBackHandler(enabled = active != null) { progress -> + // Back leaves the create flow first, then a conversation, before leaving the + // destination, exactly one level at a time (the same rule the other + // destinations use). + PredictiveBackHandler(enabled = create != null || active != null) { progress -> progress.collect { } - vm.showChatList() + if (create != null) vm.cancelNewChat() else vm.showChatList() } SlidingPaneStack( - depth = if (active != null) 1 else 0, + // The directory picker and the conversation share the second level: they + // are mutually exclusive, so a pane is never mounted empty behind either. + depth = if (create != null || active != null) 1 else 0, wide = wide, - onPopTo = { vm.showChatList() }, + onPopTo = { if (state.create != null) vm.cancelNewChat() else vm.showChatList() }, compactLabel = "Chats", backContentDescription = { "Back to chats" }, modifier = modifier, @@ -184,11 +199,14 @@ fun ChatScreen(vm: AppViewModel, wide: Boolean, modifier: Modifier = Modifier) { covered = covered, modifier = paneModifier, ) - 1 -> active?.let { thread -> - // Key by session so each conversation gets its own list state and - // disposes (saving its scroll) when the operator switches away. - key(thread.sessionId) { - ChatConversationPane(vm = vm, state = state, thread = thread, modifier = paneModifier) + 1 -> when { + create != null -> NewChatPane(vm = vm, state = state, create = create, modifier = paneModifier) + active != null -> { + // Key by session so each conversation gets its own list state + // and disposes (saving its scroll) when the operator switches away. + key(active.sessionId) { + ChatConversationPane(vm = vm, state = state, thread = active, modifier = paneModifier) + } } } } @@ -206,12 +224,16 @@ private fun ChatListPane( covered: Boolean, modifier: Modifier, ) { + // A covered pane shows its compact identity only; the server list and the + // operator's own local changes are folded into the visible projection only + // for the pane actually drawn, never for the sliver behind a conversation. if (covered) { + val count = state.visibleSessionCount PaneIdentity( title = "Chat", subtitle = when { state.open.isNotEmpty() -> "${state.open.size} open" - state.sessions.isNotEmpty() -> "${state.sessions.size} sessions" + count > 0 -> "$count sessions" else -> null }, modifier = modifier.fillMaxSize(), @@ -219,8 +241,30 @@ private fun ChatListPane( return } + // The server returns operator sessions only, with the operator's own local + // renames and removals applied on top; the app never guesses which session + // belongs to a run. + val sessions = state.visibleSessions + + // A removal is reported for what it is: a local, undoable change, never a + // pretend delete — the server is not asked to remove anything. + val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(state.lastRemoved) { + if (state.lastRemoved != null && + snackbarHostState.showSnackbar( + message = CHAT_REMOVED_MESSAGE, + actionLabel = "Undo", + duration = SnackbarDuration.Long, + ) == SnackbarResult.ActionPerformed + ) { + vm.undoRemoveChat() + } + } + var renaming by remember { mutableStateOf(null) } + Scaffold( modifier = modifier, + snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { TopAppBar( title = { Text("Chat") }, @@ -228,7 +272,7 @@ private fun ChatListPane( IconButton(onClick = vm::refreshChatSessions) { Icon(Icons.Default.Refresh, contentDescription = "Refresh chats") } - IconButton(onClick = vm::newChat) { + IconButton(onClick = vm::startNewChat) { Icon(Icons.Default.Add, contentDescription = "New chat") } }, @@ -247,17 +291,17 @@ private fun ChatListPane( NotConnectedNotice() } when { - state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…") - state.sessionsError != null && state.sessions.isEmpty() -> { + state.sessionsLoading && sessions.isEmpty() -> LoadingState("Loading chats…") + state.sessionsError != null && sessions.isEmpty() -> { ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions) } - state.sessions.isEmpty() -> EmptyState( + sessions.isEmpty() -> EmptyState( message = "No chat sessions on this server yet.", actionLabel = "New chat", - onAction = vm::newChat, + onAction = vm::startNewChat, ) else -> LazyColumn(Modifier.fillMaxSize()) { - items(state.sessions, key = { it.id }) { session -> + items(sessions, key = { it.id }) { session -> val thread = state.thread(session.id) SessionRow( session = session, @@ -265,6 +309,8 @@ private fun ChatListPane( running = thread?.running == true, active = state.activeId == session.id, onClick = { vm.openChatSession(session) }, + onRename = { renaming = session }, + onRemove = { vm.removeChat(session.id) }, ) } if (state.sessionsError != null) { @@ -281,6 +327,17 @@ private fun ChatListPane( } } } + + renaming?.let { session -> + RenameChatDialog( + session = session, + onDismiss = { renaming = null }, + onConfirm = { title -> + vm.renameChat(session.id, title) + renaming = null + }, + ) + } } @Composable @@ -290,18 +347,28 @@ private fun SessionRow( running: Boolean, active: Boolean, onClick: () -> Unit, + onRename: () -> Unit, + onRemove: () -> Unit, ) { val texts = pipelinesText() ListRow(selected = active, onClick = onClick) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth(), + ) { Text( text = sessionTitle(session), style = texts.cardTitle, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f, fill = false), + modifier = Modifier.weight(1f), ) + // The kind chip names the session kind the server reported, so an + // operator chat is tellable from anything run-related at a glance. + sessionTagLabel(session)?.let { LabelChip(it, SPACING_S, SPACING_XXS) } if (open) SessionBadge("Open", running) + SessionMenu(onRename = onRename, onRemove = onRemove) } val meta = buildList { add(sessionStatusLabel(session, running)) @@ -312,6 +379,208 @@ private fun SessionRow( } } +/** A session row's management actions: rename and remove from this device's list. */ +@Composable +private fun SessionMenu(onRename: () -> Unit, onRemove: () -> Unit) { + var expanded by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { expanded = true }, modifier = Modifier.size(ICON_BUTTON_SMALL_DP)) { + Icon( + Icons.Default.MoreVert, + contentDescription = "Chat actions", + modifier = Modifier.size(ICON_INLINE_DP), + ) + } + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + DropdownMenuItem( + text = { Text("Rename…") }, + onClick = { + expanded = false + onRename() + }, + ) + DropdownMenuItem( + text = { Text("Remove from list") }, + onClick = { + expanded = false + onRemove() + }, + ) + } + } +} + +/** + * 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 + * implying the server was told. + */ +@Composable +private fun RenameChatDialog(session: ChatSession, onDismiss: () -> Unit, onConfirm: (String) -> Unit) { + var title by remember(session.id) { mutableStateOf(sessionTitle(session)) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Rename chat") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + singleLine = true, + label = { Text("Name") }, + modifier = Modifier.fillMaxWidth(), + ) + Text( + text = "The server has no rename for a chat, so this name is kept on this device.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + confirmButton = { + TextButton(onClick = { onConfirm(title) }, enabled = title.isNotBlank()) { Text("Save") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +// ---- The create flow: choose the directory, then create ---------------------- + +/** + * Where the operator starts a new chat: the server's directories, the home first + * and the recents after it, each with its full path. It is a normal pane of the + * chat stack — Back or its Cancel control leaves without creating anything — so + * starting a chat is a step in the flow rather than a modal dead end, and a + * session is never created wherever the server happens to run. + * + * The operator's home is the default; a recent is chosen with one tap, and the + * chat is created only when the operator confirms. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun NewChatPane( + vm: AppViewModel, + state: ChatState, + create: ChatCreateState, + modifier: Modifier, +) { + val choices = remember(state.directories) { directoryChoices(state.directories) } + val selected = remember(create.directory, choices) { + choices.firstOrNull { it.createDirectory == create.directory } ?: defaultDirectoryChoice(choices) + } + Scaffold( + modifier = modifier, + topBar = { + TopAppBar( + title = { Text("Start a chat") }, + navigationIcon = { + IconButton(onClick = vm::cancelNewChat) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel new chat") + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding)) { + when { + state.directoriesError != null && !state.directoriesLoaded -> + ErrorState(state.directoriesError, onRetry = vm::refreshChatDirectories) + !state.directoriesLoaded -> LoadingState("Loading directories…") + else -> { + Text( + text = "Where should this chat live?", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + LazyColumn(Modifier.weight(1f).fillMaxWidth()) { + items(choices, key = { it.createDirectory }) { choice -> + DirectoryRow( + choice = choice, + selected = choice.createDirectory == selected?.createDirectory, + onClick = { vm.selectChatDirectory(choice.createDirectory) }, + ) + } + } + if (state.directoriesError != null) { + Text( + text = state.directoriesError, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + } + create.error?.let { error -> + Text( + text = error, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + } + NewChatActions( + directory = selected?.createDirectory ?: create.directory, + creating = create.creating, + onCreate = vm::createNewChat, + onCancel = vm::cancelNewChat, + ) + } + } + } + } +} + +/** One directory the new chat can live in: the home first, then the recents. */ +@Composable +private fun DirectoryRow(choice: ChatDirectoryChoice, selected: Boolean, onClick: () -> Unit) { + ListRow(selected = selected, onClick = onClick) { + Text( + text = choice.label, + style = pipelinesText().cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + // The home row's label is `~`, so its full path is shown beneath it; a + // recent's own label already is its full path. + choice.secondary?.let { path -> + Text(text = path, style = pipelinesText().meta, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +/** The create flow's footer: the chosen directory, its confirm and its cancel. */ +@Composable +private fun NewChatActions(directory: String, creating: Boolean, onCreate: () -> Unit, onCancel: () -> Unit) { + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP), + modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER), + ) { + Text( + text = "Start in $directory", + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onCancel, enabled = !creating) { Text("Cancel") } + Button(onClick = onCreate, enabled = !creating) { + if (creating) { + Box(contentAlignment = Alignment.Center) { + CircularProgressIndicator(Modifier.size(ICON_INLINE_DP), strokeWidth = 2.dp) + } + } else { + Text("New chat") + } + } + } + } +} + +/** 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." + /** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */ @Composable private fun SessionBadge(label: String, running: Boolean = false) { 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 cdaf4469..60320f9e 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 @@ -77,9 +77,23 @@ data class ChatThread( } /** - * The multi-chat screen state. [sessions] is the server's list; [open] is the - * ordered set of conversations the operator has opened, each preserved - * independently; [activeId] is the one currently on screen. + * The directory picker's state while a new chat is being started. It holds only + * what the picker needs: the chosen directory (the operator's home until a recent + * is picked), whether the create request is in flight, and the server's error when + * it fails. The picker is a normal pane of the chat stack, so the operator can go + * back out of it at any point. + */ +data class ChatCreateState( + val directory: String = HOME_DIRECTORY, + val creating: Boolean = false, + val error: String? = null, +) + +/** + * The multi-chat screen state. [sessions] is the server's list (operator sessions + * only — the server does the filtering, never the app); [open] is the ordered set + * of conversations the operator has opened, each preserved independently; + * [activeId] is the one currently on screen. */ data class ChatState( val sessions: List = emptyList(), @@ -88,10 +102,53 @@ data class ChatState( val sessionsError: String? = null, val open: List = emptyList(), val activeId: String? = null, + /** The server's directory choices for a new chat, home first. */ + val directories: List = emptyList(), + val directoriesLoading: Boolean = false, + val directoriesLoaded: Boolean = false, + val directoriesError: String? = null, + /** Non-null while the operator is choosing where to start a new chat. */ + val create: ChatCreateState? = null, + /** The operator's own local renames and removals (see [ChatSessionOverrides]). */ + val overrides: ChatSessionOverrides = ChatSessionOverrides(), + /** The id of the session most recently removed, while its removal can be undone. */ + val lastRemoved: String? = null, ) { val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId } fun thread(sessionId: String): ChatThread? = open.firstOrNull { it.sessionId == sessionId } + + /** + * The sessions the list shows: the server's list with the operator's own + * local changes applied — a removed chat is hidden and a renamed one shows its + * local title. This is the only filtering the app does, and it is the + * operator's explicit action, never a guess about which session belongs to a + * run: the server already returns operator sessions only. + */ + val visibleSessions: List + get() { + val overrides = this.overrides + if (overrides.hidden.isEmpty() && overrides.titles.isEmpty()) return sessions + // The hidden ids are resolved once for the whole list, so each row's + // membership check is O(1) instead of rebuilding the set per element. + val hiddenIds = overrides.hiddenIds + return sessions + .filterNot { it.id in hiddenIds } + .map { session -> overrides.titles[session.id]?.let { session.copy(title = it) } ?: session } + } + + /** + * How many sessions the list shows. The covered pane's identity shows only + * this count, so a pane drawn as a sliver never builds the renamed projection + * of [visibleSessions]; the same local removals are applied either way. + */ + val visibleSessionCount: Int + get() = if (overrides.hidden.isEmpty()) { + sessions.size + } else { + val hiddenIds = overrides.hiddenIds + sessions.count { it.id !in hiddenIds } + } } /** @@ -110,9 +167,12 @@ data class ChatState( * [now] is injectable so the running indicator's elapsed time is testable without * a device clock. */ -class ChatStore(private val now: () -> Long = System::currentTimeMillis) { +class ChatStore( + private val now: () -> Long = System::currentTimeMillis, + overrides: ChatSessionOverrides = ChatSessionOverrides(), +) { - private val _state = MutableStateFlow(ChatState()) + private val _state = MutableStateFlow(ChatState(overrides = overrides)) val state: StateFlow = _state.asStateFlow() val value: ChatState get() = _state.value @@ -131,14 +191,16 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) { * Replaces the server's session list and folds its title/busy flags into any * already-open thread, so a status change is reflected without dropping the * conversation. An open thread the server no longer lists is kept (its - * conversation is still the operator's). + * conversation is still the operator's). A local rename wins over the server's + * title, so refreshing the list never undoes what the operator named it. */ fun sessionsLoaded(sessions: List) { val byId = sessions.associateBy { it.id } + val renamed = _state.value.overrides.titles val open = _state.value.open.map { thread -> val session = byId[thread.sessionId] ?: return@map thread thread.copy( - title = session.title.ifBlank { thread.title }, + title = renamed[thread.sessionId] ?: session.title.ifBlank { thread.title }, directory = session.directory.ifBlank { thread.directory }, busy = session.busy, ) @@ -152,6 +214,107 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) { ) } + // ---- Directory choices and starting a chat ------------------------------- + + fun directoriesLoading() { + _state.value = _state.value.copy(directoriesLoading = true, directoriesError = null) + } + + /** Replaces the picker's choices with the server's (home first, recents after). */ + fun directoriesLoaded(directories: List) { + _state.value = _state.value.copy( + directories = directories.filter { it.isNotBlank() }, + directoriesLoading = false, + directoriesLoaded = true, + directoriesError = null, + ) + } + + fun directoriesFailed(message: String) { + _state.value = _state.value.copy(directoriesLoading = false, directoriesError = message) + } + + /** Opens the directory picker on its default (the operator's home). */ + fun createOpened() { + _state.value = _state.value.copy(create = ChatCreateState()) + } + + /** Picks a directory in the picker; the home stays the default until this is called. */ + fun createDirectoryChosen(directory: String) { + val create = _state.value.create ?: return + _state.value = _state.value.copy(create = create.copy(directory = directory, error = null)) + } + + /** Leaves the create flow without creating anything. */ + fun createCancelled() { + if (_state.value.create != null) _state.value = _state.value.copy(create = null) + } + + fun creating() { + val create = _state.value.create ?: return + _state.value = _state.value.copy(create = create.copy(creating = true, error = null)) + } + + fun createFailed(message: String) { + val create = _state.value.create ?: return + _state.value = _state.value.copy(create = create.copy(creating = false, error = message)) + } + + /** + * The chat was created in its chosen directory: the picker closes, the new + * (most recently used) session goes to the head of the list and becomes the + * active conversation. The caller then loads its — empty — history. + */ + fun createSucceeded(session: ChatSession) { + _state.value = _state.value.copy( + sessions = listOf(session) + _state.value.sessions.filterNot { it.id == session.id }, + create = null, + ) + open(session) + } + + // ---- Renaming and removing ---------------------------------------------- + + /** + * Renames a session locally. The server has no rename for a chat session, so + * the new title is kept on this device and left to win over the server's own + * on every later list load; the server's copy is untouched. + */ + fun rename(sessionId: String, title: String) { + val overrides = _state.value.overrides.renamed(sessionId, title) + if (overrides == _state.value.overrides) return + val renamed = overrides.titles.getValue(sessionId) + _state.value = _state.value.copy( + overrides = overrides, + open = _state.value.open.map { if (it.sessionId == sessionId) it.copy(title = renamed) else it }, + ) + } + + /** + * 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]. + */ + fun remove(sessionId: String) { + if (sessionId.isBlank()) return + if (_state.value.sessions.none { it.id == sessionId } && _state.value.thread(sessionId) == null) return + _state.value = _state.value.copy( + overrides = _state.value.overrides.hide(sessionId), + open = _state.value.open.filterNot { it.sessionId == sessionId }, + activeId = if (_state.value.activeId == sessionId) null else _state.value.activeId, + lastRemoved = sessionId, + ) + } + + /** Restores the most recently removed session to the list and forgets it. */ + fun undoRemove() { + val id = _state.value.lastRemoved ?: return + _state.value = _state.value.copy( + overrides = _state.value.overrides.restore(id), + lastRemoved = null, + ) + } + // ---- Opening / switching ------------------------------------------------- /** @@ -161,10 +324,13 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) { */ fun open(session: ChatSession): Boolean { val existing = _state.value.thread(session.id) + // A local rename always wins over the server's title, whether the thread + // is new or already open. + val title = _state.value.overrides.titles[session.id] ?: session.title if (existing == null) { val thread = ChatThread( sessionId = session.id, - title = session.title, + title = title, directory = session.directory, model = session.model, agent = session.agent, @@ -175,7 +341,7 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) { return true } val merged = existing.copy( - title = session.title.ifBlank { existing.title }, + title = title.ifBlank { existing.title }, directory = session.directory.ifBlank { existing.directory }, busy = session.busy, ) @@ -352,7 +518,7 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) { val session = _state.value.sessions.firstOrNull { it.id == sessionId } val placeholder = ChatThread( sessionId = sessionId, - title = session?.title ?: "", + title = _state.value.overrides.titles[sessionId] ?: session?.title ?: "", directory = session?.directory ?: "", busy = session?.busy ?: false, ) 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 c30e57f7..23a3a0f3 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 @@ -239,6 +239,42 @@ class ChatProtocolTest { assertNull(decoded.chatReply) } + /** + * The session list carries the server's own kind tag: an operator session + * reads `operator` and an untagged one stays untagged, so the app can label + * without ever guessing which session belongs to a run. + */ + @Test + fun chatSessionsCarryTheServersOwnKindTag() { + val json = """ + {"type":"chat_sessions","chat_sessions":[ + {"id":"ses_op","title":"Mine","directory":"/home/op","tag":"operator"}, + {"id":"ses_other","title":"Something else"}]} + """.trimIndent() + val sessions = PipelinesJson.decodeFromString(Message.serializer(), json).chatSessions!! + assertEquals(ChatProtocol.TAG_OPERATOR, sessions[0].tag) + assertEquals("", sessions[1].tag) + } + + /** The create flow's directory request and its reply round-trip the wire shape. */ + @Test + fun chatDirectoriesRequestAndResponseRoundTrip() { + val request = Message(type = Protocol.CHAT_DIRECTORIES, id = "android-7") + val decodedRequest = PipelinesJson.decodeFromString( + Message.serializer(), + PipelinesJson.encodeToString(Message.serializer(), request), + ) + assertEquals(Protocol.CHAT_DIRECTORIES, decodedRequest.type) + assertNull(decodedRequest.chatDirectories) + + val reply = """ + {"type":"chat_directories","id":"android-7", + "chat_directories":["/home/op","/home/op/work"]} + """.trimIndent() + val decoded = PipelinesJson.decodeFromString(Message.serializer(), reply) + assertEquals(listOf("/home/op", "/home/op/work"), decoded.chatDirectories) + } + /** A non-chat envelope leaves every chat field null, so the two never cross-talk. */ @Test fun nonChatEnvelopeHasNoChatPayload() { diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatDirectoriesTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatDirectoriesTest.kt new file mode 100644 index 00000000..9d19b8c3 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatDirectoriesTest.kt @@ -0,0 +1,52 @@ +package net.awan.pipelines.ui.chat + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The create flow's directory choices: the server's home first (the picker's + * default), the recents in the server's own order, and the value each choice + * sends to chat_create. Pure, so it needs no device or server. + */ +class ChatDirectoriesTest { + + @Test + fun homeIsFirstAndIsTheDefaultChoice() { + val choices = directoryChoices(listOf("/home/op", "/home/op/work")) + assertEquals(2, choices.size) + + val home = choices.first() + assertTrue(home.home) + assertEquals(HOME_DIRECTORY, home.createDirectory) + assertEquals("/home/op", home.path) + // The home row is labelled `~` and its full path is shown beneath it. + assertEquals("/home/op", home.secondary) + assertEquals(home, defaultDirectoryChoice(choices)) + } + + @Test + fun recentsKeepTheServersOrderAndCreateInTheirFullPath() { + val choices = directoryChoices(listOf("/home/op", "/home/op/work", "/home/op/repos/x")) + assertEquals( + listOf("/home/op/work", "/home/op/repos/x"), + choices.drop(1).map { it.createDirectory }, + ) + choices.drop(1).forEach { choice -> + assertFalse(choice.home) + // A recent's own label already is its full path, so nothing is repeated. + assertEquals(choice.path, choice.label) + assertNull(choice.secondary) + } + } + + @Test + fun anEmptyOrBlankReplyStillYieldsTheHomeChoice() { + assertEquals(HOME_DIRECTORY, directoryChoices(emptyList()).single().createDirectory) + assertEquals(HOME_DIRECTORY, directoryChoices(listOf("", " ")).single().createDirectory) + // Home only: no recents yet. + assertEquals(1, directoryChoices(listOf("/home/op")).size) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt new file mode 100644 index 00000000..779ceb66 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt @@ -0,0 +1,160 @@ +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.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Managing the session list: the kind chip comes from the server's tag, the + * create flow defaults to the operator's home and creates in the chosen + * directory, and rename/removal are local, honest (the server list is untouched) + * and reversible. Driven against [ChatStore] with no device or server. + */ +class ChatSessionManagementTest { + + private fun session( + id: String, + title: String = id, + tag: String = ChatProtocol.TAG_OPERATOR, + directory: String = "/home/op", + ) = ChatSession(id = id, title = title, tag = tag, directory = directory) + + @Test + fun theKindChipComesFromTheServersOwnTag() { + assertEquals("Operator", sessionTagLabel(session("a"))) + // An untagged session shows no chip; an unknown tag is shown verbatim. + assertNull(sessionTagLabel(session("b", tag = ""))) + assertEquals("scratch", sessionTagLabel(session("c", tag = "scratch"))) + } + + @Test + fun theCreateFlowDefaultsToHomeAndCreatesInTheChosenDirectory() { + val store = ChatStore() + store.createOpened() + assertEquals(HOME_DIRECTORY, store.value.create!!.directory) + + store.createDirectoryChosen("/home/op/work") + assertEquals("/home/op/work", store.value.create!!.directory) + + store.createSucceeded(session("new", "New chat", directory = "/home/op/work")) + assertNull(store.value.create) + assertEquals("new", store.value.activeId) + assertEquals(listOf("new"), store.value.visibleSessions.map { it.id }) + assertEquals("/home/op/work", store.value.active!!.directory) + } + + @Test + fun cancellingTheCreateFlowLeavesTheListUntouched() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a"))) + store.createOpened() + store.createCancelled() + assertNull(store.value.create) + assertEquals(listOf("a"), store.value.visibleSessions.map { it.id }) + } + + @Test + fun renameWinsOverTheServersTitleAndSurvivesARefresh() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a", "Server title"))) + store.rename("a", " My chat ") + assertEquals("My chat", store.value.visibleSessions.single().title) + + // A refresh carrying the server's own title does not undo the local rename. + store.sessionsLoaded(listOf(session("a", "Server title"))) + assertEquals("My chat", store.value.visibleSessions.single().title) + } + + @Test + fun renameAppliesToAnAlreadyOpenConversation() { + val store = ChatStore() + store.open(session("a")) + store.rename("a", "Renamed") + assertEquals("Renamed", store.value.thread("a")!!.title) + } + + @Test + fun removeHidesTheSessionUntilItIsUndone() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a"), session("b"))) + store.remove("a") + assertEquals(listOf("b"), store.value.visibleSessions.map { it.id }) + assertEquals("a", store.value.lastRemoved) + + // The server still lists it, so a refresh does not bring it back... + store.sessionsLoaded(listOf(session("a"), session("b"))) + assertEquals(listOf("b"), store.value.visibleSessions.map { it.id }) + + // ...until the removal is undone. + store.undoRemove() + assertEquals(listOf("a", "b"), store.value.visibleSessions.map { it.id }) + assertNull(store.value.lastRemoved) + } + + @Test + fun removeClosesTheOpenConversationWithoutTouchingTheServerList() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a"))) + store.open(session("a")) + store.remove("a") + assertNull(store.value.thread("a")) + assertNull(store.value.activeId) + // Nothing is deleted: the server's list still holds it, only hidden here. + assertEquals(listOf("a"), store.value.sessions.map { it.id }) + } + + @Test + fun removingSomethingThatIsNotListedIsANoOp() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a"))) + store.remove("ghost") + assertNull(store.value.lastRemoved) + store.undoRemove() + assertEquals(listOf("a"), store.value.visibleSessions.map { it.id }) + } + + @Test + fun overridesSurviveAnEncodeDecodeRoundTrip() { + val overrides = ChatSessionOverrides().renamed("a", "Mine").hide("b") + assertEquals(overrides, ChatSessionOverrides.decode(overrides.encode())) + // Nothing stored, or something unreadable, is simply no overrides. + assertEquals(ChatSessionOverrides(), ChatSessionOverrides.decode("")) + assertEquals(ChatSessionOverrides(), ChatSessionOverrides.decode("{")) + } + + @Test + fun aStoredOverrideSetIsAppliedByAFreshStore() { + val stored = ChatSessionOverrides().renamed("a", "Mine").hide("b").encode() + val store = ChatStore(overrides = ChatSessionOverrides.decode(stored)) + store.sessionsLoaded(listOf(session("a", "Server title"), session("b"))) + assertEquals(listOf("a"), store.value.visibleSessions.map { it.id }) + assertEquals("Mine", store.value.visibleSessions.single().title) + } + + @Test + fun theListShowsTheServersSessionsVerbatimWhenNothingIsOverridden() { + val store = ChatStore() + val listed = listOf(session("a"), session("b", "Other")) + store.sessionsLoaded(listed) + // No app-side filtering or retitling when the operator changed nothing. + assertTrue(store.value.visibleSessions == listed) + } + + @Test + fun theCoveredPaneCountMatchesTheVisibleList() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a"), session("b"), session("c"))) + assertEquals(3, store.value.visibleSessionCount) + + // The covered pane's count tracks the same removals as the list itself. + store.remove("b") + assertEquals(2, store.value.visibleSessionCount) + assertEquals(store.value.visibleSessions.size, store.value.visibleSessionCount) + + store.undoRemove() + assertEquals(3, store.value.visibleSessionCount) + } +}