android: add slash commands to the chat composer, starting with /new
The composer now reads a leading slash as a command instead of a prompt, so the operator can start a session, rename it, stop a turn or ask for help without leaving the input field — the same surface the pipeline terminal gives with `:status`, `:logs`, … - ChatCommands.kt: parsing (a bare `/`, an unknown word, an argument, text that merely starts with a slash), the filtered offer list, the Enter target, the `/help` listing, the effect routing and the host interface. Pure, so the routing is testable without a device or server. - ChatComposer.kt: the offer list above the field, Up/Down to move the highlight and Enter/tap to run the highlighted row, shown only while the draft is a bare command word. Sending, attachments, stop-while-streaming, queued state and the field's ordinary keyboard action are unchanged. - AppViewModel.kt: one shared prompt path (`postChatPrompt`) for the composer and the unknown-command offer, and a host that performs the effects. `/new` creates in the current session's directory and switches to it, leaving the old session open, listed and with its history; `/rename` uses the device's own local rename and says so; `/stop` interrupts a running turn; `/close` reports that this revision has no real session close rather than dressing up the local hide. - ChatStore.kt / ChatTranscript.kt / ChatCommandUi.kt: local command lines (`ChatCommandNotice`) rendered as their own transcript item, visually distinct from a message to the agent, with an error container for a failed command. - An unrecognised `/…` is never sent to the agent: it becomes an offer to send it as a message or cancel, and the offer is taken once so a stale tap sends nothing. Running a command adds nothing to the model's conversation. - Dimens.kt: one new token, CHAT_COMMAND_LIST_MAX_HEIGHT, for the capped list. - ChatCommandsTest.kt: parsing, filtering, `/new` in the current directory and switching, `/rename` and `/close` delegating, `/stop` only while running, and the unknown command never reaching the prompt path. Checks made before committing: this is an Android-app-only change with no protocol, server, installer or Docker change, so the packaged templates and the packaged authoring skill references (internal/author/skill/references/) are unaffected and no managed-file inventory in internal/author/install.go changes; none of them needed updating. No dependency was added — Icons.Default.Terminal comes from the already-declared material-icons-extended. Verified with the Android map's own checks for an implementation change, build plus unit tests (`--offline --no-daemon :app:assembleDebug` and `:app:testDebugUnitTest`), and DimensTest's geometry-token rule holds: the only new dimension is the named token above. Device behaviour was deliberately not exercised here (this stage does not use adb); the rendered offer list, D-pad handling and notice item belong to visual review. Documentation that is now stale (not edited here; a single writer folds shared docs): android/README.md's chat section describes the composer without the slash commands — it should gain the command vocabulary, the offer list and the unknown-command guard.
This commit is contained in:
@@ -41,12 +41,15 @@ import net.awan.pipelines.data.transport.ServerUrl
|
|||||||
import net.awan.pipelines.notify.NoRunAlerts
|
import net.awan.pipelines.notify.NoRunAlerts
|
||||||
import net.awan.pipelines.notify.RunAlertSink
|
import net.awan.pipelines.notify.RunAlertSink
|
||||||
import net.awan.pipelines.notify.runAlerts
|
import net.awan.pipelines.notify.runAlerts
|
||||||
|
import net.awan.pipelines.ui.chat.CHAT_CLOSE_UNAVAILABLE
|
||||||
import net.awan.pipelines.ui.chat.ChatAttachment
|
import net.awan.pipelines.ui.chat.ChatAttachment
|
||||||
|
import net.awan.pipelines.ui.chat.ChatCommandHost
|
||||||
import net.awan.pipelines.ui.chat.ChatSessionOverrides
|
import net.awan.pipelines.ui.chat.ChatSessionOverrides
|
||||||
import net.awan.pipelines.ui.chat.ChatSeenState
|
import net.awan.pipelines.ui.chat.ChatSeenState
|
||||||
import net.awan.pipelines.ui.chat.ChatState
|
import net.awan.pipelines.ui.chat.ChatState
|
||||||
import net.awan.pipelines.ui.chat.ChatStore
|
import net.awan.pipelines.ui.chat.ChatStore
|
||||||
import net.awan.pipelines.ui.chat.attachmentFiles
|
import net.awan.pipelines.ui.chat.attachmentFiles
|
||||||
|
import net.awan.pipelines.ui.chat.runChatSlashCommand
|
||||||
|
|
||||||
/** Generic loading/empty/error/data state used by every screen. */
|
/** Generic loading/empty/error/data state used by every screen. */
|
||||||
data class LoadState<T>(
|
data class LoadState<T>(
|
||||||
@@ -1131,13 +1134,25 @@ class AppViewModel(
|
|||||||
if (!thread.canSend) return
|
if (!thread.canSend) return
|
||||||
val text = thread.draft.trim()
|
val text = thread.draft.trim()
|
||||||
val attachments = thread.attachments
|
val attachments = thread.attachments
|
||||||
val localId = chatStore.appendLocalUserMessage(sessionId, text, attachments) ?: return
|
|
||||||
chatStore.clearDraft(sessionId)
|
chatStore.clearDraft(sessionId)
|
||||||
chatStore.clearAttachments(sessionId)
|
chatStore.clearAttachments(sessionId)
|
||||||
|
postChatPrompt(sessionId, text, attachments)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One prompt, from the composer or from an unknown-command offer the operator
|
||||||
|
* chose to send: appends the optimistic turn, flags the chat running and posts
|
||||||
|
* it, taking the bubble and the attachments back out if the server rejects it.
|
||||||
|
* Every caller has already cleared the draft it sent.
|
||||||
|
*/
|
||||||
|
private fun postChatPrompt(sessionId: String, text: String, attachments: List<ChatAttachment>) {
|
||||||
|
val body = text.trim()
|
||||||
|
if (body.isEmpty()) return
|
||||||
|
val localId = chatStore.appendLocalUserMessage(sessionId, body, attachments) ?: return
|
||||||
chatStore.running(sessionId, true)
|
chatStore.running(sessionId, true)
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
val queued = repository.chatPrompt(sessionId, text, attachmentFiles(attachments))
|
val queued = repository.chatPrompt(sessionId, body, attachmentFiles(attachments))
|
||||||
// The server accepted the prompt (queued or sent); a queued prompt
|
// The server accepted the prompt (queued or sent); a queued prompt
|
||||||
// is one waiting behind an in-flight turn, and the composer says so
|
// is one waiting behind an in-flight turn, and the composer says so
|
||||||
// instead of blocking input.
|
// instead of blocking input.
|
||||||
@@ -1154,6 +1169,88 @@ class AppViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Slash commands ------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs one composer slash command against [sessionId]'s conversation. The
|
||||||
|
* draft is always consumed here — a slash draft is never handed to the prompt
|
||||||
|
* path — so only an explicit "Send as message" from an unknown-command offer
|
||||||
|
* reaches the agent. Every outcome is reported as a local transcript line.
|
||||||
|
*/
|
||||||
|
fun submitChatCommand(sessionId: String, text: String) {
|
||||||
|
val thread = chatStore.value.thread(sessionId) ?: return
|
||||||
|
chatStore.clearDraft(sessionId)
|
||||||
|
runChatSlashCommand(text, thread, SessionChatCommandHost(sessionId))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dismisses one local command line (the operator cancelled its offer). */
|
||||||
|
fun dismissChatCommandNotice(sessionId: String, noticeId: String) =
|
||||||
|
chatStore.dismissNotice(sessionId, noticeId)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends the draft an unknown-command offer kept, through the ordinary prompt
|
||||||
|
* path, once the operator chose to. The offer is taken first, so a stale tap
|
||||||
|
* can neither send the same draft twice nor send anything at all.
|
||||||
|
*/
|
||||||
|
fun sendChatCommandOffer(sessionId: String, noticeId: String) {
|
||||||
|
if (chatStore.value.thread(sessionId) == null) return
|
||||||
|
val text = chatStore.takeNoticeOffer(sessionId, noticeId) ?: return
|
||||||
|
postChatPrompt(sessionId, text, emptyList())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The real effects behind a slash command. `/new` creates in the current
|
||||||
|
* session's directory and switches to it (the old one stays open, listed, with
|
||||||
|
* its history); `/rename` uses the device's own rename; `/stop` interrupts;
|
||||||
|
* `/close` reports that this build has no real close instead of hiding the
|
||||||
|
* session. Nothing here is ever a prompt.
|
||||||
|
*/
|
||||||
|
private inner class SessionChatCommandHost(private val sessionId: String) : ChatCommandHost {
|
||||||
|
override fun startSession(directory: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val created = repository.chatCreate(title = "New chat", directory = directory)
|
||||||
|
chatStore.createSucceeded(created)
|
||||||
|
chatStore.history(created.id, emptyList())
|
||||||
|
chatStore.notice(
|
||||||
|
created.id,
|
||||||
|
"Started a new session “${created.title.ifBlank { "New chat" }}” in $directory.",
|
||||||
|
)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
if (t is CancellationException) throw t
|
||||||
|
chatStore.notice(
|
||||||
|
sessionId,
|
||||||
|
"Couldn't start a new session in $directory: ${ErrorMessages.describe(t)}",
|
||||||
|
failed = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun finishSession() {
|
||||||
|
// No session close exists in this revision: the honest answer, never
|
||||||
|
// the local hide dressed up as one.
|
||||||
|
chatStore.notice(sessionId, CHAT_CLOSE_UNAVAILABLE, failed = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun renameSession(title: String) {
|
||||||
|
chatStore.rename(sessionId, title)
|
||||||
|
chatStore.notice(
|
||||||
|
sessionId,
|
||||||
|
"Renamed this session to “$title” on this device only; the server's title is unchanged.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun stopTurn() {
|
||||||
|
stopChat(sessionId)
|
||||||
|
chatStore.notice(sessionId, "Stopping the running turn…")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun notify(text: String, failed: Boolean, offer: String?) {
|
||||||
|
chatStore.notice(sessionId, text, failed, offer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Answers a pending approval. The card settles in place optimistically so a
|
* Answers a pending approval. The card settles in place optimistically so a
|
||||||
* laggy round-trip over a tunnel never shows the old buttons again; a failed
|
* laggy round-trip over a tunnel never shows the old buttons again; a failed
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package net.awan.pipelines.ui.chat
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
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.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Terminal
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.minimumInteractiveComponentSize
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.semantics.selected
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import net.awan.pipelines.ui.theme.CHAT_COMMAND_LIST_MAX_HEIGHT
|
||||||
|
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
|
||||||
|
import net.awan.pipelines.ui.theme.SPACING_M
|
||||||
|
import net.awan.pipelines.ui.theme.SPACING_S
|
||||||
|
import net.awan.pipelines.ui.theme.SPACING_XS
|
||||||
|
import net.awan.pipelines.ui.theme.pipelinesText
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The slash-command offer list, shown above the composer while the draft is a
|
||||||
|
* bare command word. Each row names the command and says in a few words what it
|
||||||
|
* does; the highlighted row is the one Enter runs, and a tap runs a row directly.
|
||||||
|
* It is capped and scrolls rather than growing without bound over the transcript.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun ChatCommandSuggestions(
|
||||||
|
commands: List<ChatCommand>,
|
||||||
|
selectedIndex: Int,
|
||||||
|
onPick: (ChatCommand) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
if (commands.isEmpty()) return
|
||||||
|
Surface(
|
||||||
|
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||||
|
shape = MaterialTheme.shapes.medium,
|
||||||
|
modifier = modifier.fillMaxWidth().heightIn(max = CHAT_COMMAND_LIST_MAX_HEIGHT),
|
||||||
|
) {
|
||||||
|
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||||
|
commands.forEachIndexed { index, command ->
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(SPACING_M),
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(
|
||||||
|
if (index == selectedIndex) {
|
||||||
|
MaterialTheme.colorScheme.secondaryContainer
|
||||||
|
} else {
|
||||||
|
Color.Transparent
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.minimumInteractiveComponentSize()
|
||||||
|
// The highlight is also reported to assistive tech, so the
|
||||||
|
// row Enter runs is not conveyed by colour alone.
|
||||||
|
.semantics { selected = index == selectedIndex }
|
||||||
|
.clickable(role = Role.Button) { onPick(command) }
|
||||||
|
.padding(horizontal = SPACING_M, vertical = SPACING_S),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "/" + command.name,
|
||||||
|
style = pipelinesText().cardTitle,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = command.summary,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One local command line in the transcript. It is deliberately unlike a message
|
||||||
|
* bubble: full width, a `Command` label and a terminal glyph, and a container
|
||||||
|
* that turns to the error colour when the command could not be honoured. An
|
||||||
|
* unrecognised command keeps the operator's draft as an offer — send it as a
|
||||||
|
* message or cancel — so a typo never becomes a prompt on its own.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun ChatCommandNoticeItem(
|
||||||
|
notice: ChatCommandNotice,
|
||||||
|
onSendAsMessage: () -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
val container = if (notice.failed) {
|
||||||
|
MaterialTheme.colorScheme.errorContainer
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.surfaceContainerHigh
|
||||||
|
}
|
||||||
|
val content = if (notice.failed) {
|
||||||
|
MaterialTheme.colorScheme.onErrorContainer
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.onSurface
|
||||||
|
}
|
||||||
|
Surface(
|
||||||
|
color = container,
|
||||||
|
shape = MaterialTheme.shapes.medium,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Default.Terminal,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = content,
|
||||||
|
modifier = Modifier.size(ICON_INLINE_DP),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = if (notice.failed) "Command failed" else "Command",
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(text = notice.text, style = MaterialTheme.typography.bodySmall, color = content)
|
||||||
|
if (notice.offer != null) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
|
||||||
|
TextButton(onClick = onSendAsMessage) { Text("Send as message") }
|
||||||
|
TextButton(onClick = onDismiss) { Text("Cancel") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
package net.awan.pipelines.ui.chat
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One command the composer understands. [name] is the word after the slash,
|
||||||
|
* [usage] is what the operator types (including any argument) and [summary] is
|
||||||
|
* the few-word description the offer list shows beside it. [takesArgument] is
|
||||||
|
* false for the commands that act on the current session alone, so a stray
|
||||||
|
* argument is reported instead of being silently ignored.
|
||||||
|
*/
|
||||||
|
internal data class ChatCommand(
|
||||||
|
val name: String,
|
||||||
|
val summary: String,
|
||||||
|
val usage: String,
|
||||||
|
val takesArgument: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal const val CHAT_COMMAND_NEW = "new"
|
||||||
|
internal const val CHAT_COMMAND_CLOSE = "close"
|
||||||
|
internal const val CHAT_COMMAND_RENAME = "rename"
|
||||||
|
internal const val CHAT_COMMAND_STOP = "stop"
|
||||||
|
internal const val CHAT_COMMAND_HELP = "help"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The commands offered by the composer, in the order the list shows them. The
|
||||||
|
* terminal's own vocabulary is the model here (`:status`, `:logs`, …): a command
|
||||||
|
* acts on the chat surface itself and is never sent to the agent.
|
||||||
|
*
|
||||||
|
* `/close` is shown as unavailable in this revision: the server has no request
|
||||||
|
* that finishes a session for every client yet, and the app will not pretend the
|
||||||
|
* local "remove from list" is that close.
|
||||||
|
*/
|
||||||
|
internal val CHAT_COMMANDS: List<ChatCommand> = listOf(
|
||||||
|
ChatCommand(CHAT_COMMAND_NEW, "Start a fresh session in this directory", "/new"),
|
||||||
|
ChatCommand(
|
||||||
|
CHAT_COMMAND_CLOSE,
|
||||||
|
"Finish this session for every client (not available in this build)",
|
||||||
|
"/close",
|
||||||
|
),
|
||||||
|
ChatCommand(CHAT_COMMAND_RENAME, "Rename this session on this device", "/rename <title>", takesArgument = true),
|
||||||
|
ChatCommand(CHAT_COMMAND_STOP, "Stop the turn that is running", "/stop"),
|
||||||
|
ChatCommand(CHAT_COMMAND_HELP, "List every command", "/help"),
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the composer's draft parses to. [Plain] is any text that is not a slash
|
||||||
|
* command and follows the ordinary send path. [Unknown] is a draft that starts
|
||||||
|
* with a slash but names no command: it must never be sent as a prompt without
|
||||||
|
* the operator explicitly choosing to, so [text] is carried verbatim.
|
||||||
|
*/
|
||||||
|
internal sealed interface ChatInput {
|
||||||
|
data object Plain : ChatInput
|
||||||
|
data class Invocation(val command: ChatCommand, val argument: String) : ChatInput
|
||||||
|
data class Unknown(val text: String, val token: String) : ChatInput
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses [text] as a slash command. Only the start of the draft counts, the
|
||||||
|
* command word is the run of non-space characters after the slash, and the rest
|
||||||
|
* (trimmed) is its argument. Recognition is case-insensitive; the returned
|
||||||
|
* command is always the canonical entry from [CHAT_COMMANDS].
|
||||||
|
*/
|
||||||
|
internal fun parseChatInput(text: String): ChatInput {
|
||||||
|
val trimmed = text.trim()
|
||||||
|
if (!trimmed.startsWith("/")) return ChatInput.Plain
|
||||||
|
val token = trimmed.takeWhile { !it.isWhitespace() }
|
||||||
|
val argument = trimmed.drop(token.length).trim()
|
||||||
|
val name = token.removePrefix("/")
|
||||||
|
val command = CHAT_COMMANDS.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||||
|
?: return ChatInput.Unknown(text = trimmed, token = token)
|
||||||
|
return ChatInput.Invocation(command = command, argument = argument)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The commands the offer list shows for [draft]: every command after a bare `/`,
|
||||||
|
* narrowed by the command word as the operator keeps typing. The list is for the
|
||||||
|
* command word only, so once an argument begins (a space follows the word) it
|
||||||
|
* hides and the draft is executed as typed. Text that does not start with a
|
||||||
|
* slash offers nothing.
|
||||||
|
*/
|
||||||
|
internal fun chatCommandSuggestions(draft: String): List<ChatCommand> {
|
||||||
|
val trimmed = draft.trimStart()
|
||||||
|
if (!trimmed.startsWith("/")) return emptyList()
|
||||||
|
if (trimmed.any { it.isWhitespace() }) return emptyList()
|
||||||
|
val query = trimmed.drop(1)
|
||||||
|
return CHAT_COMMANDS.filter { it.name.startsWith(query, ignoreCase = true) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The command text Enter runs for [draft] while the offer list is showing. The
|
||||||
|
* list's highlighted entry wins, so a partially typed word (`/clo`) is runnable
|
||||||
|
* with Enter without also being sent as a prompt; the caller clamps [selected]
|
||||||
|
* to the list. Returns null when no list is showing, which is when the ordinary
|
||||||
|
* send path applies.
|
||||||
|
*/
|
||||||
|
internal fun chatCommandForEnter(draft: String, selected: Int): String? {
|
||||||
|
val suggestions = chatCommandSuggestions(draft)
|
||||||
|
if (suggestions.isEmpty()) return null
|
||||||
|
val command = suggestions.getOrNull(selected) ?: suggestions.first()
|
||||||
|
return "/" + command.name
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `/help` reply: every command with its usage and what it does. */
|
||||||
|
internal fun chatCommandHelp(): String =
|
||||||
|
CHAT_COMMANDS.joinToString("\n") { "${it.usage} — ${it.summary}" }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a parsed invocation asks the chat surface to do. Kept separate from the
|
||||||
|
* side effects so the routing (which command is available, which one needs an
|
||||||
|
* argument, which argument it receives) is unit-testable without a server.
|
||||||
|
*/
|
||||||
|
internal sealed interface ChatCommandEffect {
|
||||||
|
/** Create a fresh session in [directory] and switch to it. */
|
||||||
|
data class StartSession(val directory: String) : ChatCommandEffect
|
||||||
|
|
||||||
|
/** Finish the current session for every client. */
|
||||||
|
data object FinishSession : ChatCommandEffect
|
||||||
|
|
||||||
|
/** Rename the current session to [title] (the device's own rename today). */
|
||||||
|
data class RenameSession(val title: String) : ChatCommandEffect
|
||||||
|
|
||||||
|
/** Interrupt the session's running turn. */
|
||||||
|
data object StopTurn : ChatCommandEffect
|
||||||
|
|
||||||
|
/** Show the command list in the transcript. */
|
||||||
|
data object ShowHelp : ChatCommandEffect
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A command that cannot act as asked; [text] says why. [offer] is set for an
|
||||||
|
* unknown command and carries the operator's draft, so the transcript can
|
||||||
|
* offer to send it as a message instead — the one way it reaches the agent.
|
||||||
|
*/
|
||||||
|
data class Report(val text: String, val offer: String? = null) : ChatCommandEffect
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routes parsed [input] to one effect. [thread] supplies the current session's
|
||||||
|
* directory (which `/new` must reuse) and whether a turn is running (which
|
||||||
|
* `/stop` needs). A null result is text that is not a command at all.
|
||||||
|
*/
|
||||||
|
internal fun chatCommandEffect(input: ChatInput, thread: ChatThread): ChatCommandEffect? = when (input) {
|
||||||
|
ChatInput.Plain -> null
|
||||||
|
is ChatInput.Unknown -> ChatCommandEffect.Report(
|
||||||
|
"“${input.token}” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.",
|
||||||
|
offer = input.text,
|
||||||
|
)
|
||||||
|
is ChatInput.Invocation -> {
|
||||||
|
val command = input.command
|
||||||
|
if (!command.takesArgument && input.argument.isNotBlank()) {
|
||||||
|
ChatCommandEffect.Report("${command.usage} does not take an argument.")
|
||||||
|
} else {
|
||||||
|
when (command.name) {
|
||||||
|
CHAT_COMMAND_NEW ->
|
||||||
|
if (thread.directory.isBlank()) {
|
||||||
|
ChatCommandEffect.Report(
|
||||||
|
"Can't start a new session here: the server reported no directory for this chat.",
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
ChatCommandEffect.StartSession(thread.directory)
|
||||||
|
}
|
||||||
|
CHAT_COMMAND_CLOSE -> ChatCommandEffect.FinishSession
|
||||||
|
CHAT_COMMAND_RENAME ->
|
||||||
|
if (input.argument.isBlank()) {
|
||||||
|
ChatCommandEffect.Report(
|
||||||
|
"Usage: ${command.usage} — renames this session on this device.",
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
ChatCommandEffect.RenameSession(input.argument)
|
||||||
|
}
|
||||||
|
CHAT_COMMAND_STOP ->
|
||||||
|
if (thread.running) {
|
||||||
|
ChatCommandEffect.StopTurn
|
||||||
|
} else {
|
||||||
|
ChatCommandEffect.Report("No turn is running in this chat.")
|
||||||
|
}
|
||||||
|
CHAT_COMMAND_HELP -> ChatCommandEffect.ShowHelp
|
||||||
|
else -> ChatCommandEffect.Report("“/${command.name}” is not a command.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The effects the chat surface actually performs. [notify] appends a local
|
||||||
|
* command line to the transcript; it is not a prompt, so nothing here reaches
|
||||||
|
* the agent unless the operator explicitly sends an unknown command as a
|
||||||
|
* message from its offer.
|
||||||
|
*/
|
||||||
|
internal interface ChatCommandHost {
|
||||||
|
fun startSession(directory: String)
|
||||||
|
fun finishSession()
|
||||||
|
fun renameSession(title: String)
|
||||||
|
fun stopTurn()
|
||||||
|
fun notify(text: String, failed: Boolean = false, offer: String? = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs [text] against the current [thread] through [host]. A draft that starts
|
||||||
|
* with a slash is always consumed here (the caller clears it) and is never
|
||||||
|
* handed to the prompt path; an unknown command becomes an offer the operator
|
||||||
|
* must answer, and an argument-less command rejects extra words instead of
|
||||||
|
* guessing what they meant.
|
||||||
|
*/
|
||||||
|
internal fun runChatSlashCommand(text: String, thread: ChatThread, host: ChatCommandHost) {
|
||||||
|
when (val effect = chatCommandEffect(parseChatInput(text), thread)) {
|
||||||
|
null -> Unit
|
||||||
|
is ChatCommandEffect.StartSession -> host.startSession(effect.directory)
|
||||||
|
ChatCommandEffect.FinishSession -> host.finishSession()
|
||||||
|
is ChatCommandEffect.RenameSession -> host.renameSession(effect.title)
|
||||||
|
ChatCommandEffect.StopTurn -> host.stopTurn()
|
||||||
|
ChatCommandEffect.ShowHelp -> host.notify(chatCommandHelp())
|
||||||
|
is ChatCommandEffect.Report -> host.notify(effect.text, failed = true, offer = effect.offer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What `/close` says in this revision, where no real session close exists. */
|
||||||
|
internal const val CHAT_CLOSE_UNAVAILABLE =
|
||||||
|
"Can't finish this session: this build has no real session close yet, so nothing was " +
|
||||||
|
"changed. The session stays open and listed; no local hide was used instead."
|
||||||
@@ -19,9 +19,19 @@ import androidx.compose.material3.OutlinedTextField
|
|||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.input.key.Key
|
||||||
|
import androidx.compose.ui.input.key.KeyEventType
|
||||||
|
import androidx.compose.ui.input.key.key
|
||||||
|
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||||
|
import androidx.compose.ui.input.key.type
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -35,8 +45,27 @@ internal fun ChatComposer(
|
|||||||
onRemoveAttachment: (String) -> Unit,
|
onRemoveAttachment: (String) -> Unit,
|
||||||
onSend: () -> Unit,
|
onSend: () -> Unit,
|
||||||
onStop: () -> Unit,
|
onStop: () -> Unit,
|
||||||
|
onRunCommand: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
val action = composerAction(thread)
|
val action = composerAction(thread)
|
||||||
|
// The slash-command offer list follows the draft: every command after a bare
|
||||||
|
// `/`, narrowed as the operator keeps typing, hidden once an argument begins.
|
||||||
|
// The highlighted row is what Enter runs, and a tap runs a row directly, so a
|
||||||
|
// half-typed command is never sent as a prompt.
|
||||||
|
val suggestions = chatCommandSuggestions(thread.draft)
|
||||||
|
var selected by remember(thread.sessionId) { mutableIntStateOf(0) }
|
||||||
|
LaunchedEffect(suggestions) {
|
||||||
|
if (selected !in suggestions.indices) selected = 0
|
||||||
|
}
|
||||||
|
val slashDraft = thread.draft.trimStart().startsWith("/")
|
||||||
|
val submit: () -> Unit = {
|
||||||
|
val command = chatCommandForEnter(thread.draft, selected)
|
||||||
|
when {
|
||||||
|
command != null -> onRunCommand(command)
|
||||||
|
slashDraft -> onRunCommand(thread.draft)
|
||||||
|
action == ComposerAction.Send && thread.canSend -> onSend()
|
||||||
|
}
|
||||||
|
}
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
// The platform picker: the operator chooses files and they are only resolved
|
// The platform picker: the operator chooses files and they are only resolved
|
||||||
@@ -62,6 +91,12 @@ internal fun ChatComposer(
|
|||||||
if (thread.attachments.isNotEmpty()) {
|
if (thread.attachments.isNotEmpty()) {
|
||||||
ChatAttachmentStrip(attachments = thread.attachments, onRemove = onRemoveAttachment)
|
ChatAttachmentStrip(attachments = thread.attachments, onRemove = onRemoveAttachment)
|
||||||
}
|
}
|
||||||
|
ChatCommandSuggestions(
|
||||||
|
commands = suggestions,
|
||||||
|
selectedIndex = selected,
|
||||||
|
onPick = { onRunCommand("/" + it.name) },
|
||||||
|
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
|
||||||
|
)
|
||||||
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) {
|
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) {
|
||||||
IconButton(
|
IconButton(
|
||||||
onClick = { picker.launch(arrayOf("*/*")) },
|
onClick = { picker.launch(arrayOf("*/*")) },
|
||||||
@@ -71,13 +106,30 @@ internal fun ChatComposer(
|
|||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = thread.draft,
|
value = thread.draft,
|
||||||
onValueChange = onDraft,
|
onValueChange = onDraft,
|
||||||
placeholder = { Text("Message the agent…") },
|
placeholder = { Text("Message the agent… or / for commands") },
|
||||||
minLines = 1,
|
minLines = 1,
|
||||||
maxLines = 6,
|
maxLines = 6,
|
||||||
keyboardActions = KeyboardActions(
|
keyboardActions = KeyboardActions(onSend = { submit() }),
|
||||||
onSend = { if (action == ComposerAction.Send && thread.canSend) onSend() },
|
// Up/Down move the highlight and Enter runs it, but only while
|
||||||
),
|
// the offer list is showing, so every other key — and the
|
||||||
modifier = Modifier.weight(1f),
|
// field's ordinary send action — is left untouched.
|
||||||
|
modifier = Modifier.weight(1f).onPreviewKeyEvent { event ->
|
||||||
|
if (suggestions.isEmpty()) return@onPreviewKeyEvent false
|
||||||
|
when (event.key) {
|
||||||
|
Key.DirectionDown, Key.DirectionUp -> {
|
||||||
|
if (event.type == KeyEventType.KeyDown) {
|
||||||
|
val step = if (event.key == Key.DirectionDown) 1 else -1
|
||||||
|
selected = (selected + step + suggestions.size) % suggestions.size
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Key.Enter, Key.NumPadEnter -> {
|
||||||
|
if (event.type == KeyEventType.KeyDown) submit()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
when (action) {
|
when (action) {
|
||||||
// While a turn is in flight the send control becomes the stop
|
// While a turn is in flight the send control becomes the stop
|
||||||
@@ -85,7 +137,7 @@ internal fun ChatComposer(
|
|||||||
ComposerAction.Stop -> IconButton(onClick = onStop) {
|
ComposerAction.Stop -> IconButton(onClick = onStop) {
|
||||||
Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error)
|
Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error)
|
||||||
}
|
}
|
||||||
ComposerAction.Send -> IconButton(onClick = onSend, enabled = thread.canSend) {
|
ComposerAction.Send -> IconButton(onClick = { submit() }, enabled = thread.canSend || slashDraft) {
|
||||||
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
|
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,10 +102,11 @@ internal fun ChatConversationPane(
|
|||||||
// A turn blocked on an approval is not generating, so the running indicator
|
// A turn blocked on an approval is not generating, so the running indicator
|
||||||
// (and its ticking clock) stands down while the card is unanswered.
|
// (and its ticking clock) stands down while the card is unanswered.
|
||||||
val showRunning = thread.running && !awaiting
|
val showRunning = thread.running && !awaiting
|
||||||
// The count of the transcript's items: the messages, the running indicator
|
// The count of the transcript's items: the messages, the local command lines,
|
||||||
// while a turn is in flight and a pending approval card, which is the last item
|
// the running indicator while a turn is in flight and a pending approval card,
|
||||||
// the top bar's approval action jumps to.
|
// which is the last item the top bar's approval action jumps to.
|
||||||
val itemCount = thread.messages.size + (if (showRunning) 1 else 0) + (if (approval != null) 1 else 0)
|
val itemCount = thread.messages.size + thread.notices.size +
|
||||||
|
(if (showRunning) 1 else 0) + (if (approval != null) 1 else 0)
|
||||||
// The position the operator left this conversation at, read once: a
|
// The position the operator left this conversation at, read once: a
|
||||||
// conversation with none of its own opens at its newest message instead (see
|
// conversation with none of its own opens at its newest message instead (see
|
||||||
// chatOpensAtNewest), so the current turn is never hunted for.
|
// chatOpensAtNewest), so the current turn is never hunted for.
|
||||||
@@ -212,9 +213,10 @@ internal fun ChatConversationPane(
|
|||||||
message = thread.error,
|
message = thread.error,
|
||||||
onRetry = { vm.loadChatHistory(thread.sessionId) },
|
onRetry = { vm.loadChatHistory(thread.sessionId) },
|
||||||
)
|
)
|
||||||
thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState(
|
thread.messages.isEmpty() && thread.notices.isEmpty() && !thread.running && approval == null ->
|
||||||
message = "This chat has no messages yet. Ask something below.",
|
EmptyState(
|
||||||
)
|
message = "This chat has no messages yet. Ask something below.",
|
||||||
|
)
|
||||||
else -> ChatTranscript(
|
else -> ChatTranscript(
|
||||||
thread = thread,
|
thread = thread,
|
||||||
listState = listState,
|
listState = listState,
|
||||||
@@ -227,6 +229,8 @@ internal fun ChatConversationPane(
|
|||||||
onDecision = { decision ->
|
onDecision = { decision ->
|
||||||
approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) }
|
approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) }
|
||||||
},
|
},
|
||||||
|
onNoticeSend = { vm.sendChatCommandOffer(thread.sessionId, it) },
|
||||||
|
onNoticeDismiss = { vm.dismissChatCommandNotice(thread.sessionId, it) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -245,6 +249,7 @@ internal fun ChatConversationPane(
|
|||||||
onRemoveAttachment = { vm.removeChatAttachment(thread.sessionId, it) },
|
onRemoveAttachment = { vm.removeChatAttachment(thread.sessionId, it) },
|
||||||
onSend = { vm.sendChatPrompt(thread.sessionId) },
|
onSend = { vm.sendChatPrompt(thread.sessionId) },
|
||||||
onStop = { vm.stopChat(thread.sessionId) },
|
onStop = { vm.stopChat(thread.sessionId) },
|
||||||
|
onRunCommand = { vm.submitChatCommand(thread.sessionId, it) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,20 @@ data class ChatAttachment(
|
|||||||
val displayName: String get() = name.ifBlank { uri.substringAfterLast('/').ifBlank { "file" } }
|
val displayName: String get() = name.ifBlank { uri.substringAfterLast('/').ifBlank { "file" } }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One local line in a conversation reporting what a slash command did. It is
|
||||||
|
* rendered as its own transcript item, visibly distinct from a message to the
|
||||||
|
* agent, and is never part of [ChatThread.messages]. [failed] marks a command
|
||||||
|
* that could not be honoured; [offer] carries the draft of an unrecognised
|
||||||
|
* command so the operator can choose to send it as a message, or cancel.
|
||||||
|
*/
|
||||||
|
data class ChatCommandNotice(
|
||||||
|
val id: String,
|
||||||
|
val text: String,
|
||||||
|
val failed: Boolean = false,
|
||||||
|
val offer: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One open conversation. The conversation itself, whether it is running, its
|
* One open conversation. The conversation itself, whether it is running, its
|
||||||
* unsent composer draft and its scroll position all live here, so switching to
|
* unsent composer draft and its scroll position all live here, so switching to
|
||||||
@@ -87,6 +101,14 @@ data class ChatThread(
|
|||||||
* sent, and restored (flagged with the server's error) if the send fails.
|
* sent, and restored (flagged with the server's error) if the send fails.
|
||||||
*/
|
*/
|
||||||
val attachments: List<ChatAttachment> = emptyList(),
|
val attachments: List<ChatAttachment> = emptyList(),
|
||||||
|
/**
|
||||||
|
* The local command lines this conversation has shown (a slash command's
|
||||||
|
* outcome, its `/help` list or an unknown-command offer). They are part of the
|
||||||
|
* thread so a switch away and back keeps them, but they are never part of
|
||||||
|
* [messages] and are never sent to the agent: running a command adds nothing
|
||||||
|
* to the model's context.
|
||||||
|
*/
|
||||||
|
val notices: List<ChatCommandNotice> = emptyList(),
|
||||||
/**
|
/**
|
||||||
* Where the operator left this conversation's transcript, or null while they
|
* Where the operator left this conversation's transcript, or null while they
|
||||||
* have not been there yet. Null is distinct from any position — including the
|
* have not been there yet. Null is distinct from any position — including the
|
||||||
@@ -284,6 +306,9 @@ class ChatStore(
|
|||||||
/** Monotonic source of attachment ids, so two attachments are never keyed alike. */
|
/** Monotonic source of attachment ids, so two attachments are never keyed alike. */
|
||||||
private var attachmentSeq = 0
|
private var attachmentSeq = 0
|
||||||
|
|
||||||
|
/** Monotonic source of command-notice ids, so two transcript lines never share a key. */
|
||||||
|
private var noticeSeq = 0
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Monotonic source of optimistic user-turn ids. Counting the local messages a
|
* Monotonic source of optimistic user-turn ids. Counting the local messages a
|
||||||
* thread currently holds would re-mint the id of a turn that was removed (a
|
* thread currently holds would re-mint the id of a turn that was removed (a
|
||||||
@@ -544,6 +569,45 @@ class ChatStore(
|
|||||||
|
|
||||||
private fun needsResync(thread: ChatThread): Boolean = thread.running || !thread.loaded
|
private fun needsResync(thread: ChatThread): Boolean = thread.running || !thread.loaded
|
||||||
|
|
||||||
|
// ---- Local command lines -------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Appends a local command line to [sessionId]'s transcript and returns its id.
|
||||||
|
* A notice lives beside the conversation, never inside it: it is not a
|
||||||
|
* [ChatMessage] and nothing here is sent to the agent. [offer] is set only for
|
||||||
|
* an unrecognised command, whose draft the operator can still choose to send.
|
||||||
|
*/
|
||||||
|
fun notice(
|
||||||
|
sessionId: String,
|
||||||
|
text: String,
|
||||||
|
failed: Boolean = false,
|
||||||
|
offer: String? = null,
|
||||||
|
): String? {
|
||||||
|
var id: String? = null
|
||||||
|
update(sessionId) { thread ->
|
||||||
|
id = NOTICE_PREFIX + (++noticeSeq)
|
||||||
|
thread.copy(notices = thread.notices + ChatCommandNotice(id!!, text, failed, offer))
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drops one local command line (the operator answered or dismissed its offer). */
|
||||||
|
fun dismissNotice(sessionId: String, noticeId: String) = update(sessionId) {
|
||||||
|
it.copy(notices = it.notices.filterNot { notice -> notice.id == noticeId })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Takes the draft an unrecognised-command notice offers to send, removing the
|
||||||
|
* notice. Null when the notice is gone or carries no offer, so a stale tap can
|
||||||
|
* never send anything.
|
||||||
|
*/
|
||||||
|
fun takeNoticeOffer(sessionId: String, noticeId: String): String? {
|
||||||
|
val notice = _state.value.thread(sessionId)?.notices?.firstOrNull { it.id == noticeId } ?: return null
|
||||||
|
val offer = notice.offer ?: return null
|
||||||
|
dismissNotice(sessionId, noticeId)
|
||||||
|
return offer
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Per-thread edits ----------------------------------------------------
|
// ---- Per-thread edits ----------------------------------------------------
|
||||||
|
|
||||||
fun draft(sessionId: String, text: String) = update(sessionId) { it.copy(draft = text) }
|
fun draft(sessionId: String, text: String) = update(sessionId) { it.copy(draft = text) }
|
||||||
@@ -892,5 +956,6 @@ class ChatStore(
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val LOCAL_MESSAGE_PREFIX = "local-"
|
const val LOCAL_MESSAGE_PREFIX = "local-"
|
||||||
|
const val NOTICE_PREFIX = "notice-"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,6 +93,8 @@ internal fun ChatTranscript(
|
|||||||
reasoning: ReasoningExpansion,
|
reasoning: ReasoningExpansion,
|
||||||
onToggleReasoning: (String) -> Unit,
|
onToggleReasoning: (String) -> Unit,
|
||||||
onDecision: (String) -> Unit,
|
onDecision: (String) -> Unit,
|
||||||
|
onNoticeSend: (String) -> Unit,
|
||||||
|
onNoticeDismiss: (String) -> Unit,
|
||||||
) {
|
) {
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val density = LocalDensity.current
|
val density = LocalDensity.current
|
||||||
@@ -147,7 +149,7 @@ internal fun ChatTranscript(
|
|||||||
// re-place (and re-follow) a transcript the operator had scrolled up.
|
// re-place (and re-follow) a transcript the operator had scrolled up.
|
||||||
var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) }
|
var placed by rememberSaveable(thread.sessionId) { mutableStateOf(false) }
|
||||||
val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } }
|
val viewportHeight by remember(listState) { derivedStateOf { listState.layoutInfo.viewportSize.height } }
|
||||||
LaunchedEffect(thread.messages, thread.running, approval?.requestId, viewportHeight) {
|
LaunchedEffect(thread.messages, thread.notices, thread.running, approval?.requestId, viewportHeight) {
|
||||||
if (itemCount <= 0) return@LaunchedEffect
|
if (itemCount <= 0) return@LaunchedEffect
|
||||||
if (!placed) {
|
if (!placed) {
|
||||||
// Wait for the first measure: placement run before it would no-op and
|
// Wait for the first measure: placement run before it would no-op and
|
||||||
@@ -192,6 +194,15 @@ internal fun ChatTranscript(
|
|||||||
onToggleReasoning = onToggleReasoning,
|
onToggleReasoning = onToggleReasoning,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// A slash command reports as its own line, after the turns it acted
|
||||||
|
// between and visually distinct from any message to the agent.
|
||||||
|
items(thread.notices, key = { it.id }) { notice ->
|
||||||
|
ChatCommandNoticeItem(
|
||||||
|
notice = notice,
|
||||||
|
onSendAsMessage = { onNoticeSend(notice.id) },
|
||||||
|
onDismiss = { onNoticeDismiss(notice.id) },
|
||||||
|
)
|
||||||
|
}
|
||||||
if (showRunning) {
|
if (showRunning) {
|
||||||
item(key = "pending") { RunningIndicator(thread) }
|
item(key = "pending") { RunningIndicator(thread) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -246,6 +246,13 @@ internal val CHAT_ATTACHMENT_PREVIEW_DP = 160.dp
|
|||||||
/** An attachment's name column stops here so its remove action keeps its place. */
|
/** An attachment's name column stops here so its remove action keeps its place. */
|
||||||
internal val CHAT_ATTACHMENT_NAME_MAX_WIDTH_DP = 180.dp
|
internal val CHAT_ATTACHMENT_NAME_MAX_WIDTH_DP = 180.dp
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How tall the composer's slash-command offer list may grow before it scrolls:
|
||||||
|
* tall enough for the whole vocabulary at a normal text size, so the composer
|
||||||
|
* never covers the transcript with an unbounded menu.
|
||||||
|
*/
|
||||||
|
internal val CHAT_COMMAND_LIST_MAX_HEIGHT = 240.dp
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How close to the end of the transcript the viewport must be for new content to
|
* How close to the end of the transcript the viewport must be for new content to
|
||||||
* keep following it: about one comfortable line of text, so the operator can be a
|
* keep following it: about one comfortable line of text, so the operator can be a
|
||||||
|
|||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package net.awan.pipelines.ui.chat
|
||||||
|
|
||||||
|
import net.awan.pipelines.data.protocol.ChatMessage
|
||||||
|
import net.awan.pipelines.data.protocol.ChatPart
|
||||||
|
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.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The composer's slash commands: parsing a draft, narrowing the offer list,
|
||||||
|
* routing to the real effect, and — the point of the whole feature — never
|
||||||
|
* letting a typo become a prompt. All pure, so no device or server is involved;
|
||||||
|
* the store-backed cases drive [ChatStore] itself for the create/rename/close
|
||||||
|
* transitions the effects delegate to.
|
||||||
|
*/
|
||||||
|
class ChatCommandsTest {
|
||||||
|
|
||||||
|
private fun thread(
|
||||||
|
id: String = "s",
|
||||||
|
directory: String = "/repo",
|
||||||
|
running: Boolean = false,
|
||||||
|
) = ChatThread(sessionId = id, directory = directory, running = running)
|
||||||
|
|
||||||
|
private fun session(id: String, title: String = id, directory: String = "/repo") =
|
||||||
|
ChatSession(id = id, title = title, directory = directory)
|
||||||
|
|
||||||
|
private fun message(id: String, role: String, body: String) = ChatMessage(
|
||||||
|
id = id,
|
||||||
|
sessionId = "",
|
||||||
|
role = role,
|
||||||
|
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "$id-p", text = body)),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A host that records every effect instead of performing it. */
|
||||||
|
private class RecordingHost : ChatCommandHost {
|
||||||
|
data class Notice(val text: String, val failed: Boolean, val offer: String?)
|
||||||
|
|
||||||
|
val started = mutableListOf<String>()
|
||||||
|
var finishes = 0
|
||||||
|
val renames = mutableListOf<String>()
|
||||||
|
var stops = 0
|
||||||
|
val notices = mutableListOf<Notice>()
|
||||||
|
|
||||||
|
override fun startSession(directory: String) { started += directory }
|
||||||
|
override fun finishSession() { finishes++ }
|
||||||
|
override fun renameSession(title: String) { renames += title }
|
||||||
|
override fun stopTurn() { stops++ }
|
||||||
|
override fun notify(text: String, failed: Boolean, offer: String?) {
|
||||||
|
notices += Notice(text, failed, offer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Parsing -------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aLoneSlashIsNotACommand() {
|
||||||
|
val parsed = parseChatInput("/")
|
||||||
|
assertTrue(parsed is ChatInput.Unknown)
|
||||||
|
assertEquals("/", (parsed as ChatInput.Unknown).token)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aKnownCommandParsesWithItsArgument() {
|
||||||
|
val bare = parseChatInput("/new")
|
||||||
|
assertEquals(
|
||||||
|
ChatInput.Invocation(CHAT_COMMANDS.first { it.name == CHAT_COMMAND_NEW }, ""),
|
||||||
|
bare,
|
||||||
|
)
|
||||||
|
val withArg = parseChatInput("/rename My session ")
|
||||||
|
assertTrue(withArg is ChatInput.Invocation)
|
||||||
|
withArg as ChatInput.Invocation
|
||||||
|
assertEquals(CHAT_COMMAND_RENAME, withArg.command.name)
|
||||||
|
assertEquals("My session", withArg.argument)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun textThatMerelyStartsWithASlashIsUnknown() {
|
||||||
|
val parsed = parseChatInput("/usr/bin/env go test")
|
||||||
|
assertTrue(parsed is ChatInput.Unknown)
|
||||||
|
assertEquals("/usr/bin/env", (parsed as ChatInput.Unknown).token)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun textThatDoesNotStartWithASlashIsPlain() {
|
||||||
|
assertEquals(ChatInput.Plain, parseChatInput("hello /new"))
|
||||||
|
assertEquals(ChatInput.Plain, parseChatInput(""))
|
||||||
|
assertEquals(ChatInput.Plain, parseChatInput(" plain message"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Filtering the offer list --------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aSlashOffersEveryCommandAndTypingNarrowsThem() {
|
||||||
|
assertEquals(CHAT_COMMANDS.map { it.name }, chatCommandSuggestions("/").map { it.name })
|
||||||
|
assertEquals(listOf(CHAT_COMMAND_NEW), chatCommandSuggestions("/n").map { it.name })
|
||||||
|
assertEquals(listOf(CHAT_COMMAND_RENAME), chatCommandSuggestions("/re").map { it.name })
|
||||||
|
// Case-insensitive, so a capitalised word still finds the command.
|
||||||
|
assertEquals(listOf(CHAT_COMMAND_CLOSE), chatCommandSuggestions("/CL").map { it.name })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun theOfferListHidesOnceAnArgumentBeginsOrTheWordMatchesNothing() {
|
||||||
|
assertTrue(chatCommandSuggestions("/rename My chat").isEmpty())
|
||||||
|
assertTrue(chatCommandSuggestions("/close ").isEmpty())
|
||||||
|
assertTrue(chatCommandSuggestions("/zzz").isEmpty())
|
||||||
|
assertTrue(chatCommandSuggestions("plain text").isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun enterRunsTheHighlightedCommandButNeverAPartialWord() {
|
||||||
|
// A bare slash with a later row highlighted runs that row, not a prompt.
|
||||||
|
assertEquals("/close", chatCommandForEnter("/", 1))
|
||||||
|
assertEquals("/rename", chatCommandForEnter("/", 2))
|
||||||
|
assertEquals("/new", chatCommandForEnter("/", 0))
|
||||||
|
assertEquals("/new", chatCommandForEnter("/n", 0))
|
||||||
|
// With no offer list showing, Enter is the ordinary send path.
|
||||||
|
assertNull(chatCommandForEnter("/rename My chat", 0))
|
||||||
|
assertNull(chatCommandForEnter("hello", 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Routing -------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun newUsesTheCurrentSessionsDirectoryAndSwitchesToTheFreshSession() {
|
||||||
|
val store = ChatStore()
|
||||||
|
val old = session("old", "Old chat", directory = "/repo/work")
|
||||||
|
store.sessionsLoaded(listOf(old))
|
||||||
|
store.open(old)
|
||||||
|
store.history("old", listOf(message("m1", ChatProtocol.ROLE_USER, "keep me")))
|
||||||
|
|
||||||
|
val host = object : ChatCommandHost by RecordingHost() {
|
||||||
|
override fun startSession(directory: String) {
|
||||||
|
val created = session("fresh", "New chat", directory = directory)
|
||||||
|
store.createSucceeded(created)
|
||||||
|
store.history(created.id, emptyList())
|
||||||
|
store.notice(created.id, "Started a new session “New chat” in $directory.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runChatSlashCommand("/new", store.value.thread("old")!!, host)
|
||||||
|
|
||||||
|
// Created in the current session's directory and switched to.
|
||||||
|
assertEquals("fresh", store.value.activeId)
|
||||||
|
assertEquals("/repo/work", store.value.thread("fresh")!!.directory)
|
||||||
|
// The old session is untouched: still open, still listed, history intact.
|
||||||
|
assertEquals(listOf("m1"), store.value.thread("old")!!.messages.map { it.id })
|
||||||
|
assertTrue(store.value.open.any { it.sessionId == "old" })
|
||||||
|
assertTrue(store.value.visibleSessions.any { it.id == "old" })
|
||||||
|
// The command is reported as its own line on the new conversation.
|
||||||
|
assertEquals(1, store.value.thread("fresh")!!.notices.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun newWithoutADirectoryIsRefusedInsteadOfGuessingOne() {
|
||||||
|
val host = RecordingHost()
|
||||||
|
runChatSlashCommand("/new", thread(directory = ""), host)
|
||||||
|
assertTrue(host.started.isEmpty())
|
||||||
|
assertEquals(1, host.notices.size)
|
||||||
|
assertTrue(host.notices.single().failed)
|
||||||
|
assertTrue(host.notices.single().text.contains("no directory"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun renameDelegatesToTheRealLocalRename() {
|
||||||
|
val store = ChatStore()
|
||||||
|
store.sessionsLoaded(listOf(session("old", "Old chat")))
|
||||||
|
store.open(session("old", "Old chat"))
|
||||||
|
|
||||||
|
val host = object : ChatCommandHost by RecordingHost() {
|
||||||
|
override fun renameSession(title: String) {
|
||||||
|
store.rename("old", title)
|
||||||
|
store.notice("old", "Renamed locally.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runChatSlashCommand("/rename Cool name", store.value.thread("old")!!, host)
|
||||||
|
|
||||||
|
assertEquals("Cool name", store.value.thread("old")!!.title)
|
||||||
|
assertEquals("Cool name", store.value.visibleSessions.single().title)
|
||||||
|
// The report is honest that the rename is the device's own.
|
||||||
|
assertTrue(store.value.thread("old")!!.notices.single().text.contains("Renamed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun closeDelegatesToTheRealCloseWhichThisRevisionDoesNotHave() {
|
||||||
|
val store = ChatStore()
|
||||||
|
store.sessionsLoaded(listOf(session("old")))
|
||||||
|
store.open(session("old"))
|
||||||
|
store.history("old", listOf(message("m1", ChatProtocol.ROLE_USER, "kept")))
|
||||||
|
|
||||||
|
val host = object : ChatCommandHost by RecordingHost() {
|
||||||
|
override fun finishSession() {
|
||||||
|
store.notice("old", CHAT_CLOSE_UNAVAILABLE, failed = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runChatSlashCommand("/close", store.value.thread("old")!!, host)
|
||||||
|
|
||||||
|
// The close is reported plainly and nothing is faked with the local hide.
|
||||||
|
assertTrue(store.value.thread("old")!!.notices.single().text.contains("no real session close"))
|
||||||
|
assertTrue(store.value.open.any { it.sessionId == "old" })
|
||||||
|
assertTrue(store.value.visibleSessions.any { it.id == "old" })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aRenameWithoutATitleReportsTheUsage() {
|
||||||
|
val host = RecordingHost()
|
||||||
|
runChatSlashCommand("/rename", thread(), host)
|
||||||
|
assertTrue(host.renames.isEmpty())
|
||||||
|
assertTrue(host.notices.single().text.contains("/rename <title>"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun stopOnlyInterruptsARunningTurn() {
|
||||||
|
val idle = RecordingHost()
|
||||||
|
runChatSlashCommand("/stop", thread(running = false), idle)
|
||||||
|
assertEquals(0, idle.stops)
|
||||||
|
assertTrue(idle.notices.single().text.contains("No turn is running"))
|
||||||
|
|
||||||
|
val running = RecordingHost()
|
||||||
|
runChatSlashCommand("/stop", thread(running = true), running)
|
||||||
|
assertEquals(1, running.stops)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun helpListsEveryCommand() {
|
||||||
|
val host = RecordingHost()
|
||||||
|
runChatSlashCommand("/help", thread(), host)
|
||||||
|
val text = host.notices.single().text
|
||||||
|
CHAT_COMMANDS.forEach { assertTrue("missing ${it.usage}", text.contains(it.usage)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aCommandThatTakesNoArgumentRejectsOne() {
|
||||||
|
val host = RecordingHost()
|
||||||
|
runChatSlashCommand("/new please", thread(), host)
|
||||||
|
assertTrue(host.started.isEmpty())
|
||||||
|
assertTrue(host.notices.single().text.contains("does not take an argument"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun plainTextIsNotACommandAndRunsNoEffect() {
|
||||||
|
val host = RecordingHost()
|
||||||
|
runChatSlashCommand("just a question", thread(), host)
|
||||||
|
assertTrue(host.notices.isEmpty())
|
||||||
|
assertEquals(0, host.finishes)
|
||||||
|
assertTrue(host.started.isEmpty())
|
||||||
|
assertTrue(host.renames.isEmpty())
|
||||||
|
assertEquals(0, host.stops)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- The unknown-command guard -------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun anUnknownCommandIsOfferedNeverSentAndNeverReachesThePromptPath() {
|
||||||
|
val store = ChatStore()
|
||||||
|
store.open(session("old"))
|
||||||
|
store.history("old", listOf(message("m1", ChatProtocol.ROLE_USER, "existing")))
|
||||||
|
|
||||||
|
// The host writes the offer to the real store and counts any effect; the
|
||||||
|
// prompt path is structurally absent from ChatCommandHost, so an unknown
|
||||||
|
// command cannot reach the agent through it.
|
||||||
|
val effects = RecordingHost()
|
||||||
|
val host = object : ChatCommandHost by effects {
|
||||||
|
override fun notify(text: String, failed: Boolean, offer: String?) {
|
||||||
|
store.notice("old", text, failed, offer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runChatSlashCommand("/nonsense", store.value.thread("old")!!, host)
|
||||||
|
|
||||||
|
val notice = store.value.thread("old")!!.notices.single()
|
||||||
|
assertTrue(notice.failed)
|
||||||
|
assertTrue(notice.text.contains("is not a command"))
|
||||||
|
assertEquals("/nonsense", notice.offer)
|
||||||
|
// Nothing reached the agent and no other command ran.
|
||||||
|
assertEquals(listOf("m1"), store.value.thread("old")!!.messages.map { it.id })
|
||||||
|
assertTrue(effects.started.isEmpty())
|
||||||
|
assertEquals(0, effects.finishes)
|
||||||
|
assertTrue(effects.renames.isEmpty())
|
||||||
|
assertEquals(0, effects.stops)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun theOfferCanBeTakenOnceToSendAsAMessage() {
|
||||||
|
val store = ChatStore()
|
||||||
|
store.open(session("old"))
|
||||||
|
val id = store.notice("old", "not a command", failed = true, offer = "/nonsense")!!
|
||||||
|
assertEquals("/nonsense", store.takeNoticeOffer("old", id))
|
||||||
|
// Taking it removes the offer so a stale tap sends nothing.
|
||||||
|
assertNull(store.takeNoticeOffer("old", id))
|
||||||
|
assertTrue(store.value.thread("old")!!.notices.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun noticesDoNotTouchTheModelConversation() {
|
||||||
|
val store = ChatStore()
|
||||||
|
store.open(session("old"))
|
||||||
|
store.history("old", listOf(message("m1", ChatProtocol.ROLE_USER, "existing")))
|
||||||
|
store.notice("old", "Command", failed = false)
|
||||||
|
store.notice("old", "Command failed", failed = true)
|
||||||
|
// Local command lines sit beside the conversation; the messages are as the
|
||||||
|
// server reported them, so running a command adds nothing to the model.
|
||||||
|
assertEquals(listOf("m1"), store.value.thread("old")!!.messages.map { it.id })
|
||||||
|
assertEquals(2, store.value.thread("old")!!.notices.size)
|
||||||
|
assertFalse(store.value.thread("old")!!.notices.any { it.id == "m1" })
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user