Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: create bots and group chats from a profile sheet, and give group chats slash commands

leepokai89b92cca44ce
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
index f4d1eb7f..02cb73ae 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
@@ -12,6 +12,7 @@ import androidx.compose.ui.test.junit4.createComposeRule
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.test.platform.app.InstrumentationRegistry
import com.codync.android.core.*
+import com.codync.android.design.AvatarPalette
import com.codync.android.design.LocalDismissModal
import kotlinx.serialization.json.*
import org.junit.Assert.*
@@ -21,7 +22,7 @@ import org.junit.Rule
import org.junit.Test
import java.io.File
-/** Read-only UI fixtures: no test taps Save or Create, so production bots are never changed. */
+/** Read-only UI fixtures for the bot settings and the New bot / New group chat dialogs: no test taps Save or Create, so production bots are never changed. */
class BotEditorTest {
@get:Rule val compose = createComposeRule()
private val scout = BotDraft(id = "fixture", name = "Scout", avatarShape = "blob", avatarColor = "blue")
@@ -54,21 +55,46 @@ class BotEditorTest {
assertTrue(closed)
}
- @Test fun newBotsStayUnnamedAndNeedTheComputerToCreate() {
- render(BotDraft(avatarShape = "blob", avatarColor = "blue"))
+ @Test fun aNewBotIsItsFaceAndAnOptionalName() {
+ compose.setContent { Hosted { NewBotView(fixture(), viewModel()) } }
compose.onNodeWithText("New bot").assertIsDisplayed()
- compose.onNodeWithText("Name").assertDoesNotExist()
+ compose.onNode(hasSetTextAction() and hasText("Name your bot")).assertIsDisplayed().assertIsFocused()
compose.onNodeWithContentDescription("Create").assertIsEnabled()
- compose.onNodeWithContentDescription("Agent: Claude").performScrollTo().assertIsDisplayed()
- snapshot("bot-editor-new-preview.png")
+ compose.onNodeWithContentDescription("Agent: Claude").assertDoesNotExist()
+ compose.onNodeWithContentDescription("teardrop shape").performClick().assertIsSelected()
+ compose.onNodeWithContentDescription("Gray").performClick().assertIsSelected()
+ // Every shape and color shows at once: the grids wrap instead of scrolling sideways.
+ (AvatarPalette.shapes.map { "$it shape" } + AvatarPalette.colors.keys.map { it.replaceFirstChar(Char::uppercase) })
+ .forEach { compose.onNodeWithContentDescription(it).assertIsDisplayed() }
+ snapshot("new-bot-preview.png")
}
@Test fun anOfflineNewBotCannotBeCreated() {
- render(BotDraft(avatarShape = "blob", avatarColor = "blue"), fixture().copy(actualConnection = LinkState.Connecting))
+ compose.setContent { Hosted { NewBotView(fixture().copy(actualConnection = LinkState.Connecting), viewModel()) } }
compose.onNodeWithContentDescription("Create").assertIsNotEnabled()
compose.onNodeWithText("Connect this computer to create the bot.").assertIsDisplayed()
}
+ @Test fun aNewGroupIsNamedAfterThePickedBotsUntilNamed() {
+ val bots = listOf(Bot("a", "Scout", avatarShape = "blob"), Bot("b", "Reviewer", avatarShape = "hex"))
+ compose.setContent { Hosted { NewGroupView(fixture().copy(bots = bots), viewModel()) } }
+ compose.onNodeWithText("New group chat").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Create").assertIsNotEnabled()
+ compose.onNode(hasSetTextAction() and hasText("Name your group")).assertIsDisplayed()
+ compose.onNodeWithContentDescription("Scout").performClick().assertIsSelected()
+ compose.onNodeWithContentDescription("Reviewer").performClick().assertIsSelected()
+ compose.onNode(hasSetTextAction() and hasText("Scout, Reviewer")).assertIsDisplayed()
+ compose.onNodeWithContentDescription("Create").assertIsEnabled()
+ compose.onNodeWithContentDescription("Scout").performClick().assertIsNotSelected()
+ snapshot("new-group-preview.png")
+ }
+
+ @Test fun aNewGroupWithoutBotsSaysToCreateOneFirst() {
+ compose.setContent { Hosted { NewGroupView(fixture(), viewModel()) } }
+ compose.onNodeWithText("No bots yet. Create a bot first.").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Create").assertIsNotEnabled()
+ }
+
@Test fun workspaceAndPermissionsUseMenusWhileNotificationsAndPluginsUseRealSwitches() {
val plugins = PluginListing(listOf(InstalledConnector("git", "GitHub", kind = "local", command = "git-server")),
listOf(InstalledSkill("review", "Review changes", "Review before pushing", "local", "/skills/review.md")))
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
index af1d218d..bcfcaab7 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
@@ -41,6 +41,7 @@ class LayoutTest {
compose.onNodeWithText("New group chat").assertIsDisplayed()
compose.onNodeWithText("New bot").performClick()
compose.onNodeWithContentDescription("Create").assertIsDisplayed()
+ compose.onNode(hasSetTextAction() and hasText("Name your bot")).assertIsDisplayed()
compose.onNodeWithContentDescription("Close").performClick()
compose.onNodeWithContentDescription("Create").assertDoesNotExist()
compose.onNode(tab("State")).performClick().assertIsSelected()
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt
index 55cce2b1..8acc4b3d 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt
@@ -35,13 +35,9 @@ class LiveManagementTest {
compose.runOnUiThread { store.openBot(null) }
compose.onNodeWithContentDescription("New").performClick()
compose.onNodeWithText("New group chat").performClick()
- compose.onNodeWithText("Add Member").performClick()
- val search = hasSetTextAction() and hasText("Search bots")
- compose.onNode(search).performTextReplacement(member.name)
- compose.onNodeWithContentDescription("Add " + member.name).performClick()
- compose.onNode(search).performTextReplacement(parent.name)
- compose.onNodeWithContentDescription("Add " + parent.name).performClick()
- compose.onNodeWithContentDescription("Remove " + member.name).assertIsDisplayed()
+ // The member tiles, not the roster rows behind the sheet (those share the bot's name).
+ compose.onNode(hasContentDescription(member.name) and isSelectable()).performScrollTo().performClick().assertIsSelected()
+ compose.onNode(hasContentDescription(parent.name) and isSelectable()).performScrollTo().performClick().assertIsSelected()
compose.onNodeWithContentDescription("Create").performClick()
compose.waitUntil(30_000) { store.state.value.bots.any { it.id == store.state.value.selectedBot && it.kind == "group" } }
val group = store.state.value.bots.single { it.id == store.state.value.selectedBot }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
index 37e7f3c6..2d16f9a7 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
@@ -41,6 +41,16 @@ fun AppStore.saveGroup(draft: GroupDraft, onSaved: () -> Unit) = action("editor"
onSaved()
}
+/** `/fast`: a bot's own Fast mode, or a group's members' together (each member's own setting, so it holds in their chats too). */
+fun AppStore.toggleFastMode(bot: Bot) {
+ if (bot.kind != "group") return setFastMode(bot, !bot.fastMode)
+ val group = GroupFastMode(bot.memberBots(state.value.bots))
+ for (member in group.members) setFastMode(member, group.state == FastModeState.Off)
+}
+private fun AppStore.setFastMode(bot: Bot, on: Boolean) {
+ command("updateBot", buildJsonObject { put("id", bot.id); put("fastMode", on) }, "roster:" + bot.id)
+}
+
fun AppStore.deleteBot(bot: Bot, onDeleted: () -> Unit) = action("delete:" + bot.id) {
val active = ready()
active.call("deleteBot", body("botId" to bot.id))
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
index 25cdf8f7..aac3c74b 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
@@ -17,8 +17,7 @@ import com.codync.android.design.*
/** A bot's character, or a group's members. */
@Composable internal fun BotAvatar(bot: Bot, bots: List<Bot>, size: Dp = 44.dp) {
- if (bot.kind == "group") GroupAvatar(bot.members.mapNotNull { id -> bots.firstOrNull { it.id == id } }
- .map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, size)
+ if (bot.kind == "group") GroupAvatar(bot.memberBots(bots).map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, size)
else CharacterAvatar(bot.avatarShape, bot.avatarColor, size, bot.status)
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
index 6cfa33bd..4bf97795 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
@@ -33,7 +33,7 @@ import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonPrimitive
-/** Create or edit a bot in a sheet, as iOS `BotEditorView`: the settings form plus Close and Save. */
+/** A bot's settings in a sheet, as iOS `BotEditorView`: the settings form plus Close and Save. New bots start in [NewBotView]. */
@Composable fun BotEditor(state: AppState, initial: BotDraft, store: AppStore) {
var draft by remember(initial.id) { mutableStateOf(initial) }
var folders by remember { mutableStateOf(false) }
@@ -41,14 +41,11 @@ import kotlinx.serialization.json.jsonPrimitive
val online = state.actualConnection is LinkState.Ready
val saving = "editor" in state.busy
val dismiss = LocalDismissModal.current
- val isNew = draft.id == null
- // A new bot starts on an installed agent we know, with every connector and skill on.
- LaunchedEffect(state.hello, state.plugins) { if (isNew) draft = fillDefaults(draft, state) }
LaunchedEffect(online) { if (online) store.refreshPlugins() }
Column(Modifier.fillMaxSize()) {
- ModalHeader(if (isNew) "New bot" else "Settings") {
+ ModalHeader("Settings") {
if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
- else IconButton(if (isNew) "Create" else "Save", "checkmark", enabled = draft.isValid && online) {
+ else IconButton("Save", "checkmark", enabled = draft.isValid && online) {
store.saveBot(draft) { dismiss() }
}
}
@@ -62,21 +59,10 @@ import kotlinx.serialization.json.jsonPrimitive
CodyncSheet(viewingSkill, { viewingSkill = null }) { SkillSheet(it, state, store) }
}
-/** Picks an installed agent we know; connectors and skills start on once the computer has listed them. */
-private fun fillDefaults(draft: BotDraft, state: AppState): BotDraft {
- val backends = backends(state)
- var next = draft
- if (backends.none { it.text("id") == draft.backend && it.available }) backends.firstOrNull { it.available && it.curated }?.text("id")
- ?.let { next = next.copy(backend = it) }
- val plugins = state.plugins
- if (plugins != null && next.connectors == null && plugins.connectors.isNotEmpty()) next = next.copy(connectors = plugins.connectors.map { it.id })
- if (plugins != null && next.skills.isEmpty() && plugins.skills.isNotEmpty() && draft.skills.isEmpty()) next = next.copy(skills = plugins.skills.map { it.id })
- return next
-}
-
-private fun backends(state: AppState): List<JsonObject> = (state.hello?.get("backends") as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }
-private val JsonObject.available get() = this["available"]?.jsonPrimitive?.booleanOrNull == true
-private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOrNull != false
+/** The computer's agents, as its hello lists them. */
+internal fun backends(state: AppState): List<JsonObject> = (state.hello?.get("backends") as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }
+internal val JsonObject.available get() = this["available"]?.jsonPrimitive?.booleanOrNull == true
+internal val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOrNull != false
/** Bot settings: a big avatar, then sections in the Settings style (`CardSection`). */
@Composable private fun BotSettingsForm(state: AppState, store: AppStore, draft: BotDraft, change: (BotDraft) -> Unit, viewSkill: (SkillRef) -> Unit,
@@ -91,8 +77,8 @@ private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOr
AvatarPicker(draft.avatarShape, draft.avatarColor, { change(draft.copy(avatarShape = it)) }, { change(draft.copy(avatarColor = it)) })
}
CardSection("Profile") {
- // A new bot is named from its first conversations; rename it any time after.
- if (draft.id != null) row { Field("Name") { FieldBox(draft.name, { change(draft.copy(name = it)) }, "Name") } }
+ // A bot left unnamed at creation is named from its first conversations; rename it any time after.
+ row { Field("Name") { FieldBox(draft.name, { change(draft.copy(name = it)) }, "Name") } }
row {
Field("Standing instructions", "Rules that always apply. Put task-specific requests in the chat instead.") {
FieldBox(draft.description, { change(draft.copy(description = it)) }, "e.g. Reviews PRs. Never pushes without asking.", 3, 8)
@@ -103,8 +89,7 @@ private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOr
row {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
ValueRow("Computer", state.computers.firstOrNull()?.name ?: "Your computer")
- if (!online) Text(if (draft.id == null) "Connect this computer to create the bot." else "Reconnect to this computer to save settings.",
- style = Type.caption, color = Palette.warning)
+ if (!online) Text("Reconnect to this computer to save settings.", style = Type.caption, color = Palette.warning)
}
}
row {
@@ -171,7 +156,7 @@ private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOr
plugins?.connectors.orEmpty().map { Triple(it.id, it.name, it.command ?: it.url.orEmpty()) },
draft.connectors ?: plugins?.connectors.orEmpty().map { it.id }, { change(draft.copy(connectors = it)) })
PluginToggles("Skills", "No skills yet. Get some from Extensions, or write your own.",
- plugins?.skills.orEmpty().map { Triple(it.id, it.name, it.description) }, draft.skills, { change(draft.copy(skills = it)) }) { id ->
+ plugins?.skills.orEmpty().map { Triple(it.id, it.name, it.description) }, draft.skills.orEmpty(), { change(draft.copy(skills = it)) }) { id ->
plugins?.skills?.firstOrNull { it.id == id }?.let { viewSkill(SkillRef(it.id, it.name, it.description)) }
}
draft.id?.let { MemoryCard(it, store) }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
index 85383cb0..ad08d04f 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
@@ -396,7 +396,7 @@ internal fun currentThinking(entries: List<Entry>, botId: String, thread: String
/** The start of an empty chat: who the bot is and how it works. */
@Composable internal fun IntroCard(bot: Bot, state: AppState) {
- val members = bot.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }
+ val members = bot.memberBots(state.bots)
Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp).padding(top = 40.dp), horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)) {
BotAvatar(bot, state.bots, 72.dp)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
index 40d565b5..1a56e059 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
@@ -39,6 +39,8 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }
var showPairing by rememberSaveable { mutableStateOf(false) }
var showUsage by rememberSaveable { mutableStateOf(false) }
var showMarketplace by rememberSaveable { mutableStateOf(false) }
+ var creatingBot by rememberSaveable { mutableStateOf(false) }
+ var creatingGroup by rememberSaveable { mutableStateOf(false) }
var access by remember { mutableStateOf<CloudComputer?>(null) }
var editor by remember { mutableStateOf<BotDraft?>(null) }
var groupEditor by remember { mutableStateOf<GroupDraft?>(null) }
@@ -46,7 +48,7 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }
var handledGeneration by rememberSaveable { mutableIntStateOf(state.generation) }
fun closeAll() {
showAccount = false; accountSettings = false; showComputers = false; showPairing = false; showMarketplace = false
- access = null; editor = null; groupEditor = null
+ creatingBot = false; creatingGroup = false; access = null; editor = null; groupEditor = null
}
// A new account or a fresh start drops whatever was open for the old one.
LaunchedEffect(state.generation) { if (handledGeneration != state.generation) { closeAll(); showUsage = false; handledGeneration = state.generation } }
@@ -88,7 +90,7 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }
}
}
Root.Tabs -> MainTabs(state, store, account = { showAccount = true }, manage = { showComputers = true }, usage = { showUsage = true },
- newBot = { editor = BotDraft() }, newGroup = { groupEditor = GroupDraft() },
+ newBot = { creatingBot = true }, newGroup = { creatingGroup = true },
edit = { bot -> if (bot.kind == "group") groupEditor = GroupDraft.from(bot) else editor = BotDraft.from(bot) }) {
ChatScreen(state, store) { bot -> if (bot.kind == "group") groupEditor = GroupDraft.from(bot) else editor = BotDraft.from(bot) }
}
@@ -121,20 +123,22 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }
AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Marketplace))
MarketplaceView(state, store)
}
- // An existing bot or group's editor is its details; a new one's isn't.
+ CodyncSheet(creatingBot && !state.loading, { creatingBot = false }) { key(state.contextId, state.generation) { NewBotView(state, store) } }
+ CodyncSheet(creatingGroup && !state.loading, { creatingGroup = false }) { key(state.contextId, state.generation) { NewGroupView(state, store) } }
+ // A bot or group's editor is its details.
CodyncSheet(groupEditor.takeIf { !state.loading }, { groupEditor = null }) { draft ->
- if (draft.id != null) AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
key(state.contextId, state.generation, draft.id) { GroupEditor(state, draft, store) }
}
CodyncSheet(editor.takeIf { !state.loading }, { editor = null }) { draft ->
- if (draft.id != null) AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
key(state.contextId, state.generation, draft.id) { BotEditor(state, draft, store) }
}
// The remote screen opens over the app once its sheets have slid away.
LaunchedEffect(state.screenRequest) { if (state.screenRequest != null) { closeAll(); showUsage = false } }
ScreenLayer(state, store)
- // One place for errors the screen showing them doesn't handle itself (pairing, access, the editors do).
- val inline = root == Root.Pairing || showPairing || access != null || editor != null || groupEditor != null
+ // One place for errors the screen showing them doesn't handle itself (pairing, access, the new and edit sheets do).
+ val inline = root == Root.Pairing || showPairing || access != null || creatingBot || creatingGroup || editor != null || groupEditor != null
CodyncDialog("Something went wrong", state.error != null && !inline, store::clearError, state.error, cancel = "OK") { emptyList() }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt b/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt
index 74da751b..b23fbfa8 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt
@@ -2,16 +2,15 @@ package com.codync.android
import androidx.compose.foundation.background
import androidx.compose.foundation.border
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.FlowRowScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.ImeAction
@@ -27,13 +26,14 @@ import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.codync.android.design.*
import com.kyant.shapes.Capsule
import com.kyant.shapes.RoundedRectangle
// The settings-form pieces of iOS `BotEditorView`: labelled fields, switch rows, the avatar
-// picker and the connector/skill toggles.
+// picker (also on New bot) and the connector/skill toggles.
/** A labeled input inside a section row: label (and an optional note) over the field. */
@Composable internal fun Field(label: String, detail: String? = null, content: @Composable () -> Unit) {
@@ -67,22 +67,34 @@ import com.kyant.shapes.RoundedRectangle
}
}
-/** The bot's face: a row of shapes over a row of colors, each with a ring when chosen. */
+/** The bot's face: every shape over every color, as wrapping centered grids, each ringed when chosen. */
@Composable internal fun AvatarPicker(shape: String, color: String, chooseShape: (String) -> Unit, chooseColor: (String) -> Unit) {
- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
- Row(Modifier.horizontalScroll(rememberScrollState()).padding(4.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
- for (option in AvatarPalette.shapes) Box(Modifier.clip(Capsule()).border(2.dp, if (option == shape) Palette.accent else Color.Transparent, Capsule())
- .clickable(role = Role.RadioButton) { chooseShape(option) }.semantics { contentDescription = "$option shape"; selected = option == shape }
- .padding(4.dp)) { CharacterAvatar(option, color, 36.dp) }
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ ChoiceGrid {
+ for (option in AvatarPalette.shapes) Box(Modifier.choice(option == shape, "$option shape") { chooseShape(option) }.ring(option == shape)) {
+ CharacterAvatar(option, color, 40.dp)
+ }
}
- Row(Modifier.horizontalScroll(rememberScrollState()).padding(4.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
- for ((id, hex) in AvatarPalette.colors) Box(Modifier.clip(Capsule()).border(2.dp, if (id == color) Palette.accent else Color.Transparent, Capsule())
- .clickable(role = Role.RadioButton) { chooseColor(id) }.semantics { contentDescription = id.replaceFirstChar(Char::uppercase); selected = id == color }
- .padding(4.dp)) { Box(Modifier.size(26.dp).clip(Capsule()).background(Color(hex))) }
+ ChoiceGrid {
+ for ((id, hex) in AvatarPalette.colors) Box(Modifier.choice(id == color, id.replaceFirstChar(Char::uppercase)) { chooseColor(id) }.ring(id == color)) {
+ Box(Modifier.size(28.dp).clip(Capsule()).background(Color(hex)))
+ }
}
}
}
+/** A grid that wraps onto centered rows, for the avatar and member choices. */
+@Composable internal fun ChoiceGrid(spacing: Dp = 10.dp, content: @Composable FlowRowScope.() -> Unit) =
+ FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(spacing, Alignment.CenterHorizontally),
+ verticalArrangement = Arrangement.spacedBy(spacing), content = content)
+
+/** A tappable choice in a [ChoiceGrid]: dims while pressed; put the [ring] on what shows it's chosen. */
+@Composable internal fun Modifier.choice(chosen: Boolean, label: String, role: Role = Role.RadioButton, choose: () -> Unit) =
+ plainButton(role = role, action = choose).semantics { contentDescription = label; selected = chosen }
+
+/** The accent ring around a chosen shape, color or member (iOS `strokeBorder(Palette.accent)`). */
+@Composable internal fun Modifier.ring(chosen: Boolean) = clip(Capsule()).border(2.dp, if (chosen) Palette.accent else Color.Transparent, Capsule()).padding(4.dp)
+
/** A card of on/off switches for the connectors or skills installed on the computer. */
@Composable internal fun PluginToggles(title: String, empty: String, items: List<Triple<String, String, String>>, selection: List<String>,
change: (List<String>) -> Unit, info: ((String) -> Unit)? = null) {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt b/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt
index 4e29c481..61d27295 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt
@@ -37,15 +37,14 @@ import com.codync.android.core.GroupDraft
import com.codync.android.design.*
/**
- * Create a group chat, or change its name, what it's for and who's in it (iOS `GroupEditorView`).
+ * Change a group chat's name, what it's for and who's in it (iOS `GroupEditorView`); new groups start in [NewGroupView].
* Bots are picked like recipients: members on top, a search, and the bots not in it yet.
*/
@Composable internal fun GroupEditor(state: AppState, initial: GroupDraft, store: AppStore) {
val dismiss = LocalDismissModal.current
var draft by remember(initial.id) { mutableStateOf(initial) }
var query by remember { mutableStateOf("") }
- // A new group starts in the picker; an existing one shows its members first.
- var adding by remember { mutableStateOf(initial.id == null && initial.members.isEmpty()) }
+ var adding by remember { mutableStateOf(false) }
var confirmDelete by remember { mutableStateOf(false) }
val saving = "editor" in state.busy
val picked = draft.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }
@@ -56,9 +55,9 @@ import com.codync.android.design.*
query = ""
}
Column(Modifier.fillMaxSize().background(Palette.background)) {
- ModalHeader(if (draft.id == null) "New group chat" else "Group chat") {
+ ModalHeader("Group chat") {
if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
- else IconButton(if (draft.id == null) "Create" else "Save", "checkmark", enabled = draft.members.isNotEmpty()) {
+ else IconButton("Save", "checkmark", enabled = draft.members.isNotEmpty()) {
store.saveGroup(draft) { dismiss() }
}
}
@@ -92,7 +91,7 @@ import com.codync.android.design.*
AnimatedVisibility(state.error != null, enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
Text(state.error.orEmpty(), style = Type.footnote, color = Palette.danger)
}
- if (draft.id != null) LinkButton("Delete group chat", color = Palette.danger) { confirmDelete = true }
+ LinkButton("Delete group chat", color = Palette.danger) { confirmDelete = true }
}
}
val group = state.bots.firstOrNull { it.id == draft.id }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
index b1df45c6..402fe005 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
@@ -10,8 +10,6 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
-import kotlinx.serialization.json.buildJsonObject
-import kotlinx.serialization.json.put
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateDpAsState
@@ -124,24 +122,26 @@ private enum class Trailing { Interrupt, Stop, Call, Send }
}
val placeholder = when {
thread != null -> "Reply…"
- bot.kind == "group" -> "Message everyone · @ to ask one bot"
+ bot.kind == "group" -> "Ask everyone · @ to ask one bot"
working -> "Queue a message for ${bot.name}"
else -> "Ask ${bot.name}"
}
val typed = text.text.toString()
- val commands = SlashCommands.query(typed)?.let { SlashCommands.list(bot, it, state.plugins?.skills.orEmpty(), state.hello?.text("version")) }.orEmpty()
+ val members = bot.memberBots(state.bots)
+ val commands = SlashCommands.query(typed)?.let { SlashCommands.list(bot, it, state.plugins?.skills.orEmpty(), state.hello?.text("version"), members) }.orEmpty()
// Starting a command: list the computer's skills again, once each time the draft becomes "/".
- val startingCommand = typed == "/" && bot.kind != "group"
+ val startingCommand = typed == "/"
LaunchedEffect(startingCommand) { if (startingCommand && online) store.refreshPlugins() }
+ // The one way a group's box differs: @ asks one of its bots.
val mentions = if (bot.kind != "group") emptyList() else mentionQuery(typed)?.let { query ->
- bot.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }.filter { query.isEmpty() || it.name.contains(query, true) }
+ members.filter { query.isEmpty() || it.name.contains(query, true) }
}.orEmpty()
fun clear() = text.edit { replace(0, length, "") }
fun run(command: SlashCommand) {
val skill = command.skill
when {
skill != null -> text.setTextAndPlaceCursorAtEnd("/$skill ")
- else -> { store.command("updateBot", buildJsonObject { put("id", bot.id); put("fastMode", !bot.fastMode) }, "roster:" + bot.id); clear() }
+ else -> { store.toggleFastMode(bot); clear() }
}
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
@@ -183,7 +183,7 @@ private enum class Trailing { Interrupt, Stop, Call, Send }
Trailing.Stop -> store.command("stop", body("botId" to bot.id))
Trailing.Call -> onCall?.invoke()
Trailing.Send -> {
- val command = if (files.isEmpty()) SlashCommands.builtIn(bot, typed) else null
+ val command = if (files.isEmpty()) SlashCommands.builtIn(bot, typed, members) else null
if (command != null) run(command) else store.sendDraft(bot.id, thread, typed) { clear() }
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt b/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt
new file mode 100644
index 00000000..5ea3759f
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt
@@ -0,0 +1,115 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.BotDraft
+import com.codync.android.core.GroupDraft
+import com.codync.android.core.LinkState
+import com.codync.android.design.*
+
+/** A new bot from its face and name (iOS `NewBotView`); the rest starts on the defaults and changes later in its Settings. */
+@Composable fun NewBotView(state: AppState, store: AppStore) {
+ var draft by remember { mutableStateOf(BotDraft()) }
+ val online = state.actualConnection is LinkState.Ready
+ val dismiss = LocalDismissModal.current
+ // A new bot starts on an installed agent we know; the host turns on every connector and skill.
+ LaunchedEffect(state.hello) { draft = fillDefaults(draft, state) }
+ CreateLayout(state, "New bot", draft.name, { draft = draft.copy(name = it) }, "Name your bot", online, { store.saveBot(draft) { dismiss() } },
+ { CharacterAvatar(draft.avatarShape, draft.avatarColor, 96.dp) }) {
+ AvatarPicker(draft.avatarShape, draft.avatarColor, { draft = draft.copy(avatarShape = it) }, { draft = draft.copy(avatarColor = it) })
+ if (!online) Text("Connect this computer to create the bot.", style = Type.caption, color = Palette.warning)
+ }
+}
+
+/** A new group chat from the bots it brings together (iOS `NewGroupView`); what it works on is set later in its editor. */
+@Composable fun NewGroupView(state: AppState, store: AppStore) {
+ var name by remember { mutableStateOf("") }
+ var members by remember { mutableStateOf(emptyList<String>()) }
+ val dismiss = LocalDismissModal.current
+ val bots = roster(state.bots).filter { it.kind != "group" }
+ val picked = members.mapNotNull { id -> bots.firstOrNull { it.id == id } }
+ CreateLayout(state, "New group chat", name, { name = it }, picked.joinToString(", ") { it.name }.ifEmpty { "Name your group" }, picked.isNotEmpty(),
+ { store.saveGroup(GroupDraft(name = name, members = picked.map(Bot::id))) { dismiss() } },
+ { GroupAvatar(picked.map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, 96.dp) }) {
+ if (bots.isEmpty()) Text("No bots yet. Create a bot first.", style = Type.subheadline, color = Palette.secondary)
+ else ChoiceGrid(8.dp) {
+ for (bot in bots) MemberTile(bot, state.bots, bot.id in members) { members = if (bot.id in members) members - bot.id else members + bot.id }
+ }
+ Text("Everyone answers in turn unless you @mention someone.", style = Type.caption, color = Palette.tertiary)
+ }
+}
+
+/** Both create dialogs' layout (iOS `CreateForm`): a big preview, the centered name (Done creates), the grids, then any save error. */
+@Composable private fun CreateLayout(state: AppState, title: String, name: String, rename: (String) -> Unit, prompt: String, canCreate: Boolean,
+ create: () -> Unit, preview: @Composable () -> Unit, content: @Composable ColumnScope.() -> Unit) {
+ val saving = "editor" in state.busy
+ val focus = remember { FocusRequester() }
+ LaunchedEffect(Unit) { focus.requestFocus() }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(title) {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Create", "checkmark", enabled = canCreate, action = create)
+ }
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 24.dp),
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ preview()
+ PlainTextField(name, rename, Modifier.fillMaxWidth().focusRequester(focus), prompt, singleLine = true,
+ style = Type.title2.semibold.copy(textAlign = TextAlign.Center),
+ keyboard = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Done),
+ actions = KeyboardActions(onDone = { if (canCreate && !saving) create() }))
+ content()
+ AnimatedVisibility(state.error != null, enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
+ Text(state.error.orEmpty(), style = Type.footnote, color = Palette.danger)
+ }
+ }
+ }
+}
+
+/** A bot to pick for the group: its avatar, ringed when picked, over its name. */
+@Composable private fun MemberTile(bot: Bot, bots: List<Bot>, picked: Boolean, toggle: () -> Unit) {
+ Column(Modifier.width(64.dp).choice(picked, bot.name, Role.Checkbox, toggle), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Box(Modifier.ring(picked)) { BotAvatar(bot, bots, 44.dp) }
+ Text(bot.name, style = Type.caption, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+/** Picks an installed agent we know (a registry agent nobody chose is never the default). */
+private fun fillDefaults(draft: BotDraft, state: AppState): BotDraft {
+ val backends = backends(state)
+ if (backends.any { it.text("id") == draft.backend && it.available }) return draft
+ return backends.firstOrNull { it.available && it.curated }?.text("id")?.let { draft.copy(backend = it) } ?: draft
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt b/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt
index 99d6f9db..51d14429 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt
@@ -23,7 +23,11 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.codync.android.core.AppVersion
import com.codync.android.core.Bot
+import com.codync.android.core.FastModeState
+import com.codync.android.core.GroupFastMode
import com.codync.android.core.InstalledSkill
+import com.codync.android.core.fastModeDetail
+import com.codync.android.core.fastModeState
import com.codync.android.design.*
import com.kyant.shapes.Capsule
import com.kyant.shapes.RoundedRectangle
@@ -33,30 +37,43 @@ internal data class SlashCommand(val name: String, val icon: String, val title:
val skill: String? = null)
/**
- * The composer's `/` commands, listed while the draft is just `/partial` (iOS `SlashCommands`): Fast mode
- * runs here (a new session is in the bot's menu); a skill fills in `/<id> `, which the host turns into "read this skill first".
+ * The composer's `/` commands, listed while the draft is just `/partial`, the same in a group (iOS `SlashCommands`): Fast mode
+ * runs here (a group's on each member; a new session is in the bot's menu); a skill fills in `/<id> `, which the host turns into
+ * "read this skill first".
*/
internal object SlashCommands {
/** The first host that understands `/skill` messages; older ones get the text as typed. */
private const val MIN_SKILLS_HOST = "2.14.1"
+ /** The first host that runs `/skill` in a group's prompts (host/src/chat/group.rs `line`). */
+ private const val MIN_GROUP_SKILLS_HOST = "2.20.1"
/** The command name being typed after a leading `/`, before any space. */
fun query(draft: String): String? = if (draft.startsWith("/") && draft.none(Char::isWhitespace)) draft.drop(1) else null
- /** Built-in commands, then the bot's skills, whose name or title holds `query` (none in a group). */
- fun list(bot: Bot, query: String, skills: List<InstalledSkill>, hostVersion: String?): List<SlashCommand> {
- if (bot.kind == "group") return emptyList()
- val own = if (hostVersion != null && AppVersion.isBelow(hostVersion, MIN_SKILLS_HOST)) emptyList()
- else skills.filter { it.id in bot.skills }.map { SlashCommand(it.id, "book.pages", it.name, it.description, false, it.id) }
- return (builtIn(bot) + own).filter { query.isEmpty() || it.name.contains(query, true) || it.title.contains(query, true) }
+ /** Built-in commands, then the skills the bot has on (a group's: any member's), whose name or title holds `query`. `members` are a group's bots. */
+ fun list(bot: Bot, query: String, skills: List<InstalledSkill>, hostVersion: String?, members: List<Bot> = emptyList()): List<SlashCommand> {
+ val group = bot.kind == "group"
+ val owners = if (group) members else listOf(bot)
+ val own = if (hostVersion != null && AppVersion.isBelow(hostVersion, if (group) MIN_GROUP_SKILLS_HOST else MIN_SKILLS_HOST)) emptyList()
+ else skills.filter { skill -> owners.any { skill.id in it.skills } }.map { SlashCommand(it.id, "book.pages", it.name, it.description, false, it.id) }
+ return (builtIn(bot, members) + own).filter { query.isEmpty() || it.name.contains(query, true) || it.title.contains(query, true) }
}
/** A draft that is just a built-in command (`/fast`): sending it runs the command. */
- fun builtIn(bot: Bot, draft: String): SlashCommand? = query(draft.trim())?.let { name -> builtIn(bot).firstOrNull { it.name == name } }
+ fun builtIn(bot: Bot, draft: String, members: List<Bot> = emptyList()): SlashCommand? =
+ query(draft.trim())?.let { name -> builtIn(bot, members).firstOrNull { it.name == name } }
- private fun builtIn(bot: Bot): List<SlashCommand> = if (bot.kind == "group") emptyList() else buildList {
- if (bot.fastModeShown) add(SlashCommand("fast", "bolt", "Fast mode", bot.fastModeRefusal
- ?: if (bot.fastMode) "Turn off and return to standard speed" else "Turn on for faster replies and more usage", bot.fastModeRefusal != null))
+ /** Fast mode, while the bot (or a member of the group) shows it. */
+ private fun builtIn(bot: Bot, members: List<Bot>): List<SlashCommand> {
+ val (detail, state) = if (bot.kind == "group") {
+ val group = GroupFastMode(members)
+ if (group.members.isEmpty()) return emptyList()
+ group.detail to group.state
+ } else {
+ if (!bot.fastModeShown) return emptyList()
+ bot.fastModeDetail to bot.fastModeState
+ }
+ return listOf(SlashCommand("fast", "bolt", "Fast mode", detail, state == FastModeState.Refused))
}
}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt
index d503fd20..643e7f60 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt
@@ -1,6 +1,8 @@
package com.codync.android
import com.codync.android.core.Bot
+import com.codync.android.core.FastModeState
+import com.codync.android.core.GroupFastMode
import com.codync.android.core.InstalledSkill
import org.junit.Assert.*
import org.junit.Test
@@ -18,6 +20,39 @@ class SlashCommandsTest {
assertTrue(SlashCommands.list(Bot("g", "Team", kind = "group"), "", skills, null).isEmpty())
}
+ @Test fun `a group lists its members' Fast mode and the union of their skills`() {
+ val group = Bot("g", "Team", kind = "group", members = listOf("a", "b", "c"))
+ val skills = listOf(InstalledSkill("review", "Review", "", "src", "/p"), InstalledSkill("notes", "Notes", "", "src", "/q"),
+ InstalledSkill("unused", "Unused", "", "src", "/r"))
+ val scout = Bot("a", "Scout", skills = listOf("review"))
+ val writer = Bot("b", "Writer", skills = listOf("review", "notes"))
+ val plain = Bot("c", "Plain", fastModeSupport = "unsupported")
+ fun fast(vararg members: Bot) = SlashCommands.list(group, "fast", skills, null, members.toList()).single()
+
+ assertEquals(listOf("fast", "review", "notes"), SlashCommands.list(group, "", skills, null, listOf(scout, writer, plain)).map { it.name })
+ assertEquals("Turn on for every bot here: faster replies and more usage", fast(scout.copy(fastMode = true), writer).detail)
+ // Members without Fast mode don't count toward "on".
+ assertEquals("Turn off for every bot here and return to standard speed", fast(scout.copy(fastMode = true), writer.copy(fastMode = true), plain).detail)
+ val refused = fast(scout.copy(fastMode = true), writer.copy(fastMode = true, fastModeSupport = "refused", fastModeIssue = "busy"))
+ assertEquals("Writer: The agent turned it off: busy. Switch it off and on to try again.", refused.detail)
+ assertTrue(refused.warning)
+ assertEquals("fast", SlashCommands.builtIn(group, " /fast ", listOf(scout))?.name)
+ assertEquals(listOf("review"), SlashCommands.list(group, "", skills, null, listOf(plain, Bot("d", "Old", fastModeSupport = "unsupported",
+ skills = listOf("review")))).map { it.name })
+ assertNull(SlashCommands.builtIn(group, "/fast", listOf(plain)))
+ // Only a host that runs `/skill` in group prompts gets the skills.
+ assertEquals(listOf("fast"), SlashCommands.list(group, "", skills, "2.20.0", listOf(scout, writer)).map { it.name })
+ assertEquals(listOf("fast", "review", "notes"), SlashCommands.list(group, "", skills, "2.20.1", listOf(scout, writer)).map { it.name })
+ }
+
+ @Test fun `a group's Fast mode turns every member that shows it the opposite way`() {
+ val on = GroupFastMode(listOf(Bot("a", fastMode = true), Bot("b", fastMode = true), Bot("c", fastModeSupport = "unsupported")))
+ assertEquals(listOf("a", "b"), on.members.map { it.id })
+ assertEquals(FastModeState.On, on.state)
+ assertEquals(FastModeState.Off, GroupFastMode(listOf(Bot("a", fastMode = true), Bot("b"))).state)
+ assertEquals(FastModeState.Off, GroupFastMode(emptyList()).state)
+ }
+
@Test fun `mentions start after a space and stay short`() {
assertEquals("Re", mentionQuery("hi @Re"))
assertNull(mentionQuery("mail@host"))
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
index 775d6d39..7799cfc1 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
@@ -24,10 +24,12 @@ data class BotDraft(
val hidden: Boolean = false,
val notify: Boolean? = null,
val connectors: List<String>? = null,
- val skills: List<String> = emptyList(),
+ /** Unset on a new bot, like [connectors]: the host turns on every installed one. */
+ val skills: List<String>? = null,
val computer: Boolean = false,
) {
- val isValid: Boolean get() = id == null || name.isNotBlank()
+ /** A saved bot keeps a name; only a new one goes without (the host names it after its first conversations). */
+ val isValid: Boolean get() = name.isNotBlank()
fun toggleNotifications(): BotDraft = copy(notify = !(notify ?: true))
fun body(): JsonObject {
val normalized = if (backend == "custom") this else copy(command = null)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/FastMode.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/FastMode.kt
new file mode 100644
index 00000000..3c75c55f
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/FastMode.kt
@@ -0,0 +1,37 @@
+package com.codync.android.core
+
+// Fast mode in the chat (the composer's `/fast`) and bot settings, as iOS `Bot+FastMode.swift`; the host reports
+// what the agent offers (`fastModeSupport`, `fastModeIssue`): docs/features/marketplace.md, "Fast mode".
+
+enum class FastModeState { On, Off, Refused }
+
+val Bot.fastModeState: FastModeState get() = when {
+ !fastMode -> FastModeState.Off
+ fastModeSupport == "refused" -> FastModeState.Refused
+ else -> FastModeState.On
+}
+
+/** What picking `/fast` in the composer's command list does, or why it isn't in effect. */
+val Bot.fastModeDetail: String get() = when (fastModeState) {
+ FastModeState.Off -> "Turn on for faster replies and more usage"
+ FastModeState.On -> "Turn off and return to standard speed"
+ FastModeState.Refused -> fastModeRefusal.orEmpty()
+}
+
+/** A group's `/fast`: the members that show Fast mode, switched together. Each member's own setting, so it holds in their own chats too. */
+class GroupFastMode(members: List<Bot>) {
+ val members: List<Bot> = members.filter { it.fastModeShown }
+
+ /** On once every member that shows it has it on; refused when one of their agents turned it off. */
+ val state: FastModeState get() = when {
+ members.isEmpty() || !members.all { it.fastMode } -> FastModeState.Off
+ members.any { it.fastModeState == FastModeState.Refused } -> FastModeState.Refused
+ else -> FastModeState.On
+ }
+
+ val detail: String get() = when (state) {
+ FastModeState.Off -> "Turn on for every bot here: faster replies and more usage"
+ FastModeState.On -> "Turn off for every bot here and return to standard speed"
+ FastModeState.Refused -> members.firstOrNull { it.fastModeState == FastModeState.Refused }?.let { "${it.name}: ${it.fastModeRefusal}" }.orEmpty()
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
index 2814189f..3519b737 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
@@ -58,6 +58,9 @@ data class Bot(
val fastModeRefusal: String? get() = if (fastMode && fastModeSupport == "refused")
"The agent turned it off: ${fastModeIssue ?: "not available"}. Switch it off and on to try again." else null
+ /** A group's bots, in member order, from [bots]. */
+ fun memberBots(bots: List<Bot>): List<Bot> = members.mapNotNull { id -> bots.firstOrNull { it.id == id } }
+
/** Working right now in this chat's main conversation (`thread == null`) or in that thread. */
fun isWorking(chat: String, thread: String?): Boolean =
status in listOf("working", "needsInput") && (workingChat ?: id) == chat && workingThread == thread
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt
index 5054db9c..f01b1c40 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt
@@ -18,8 +18,11 @@ class AgentSettingsTest {
@Test fun `new bot defaults preserve host connectors and a nullable notification toggle turns off`() {
val draft = BotDraft(command = "stale custom command")
- assertTrue(draft.isValid)
+ assertFalse("an unnamed bot is only created, never saved", draft.isValid)
+ assertTrue(draft.copy(name = "Scout").isValid)
+ // Left unset, the host turns on every connector and skill.
assertEquals(JsonNull, draft.body()["connectors"])
+ assertEquals(JsonNull, draft.body()["skills"])
assertEquals(JsonNull, draft.body()["command"])
// An unset switch is left out: the host's booleans don't take null.
assertFalse("fastMode" in draft.body() || "notify" in draft.body())
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt
index ed97d373..f1e741a4 100644
--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt
@@ -301,10 +301,10 @@ class CardRows internal constructor() {
BasicTextField(text, onChange, modifier, enabled = enabled, singleLine = singleLine, minLines = minLines, maxLines = maxLines,
textStyle = style.copy(color = Palette.text), cursorBrush = SolidColor(Palette.accent), keyboardOptions = keyboard, keyboardActions = actions,
decorationBox = { field ->
- Box(contentAlignment = Alignment.CenterStart) {
- // A centered field centers its placeholder too.
- if (text.isEmpty()) Text(prompt, if (style.textAlign == TextAlign.Center) Modifier.fillMaxWidth() else Modifier, style = style,
- color = Palette.tertiary, maxLines = if (singleLine) 1 else Int.MAX_VALUE)
+ val centered = style.textAlign == TextAlign.Center
+ // A centered field spans its width, so its placeholder and empty cursor sit in the middle too.
+ Box(contentAlignment = Alignment.CenterStart, propagateMinConstraints = centered) {
+ if (text.isEmpty()) Text(prompt, style = style, color = Palette.tertiary, maxLines = if (singleLine) 1 else Int.MAX_VALUE)
field()
}
})
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index a8540d1d..a3737686 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -129,7 +129,7 @@ function menu() {
{ label: 'Smaller', accelerator: 'CmdOrCtrl+-', click: () => send({ kind: 'stepTextSize', up: false }, false) },
{ label: 'Actual Size', accelerator: 'CmdOrCtrl+0', click: () => send({ kind: 'stepTextSize', up: null }, false) },
{ type: 'separator' },
- { label: 'New Chat', accelerator: 'CmdOrCtrl+N', click: () => send({ kind: 'newChat' }) },
+ { label: 'New Bot', accelerator: 'CmdOrCtrl+N', click: () => send({ kind: 'newBot' }) },
{ label: 'Search Bots', accelerator: 'CmdOrCtrl+F', click: () => send({ kind: 'search' }) },
{ label: 'Toggle Sidebar', accelerator: 'Ctrl+CmdOrCtrl+S', click: () => send({ kind: 'toggleSidebar' }, false) },
{ label: 'Conversation Details', accelerator: 'Alt+CmdOrCtrl+I', click: () => send({ kind: 'toggleDetails' }, false) },
diff --git a/apps/desktop/src/main/island.ts b/apps/desktop/src/main/island.ts
index ec2d17a5..3720de1a 100644
--- a/apps/desktop/src/main/island.ts
+++ b/apps/desktop/src/main/island.ts
@@ -99,7 +99,7 @@ export class Island {
)
ipcMain.on('island:openBot', (_e, ref: string) => this.deps.send({ kind: 'openBot', ref }))
ipcMain.on('island:send', (_e, ref: string, text: string) => this.deps.send({ kind: 'sendMessage', ref, text }, false))
- ipcMain.on('island:newBot', () => this.deps.send({ kind: 'newChat' }))
+ ipcMain.on('island:newBot', () => this.deps.send({ kind: 'newBot' }))
ipcMain.on('island:openApp', () => this.deps.openApp())
ipcMain.on('island:focusable', (_e, on: boolean) => this.setFocusable(on))
ipcMain.on('island:keys', (_e, on: boolean) => this.setKeys(on))
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.ts
index 267adb2c..35308f6e 100644
--- a/apps/desktop/src/renderer/store/bot-mirror.ts
+++ b/apps/desktop/src/renderer/store/bot-mirror.ts
@@ -43,7 +43,7 @@ export class BotMirror extends Observable {
routineDrafts = new Map<string, string>()
readonly composerDrafts: ComposerDrafts
lastError: string | null = null
- /** A kit view selected a bot on this store (new chat, editor); the account picks it up. */
+ /** A kit view selected a bot on this store (new bot or group, editor); the account picks it up. */
selection: string | null = null
/** Permission cards whose answer is on its way, with the chosen option. */
answering = new Map<string, string>()
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 6b03f952..63ac3f30 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -1,9 +1,9 @@
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
import type { WindowCommand } from '@shared/ipc'
import { isSSHConnecting, showsChat as shouldShowChat } from '@shared/ssh-startup'
import { draftOf, type Bot, type BotDraft } from '@shared/models'
import { CharacterAvatar } from '../components/Avatar'
-import { Button, ChoicePicker, IconButton, ResizeHandle } from '../components/Controls'
+import { Button, IconButton, ResizeHandle } from '../components/Controls'
import { AnchoredMenu, Dialog, ModalHeader, Sheet, type MenuItem } from '../components/Overlay'
import { HStack, Spacer } from '../components/Stack'
import { Text } from '../components/Text'
@@ -12,7 +12,7 @@ import { prefs, stepTextSize, usePref, DEFAULT_TEXT_SIZE } from '../lib/prefs'
import { useApp, StoreContext } from '../store/context'
import { account } from '../store/account'
import { analytics } from '../store/analytics'
-import { refKey, sameRef, parseRef, type BotRef } from '../store/app-model'
+import { refKey, sameRef, parseRef } from '../store/app-model'
import type { BotStore } from '../store/bot-store'
import { useComputerRoster } from '../store/computer-roster'
import { BotRoster } from './BotRoster'
@@ -20,7 +20,7 @@ import { SidebarFooter } from './SidebarFooter'
import { UpdateBadge } from './UpdateButton'
import { ComputerFilterHeader, computerSelection } from './ComputerFilterHeader'
import { ThreadView } from './thread/ThreadView'
-import { NewChatView } from './bots/NewChatView'
+import { NewBotView, NewGroupView } from './bots/NewBotView'
import { BotEditorView } from './bots/BotEditorView'
import { MarketplaceView } from './marketplace/MarketplaceView'
import { SettingsView, type SettingsPage } from './settings/SettingsView'
@@ -163,6 +163,12 @@ interface EditTarget {
store: BotStore
}
+/** A new bot or group chat being made, and the computer it goes to. */
+interface CreateTarget {
+ kind: 'bot' | 'group'
+ computerId: string
+}
+
function ChatSplitView() {
const app = useApp()
const ssh = useSSH()
@@ -171,10 +177,7 @@ function ChatSplitView() {
const [sidebarWidth, setSidebarWidth] = usePref(prefs.sidebarWidth)
const [hidden, setHidden] = usePref(prefs.hiddenComputers)
const [searching, setSearching] = useState(false)
- const [composing, setComposing] = useState(false)
- const [composingGroup, setComposingGroup] = useState(false)
- const [composeComputer, setComposeComputer] = useState<string | null>(null)
- const previousSelection = useRef<BotRef | null>(null)
+ const [creating, setCreating] = useState<CreateTarget | null>(null)
const [newMenu, setNewMenu] = useState(false)
const [railNewMenu, setRailNewMenu] = useState(false)
const [contextBot, setContextBot] = useState<{ target: BotTarget; x: number; y: number } | null>(null)
@@ -205,29 +208,23 @@ function ChatSplitView() {
const shown = new Set(computerSelection(app.computers.map((c) => c.id), hidden).shown)
const onlineStores = stores.filter((s) => shown.has(s.computer.id) && s.connection.kind === 'online' && !s.mismatch)
const selectedStore = app.selectedStore
- const composeStore = composeComputer ? app.store(composeComputer) : null
+ const createStore = creating ? app.store(creating.computerId) : null
const roster = useComputerRoster(app, shown)
const visibleRoster = roster.items
- const compose = (group = false) => {
- setComposingGroup(group)
+ const create = (kind: CreateTarget['kind']) => {
// The selected bot's computer if it's online, else this computer, else any online one.
const target = [selectedStore, app.local].find((s) => s && onlineStores.includes(s)) ?? onlineStores[0]
- if (!target) return
- if (!composing) previousSelection.current = app.selection
- setComposeComputer(target.computer.id)
- app.select(null)
- setComposing(true)
+ if (target) setCreating({ kind, computerId: target.computer.id })
}
-
- useEffect(() => {
- if (app.selection) setComposing(false)
- }, [app.selection])
+ const computerChoice = creating && onlineStores.length > 1
+ ? { options: onlineStores.map((s) => ({ id: s.computer.id, label: s.hostName })), selection: creating.computerId, onChange: (computerId: string) => setCreating({ ...creating, computerId }) }
+ : null
useEffect(
() =>
window.codync.app.onCommand((c) => {
- if (c.kind === 'newChat' && onlineStores.length) compose()
+ if (c.kind === 'newBot' && onlineStores.length) create('bot')
if (c.kind === 'search') setSearching(true)
if (c.kind === 'toggleSidebar') setCompact(!prefs.sidebarCompact.get())
}),
@@ -238,10 +235,10 @@ function ChatSplitView() {
useEffect(() => {
const target = window.codync.debugOpen
if (!target || debugOpened.current) return
- if (target === 'compose' || target === 'group') {
+ if (target === 'newBot' || target === 'newGroup') {
if (!onlineStores.length) return
debugOpened.current = true
- compose(target === 'group')
+ create(target === 'newBot' ? 'bot' : 'group')
} else if (target === 'plugins') {
if (!app.local) return
debugOpened.current = true
@@ -258,8 +255,8 @@ function ChatSplitView() {
})
const newItems = (): MenuItem[] => [
- { title: 'New chat', icon: 'square.and.pencil', action: () => compose() },
- { title: 'New group chat', icon: 'person.2', action: () => compose(true) },
+ { title: 'New bot', icon: 'plus', action: () => create('bot') },
+ { title: 'New group chat', icon: 'person.2', action: () => create('group') },
]
const openMarketplace = () => setMarketplace((selectedStore ?? app.local ?? onlineStores[0])?.computer.id ?? null)
@@ -306,24 +303,7 @@ function ChatSplitView() {
const selectedBot = selected && selectedStore?.bots.get(selected.botId)
let detail: ReactNode
- if (composing && composeStore) {
- detail = (
- <div className="detail-column" key={`${composeStore.computer.id}-${composingGroup}`}>
- {onlineStores.length > 1 ? (
- <ComputerPicker stores={onlineStores} value={composeStore.computer.id} onChange={setComposeComputer} />
- ) : null}
- <StoreContext.Provider value={composeStore}>
- <NewChatView
- group={composingGroup}
- onClose={() => {
- setComposing(false)
- if (!app.selection) app.select(previousSelection.current)
- }}
- />
- </StoreContext.Provider>
- </div>
- )
- } else if (selected && selectedStore && selectedBot) {
+ if (selected && selectedStore && selectedBot) {
detail = (
<StoreContext.Provider value={selectedStore}>
<ThreadView key={refKey(selected)} botId={selected.botId} />
@@ -342,8 +322,8 @@ function ChatSplitView() {
</HStack>
<Text as="div" size="title2" weight="semibold">{connecting ? 'Connecting to your computers…' : 'Your coding agents, as teammates.'}</Text>
<Text as="div" tone="secondary" className="empty-detail-message">{connecting ? 'Your bots will appear once connected. Manage computers to see connection progress.' : 'Pick a bot, or create one for each kind of work and point it at a project.'}</Text>
- <Button onClick={() => compose()} disabled={!onlineStores.length}>
- New Bot
+ <Button onClick={() => create('bot')} disabled={!onlineStores.length}>
+ New bot
</Button>
</div>
)
@@ -374,7 +354,7 @@ function ChatSplitView() {
{visibleRoster.length === 0 && !roster.grouped && !compact && mismatchStores.length === 0 ? (
<div className="roster-empty">
<Text as="div" size="body" weight="medium">{onlineStores.length ? 'No bots yet' : 'Waiting for a computer'}</Text>
- {onlineStores.length ? <Text as="div" size="callout" tone="secondary">Use + to start a new chat.</Text> : null}
+ {onlineStores.length ? <Text as="div" size="callout" tone="secondary">Use + to create a bot.</Text> : null}
</div>
) : null}
</div>
@@ -432,6 +412,14 @@ function ChatSplitView() {
</StoreContext.Provider>
) : null}
</Sheet>
+ <Sheet open={creating !== null} onClose={() => setCreating(null)} maxHeight={sheetHeight}>
+ {creating && createStore ? (
+ <StoreContext.Provider value={createStore}>
+ {/* A group's bots belong to its computer: another computer starts it over. */}
+ {creating.kind === 'bot' ? <NewBotView computer={computerChoice} /> : <NewGroupView key={creating.computerId} computer={computerChoice} />}
+ </StoreContext.Provider>
+ ) : null}
+ </Sheet>
<Sheet open={marketplace !== null} onClose={() => setMarketplace(null)} width={Math.min(920, windowSize.width - 80)} height={sheetHeight} dismissOnDim>
{marketplace && app.store(marketplace) ? (
<StoreContext.Provider value={app.store(marketplace)!}>
@@ -460,14 +448,3 @@ function ChatSplitView() {
</div>
)
}
-
-/** Which computer a new chat goes to, when more than one is online. */
-function ComputerPicker({ stores, value, onChange }: { stores: BotStore[]; value: string; onChange: (id: string) => void }) {
- const options = useMemo(() => stores.map((s) => ({ id: s.computer.id, label: s.hostName })), [stores])
- return (
- <HStack gap={8} className="compose-computer">
- <Text tone="secondary">On</Text>
- <ChoicePicker selection={value} options={options} onChange={onChange} />
- </HStack>
- )
-}
diff --git a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
index b22a1f44..11c7f723 100644
--- a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
+++ b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
@@ -8,42 +8,32 @@ import { Icon } from '../../components/Icon'
import { ModalHeader, Sheet, SheetPage, useDismiss } from '../../components/Overlay'
import { HStack, IconSlot, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
-import { AVATAR_COLORS, AVATAR_SHAPES } from '../../lib/theme'
import { useStore } from '../../store/context'
import { useAgentModels } from './agent-models'
import { AgentModelPicker } from './AgentModelPicker'
-import { errorText, fillDefaults, isValid, lastPathComponent, normalized, usePlugins, type Plugins } from './drafts'
+import { errorText, isValid, lastPathComponent, normalized, usePlugins, type Plugins } from './drafts'
import { FormSheet } from '../marketplace/pieces'
import { SkillSheet, type SkillRef } from '../marketplace/SkillSheet'
-import { AnchoredPanel, AutoTextArea, Field, SwitchRow } from './parts'
+import { AnchoredPanel, AutoTextArea, AvatarPicker, Field, SwitchRow } from './parts'
import './bots.css'
-/** Create or edit a bot in a modal: the settings form plus Close / Save. */
+/** Edit a bot in a modal: the settings form plus Close / Save. New bots start in `NewBotView`. */
export function BotEditorView({ draft: initial }: { draft: BotDraft }) {
const store = useStore()
const dismiss = useDismiss()
const plugins = usePlugins(store)
- const isNew = !initial.id
- const [draft, setDraft] = useState(() => (isNew ? fillDefaults(store, initial, { connectors: [], skills: [] }) : initial))
+ const [draft, setDraft] = useState(initial)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const online = store.connection.kind === 'online'
- // A new bot's connectors and skills start on once the computer has listed them.
- useEffect(() => {
- if (isNew && plugins) setDraft((d) => fillDefaults(store, d, plugins))
- }, [isNew, plugins, store])
-
const save = () => {
if (!isValid(draft) || saving || !online) return
setSaving(true)
setError(null)
store
.save(normalized(draft))
- .then((bot) => {
- dismiss()
- if (isNew) store.setSelection(bot.id)
- })
+ .then(dismiss)
.catch((e: unknown) => setError(errorText(e)))
.finally(() => setSaving(false))
}
@@ -51,8 +41,8 @@ export function BotEditorView({ draft: initial }: { draft: BotDraft }) {
return (
<SheetPage>
<ModalHeader
- title={isNew ? 'New bot' : 'Settings'}
- trailing={saving ? <Spinner /> : <IconButton title={isNew ? 'Create' : 'Save'} icon="checkmark" disabled={!isValid(draft) || saving || !online} onClick={save} />}
+ title="Settings"
+ trailing={saving ? <Spinner /> : <IconButton title="Save" icon="checkmark" disabled={!isValid(draft) || saving || !online} onClick={save} />}
/>
<div className="bot-editor-body">
<BotSettingsForm draft={draft} onChange={setDraft} error={error} plugins={plugins} />
@@ -62,7 +52,7 @@ export function BotEditorView({ draft: initial }: { draft: BotDraft }) {
}
/**
- * Which settings a form shows: all of them (a new bot, the editor sheet), what changes often
+ * Which settings a form shows: all of them (the editor sheet), what changes often
* (instructions, model, fast mode: the inspector's Details tab) or the rest (its Settings tab).
*/
export type FormPart = 'all' | 'often' | 'rarely'
@@ -196,12 +186,9 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {
</div>
</AnchoredPanel>
</ValueRow>
- {/* A new bot is named from its first conversations (Grok Bot's flow); rename it any time after. */}
- {draft.id ? (
- <Field label="Name">
- <input className="field-box" value={draft.name} placeholder="Name" onChange={(e) => set('name', e.target.value)} />
- </Field>
- ) : null}
+ <Field label="Name">
+ <input className="field-box" value={draft.name} placeholder="Name" onChange={(e) => set('name', e.target.value)} />
+ </Field>
{part === 'all' ? instructions : null}
</CardSection>
@@ -339,27 +326,6 @@ function PluginToggles({ title, empty, items, selection, onChange, onInfo }: {
)
}
-function AvatarPicker({ shape, color, onShape, onColor }: { shape: string; color: string; onShape: (s: string) => void; onColor: (c: string) => void }) {
- return (
- <VStack gap={12}>
- <div className="swatch-row">
- {AVATAR_SHAPES.map((s) => (
- <button key={s} className={`swatch ${s === shape ? 'on' : ''}`} aria-label={`${s} shape`} aria-pressed={s === shape} onClick={() => onShape(s)}>
- <CharacterAvatar shape={s} color={color} size={36} />
- </button>
- ))}
- </div>
- <div className="swatch-row">
- {AVATAR_COLORS.map((c) => (
- <button key={c.id} className={`swatch ${c.id === color ? 'on' : ''}`} aria-label={c.label} aria-pressed={c.id === color} onClick={() => onColor(c.id)}>
- <span className="swatch-color" style={{ background: c.hex }} />
- </button>
- ))}
- </div>
- </VStack>
- )
-}
-
/** Browses folders on the host, drilling down in place. */
function FolderPicker({ start, onPick }: { start: string | null; onPick: (path: string) => void }) {
// The folders opened so far; the last one is shown.
diff --git a/apps/desktop/src/renderer/views/bots/GroupEditorView.tsx b/apps/desktop/src/renderer/views/bots/GroupEditorView.tsx
index 1baba55f..657c8b4f 100644
--- a/apps/desktop/src/renderer/views/bots/GroupEditorView.tsx
+++ b/apps/desktop/src/renderer/views/bots/GroupEditorView.tsx
@@ -12,20 +12,17 @@ import { AutoTextArea } from './parts'
import './bots.css'
/**
- * Create a group chat, or change its name, what it's for and who's in it. Bots are
- * picked like recipients: chips on top, a search, and the bots not in it yet.
+ * Change a group chat's name, what it's for and who's in it. Bots are added from a
+ * search of the ones not in it yet. New groups start in `NewGroupView`.
*/
-export function GroupEditorView({ group, members: initialMembers = [] }: { group: Bot | null; members?: string[] }) {
+export function GroupEditorView({ group }: { group: Bot }) {
const store = useStore()
const dismiss = useDismiss()
- // The group being edited; null creates one.
- const groupId = group?.id ?? null
- const [name, setName] = useState(group?.name ?? '')
- const [about, setAbout] = useState(group?.description ?? '')
- const [members, setMembers] = useState<string[]>(group?.members ?? initialMembers)
+ const [name, setName] = useState(group.name)
+ const [about, setAbout] = useState(group.description)
+ const [members, setMembers] = useState<string[]>(group.members)
const [query, setQuery] = useState('')
- // A new group starts in the picker; an existing one shows its members first.
- const [adding, setAdding] = useState(group === null && initialMembers.length === 0)
+ const [adding, setAdding] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [confirmDelete, setConfirmDelete] = useState<Bot | null>(null)
@@ -34,11 +31,10 @@ export function GroupEditorView({ group, members: initialMembers = [] }: { group
// Bots that can still join, filtered by the search.
const q = query.trim().toLowerCase()
const candidates = store.roster.filter((b) => !isGroup(b) && !members.includes(b.id) && (!q || b.name.toLowerCase().includes(q)))
- const isNew = groupId === null
const canSave = members.length > 0 && !saving
// "Alice, Bob" when no name is typed.
const defaultName = picked.length ? picked.map((b) => b.name).join(', ') : 'Name'
- const current = groupId ? store.bots.get(groupId) : undefined
+ const current = store.bots.get(group.id)
const toggle = (id: string) => {
setMembers((list) => (list.includes(id) ? list.filter((m) => m !== id) : [...list, id]))
@@ -48,21 +44,16 @@ export function GroupEditorView({ group, members: initialMembers = [] }: { group
const save = () => {
setSaving(true)
setError(null)
- const typed = name.trim()
- const finalName = typed || defaultName
- const description = about.trim()
- const done = groupId
- ? store.updateGroup({ id: groupId, kind: 'group', name: finalName, description, members, pinned: store.bots.get(groupId)?.pinned })
- : store.createGroup(finalName, description, members)
- void Promise.resolve(done)
- .then(() => dismiss())
+ store
+ .updateGroup({ id: group.id, kind: 'group', name: name.trim() || defaultName, description: about.trim(), members, pinned: current?.pinned })
+ .then(dismiss)
.catch((e: unknown) => setError(errorText(e)))
.finally(() => setSaving(false))
}
return (
<SheetPage>
- <ModalHeader icon="person.2" title={isNew ? 'New group chat' : 'Group chat'} trailing={saving ? <Spinner /> : <IconButton title={isNew ? 'Create' : 'Save'} icon="checkmark" disabled={!canSave} onClick={save} />} />
+ <ModalHeader icon="person.2" title="Group chat" trailing={saving ? <Spinner /> : <IconButton title="Save" icon="checkmark" disabled={!canSave} onClick={save} />} />
<div className="group-scroll">
<div className="group-form">
<div className="group-identity">
diff --git a/apps/desktop/src/renderer/views/bots/NewBotView.tsx b/apps/desktop/src/renderer/views/bots/NewBotView.tsx
new file mode 100644
index 00000000..3b7c6c35
--- /dev/null
+++ b/apps/desktop/src/renderer/views/bots/NewBotView.tsx
@@ -0,0 +1,162 @@
+import { useState, type ReactNode } from 'react'
+import { isGroup, type Bot } from '@shared/models'
+import { BotAvatar, CharacterAvatar, GroupAvatar } from '../../components/Avatar'
+import { Button, ChoicePicker, Spinner } from '../../components/Controls'
+import { ModalHeader, useDismiss } from '../../components/Overlay'
+import { HStack, Spacer, VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { useStore } from '../../store/context'
+import { errorText, fillDefaults, newDraft } from './drafts'
+import { AvatarPicker } from './parts'
+import './bots.css'
+
+/** Which computer a new bot or group goes to; shown when more than one is online. */
+export interface ComputerChoice {
+ options: { id: string; label: string }[]
+ selection: string
+ onChange: (id: string) => void
+}
+
+/**
+ * A new bot from its looks and an optional name (Grok Bot's "Create New Bot"); the rest starts on
+ * the defaults and changes in its Settings. Unnamed, the host names it after its first conversations.
+ */
+export function NewBotView({ computer }: { computer: ComputerChoice | null }) {
+ const store = useStore()
+ const [draft, setDraft] = useState(newDraft)
+
+ const create = async () => {
+ const bot = await store.save(fillDefaults(store, { ...draft, name: draft.name.trim() }))
+ store.setSelection(bot.id)
+ }
+
+ return (
+ <CreateLayout
+ title="New bot"
+ preview={<CharacterAvatar shape={draft.avatarShape} color={draft.avatarColor} size={96} />}
+ name={draft.name}
+ placeholder="Name your bot"
+ onName={(name) => setDraft((d) => ({ ...d, name }))}
+ canCreate
+ computer={computer}
+ create={create}
+ >
+ <AvatarPicker
+ shape={draft.avatarShape}
+ color={draft.avatarColor}
+ onShape={(avatarShape) => setDraft((d) => ({ ...d, avatarShape }))}
+ onColor={(avatarColor) => setDraft((d) => ({ ...d, avatarColor }))}
+ />
+ </CreateLayout>
+ )
+}
+
+/** A new group chat, laid out like a new bot: its face, an optional name, then the bots to put in it. */
+export function NewGroupView({ computer }: { computer: ComputerChoice | null }) {
+ const store = useStore()
+ const [name, setName] = useState('')
+ const [members, setMembers] = useState<string[]>([])
+ const bots = store.roster.filter((b) => !isGroup(b))
+ const picked = members.map((id) => store.bots.get(id)).filter((b): b is Bot => !!b)
+ // "Alice, Bob" when no name is typed.
+ const defaultName = picked.map((b) => b.name).join(', ')
+
+ const toggle = (id: string) => setMembers((list) => (list.includes(id) ? list.filter((m) => m !== id) : [...list, id]))
+ const create = async () => {
+ await store.createGroup(name.trim() || defaultName, '', members)
+ }
+
+ return (
+ <CreateLayout
+ title="New group chat"
+ preview={<GroupAvatar members={picked} size={96} />}
+ name={name}
+ placeholder={defaultName || 'Name your group'}
+ onName={setName}
+ canCreate={members.length > 0}
+ computer={computer}
+ create={create}
+ >
+ {bots.length ? (
+ <HStack wrap justify="center" align="flex-start" gap={4} className="create-members">
+ {bots.map((bot) => {
+ const on = members.includes(bot.id)
+ return (
+ <button key={bot.id} className="press create-member" aria-pressed={on} onClick={() => toggle(bot.id)}>
+ <span className={`swatch ${on ? 'on' : ''}`}>
+ <BotAvatar bot={bot} size={44} animated={false} />
+ </span>
+ <Text size="caption" tone={on ? 'text' : 'secondary'} truncate className="create-member-name">{bot.name}</Text>
+ </button>
+ )
+ })}
+ </HStack>
+ ) : (
+ <Text tone="secondary">No bots yet. Create a bot first.</Text>
+ )}
+ <Text as="div" size="caption" tone="tertiary">Everyone answers in turn unless you @mention someone.</Text>
+ </CreateLayout>
+ )
+}
+
+/** The create sheet both share: the face, a centered name field, the choices, then Cancel / Create. */
+function CreateLayout({ title, preview, name, placeholder, onName, canCreate, computer, create, children }: {
+ title: string
+ preview: ReactNode
+ name: string
+ placeholder: string
+ onName: (name: string) => void
+ canCreate: boolean
+ computer: ComputerChoice | null
+ create: () => Promise<void>
+ children: ReactNode
+}) {
+ const store = useStore()
+ const dismiss = useDismiss()
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const ready = canCreate && !saving && store.connection.kind === 'online'
+
+ const submit = () => {
+ if (!ready) return
+ setSaving(true)
+ setError(null)
+ create()
+ .then(dismiss)
+ .catch((e: unknown) => setError(errorText(e)))
+ .finally(() => setSaving(false))
+ }
+
+ return (
+ <VStack className="create-sheet">
+ <ModalHeader title={title} />
+ <VStack align="center" gap={20} className="create-body">
+ {preview}
+ <input
+ className="field-box create-name"
+ autoFocus
+ value={name}
+ placeholder={placeholder}
+ aria-label="Name"
+ onChange={(e) => onName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.nativeEvent.isComposing && e.keyCode !== 229) submit()
+ }}
+ />
+ {children}
+ {error ? <Text size="footnote" tone="danger" className="fade-in">{error}</Text> : null}
+ </VStack>
+ <HStack gap={8} className="create-footer">
+ {computer ? (
+ <HStack gap={8}>
+ <Text tone="secondary">On</Text>
+ <ChoicePicker selection={computer.selection} options={computer.options} onChange={computer.onChange} />
+ </HStack>
+ ) : null}
+ <Spacer />
+ <Button kind="secondary" onClick={dismiss}>Cancel</Button>
+ <Button onClick={submit} disabled={!ready}>{saving ? <Spinner /> : 'Create'}</Button>
+ </HStack>
+ </VStack>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/bots/NewChatView.tsx b/apps/desktop/src/renderer/views/bots/NewChatView.tsx
deleted file mode 100644
index 073aa053..00000000
--- a/apps/desktop/src/renderer/views/bots/NewChatView.tsx
+++ /dev/null
@@ -1,222 +0,0 @@
-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
-import { draftOf, isGroup, type Bot } from '@shared/models'
-import { BotAvatar, GroupAvatar } from '../../components/Avatar'
-import { Hairline, IconButton } from '../../components/Controls'
-import { Icon } from '../../components/Icon'
-import { SheetPage } from '../../components/Overlay'
-import { HStack, Spacer } from '../../components/Stack'
-import { Text } from '../../components/Text'
-import { useStore } from '../../store/context'
-import { createDefaultBot, errorText } from './drafts'
-import { AutoTextArea, BotChip } from './parts'
-import './bots.css'
-
-/**
- * Desktop "new message" page (Grok Bot's compose): a To: field that searches your
- * bots or creates a new one, with ⌘1…⌘9 shortcuts, and the message box underneath.
- * Picked bots become chips in the To: field; one opens its chat, several start a
- * group chat with them (or open the one they already share). Whatever you typed is sent.
- * `group` is "New group chat": the same page, but it only gathers bots and needs two.
- */
-export function NewChatView({ group, onClose }: { group: boolean; onClose: () => void }) {
- const store = useStore()
- const [query, setQuery] = useState('')
- const [draft, setDraft] = useState('')
- const [recipients, setRecipients] = useState<string[]>([])
- const [creating, setCreating] = useState(false)
- const toField = useRef<HTMLInputElement>(null)
- const chips = useRef<HTMLDivElement>(null)
-
- // Bots not picked yet; a group can only be opened on its own, so groups go once someone's picked.
- const q = query.trim().toLowerCase()
- const matches = store.roster.filter((b) => !recipients.includes(b.id) && !(isGroup(b) && (group || recipients.length > 0)) && (!q || b.name.toLowerCase().includes(q)))
- const picked = recipients.map((id) => store.bots.get(id)).filter((b): b is Bot => !!b)
-
- const toPrompt = group ? (recipients.length < 2 ? 'Add bots to the group' : 'Add another bot') : recipients.length ? 'Add another bot' : 'Search or create bots'
- const placeholder = group
- ? picked.length < 2
- ? 'Pick at least two bots'
- : 'Message the group'
- : picked.length === 0
- ? 'Message Bot'
- : `Message ${picked.map((b) => b.name).join(', ')}`
-
- useEffect(() => {
- toField.current?.focus()
- }, [])
-
- // The field stays in view as chips are added.
- useLayoutEffect(() => {
- const el = chips.current
- if (el) el.scrollTo({ left: el.scrollWidth, behavior: 'smooth' })
- }, [recipients])
-
- const open = (id: string) => {
- const text = draft.trim()
- store.setSelection(id)
- if (text) store.send(text, id)
- onClose()
- }
-
- // A bot becomes a chip; a group (with nobody picked) opens right away.
- const choose = (bot: Bot) => {
- if (isGroup(bot)) return open(bot.id)
- setRecipients((list) => [...list, bot.id])
- setQuery('')
- toField.current?.focus()
- }
-
- const remove = (id: string) => setRecipients((list) => list.filter((r) => r !== id))
-
- // One bot: its chat. Several: their group chat.
- const start = () => {
- if (recipients.length === 0) return
- if (recipients.length === 1) {
- if (!group) open(recipients[0]!)
- return
- }
- store
- .createGroup(picked.map((b) => b.name).join(', '), '', recipients)
- .then((g) => open(g.id))
- .catch((e: unknown) => store.setError(errorText(e)))
- }
-
- const create = () => {
- if (creating) return
- setCreating(true)
- const name = query.trim()
- const alone = recipients.length === 0 && !group
- void (async () => {
- try {
- let bot = await createDefaultBot(store)
- if (name) bot = await store.save({ ...draftOf(bot), name })
- if (alone) {
- open(bot.id)
- } else {
- // `createDefaultBot` selected it; stay here and add it to the others.
- store.setSelection(null)
- choose(bot)
- }
- } catch (e) {
- store.setError(errorText(e))
- }
- setCreating(false)
- })()
- }
-
- // Return in To: picks the top match, or with the field empty, starts the chat.
- const submitTo = () => {
- if (q) {
- if (matches[0]) choose(matches[0])
- else create()
- } else {
- start()
- }
- }
-
- // ⌘1 creates, ⌘2…⌘9 pick the matches; Escape closes.
- const keys = useRef({ create, choose, matches, onClose })
- keys.current = { create, choose, matches, onClose }
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- e.preventDefault()
- keys.current.onClose()
- return
- }
- if (!e.metaKey || e.shiftKey || e.altKey || e.ctrlKey) return
- const n = Number(e.key)
- if (!Number.isInteger(n) || n < 1 || n > 9) return
- e.preventDefault()
- if (n === 1) keys.current.create()
- else {
- const bot = keys.current.matches[n - 2]
- if (bot) keys.current.choose(bot)
- }
- }
- window.addEventListener('keydown', onKey)
- return () => window.removeEventListener('keydown', onKey)
- }, [])
-
- return (
- <SheetPage>
- <HStack gap={8} className="drag compose-to">
- <Text tone="secondary" className="compose-to-label">To:</Text>
- <div ref={chips} className="chip-row no-drag">
- {picked.map((bot) => (
- <BotChip key={bot.id} bot={bot} onRemove={() => remove(bot.id)} />
- ))}
- <input
- ref={toField}
- value={query}
- placeholder={toPrompt}
- className="compose-to-input"
- onChange={(e) => setQuery(e.target.value)}
- onKeyDown={(e) => {
- if (e.nativeEvent.isComposing || e.keyCode === 229) return
- if (e.key === 'Enter') {
- e.preventDefault()
- submitTo()
- } else if (e.key === 'Backspace' && !query && recipients.length) {
- // Backspace in an empty field takes the last chip back out.
- e.preventDefault()
- remove(recipients[recipients.length - 1]!)
- }
- }}
- />
- </div>
- <IconButton title="Close" icon="xmark" className="no-drag" onClick={onClose} />
- </HStack>
- <Hairline />
-
- <div className="compose-list">
- <PickRow shortcut={1} onClick={create} icon={
- <span className="compose-create-icon">
- <Icon key={creating ? 'hourglass' : 'plus'} name={creating ? 'hourglass' : 'plus'} size={13} weight="medium" className="fade-in" />
- </span>
- }>
- {query ? `Create “${query}”` : 'Create new Bot'}
- </PickRow>
- {matches.map((bot, i) => (
- <PickRow key={bot.id} shortcut={i + 2 <= 9 ? i + 2 : null} onClick={() => choose(bot)} icon={isGroup(bot) ? <GroupAvatar members={store.members(bot)} size={26} animated={false} /> : <BotAvatar bot={bot} size={26} animated={false} />}>
- {bot.name}
- </PickRow>
- ))}
- </div>
-
- <Spacer />
-
- <div className="compose-box">
- <AutoTextArea
- value={draft}
- onChange={setDraft}
- placeholder={placeholder}
- minRows={1}
- maxRows={6}
- onKeyDown={(e) => {
- // Return sends, Shift-Return adds a line; an input method's Return picks its candidate.
- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) {
- e.preventDefault()
- start()
- }
- }}
- />
- </div>
- </SheetPage>
- )
-}
-
-function PickRow({ shortcut, onClick, icon, children }: { shortcut: number | null; onClick: () => void; icon: ReactNode; children: ReactNode }) {
- return (
- <button className="press pick-row hover fade-in" onClick={onClick}>
- {icon}
- <Text tone="text" truncate grow>{children}</Text>
- {shortcut !== null ? (
- <HStack as="span" align="stretch" gap={3}>
- <span className="key-cap">⌘</span>
- <span className="key-cap">{shortcut}</span>
- </HStack>
- ) : null}
- </button>
- )
-}
diff --git a/apps/desktop/src/renderer/views/bots/bots.css b/apps/desktop/src/renderer/views/bots/bots.css
index 4cc800f2..1fa2b88b 100644
--- a/apps/desktop/src/renderer/views/bots/bots.css
+++ b/apps/desktop/src/renderer/views/bots/bots.css
@@ -122,9 +122,12 @@ textarea.field-box {
border-radius: var(--radius-s);
}
.avatar-picker-panel {
- width: 300px;
padding: 14px;
}
+/* Five shapes and six colors to a row, like the new bot sheet. */
+.avatar-picker {
+ width: 272px;
+}
/* A selectable avatar shape or color, ringed when chosen. */
.swatch {
@@ -140,9 +143,9 @@ textarea.field-box {
}
.swatch-row {
display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
gap: 10px;
- padding: 4px;
- overflow-x: auto;
}
.swatch-color {
display: block;
@@ -151,120 +154,39 @@ textarea.field-box {
border-radius: 50%;
}
-/* A picked bot: To: field and group editor. */
-.bot-chip {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- padding: 5px 6px 5px 8px;
- background: var(--bubble-agent);
- border-radius: var(--radius-pill);
- flex: none;
- animation: chip-in var(--layout) both;
+/* New bot and new group chat (NewBotView): the face, a centered name, the choices, then the buttons. */
+.create-sheet {
+ width: 400px;
}
-.bot-chip-name {
- max-width: 220px;
-}
-.bot-chip-remove {
- display: grid;
- place-items: center;
- width: 18px;
- height: 18px;
-}
-@keyframes chip-in {
- from {
- opacity: 0;
- transform: scale(0.85);
- }
-}
-.chip-row {
- display: flex;
- flex: 1;
- align-items: center;
- gap: 6px;
- overflow-x: auto;
- min-width: 0;
-}
-
-/* Rows in the new message list and the group editor. */
-.pick-row {
- display: flex;
- align-items: center;
- gap: 12px;
- width: 100%;
- padding: 8px 12px;
- border-radius: var(--radius-m);
- transition: background-color var(--hover), transform var(--press);
-}
-.pick-row.hover:hover {
- background: var(--bubble-agent);
-}
-.key-cap {
- min-width: 18px;
- min-height: 18px;
- display: grid;
- place-items: center;
- border-radius: var(--radius-xs);
- background: var(--background);
- color: var(--secondary);
- font-family: var(--mono);
- font-size: var(--text-caption);
+.create-body {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 4px 24px 20px;
}
-
-/* The new message page's To: row (NewChatView). */
-.compose-to {
- padding: 12px 22px;
+.create-name.field-box {
+ background: var(--field);
+ text-align: center;
font-size: var(--text-title3);
- font-weight: 400;
+ padding: 10px 12px;
}
-.compose-to-label {
- flex: none;
-}
-.compose-to-input {
- flex: 1;
- min-width: 200px;
- color: var(--text);
- user-select: text;
-}
-.compose-create-icon {
- display: grid;
- place-items: center;
- width: 26px;
- height: 26px;
- border-radius: 50%;
- background: var(--bubble-agent);
+.create-members {
+ width: 100%;
}
-
-.compose-list {
- max-height: 460px;
- overflow-y: auto;
- background: var(--surface);
- border-radius: var(--radius-l);
- box-shadow: var(--shadow-m);
- max-width: 620px;
- margin: 10px 22px 0;
- padding: 8px;
+.create-member {
display: flex;
flex-direction: column;
- gap: 2px;
+ align-items: center;
+ gap: 4px;
+ width: 68px;
+ padding: 2px 0;
+ transition: transform var(--press);
}
-.compose-box {
- display: flex;
- align-items: flex-end;
- margin: 16px;
- padding: 6px 6px 6px 18px;
- background: var(--bubble-user);
- border-radius: var(--radius-xl);
- box-shadow: var(--shadow-s);
+.create-member-name {
+ max-width: 100%;
}
-.compose-box textarea {
- flex: 1;
- min-width: 0;
- font-size: var(--conversation);
- line-height: calc(round(up, calc(var(--conversation) * 1.25), 1px));
- padding: 11px 0;
- user-select: text;
- cursor: text;
+.create-footer {
+ padding: 12px 20px 20px;
}
/* Folder levels slide in from the side they were opened toward. */
diff --git a/apps/desktop/src/renderer/views/bots/drafts.ts b/apps/desktop/src/renderer/views/bots/drafts.ts
index eb2deb13..89e83d2d 100644
--- a/apps/desktop/src/renderer/views/bots/drafts.ts
+++ b/apps/desktop/src/renderer/views/bots/drafts.ts
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'
-import type { Bot, BotDraft } from '@shared/models'
+import type { BotDraft } from '@shared/models'
import { AVATAR_COLORS, AVATAR_SHAPES } from '../../lib/theme'
import type { BotStore } from '../../store/bot-store'
@@ -32,29 +32,27 @@ export function newDraft(): BotDraft {
return { name: '', description: '', avatarColor: pick(AVATAR_COLORS).id, avatarShape: pick(AVATAR_SHAPES), backend: 'claude', cwd: '', permission: 'auto' }
}
-/** A new bot may go without a name: the host names it after its first conversations. */
-export const isValid = (d: BotDraft) => !d.id ||d.name.trim() !== ''
+/** A saved bot keeps a name; only a new one may go without (the host names it after its first conversations). */
+export const isValid = (d: BotDraft) => d.name.trim() !== ''
/** What the host should get: no stale command unless the agent is custom. */
export const normalized = (d: BotDraft): BotDraft => (d.backend === 'custom' ? d : { ...d, command: null })
/**
* Picks an installed agent we know (a registry agent nobody chose is never the default);
- * empty cwd requests a personal workspace from the host.
+ * empty cwd requests a personal workspace from the host. Connectors and skills stay unset:
+ * the host turns on every one it can run.
*/
-export function fillDefaults(store: BotStore, draft: BotDraft, plugins: Plugins): BotDraft {
+export function fillDefaults(store: BotStore, draft: BotDraft): BotDraft {
const next = { ...draft }
const backends = store.hello?.backends ?? []
const first = backends.find((b) => b.available && b.curated === true)
if (backends.find((b) => b.id === next.backend)?.available !== true && first) next.backend = first.id
- // Connectors and skills start on; left unset, the host turns on every one.
- if (next.connectors === undefined && plugins.connectors.length) next.connectors = plugins.connectors.map((c) => c.id)
- if (next.skills === undefined && plugins.skills.length) next.skills = plugins.skills.map((s) => s.id)
return next
}
/** The connectors and skills installed on the computer (kit `refreshPlugins`). */
-export async function loadPlugins(store: BotStore): Promise<Plugins> {
+async function loadPlugins(store: BotStore): Promise<Plugins> {
const client = store.client
if (!client) return { connectors: [], skills: [] }
const [c, s] = await Promise.allSettled([
@@ -77,13 +75,6 @@ export function usePlugins(store: BotStore): Plugins | null {
return plugins
}
-/** Creates an unnamed bot with sensible defaults and opens it (desktop compose flow). */
-export async function createDefaultBot(store: BotStore): Promise<Bot> {
- const bot = await store.save(fillDefaults(store, newDraft(), await loadPlugins(store)))
- store.setSelection(bot.id)
- return bot
-}
-
export const lastPathComponent = (path: string) => path.split('/').filter(Boolean).pop() ?? path
export const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e))
diff --git a/apps/desktop/src/renderer/views/bots/parts.tsx b/apps/desktop/src/renderer/views/bots/parts.tsx
index ff4d19a0..eb14f0c1 100644
--- a/apps/desktop/src/renderer/views/bots/parts.tsx
+++ b/apps/desktop/src/renderer/views/bots/parts.tsx
@@ -1,12 +1,10 @@
import { useId, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
-import type { Bot } from '@shared/models'
-import { BotAvatar } from '../../components/Avatar'
+import { CharacterAvatar } from '../../components/Avatar'
import { RowLabel, Switch } from '../../components/Controls'
-import { Icon } from '../../components/Icon'
import { anchorPlacement, useEscape, usePresence } from '../../components/Overlay'
import { VStack } from '../../components/Stack'
-import { Text } from '../../components/Text'
+import { AVATAR_COLORS, AVATAR_SHAPES } from '../../lib/theme'
import './bots.css'
/** A labeled input inside a section row: label (and an optional note) over the field, which they name. */
@@ -52,16 +50,25 @@ export function AutoTextArea({ value, onChange, placeholder, minRows, maxRows, c
return <textarea ref={ref} rows={minRows} className={className} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} onKeyDown={onKeyDown} />
}
-/** A picked bot (To: field, group editor); its x takes it back out. */
-export function BotChip({ bot, onRemove }: { bot: Bot; onRemove: () => void }) {
+/** The avatar's shape and color: each a wrapping, centered row of choices, ringed when picked. */
+export function AvatarPicker({ shape, color, onShape, onColor }: { shape: string; color: string; onShape: (s: string) => void; onColor: (c: string) => void }) {
return (
- <span className="bot-chip">
- <BotAvatar bot={bot} size={20} animated={false} />
- <Text size="body" tone="text" truncate className="bot-chip-name">{bot.name}</Text>
- <button className="bot-chip-remove" aria-label={`Remove ${bot.name}`} title={`Remove ${bot.name}`} onClick={onRemove}>
- <Icon name="xmark" size={10} weight="semibold" color="var(--secondary)" />
- </button>
- </span>
+ <VStack gap={12} className="avatar-picker">
+ <div className="swatch-row">
+ {AVATAR_SHAPES.map((s) => (
+ <button key={s} className={`swatch ${s === shape ? 'on' : ''}`} aria-label={`${s} shape`} aria-pressed={s === shape} onClick={() => onShape(s)}>
+ <CharacterAvatar shape={s} color={color} size={36} />
+ </button>
+ ))}
+ </div>
+ <div className="swatch-row">
+ {AVATAR_COLORS.map((c) => (
+ <button key={c.id} className={`swatch ${c.id === color ? 'on' : ''}`} aria-label={c.label} aria-pressed={c.id === color} onClick={() => onColor(c.id)}>
+ <span className="swatch-color" style={{ background: c.hex }} />
+ </button>
+ ))}
+ </div>
+ </VStack>
)
}
diff --git a/apps/desktop/src/renderer/views/chat-window.css b/apps/desktop/src/renderer/views/chat-window.css
index e35cff67..1927d36b 100644
--- a/apps/desktop/src/renderer/views/chat-window.css
+++ b/apps/desktop/src/renderer/views/chat-window.css
@@ -288,17 +288,6 @@ html[data-platform="darwin"] .sidebar-header {
position: relative;
overflow: hidden;
}
-.detail-column {
- display: flex;
- flex-direction: column;
- height: 100%;
-}
-/* Which computer a new chat goes to (ComputerPicker). */
-.compose-computer {
- padding: 12px 22px 0;
- font-size: var(--text-callout);
- font-weight: 400;
-}
/* The title bar strip of detail views that draw no top chrome of their own, so the window
still moves from there. */
.detail-drag {
diff --git a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
index feceda3c..3053ba2e 100644
--- a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
@@ -74,7 +74,7 @@ export function NodeNotice({ onAdd }: { onAdd: () => void }) {
* Getting an agent ready on the computer: install it, add Node.js when it runs on Node and
* the computer has none, then sign in. Sign-in
* options come from the agent itself (ACP), plus Codync's own command for
- * CLIs it knows. Bots are made from New chat, not here.
+ * CLIs it knows. Bots are made from New bot, not here.
*/
/** `recheck`: opened from a chat's sign-in request, whose agent refused a turn, so the agent is
* asked again however signed in it looked. */
diff --git a/apps/desktop/src/renderer/views/search-palette.css b/apps/desktop/src/renderer/views/search-palette.css
index fe7ac454..65d1a96b 100644
--- a/apps/desktop/src/renderer/views/search-palette.css
+++ b/apps/desktop/src/renderer/views/search-palette.css
@@ -41,6 +41,18 @@
.palette-row.active {
background: var(--bubble-user);
}
+/* A row's shortcut key. */
+.key-cap {
+ min-width: 18px;
+ min-height: 18px;
+ display: grid;
+ place-items: center;
+ border-radius: var(--radius-xs);
+ background: var(--background);
+ color: var(--secondary);
+ font-family: var(--mono);
+ font-size: var(--text-caption);
+}
.palette-key {
flex: none;
font-family: inherit;
diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsx
index 524d365b..5eaa4651 100644
--- a/apps/desktop/src/renderer/views/thread/Composer.tsx
+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx
@@ -1,5 +1,6 @@
import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
import { isBelow } from '@shared/compat'
+import { groupFastMode } from '@shared/fast-mode'
import { isGroup, isWorkingIn, type Bot } from '@shared/models'
import { BotAvatar } from '../../components/Avatar'
import { Icon } from '../../components/Icon'
@@ -14,13 +15,13 @@ import { composerEnter } from './composer-keyboard'
import { CommandMenu, useCommandMenu } from './CommandMenu'
import { ComposerAttachment } from './ComposerAttachment'
import { useDictation } from './dictation'
-import { builtInCommand, SKILLS_HOST, slashCommands, slashQuery, type SlashCommand } from './slash-commands'
+import { builtInCommand, GROUP_SKILLS_HOST, SKILLS_HOST, slashCommands, slashQuery, type SlashCommand } from './slash-commands'
type Trailing = 'interrupt' | 'stop' | 'call' | 'send'
/**
* The message box under a chat or a thread: send, or stop while the bot (or the group) is
- * working there. In a group, typing `@` suggests its bots; with one bot, a leading `/` lists its commands.
+ * working there. A leading `/` lists the commands (a group's are its bots'); in a group, typing `@` suggests its bots.
*/
export function Composer({ botId, thread = null, onCall, onInterrupt }: {
botId: string
@@ -57,7 +58,9 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
const canSend = !empty && (store.connection.kind === 'online' || (store.canQueue && !files.length))
const canAttach = !!bot
- const placeholder = thread ? 'Reply…' : bot && isGroup(bot) ? 'Message everyone · @ to ask one bot' : working ? `Queue a message for ${bot?.name ?? ''}` : `Ask ${bot?.name ?? ''}`
+ const members = bot && isGroup(bot) ? store.members(bot) : []
+
+ const placeholder = thread ? 'Reply…' : bot && isGroup(bot) ? 'Ask everyone · @ to ask one bot' : working ? `Queue a message for ${bot?.name ?? ''}` : `Ask ${bot?.name ?? ''}`
// A routine's "Try it" fills the box.
const routineDraft = store.routineDrafts.get(botId)
@@ -98,7 +101,7 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
return /\n/.test(query) || query.length > 24 ? null : query
})()
const suggestions: Bot[] =
- mentionQuery !== null && bot ? store.members(bot).filter((m) => !mentionQuery || m.name.toLowerCase().includes(mentionQuery.toLowerCase())) : []
+ mentionQuery !== null ? members.filter((m) => !mentionQuery || m.name.toLowerCase().includes(mentionQuery.toLowerCase())) : []
const mention = (member: Bot) => {
const at = draft.lastIndexOf('@')
@@ -107,16 +110,21 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
field.current?.focus()
}
- // Not in a group: each member has its own skills.
- const skillsShown = !!bot && !isGroup(bot) && !isBelow(store.hello?.version ?? '', SKILLS_HOST)
+ const skillsShown = !!bot && !isBelow(store.hello?.version ?? '', isGroup(bot) ? GROUP_SKILLS_HOST : SKILLS_HOST)
const slash = slashQuery(draft)
- const commands = slash === null ? [] : slashCommands(bot, slash, skillsShown ? plugins.installedSkills : [])
+ const commands = slash === null ? [] : slashCommands(bot, slash, skillsShown ? plugins.installedSkills : [], members)
const run = (command: SlashCommand) => {
if (!bot) return
switch (command.action.kind) {
case 'fast':
- store.setFastMode(bot, !bot.fastMode)
+ if (isGroup(bot)) {
+ // Each member's own Fast mode: all on, or all back off.
+ const fast = groupFastMode(members)
+ for (const m of fast?.members ?? []) store.setFastMode(m, fast?.state === 'off')
+ } else {
+ store.setFastMode(bot, !bot.fastMode)
+ }
setDraft('')
break
case 'skill':
@@ -141,7 +149,7 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
}
const submit = () => {
- const command = files.length ? null : builtInCommand(bot, draft)
+ const command = files.length ? null : builtInCommand(bot, draft, members)
if (command) return run(command)
if (!canSend) return
store.send(draft, botId, thread, files, undefined, pasted.current)
diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
index c754368a..11928020 100644
--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx
+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
@@ -214,7 +214,7 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })
{templateDraft ? <BotTemplateView draft={templateDraft} /> : null}
</Sheet>
<Sheet open={editingGroup} onClose={() => setEditingGroup(false)} width={420} height={560}>
- <GroupEditorView group={bot} />
+ {bot ? <GroupEditorView group={bot} /> : null}
</Sheet>
</div>
)
diff --git a/apps/desktop/src/renderer/views/thread/slash-commands.test.ts b/apps/desktop/src/renderer/views/thread/slash-commands.test.ts
index ca7c522c..323107ea 100644
--- a/apps/desktop/src/renderer/views/thread/slash-commands.test.ts
+++ b/apps/desktop/src/renderer/views/thread/slash-commands.test.ts
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
+import { groupFastMode } from '../../../shared/fast-mode.ts'
import { normalizeBot } from '../../../shared/models.ts'
import { builtInCommand, returnRuns, slashCommands, slashQuery } from './slash-commands.ts'
@@ -24,7 +25,26 @@ test('built-in commands come first, then only the bot\'s own skills, by name or
assert.deepEqual(slashCommands(normalizeBot({ id: 'b', skills: ['pdf'] }), 'xl', installed), [])
assert.deepEqual(slashCommands(normalizeBot({ id: 'b' }), '', []).map((c) => c.name), ['fast'], 'offered until the agent says otherwise')
assert.deepEqual(slashCommands(normalizeBot({ id: 'b', fastModeSupport: 'unsupported' }), '', []), [], 'no Fast mode on offer')
- assert.deepEqual(slashCommands(normalizeBot({ id: 'g', kind: 'group', fastModeSupport: 'offered' }), '', installed), [])
+})
+
+test('a group lists its bots\' commands: Fast mode for all of them, then every skill one of them has', () => {
+ const group = normalizeBot({ id: 'g', kind: 'group', members: ['a', 'b'] })
+ const a = normalizeBot({ id: 'a', name: 'Ada', skills: ['pdf'], fastModeSupport: 'offered' })
+ const b = normalizeBot({ id: 'b', name: 'Bo', skills: ['pdf', 'xlsx'], fastModeSupport: 'unsupported' })
+ assert.deepEqual(slashCommands(group, '', installed, [a, b]).map((c) => c.name), ['fast', 'pdf', 'xlsx'])
+ assert.deepEqual(slashCommands(group, '', installed, [b]).map((c) => c.name), ['pdf', 'xlsx'], 'no bot here has Fast mode')
+ assert.equal(builtInCommand(group, '/fast', [a, b])?.action.kind, 'fast')
+ assert.equal(builtInCommand(group, '/fast', [b]), null)
+
+ const both = [a, normalizeBot({ ...b, fastModeSupport: 'offered' })]
+ assert.equal(groupFastMode(both)?.state, 'off')
+ assert.equal(groupFastMode([{ ...a, fastMode: true }, both[1]!])?.state, 'off', 'on once every bot has it on')
+ const on = both.map((m) => ({ ...m, fastMode: true }))
+ assert.equal(groupFastMode(on)?.state, 'on')
+ const refused = groupFastMode([on[0]!, { ...on[1]!, fastModeSupport: 'refused', fastModeIssue: 'quota' }])
+ assert.equal(refused?.state, 'refused')
+ assert.match(refused?.detail ?? '', /^Bo: The agent turned it off: quota/)
+ assert.deepEqual(groupFastMode([a, b])?.members.map((m) => m.id), ['a'], 'only the bots that have it')
})
test('sending just a built-in command runs it; anything else is a message', () => {
diff --git a/apps/desktop/src/renderer/views/thread/slash-commands.ts b/apps/desktop/src/renderer/views/thread/slash-commands.ts
index 028c7686..7f77bc9a 100644
--- a/apps/desktop/src/renderer/views/thread/slash-commands.ts
+++ b/apps/desktop/src/renderer/views/thread/slash-commands.ts
@@ -1,11 +1,14 @@
// The composer's `/` commands, listed while the draft is just `/partial`: Fast mode runs here
// through the host's `updateBot` (a new session is in the bot's menu); a skill fills in `/<id> `, and the host turns that message into "read this skill first"
-// (host/src/market/skills.rs `expand_command`). docs/features/marketplace.md, "Commands".
-import { fastModeDetail, fastModeShown, fastModeState } from '../../../shared/fast-mode.ts'
+// (host/src/market/skills.rs `expand_command`). A group lists its members' commands: Fast mode
+// for all of them, and every skill one of them has. docs/features/marketplace.md, "Commands".
+import { fastModeDetail, fastModeShown, fastModeState, groupFastMode, type FastModeState } from '../../../shared/fast-mode.ts'
import type { Bot } from '../../../shared/models.ts'
/** The first host with `/skill` messages and skill details; older ones get the text as typed. */
export const SKILLS_HOST = '2.14.1'
+/** The first host that runs `/skill` in a group's prompts (host/src/chat/group.rs `line`). */
+export const GROUP_SKILLS_HOST = '2.20.1'
export type SlashAction = { kind: 'fast' } | { kind: 'skill'; id: string }
@@ -24,28 +27,35 @@ export function slashQuery(draft: string): string | null {
return /^\/\S*$/.test(draft) ? draft.slice(1) : null
}
-/** The bot's built-in commands; a group has none (each member has its own agent). */
-function builtIn(bot: Bot): SlashCommand[] {
- if (bot.kind === 'group') return []
- return fastModeShown(bot)
- ? [{ name: 'fast', icon: 'bolt', title: 'Fast mode', detail: fastModeDetail(bot), warning: fastModeState(bot) === 'refused', action: { kind: 'fast' } }]
- : []
+/** The bot's built-in commands; a group's Fast mode is its members' (`groupFastMode`). */
+function builtIn(bot: Bot, members: Bot[]): SlashCommand[] {
+ const fast = bot.kind === 'group' ? groupFastMode(members) : ownFastMode(bot)
+ return fast ? [{ name: 'fast', icon: 'bolt', title: 'Fast mode', detail: fast.detail, warning: fast.state === 'refused', action: { kind: 'fast' } }] : []
}
-/** Built-in commands, then the bot's skills (ids in `bot.skills`), whose name or title holds `query`. */
-export function slashCommands(bot: Bot | null, query: string, installedSkills: { id: string; name: string; description: string }[]): SlashCommand[] {
- if (!bot || bot.kind === 'group') return []
+/** A bot's own Fast mode, while it shows it. */
+function ownFastMode(bot: Bot): { state: FastModeState; detail: string } | null {
+ return fastModeShown(bot) ? { state: fastModeState(bot), detail: fastModeDetail(bot) } : null
+}
+
+/**
+ * Built-in commands, then the bot's skills (ids in `bot.skills`; a group's `members` have them),
+ * whose name or title holds `query`.
+ */
+export function slashCommands(bot: Bot | null, query: string, installedSkills: { id: string; name: string; description: string }[], members: Bot[] = []): SlashCommand[] {
+ if (!bot) return []
+ const enabled = bot.kind === 'group' ? members.flatMap((m) => m.skills) : bot.skills
const skills = installedSkills
- .filter((s) => bot.skills.includes(s.id))
+ .filter((s) => enabled.includes(s.id))
.map((s): SlashCommand => ({ name: s.id, icon: 'book.pages', title: s.name, detail: s.description, warning: false, action: { kind: 'skill', id: s.id } }))
const q = query.toLowerCase()
- return [...builtIn(bot), ...skills].filter((c) => c.name.includes(q) || c.title.toLowerCase().includes(q))
+ return [...builtIn(bot, members), ...skills].filter((c) => c.name.includes(q) || c.title.toLowerCase().includes(q))
}
/** A draft that is just a built-in command (`/fast`): sending it runs the command. */
-export function builtInCommand(bot: Bot | null, draft: string): SlashCommand | null {
+export function builtInCommand(bot: Bot | null, draft: string, members: Bot[] = []): SlashCommand | null {
const name = slashQuery(draft.trim())
- return bot && name !== null ? (builtIn(bot).find((c) => c.name === name) ?? null) : null
+ return bot && name !== null ? (builtIn(bot, members).find((c) => c.name === name) ?? null) : null
}
/**
diff --git a/apps/desktop/src/shared/fast-mode.ts b/apps/desktop/src/shared/fast-mode.ts
index 7917cae7..310847a9 100644
--- a/apps/desktop/src/shared/fast-mode.ts
+++ b/apps/desktop/src/shared/fast-mode.ts
@@ -24,6 +24,19 @@ export function fastModeRefusal(bot: Bot): string | null {
return `The agent turned it off: ${bot.fastModeIssue ?? 'not available'}. Switch it off and on to try again.`
}
+/**
+ * A group's `/fast`: its members that show Fast mode, on once all of them have it on. Picking it
+ * sets each one's own Fast mode, so it follows them into their own chats.
+ */
+export function groupFastMode(members: Bot[]): { members: Bot[]; state: FastModeState; detail: string } | null {
+ const shown = members.filter(fastModeShown)
+ if (!shown.length) return null
+ if (!shown.every((m) => m.fastMode)) return { members: shown, state: 'off', detail: 'Turn on for every bot here: faster replies and more usage' }
+ const refused = shown.find((m) => fastModeState(m) === 'refused')
+ if (refused) return { members: shown, state: 'refused', detail: `${refused.name}: ${fastModeRefusal(refused)}` }
+ return { members: shown, state: 'on', detail: 'Turn off for every bot here and return to standard speed' }
+}
+
/** What picking `/fast` in the composer's command list does, or why it isn't in effect. */
export function fastModeDetail(bot: Bot): string {
switch (fastModeState(bot)) {
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index 5aa625e3..282a260e 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -64,7 +64,7 @@ export type WindowCommand =
| { kind: 'setUsageIconStyle'; style: 'character' | 'original' }
| { kind: 'setRemoteScreen'; on: boolean }
| { kind: 'computerAccess' }
- | { kind: 'newChat' }
+ | { kind: 'newBot' }
| { kind: 'search' }
| { kind: 'toggleSidebar' }
| { kind: 'toggleDetails' }
@@ -119,7 +119,7 @@ export interface CodyncBridge {
computerName: string
/** This launch was started by the login item (Open at login). */
openedAtLogin: boolean
- /** Screenshot/UI checks: CODYNC_DEBUG_OPEN=compose | group | plugins | computers | <bot name>. */
+ /** Screenshot/UI checks: CODYNC_DEBUG_OPEN=newBot | newGroup | plugins | computers | <bot name>. */
debugOpen: string | null
host: {
snapshot(): Promise<HostSnapshot>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift
index e3fd15ab..97967c76 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift
@@ -31,3 +31,25 @@ public extension Bot {
}
}
}
+
+/// A group's `/fast`: the members that show Fast mode, switched together. Each member's own
+/// setting, so it holds in their own chats too.
+public struct GroupFastMode: Sendable {
+ public let members: [Bot]
+
+ public init(_ members: [Bot]) { self.members = members.filter(\.fastModeShown) }
+
+ /// On once every member that shows it has it on; refused when one of their agents turned it off.
+ public var state: Bot.FastModeState {
+ guard !members.isEmpty, members.allSatisfy(\.fastMode) else { return .off }
+ return members.contains { $0.fastModeState == .refused } ? .refused : .on
+ }
+
+ public var detail: String {
+ switch state {
+ case .off: "Turn on for every bot here: faster replies and more usage"
+ case .on: "Turn off for every bot here and return to standard speed"
+ case .refused: members.first { $0.fastModeState == .refused }.map { "\($0.name): \($0.fastModeRefusal ?? "")" } ?? ""
+ }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/AvatarPicker.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/AvatarPicker.swift
new file mode 100644
index 00000000..66730193
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/AvatarPicker.swift
@@ -0,0 +1,98 @@
+import CodyncKit
+import SwiftUI
+
+/// Every avatar shape in the chosen color, then every color, as wrapping, centered grids
+/// (the New bot dialog and the bot's Settings).
+struct AvatarPicker: View {
+ @Binding var shape: String
+ @Binding var color: String
+
+ var body: some View {
+ VStack(spacing: 16) {
+ WrapLayout(spacing: 6) {
+ ForEach(AvatarPalette.shapes, id: \.self) { s in
+ choice("\(s) shape", chosen: s == shape) { shape = s } label: {
+ CharacterAvatar(shape: s, color: color, size: 40)
+ }
+ }
+ }
+ WrapLayout(spacing: 6) {
+ ForEach(AvatarPalette.colors) { c in
+ choice(c.label, chosen: c.id == color) { color = c.id } label: {
+ Circle().fill(c.color).frame(width: 28, height: 28)
+ }
+ }
+ }
+ }
+ .frame(maxWidth: .infinity)
+ }
+
+ private func choice(_ title: String, chosen: Bool, pick: @escaping () -> Void, @ViewBuilder label: () -> some View) -> some View {
+ Button { withAnimation(Motion.hover) { pick() } } label: { label().choiceRing(chosen) }
+ .buttonStyle(.plain)
+ .accessibilityLabel(title)
+ .accessibilityAddTraits(chosen ? .isSelected : [])
+ }
+}
+
+extension View {
+ /// The accent ring around a chosen shape, color or group member.
+ func choiceRing(_ chosen: Bool) -> some View {
+ padding(4).background(Circle().strokeBorder(chosen ? Palette.accent : .clear, lineWidth: 2))
+ }
+}
+
+/// Rows that wrap, each centered, split evenly (8 shapes are two rows of 4, not 7 and 1).
+// ponytail: even split assumes same-width items (avatars, swatches, member tiles); mixed widths could overflow a row.
+struct WrapLayout: Layout {
+ var spacing: CGFloat
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ let rows = rows(subviews, width: proposal.width ?? .infinity)
+ let height = rows.map(\.height).reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0))
+ return CGSize(width: rows.map(\.width).max() ?? 0, height: height)
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ var y = bounds.minY
+ for row in rows(subviews, width: bounds.width) {
+ var x = bounds.midX - row.width / 2
+ for i in row.items {
+ subviews[i].place(at: CGPoint(x: x, y: y), proposal: .unspecified)
+ x += subviews[i].sizeThatFits(.unspecified).width + spacing
+ }
+ y += row.height + spacing
+ }
+ }
+
+ private struct Row {
+ var items: Range<Int>
+ var width: CGFloat
+ var height: CGFloat
+ }
+
+ private func rows(_ subviews: Subviews, width: CGFloat) -> [Row] {
+ let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
+ return Self.split(sizes.map(\.width), spacing: spacing, width: width).map { items in
+ Row(items: items,
+ width: sizes[items].map(\.width).reduce(0, +) + spacing * CGFloat(items.count - 1),
+ height: sizes[items].map(\.height).max() ?? 0)
+ }
+ }
+
+ /// Each row's items: as many rows as a greedy fill needs, the items shared out evenly between them.
+ static func split(_ widths: [CGFloat], spacing: CGFloat, width: CGFloat) -> [Range<Int>] {
+ var count = 0, used: CGFloat = 0
+ for w in widths {
+ if count == 0 || used + spacing + w > width {
+ count += 1
+ used = w
+ } else {
+ used += spacing + w
+ }
+ }
+ guard count > 0 else { return [] }
+ let perRow = (widths.count + count - 1) / count
+ return stride(from: 0, to: widths.count, by: perRow).map { $0..<min($0 + perRow, widths.count) }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
index f28482eb..41356a65 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -8,52 +8,31 @@ public struct EditorRequest: Identifiable {
public init(_ draft: BotDraft) { self.draft = draft }
}
-/// Create or edit a bot in a modal (iPhone): the settings form plus Close / Save.
+/// Edit a bot in a modal (iPhone): the settings form plus Close / Save.
public struct BotEditorView: View {
@Environment(BotStore.self) private var model
@Environment(\.dismissModal) private var dismiss
@State var draft: BotDraft
- private let computers: [(id: ComputerID, label: String)]
- private let computer: Binding<ComputerID>?
-
- /// `computer` lets a new bot pick which computer it runs on; the caller swaps the `BotStore` to match.
- public init(draft: BotDraft, computers: [(id: ComputerID, label: String)] = [], computer: Binding<ComputerID>? = nil) {
- _draft = State(initialValue: draft)
- self.computers = computers
- self.computer = computer
- }
@State private var saving = false
@State private var error: String?
- private var isNew: Bool { draft.id == nil }
+ public init(draft: BotDraft) {
+ _draft = State(initialValue: draft)
+ }
public var body: some View {
VStack(spacing: 0) {
- ModalHeader(isNew ? "New bot" : "Settings") {
+ ModalHeader("Settings") {
if saving {
Spinner()
} else {
- IconButton(isNew ? "Create" : "Save", systemImage: "checkmark") { save() }
+ IconButton("Save", systemImage: "checkmark") { save() }
.disabled(!draft.isValid || saving || model.connection != .online)
}
}
- BotSettingsForm(draft: $draft, error: error, computers: computers, computer: computer)
+ BotSettingsForm(draft: $draft, error: error)
}
.background(Palette.background)
- .onAppear { if isNew { model.fillDefaults(&draft) } }
- // A new bot's connectors and skills start on once the computer has listed them.
- .onChange(of: model.installedConnectors.map(\.id) + model.installedSkills.map(\.id)) {
- if isNew { model.fillDefaults(&draft) }
- }
- .onChange(of: model.computer.id) {
- // Folders, models and connectors belong to the old computer.
- draft.cwd = ""
- draft.model = nil
- draft.modelOptions = [:]
- draft.connectors = nil
- draft.skills = nil
- model.fillDefaults(&draft)
- }
}
private func save() {
@@ -62,9 +41,8 @@ public struct BotEditorView: View {
error = nil
Task {
do {
- let bot = try await model.save(draft.normalized)
+ _ = try await model.save(draft.normalized)
dismiss()
- if isNew { model.selection = bot.id }
} catch {
self.error = error.localizedDescription
}
@@ -73,7 +51,7 @@ public struct BotEditorView: View {
}
}
-/// Which settings a form shows: all of them (a new bot), what changes often (instructions, model,
+/// Which settings a form shows: all of them (the editor), what changes often (instructions, model,
/// fast mode: the details sheet's Details page) or the rest (its Settings page).
enum FormPart {
case all, often, rarely
@@ -84,8 +62,6 @@ enum FormPart {
struct BotSettingsForm: View {
@Binding var draft: BotDraft
let error: String?
- var computers: [(id: ComputerID, label: String)] = []
- var computer: Binding<ComputerID>?
var scrolls = true
var part: FormPart = .all
@Environment(BotStore.self) private var model
@@ -189,30 +165,16 @@ struct BotSettingsForm: View {
.transition(.opacity.combined(with: .move(edge: .top)))
}
}
- // A new bot is named from its first conversations (Grok Bot's flow); rename it any time after.
- if draft.id != nil {
- Field("Name") {
- TextField("Name", text: $draft.name).fieldBox()
- }
+ Field("Name") {
+ TextField("Name", text: $draft.name).fieldBox()
}
if part == .all { instructions }
}
// On the details sheet the agent and its model are on the Details page; what's left is where it works.
CardSection(part == .all ? "Agent" : "Workspace") {
- VStack(alignment: .leading, spacing: 6) {
- ValueRow("Computer") {
- if let computer {
- ChoicePicker(selection: computer, options: computers, fitsAvailableWidth: true)
- .accessibilityLabel("Computer")
- } else {
- Text(model.hostName).lineLimit(1)
- }
- }
- if computer != nil, model.connection != .online {
- Text("Connect this computer to create the bot, or choose another computer.")
- .font(.caption).foregroundStyle(Palette.warning)
- }
+ ValueRow("Computer") {
+ Text(model.hostName).lineLimit(1)
}
if part == .all {
agentPicker
@@ -360,8 +322,8 @@ private struct FieldBox: ViewModifier {
}
extension BotDraft {
- /// A new bot may go without a name: the host names it after its first conversations.
- var isValid: Bool { id == nil || !name.trimmingCharacters(in: .whitespaces).isEmpty }
+ /// A saved bot keeps a name; only a new one goes without (the host names it after its first conversations).
+ var isValid: Bool { !name.trimmingCharacters(in: .whitespaces).isEmpty }
/// What the host should get: no stale command unless the agent is custom.
var normalized: BotDraft {
@@ -370,59 +332,3 @@ extension BotDraft {
return d
}
}
-
-public extension BotStore {
- /// Picks an installed agent we know (a registry agent nobody chose is never the default);
- /// empty cwd requests a personal workspace from the host.
- func fillDefaults(_ draft: inout BotDraft) {
- if hello?.backends.first(where: { $0.id == draft.backend })?.available != true,
- let first = hello?.backends.first(where: { $0.available && $0.curated == true }) {
- draft.backend = first.id
- }
- // Connectors and skills start on; left unset, the host turns on every one.
- if draft.connectors == nil, !installedConnectors.isEmpty {
- draft.connectors = installedConnectors.map(\.id)
- }
- if draft.skills == nil, !installedSkills.isEmpty {
- draft.skills = installedSkills.map(\.id)
- }
- }
-}
-
-struct AvatarPicker: View {
- @Binding var shape: String
- @Binding var color: String
-
- var body: some View {
- VStack(spacing: 12) {
- ScrollView(.horizontal, showsIndicators: false) {
- HStack(spacing: 10) {
- ForEach(AvatarPalette.shapes, id: \.self) { s in
- CharacterAvatar(shape: s, color: color, size: 36)
- .padding(4)
- .background(Circle().strokeBorder(s == shape ? Palette.accent : .clear, lineWidth: 2))
- .onTapGesture { withAnimation(Motion.hover) { shape = s } }
- .accessibilityLabel("\(s) shape")
- .accessibilityAddTraits(s == shape ? .isSelected : [])
- }
- }
- .padding(4)
- }
- ScrollView(.horizontal, showsIndicators: false) {
- HStack(spacing: 10) {
- ForEach(AvatarPalette.colors) { c in
- Circle()
- .fill(c.color)
- .frame(width: 26, height: 26)
- .padding(4)
- .background(Circle().strokeBorder(c.id == color ? Palette.accent : .clear, lineWidth: 2))
- .onTapGesture { withAnimation(Motion.hover) { color = c.id } }
- .accessibilityLabel(c.label)
- .accessibilityAddTraits(c.id == color ? .isSelected : [])
- }
- }
- .padding(4)
- }
- }
- }
-}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/GroupEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/GroupEditorView.swift
index 4fb897cc..8f0fb911 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/GroupEditorView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/GroupEditorView.swift
@@ -1,29 +1,26 @@
import CodyncKit
import SwiftUI
-/// Create a group chat, or change its name, what it's for and who's in it. Bots are
-/// picked like recipients: chips on top, a search, and the bots not in it yet.
+/// Change a group chat's name, what it's for and who's in it. Bots are picked like
+/// recipients: chips on top, a search, and the bots not in it yet.
public struct GroupEditorView: View {
@Environment(BotStore.self) private var model
@Environment(\.dismissModal) private var dismiss
- /// The group being edited; nil creates one.
- let groupId: String?
+ let groupId: String
@State private var name: String
@State private var about: String
@State private var members: [String]
@State private var query = ""
- /// A new group starts in the picker; an existing one shows its members first.
- @State private var adding: Bool
+ @State private var adding = false
@State private var saving = false
@State private var error: String?
@State private var confirmDelete: Bot?
- public init(group: Bot? = nil, members: [String] = []) {
- groupId = group?.id
- _name = State(initialValue: group?.name ?? "")
- _about = State(initialValue: group?.description ?? "")
- _members = State(initialValue: group?.members ?? members)
- _adding = State(initialValue: group == nil && members.isEmpty)
+ public init(group: Bot) {
+ groupId = group.id
+ _name = State(initialValue: group.name)
+ _about = State(initialValue: group.description)
+ _members = State(initialValue: group.members)
}
private var picked: [Bot] { members.compactMap { model.bots[$0] } }
@@ -32,16 +29,15 @@ public struct GroupEditorView: View {
let q = query.trimmingCharacters(in: .whitespaces)
return model.roster.filter { !$0.isGroup && !members.contains($0.id) && (q.isEmpty || $0.name.localizedCaseInsensitiveContains(q)) }
}
- private var isNew: Bool { groupId == nil }
private var canSave: Bool { !members.isEmpty && !saving }
public var body: some View {
VStack(spacing: 0) {
- ModalHeader(isNew ? "New group chat" : "Group chat") {
+ ModalHeader("Group chat") {
if saving {
Spinner()
} else {
- IconButton(isNew ? "Create" : "Save", systemImage: "checkmark") { save() }
+ IconButton("Save", systemImage: "checkmark") { save() }
.disabled(!canSave)
}
}
@@ -110,7 +106,7 @@ public struct GroupEditorView: View {
if let error {
Text(error).font(.footnote).foregroundStyle(Palette.danger).transition(.opacity)
}
- if let group = groupId.flatMap({ model.bots[$0] }) {
+ if let group = model.bots[groupId] {
Button("Delete group chat", role: .destructive) { confirmDelete = group }
.foregroundStyle(Palette.danger)
.buttonStyle(PressScale())
@@ -159,14 +155,10 @@ public struct GroupEditorView: View {
let about = about.trimmingCharacters(in: .whitespacesAndNewlines)
Task {
do {
- if let groupId {
- var draft = GroupDraft(name: finalName, description: about, members: members)
- draft.id = groupId
- draft.pinned = model.bots[groupId]?.pinned
- try await model.updateGroup(draft)
- } else {
- _ = try await model.createGroup(name: finalName, description: about, members: members)
- }
+ var draft = GroupDraft(name: finalName, description: about, members: members)
+ draft.id = groupId
+ draft.pinned = model.bots[groupId]?.pinned
+ try await model.updateGroup(draft)
dismiss()
} catch {
withAnimation(Motion.fade) { self.error = error.localizedDescription }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/NewBotView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/NewBotView.swift
new file mode 100644
index 00000000..76ea198d
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/NewBotView.swift
@@ -0,0 +1,216 @@
+import CodyncKit
+import SwiftUI
+
+/// A new bot, profile first (Grok Bot's Create New Bot): its avatar and name. Everything else
+/// starts on the usual defaults and is changed afterwards in the bot's Settings.
+public struct NewBotView: View {
+ @Environment(BotStore.self) private var model
+ @Environment(\.dismissModal) private var dismiss
+ @State private var draft = BotDraft()
+ @State private var saving = false
+ @State private var error: String?
+ private let computers: [(id: ComputerID, label: String)]
+ @Binding private var computer: ComputerID
+
+ /// `computers` can take the bot; the caller swaps the `BotStore` to match `computer`.
+ public init(computers: [(id: ComputerID, label: String)], computer: Binding<ComputerID>) {
+ self.computers = computers
+ _computer = computer
+ }
+
+ public var body: some View {
+ CreateForm(title: "New bot", placeholder: "Name your bot", name: $draft.name, saving: saving,
+ canCreate: !saving && model.connection == .online, error: error, create: save) {
+ CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 96)
+ } content: {
+ AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)
+ if computers.count > 1 || model.connection != .online {
+ VStack(alignment: .leading, spacing: 6) {
+ if computers.count > 1 {
+ ValueRow("Computer") {
+ ChoicePicker(selection: $computer, options: computers, fitsAvailableWidth: true)
+ .accessibilityLabel("Computer")
+ }
+ }
+ if model.connection != .online {
+ Text(computers.count > 1
+ ? "Connect this computer to create the bot, or choose another computer."
+ : "Connect this computer to create the bot.")
+ .font(.caption).foregroundStyle(Palette.warning)
+ }
+ }
+ }
+ }
+ }
+
+ private func save() {
+ guard !saving, model.connection == .online else { return }
+ saving = true
+ error = nil
+ var draft = draft
+ draft.name = draft.name.trimmingCharacters(in: .whitespacesAndNewlines)
+ model.fillDefaults(&draft)
+ Task {
+ do {
+ let bot = try await model.save(draft)
+ dismiss()
+ model.selection = bot.id
+ } catch {
+ withAnimation(Motion.fade) { self.error = error.localizedDescription }
+ }
+ saving = false
+ }
+ }
+}
+
+private extension BotStore {
+ /// Picks an installed agent we know (a registry agent nobody chose is never the default);
+ /// empty cwd requests a personal workspace from the host. Connectors and skills stay unset:
+ /// the host turns on every one it can run.
+ func fillDefaults(_ draft: inout BotDraft) {
+ if hello?.backends.first(where: { $0.id == draft.backend })?.available != true,
+ let first = hello?.backends.first(where: { $0.available && $0.curated == true }) {
+ draft.backend = first.id
+ }
+ }
+}
+
+/// A new group chat, laid out like a new bot: who's in it and its name. What it works on is set
+/// afterwards in the group editor.
+public struct NewGroupView: View {
+ @Environment(BotStore.self) private var model
+ @Environment(\.dismissModal) private var dismiss
+ @State private var name = ""
+ @State private var members: [String] = []
+ @State private var saving = false
+ @State private var error: String?
+
+ public init() {}
+
+ private var picked: [Bot] { members.compactMap { model.bots[$0] } }
+ /// "Alice, Bob" when no name is typed.
+ private var defaultName: String { picked.map(\.name).joined(separator: ", ") }
+
+ public var body: some View {
+ CreateForm(title: "New group chat", placeholder: picked.isEmpty ? "Name your group" : defaultName, name: $name,
+ saving: saving, canCreate: !members.isEmpty && !saving, error: error, create: save) {
+ GroupAvatar(members: picked, size: 96)
+ .animation(Motion.layout, value: members)
+ } content: {
+ let bots = model.roster.filter { !$0.isGroup }
+ VStack(spacing: 14) {
+ if bots.isEmpty {
+ Text("No bots yet. Create a bot first.").font(.subheadline).foregroundStyle(Palette.secondary)
+ } else {
+ WrapLayout(spacing: 8) {
+ ForEach(bots) { tile($0) }
+ }
+ }
+ Text("Everyone answers in turn unless you @mention someone.")
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ }
+ }
+ }
+
+ /// A bot to pick: its avatar, ringed once picked, with its name under it.
+ private func tile(_ bot: Bot) -> some View {
+ let chosen = members.contains(bot.id)
+ return Button { toggle(bot.id) } label: {
+ VStack(spacing: 4) {
+ CharacterAvatar(bot: bot, size: 44, animated: false).choiceRing(chosen)
+ Text(bot.name)
+ .font(.caption)
+ .foregroundStyle(chosen ? Palette.text : Palette.secondary)
+ .lineLimit(1)
+ }
+ .frame(width: 64)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(bot.name)
+ .accessibilityAddTraits(chosen ? .isSelected : [])
+ }
+
+ private func toggle(_ id: String) {
+ withAnimation(Motion.layout) {
+ if members.contains(id) { members.removeAll { $0 == id } } else { members.append(id) }
+ }
+ }
+
+ private func save() {
+ guard !members.isEmpty, !saving else { return }
+ saving = true
+ error = nil
+ let typed = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ let name = typed.isEmpty ? defaultName : typed
+ Task {
+ do {
+ _ = try await model.createGroup(name: name, members: members)
+ dismiss()
+ } catch {
+ withAnimation(Motion.fade) { self.error = error.localizedDescription }
+ }
+ saving = false
+ }
+ }
+}
+
+/// The create dialogs' layout: a large preview, a centered name field (Return creates), the
+/// pickers, then any save error.
+private struct CreateForm<Preview: View, Content: View>: View {
+ let title: String
+ let placeholder: String
+ @Binding var name: String
+ let saving: Bool
+ let canCreate: Bool
+ let error: String?
+ let create: () -> Void
+ @ViewBuilder let preview: Preview
+ @ViewBuilder let content: Content
+ @FocusState private var naming: Bool
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ModalHeader(title) {
+ if saving {
+ Spinner()
+ } else {
+ IconButton("Create", systemImage: "checkmark", action: create)
+ .disabled(!canCreate)
+ }
+ }
+ ScrollView {
+ VStack(spacing: 28) {
+ VStack(spacing: 16) {
+ preview
+ TextField(placeholder, text: $name)
+ .textFieldStyle(.plain)
+ .font(.title2.weight(.semibold))
+ .foregroundStyle(Palette.text)
+ .multilineTextAlignment(.center)
+ .submitLabel(.done)
+ .focused($naming)
+ .onSubmit(create)
+ }
+ content
+ if let error {
+ Text(error)
+ .font(.footnote)
+ .foregroundStyle(Palette.danger)
+ .multilineTextAlignment(.center)
+ .transition(.opacity)
+ }
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, 20)
+ .padding(.top, 8)
+ .padding(.bottom, 24)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ }
+ .background(Palette.background)
+ .onAppear { naming = true }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift
index 8c8cba32..4acd82cf 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift
@@ -41,7 +41,7 @@ struct NodeNotice: View {
/// Getting an agent ready on the computer: install it, add Node.js when it runs on Node and
/// the computer has none, then sign in. Sign-in options come from the agent itself (ACP),
-/// plus Codync's own command for CLIs it knows. Bots are made from New chat, not here.
+/// plus Codync's own command for CLIs it knows. Bots are made from New bot, not here.
struct AgentSheet: View {
let initial: Backend
/// Opened from a chat's sign-in request, whose agent refused a turn: the agent is asked
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
index 24b49f7f..a5169085 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
@@ -231,6 +231,14 @@ extension BotStore {
perform(replay: true) { _ = try await $0.updateBot(d) }
}
+ /// The composer's `/fast`: the bot's Fast mode flips; in a group, every member that shows it
+ /// goes to the opposite of the group's state.
+ public func toggleFastMode(_ bot: Bot) {
+ guard bot.isGroup else { return setFastMode(bot, !bot.fastMode) }
+ let group = GroupFastMode(members(of: bot))
+ for member in group.members { setFastMode(member, group.state == .off) }
+ }
+
// MARK: roster order
/// Puts the roster in `ids` order (pinned bots still sort first) and sends it; the host
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift
index 9f334171..7b602a8e 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift
@@ -7,12 +7,13 @@ struct CommandList: View {
let pick: (SlashCommand) -> Void
var body: some View {
- // Scrolls only once it's taller than the room it gets.
- ViewThatFits(in: .vertical) {
- rows
- ScrollView { rows }.scrollIndicators(.hidden)
+ // Hugs its rows; scrolls only once they're taller than 280 points.
+ CappedHeight(max: 280) {
+ ViewThatFits(in: .vertical) {
+ rows
+ ScrollView { rows }.scrollIndicators(.hidden)
+ }
}
- .frame(maxHeight: 280, alignment: .bottom)
.glass(in: RoundedRectangle(cornerRadius: 20, style: .continuous))
}
@@ -44,3 +45,18 @@ struct CommandList: View {
.padding(.vertical, 6)
}
}
+
+/// Offers its content at most `max` points of height and takes the content's own height: a
+/// `frame(maxHeight:)` grows to the cap whenever there's room, leaving the card half empty.
+private struct CappedHeight: Layout {
+ let max: CGFloat
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ let offer = ProposedViewSize(width: proposal.width, height: min(proposal.height ?? max, max))
+ return subviews.first?.sizeThatFits(offer) ?? .zero
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ subviews.first?.place(at: bounds.origin, proposal: ProposedViewSize(bounds.size))
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
index c5845b47..774acd3d 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
@@ -4,8 +4,8 @@ import SwiftUI
import UniformTypeIdentifiers
/// The message box under a chat or a thread: send, or stop while the bot (or the
-/// group) is working there. In a group, typing `@` suggests its bots; with one bot, a
-/// leading `/` lists its commands.
+/// group) is working there. A leading `/` lists commands (a group's act on its bots);
+/// in a group, typing `@` suggests its bots.
struct Composer: View {
let botId: String
/// Replies go to the thread on this message.
@@ -46,7 +46,7 @@ struct Composer: View {
private var placeholder: String {
let name = bot?.name ?? ""
if thread != nil { return "Reply…" }
- if bot?.isGroup == true { return "Message everyone · @ to ask one bot" }
+ if bot?.isGroup == true { return "Ask everyone · @ to ask one bot" }
return working ? "Queue a message for \(name)" : "Ask \(name)"
}
@@ -59,17 +59,21 @@ struct Composer: View {
}
private var suggestions: [Bot] {
- guard let query = mentionQuery, let bot else { return [] }
- return model.members(of: bot).filter {
+ guard let query = mentionQuery else { return [] }
+ return members.filter {
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query)
}
}
+ /// A group's bots, which its commands act on.
+ private var members: [Bot] { bot.map(model.members(of:)) ?? [] }
+
/// The bot's `/` commands while the draft is `/partial`; skills only from hosts that run them.
private var commands: [SlashCommand] {
guard let query = SlashCommands.query(draft) else { return [] }
- let skillsShown = !AppVersion.isBelow(model.hello?.version ?? "", SlashCommands.minSkillsHost)
- return SlashCommands.list(for: bot, query: query, skills: skillsShown ? model.installedSkills : [])
+ let floor = bot?.isGroup == true ? SlashCommands.minGroupSkillsHost : SlashCommands.minSkillsHost
+ let skillsShown = !AppVersion.isBelow(model.hello?.version ?? "", floor)
+ return SlashCommands.list(for: bot, members: members, query: query, skills: skillsShown ? model.installedSkills : [])
}
var body: some View {
@@ -251,7 +255,7 @@ struct Composer: View {
.onChange(of: draft) { _, value in
model.setComposerDraft(value, for: botId, thread: thread)
// Starting a command: list the computer's skills again.
- if value == "/", bot?.isGroup == false { Task { await model.refreshPlugins() } }
+ if value == "/" { Task { await model.refreshPlugins() } }
}
.onChange(of: model.routineDrafts[botId]) { _, value in
guard thread == nil, let value else { return }
@@ -346,7 +350,7 @@ struct Composer: View {
guard let bot else { return }
switch command.action {
case .fast:
- model.setFastMode(bot, !bot.fastMode)
+ model.toggleFastMode(bot)
draft = ""
case .skill(let id):
draft = "/\(id) "
@@ -355,7 +359,7 @@ struct Composer: View {
}
private func submit() {
- if files.isEmpty, let command = SlashCommands.builtIn(for: bot, draft: draft) { return run(command) }
+ if files.isEmpty, let command = SlashCommands.builtIn(for: bot, members: members, draft: draft) { return run(command) }
guard canSend else { return }
withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
guard model.sendComposerDraft(to: botId, thread: thread, files: files) else { return }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift
index ee29a6d2..6a91d2c0 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift
@@ -15,12 +15,14 @@ struct SlashCommand: Identifiable, Equatable {
var id: Action { action }
}
-/// The composer's `/` commands, listed while the draft is just `/partial`: Fast mode runs here
-/// through the host's `updateBot` (a new session is in the bot's menu); a skill fills in `/<id> `, and the host turns that message into "read this skill first"
+/// The composer's `/` commands, listed while the draft is just `/partial`, the same in a group: Fast mode runs here
+/// through the host's `updateBot` (a group's on each member; a new session is in the bot's menu); a skill fills in `/<id> `, and the host turns that message into "read this skill first"
/// (`host/src/market/skills.rs` `expand_command`). docs/features/marketplace.md, "Commands".
enum SlashCommands {
/// The first host that understands `/skill` messages; older ones get the text as typed.
static let minSkillsHost = "2.14.1"
+ /// The first host that runs `/skill` in a group's prompts (`host/src/chat/group.rs` `line`).
+ static let minGroupSkillsHost = "2.20.1"
/// The command name being typed after a leading `/`, before any space.
static func query(_ draft: String) -> String? {
@@ -28,26 +30,37 @@ enum SlashCommands {
return String(draft.dropFirst())
}
- /// Built-in commands, then the bot's skills, whose name or title holds `query` (none in a group).
- static func list(for bot: Bot?, query: String, skills: [InstalledSkill]) -> [SlashCommand] {
- guard let bot, !bot.isGroup else { return [] }
- let own = skills.filter { bot.skills.contains($0.id) }.map {
+ /// Built-in commands, then the skills the bot has on (a group's: any member's), whose name or
+ /// title holds `query`. `members` are a group's bots.
+ static func list(for bot: Bot?, members: [Bot] = [], query: String, skills: [InstalledSkill]) -> [SlashCommand] {
+ guard let bot else { return [] }
+ let owners = bot.isGroup ? members : [bot]
+ let own = skills.filter { skill in owners.contains { $0.skills.contains(skill.id) } }.map {
SlashCommand(name: $0.id, icon: "book.pages", title: $0.name, detail: $0.description, warning: false, action: .skill($0.id))
}
- return (builtIn(bot) + own).filter {
+ return (builtIn(bot, members: members) + own).filter {
query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || $0.title.localizedCaseInsensitiveContains(query)
}
}
/// A draft that is just a built-in command (`/fast`): sending it runs the command.
- static func builtIn(for bot: Bot?, draft: String) -> SlashCommand? {
+ static func builtIn(for bot: Bot?, members: [Bot] = [], draft: String) -> SlashCommand? {
guard let bot, let name = query(draft.trimmingCharacters(in: .whitespacesAndNewlines)) else { return nil }
- return builtIn(bot).first { $0.name == name }
+ return builtIn(bot, members: members).first { $0.name == name }
}
- private static func builtIn(_ bot: Bot) -> [SlashCommand] {
- guard !bot.isGroup, bot.fastModeShown else { return [] }
- return [SlashCommand(name: "fast", icon: "bolt", title: "Fast mode", detail: bot.fastModeDetail,
- warning: bot.fastModeState == .refused, action: .fast)]
+ /// Fast mode, while the bot (or a member of the group) shows it.
+ private static func builtIn(_ bot: Bot, members: [Bot]) -> [SlashCommand] {
+ let fast: (detail: String, state: Bot.FastModeState)
+ if bot.isGroup {
+ let group = GroupFastMode(members)
+ guard !group.members.isEmpty else { return [] }
+ fast = (group.detail, group.state)
+ } else {
+ guard bot.fastModeShown else { return [] }
+ fast = (bot.fastModeDetail, bot.fastModeState)
+ }
+ return [SlashCommand(name: "fast", icon: "bolt", title: "Fast mode", detail: fast.detail,
+ warning: fast.state == .refused, action: .fast)]
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
index 2137c954..702c4ccf 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -84,7 +84,7 @@ public struct ThreadView: View {
BotDetailsView(botId: botId, request: request)
}
.codyncSheet(isPresented: $editingGroup) {
- GroupEditorView(group: bot)
+ if let bot { GroupEditorView(group: bot) }
}
.codyncDialog("Start a new session?", isPresented: $confirmNewSession,
message: "The conversation stays here, but the agent starts with a fresh context.") {
diff --git a/apps/ios/Kit/Tests/CodyncUITests/SlashCommandsTests.swift b/apps/ios/Kit/Tests/CodyncUITests/SlashCommandsTests.swift
index 0bcac8bc..0c71915d 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/SlashCommandsTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/SlashCommandsTests.swift
@@ -1,4 +1,5 @@
import Foundation
+import SwiftUI
import Testing
@testable import CodyncKit
@testable import CodyncUI
@@ -24,7 +25,38 @@ private let installed = [("pdf", "PDF"), ("code-review", "Code Review"), ("xlsx"
#expect(SlashCommands.list(for: try bot(#"{"id":"b","skills":["pdf"]}"#), query: "xl", skills: installed).isEmpty)
#expect(SlashCommands.list(for: try bot(#"{"id":"b"}"#), query: "", skills: []).map(\.name) == ["fast"], "offered until the agent says otherwise")
#expect(SlashCommands.list(for: try bot(#"{"id":"b","fastModeSupport":"unsupported"}"#), query: "", skills: []).isEmpty, "no Fast mode on offer")
- #expect(SlashCommands.list(for: try bot(#"{"id":"g","kind":"group","fastModeSupport":"offered"}"#), query: "", skills: installed).isEmpty)
+}
+
+@Test func aGroupListsItsMembersFastModeAndTheirSkills() throws {
+ let group = try bot(#"{"id":"g","kind":"group","members":["a","b","c"]}"#)
+ let a = try bot(#"{"id":"a","name":"Ann","skills":["pdf"],"fastModeSupport":"offered"}"#)
+ let b = try bot(#"{"id":"b","name":"Bo","skills":["xlsx","pdf"],"fastModeSupport":"offered"}"#)
+ let none = try bot(#"{"id":"c","name":"Cy","fastModeSupport":"unsupported"}"#)
+ let list = SlashCommands.list(for: group, members: [a, b, none], query: "", skills: installed)
+ #expect(list.map(\.name) == ["fast", "pdf", "xlsx"], "Fast mode, then every member's skills once")
+ #expect(list.first?.detail == "Turn on for every bot here: faster replies and more usage")
+ let skilledOnly = try bot(#"{"id":"d","skills":["code-review"],"fastModeSupport":"unsupported"}"#)
+ #expect(SlashCommands.list(for: group, members: [none, skilledOnly], query: "", skills: installed).map(\.name) == ["code-review"],
+ "no member shows Fast mode: only skills")
+ #expect(SlashCommands.list(for: group, members: [none], query: "", skills: installed).isEmpty)
+ #expect(SlashCommands.builtIn(for: group, members: [a, b], draft: "/fast")?.action == .fast)
+ #expect(SlashCommands.builtIn(for: group, members: [none], draft: "/fast") == nil)
+}
+
+@Test func aGroupsFastModeIsOnOnlyWhenEveryMemberShowingItHasItOn() throws {
+ let on = try bot(#"{"id":"a","name":"Ann","fastMode":true,"fastModeSupport":"offered"}"#)
+ let off = try bot(#"{"id":"b","name":"Bo","fastModeSupport":"offered"}"#)
+ let hidden = try bot(#"{"id":"c","fastModeSupport":"unsupported"}"#)
+ let refused = try bot(#"{"id":"d","name":"Di","fastMode":true,"fastModeSupport":"refused","fastModeIssue":"requires extra usage"}"#)
+ #expect(GroupFastMode([on, off]).state == .off)
+ #expect(GroupFastMode([on, hidden]).state == .on, "members that don't show it don't count")
+ #expect(GroupFastMode([on, hidden]).members.map(\.id) == ["a"])
+ #expect(GroupFastMode([on, hidden]).detail == "Turn off for every bot here and return to standard speed")
+ #expect(GroupFastMode([on, refused]).state == .refused)
+ #expect(GroupFastMode([on, refused]).detail.hasPrefix("Di: The agent turned it off: requires extra usage"))
+ #expect(GroupFastMode([hidden]).state == .off)
+ let group = try bot(#"{"id":"g","kind":"group","members":["a","d"]}"#)
+ #expect(SlashCommands.list(for: group, members: [on, refused], query: "", skills: []).first?.warning == true)
}
@Test func sendingJustABuiltInCommandRunsIt() throws {
@@ -34,3 +66,15 @@ private let installed = [("pdf", "PDF"), ("code-review", "Code Review"), ("xlsx"
#expect(SlashCommands.builtIn(for: offered, draft: "/fast please") == nil)
#expect(SlashCommands.builtIn(for: try bot(#"{"id":"b","fastModeSupport":"unsupported"}"#), draft: "/fast") == nil, "without Fast mode it reaches the agent")
}
+
+@MainActor @Test func theCommandListHugsItsRowsAndScrollsPastItsCap() {
+ func height(_ count: Int) -> CGFloat {
+ let commands = (0..<count).map {
+ SlashCommand(name: "s\($0)", icon: "bolt", title: "Skill \($0)", detail: "", warning: false, action: .skill("s\($0)"))
+ }
+ return UIHostingController(rootView: CommandList(commands: commands) { _ in })
+ .sizeThatFits(in: CGSize(width: 390, height: 2000)).height
+ }
+ #expect(height(2) < 140, "two rows, not the 280-point cap")
+ #expect(height(20) == 280)
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/WrapLayoutTests.swift b/apps/ios/Kit/Tests/CodyncUITests/WrapLayoutTests.swift
new file mode 100644
index 00000000..982680b7
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/WrapLayoutTests.swift
@@ -0,0 +1,11 @@
+import Testing
+@testable import CodyncUI
+
+@Test func wrapLayoutSharesItemsEvenlyBetweenRows() {
+ // 8 shapes of 48 with 6 apart: 6 fit in 362, so two rows of 4 (not 6 and 2).
+ #expect(WrapLayout.split(Array(repeating: 48, count: 8), spacing: 6, width: 362) == [0..<4, 4..<8])
+ // 11 colors of 36: 8 fit, so rows of 6 and 5.
+ #expect(WrapLayout.split(Array(repeating: 36, count: 11), spacing: 6, width: 362) == [0..<6, 6..<11])
+ #expect(WrapLayout.split(Array(repeating: 48, count: 3), spacing: 6, width: 362) == [0..<3])
+ #expect(WrapLayout.split([], spacing: 6, width: 362).isEmpty)
+}
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index 91335b0d..bdee2de9 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -8,6 +8,7 @@ import SwiftUI
struct BotListView: View {
@Environment(AppStore.self) private var app
@Environment(AccountStore.self) private var accounts
+ @State private var creating: NewTarget?
@State private var editing: EditTarget?
@State private var editingGroup: GroupTarget?
@State private var confirmDelete: RosterItem?
@@ -47,11 +48,12 @@ struct BotListView: View {
/// Computers that can take a new bot right now.
private var onlineStores: [BotStore] {
- allStores.filter { $0.connection == .online && $0.mismatch == nil }
+ availableStores.filter { $0.connection == .online }
}
- private var allStores: [BotStore] {
- accounts.computers.compactMap { accounts.store(for: $0.id) }
+ /// Computers that can take a new bot once they're connected (not ones waiting for an update).
+ private var availableStores: [BotStore] {
+ accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.mismatch == nil }
}
/// The rows the user can drag: each shown computer's heading (with several computers), in the
@@ -78,7 +80,7 @@ struct BotListView: View {
}
// A computer waiting for an update has its card instead; its bots aren't known yet.
if roster.isEmpty && shownStores.allSatisfy({ $0.mismatch == nil }) {
- EmptyRoster(canCreate: allStores.contains { $0.mismatch == nil }, hasComputer: !accounts.computers.isEmpty,
+ EmptyRoster(canCreate: !availableStores.isEmpty, hasComputer: !accounts.computers.isEmpty,
create: newBot, showComputers: { app.showComputers = true })
}
ForEach(lines) { line in
@@ -116,42 +118,49 @@ struct BotListView: View {
.disabled(onlineStores.isEmpty)
}
// A computer that needs an update can't take a new bot.
- .disabled(!allStores.contains { $0.mismatch == nil })
+ .disabled(availableStores.isEmpty)
}
}
.refreshable {
for computer in accounts.computers { accounts.store(for: computer.id)?.restartStream() }
await accounts.refreshCloud()
}
- .codyncSheet(item: $editing) { target in
- // A new bot can move to another computer until it's created.
- let computerId = editing?.computerId ?? target.computerId
- if let store = accounts.store(for: computerId) {
- BotEditorView(draft: target.draft,
- computers: allStores.map {
- ($0.computer.id, $0.connection == .online ? $0.hostName : "\($0.hostName) (offline)")
- },
- computer: target.draft.id == nil
- ? Binding(get: { computerId }, set: { editing?.computerId = $0 })
- : nil)
- .environment(store)
- .onChange(of: store.selection) { _, botId in
- // A new bot opens its chat, on the computer it was created on.
- guard let botId else { return }
- store.selection = nil
- accounts.selection = BotReference(accountId: accounts.accountId, computerId: computerId, botId: botId)
+ .codyncSheet(item: $creating) { target in
+ if let store = accounts.store(for: target.computerId) {
+ Group {
+ switch target.kind {
+ case .bot:
+ // A new bot can move to another computer until it's created: a new target
+ // (same sheet) keeps the sheet on that computer while it slides away.
+ NewBotView(computers: availableStores.map {
+ ($0.computer.id, $0.connection == .online ? $0.hostName : "\($0.hostName) (offline)")
+ },
+ computer: Binding(get: { target.computerId },
+ set: { creating = NewTarget(kind: .bot, computerId: $0) }))
+ case .group:
+ NewGroupView()
}
+ }
+ .environment(store)
+ }
+ }
+ // A new bot or group selects itself; open its chat on the computer it was created on. Watched
+ // here, not in the sheet: the dialog closes as it selects, and a closing sheet sees no change.
+ .onChange(of: availableStores.map(\.selection)) {
+ for store in availableStores {
+ guard let botId = store.selection else { continue }
+ store.selection = nil
+ accounts.selection = BotReference(accountId: accounts.accountId, computerId: store.computer.id, botId: botId)
+ }
+ }
+ .codyncSheet(item: $editing) { target in
+ if let store = accounts.store(for: target.computerId) {
+ BotEditorView(draft: target.draft).environment(store)
}
}
.codyncSheet(item: $editingGroup) { target in
if let store = accounts.store(for: target.computerId) {
- GroupEditorView(group: target.group)
- .environment(store)
- .onChange(of: store.selection) { _, botId in
- guard let botId else { return }
- store.selection = nil
- accounts.selection = BotReference(accountId: accounts.accountId, computerId: target.computerId, botId: botId)
- }
+ GroupEditorView(group: target.group).environment(store)
}
}
.codyncDialog("Delete \(confirmDelete?.bot.name ?? "bot")?",
@@ -250,16 +259,16 @@ struct BotListView: View {
private func newGroup() {
guard let store = onlineStores.first else { return }
Task {
- // Let the menu fold away before the editor slides up.
+ // Let the menu fold away before the dialog slides up.
try? await Task.sleep(for: .milliseconds(200))
- editingGroup = GroupTarget(computerId: store.computer.id, group: nil)
+ creating = NewTarget(kind: .group, computerId: store.computer.id)
}
}
- /// A new bot starts on the first computer online; the editor's Computer row can move it.
+ /// A new bot starts on the first computer online; the dialog's Computer row can move it.
private func newBot() {
- guard let store = onlineStores.first ?? allStores.first(where: { $0.mismatch == nil }) else { return }
- editing = EditTarget(computerId: store.computer.id, draft: BotDraft())
+ guard let store = onlineStores.first ?? availableStores.first else { return }
+ creating = NewTarget(kind: .bot, computerId: store.computer.id)
}
}
@@ -363,15 +372,22 @@ private struct ComputerSection: View {
}
}
+private struct NewTarget: Identifiable {
+ enum Kind { case bot, group }
+ let id = UUID()
+ let kind: Kind
+ let computerId: ComputerID
+}
+
private struct GroupTarget: Identifiable {
let id = UUID()
let computerId: ComputerID
- let group: Bot?
+ let group: Bot
}
private struct EditTarget: Identifiable {
let id = UUID()
- var computerId: ComputerID
+ let computerId: ComputerID
let draft: BotDraft
}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index aec0ef7c..437c7357 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -10,8 +10,14 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
+- 新增 Bot 改成先設定外觀:挑形狀和顏色、取個名字(也可以不取),按一下就建立並開啟聊天。其他設定之後再到 Bot 的設定裡調整。
+- 建立群組聊天也用同樣的方式:選好成員、取個名字(可留空),按一下就開啟群組。
+- 群組聊天裡輸入「/」也能用指令了:一次幫所有成員開關 Fast mode,或叫出任一成員的技能,每個有這項技能的 Bot 都會照著做。
- 登入後不會再自動向帳號裡的電腦要求存取,也不會直接跳出驗證碼;在「電腦」裡點「Ask for access」才會開始。
### en-US
+- Creating a bot starts with how it looks: pick a shape and a color, give it a name if you like, and its chat opens. Everything else stays in the bot's Settings for later.
+- A new group chat works the same way: pick its members, name it if you like, and the group opens.
+- Typing / in a group chat now lists commands too: turn Fast mode on or off for every bot at once, or pick any member's skill and each bot that has it follows it.
- Signing in no longer asks your account's computers for access on its own or jumps straight to a code; it starts when you tap Ask for access in Computers.
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 34634c06..dc0b9343 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -126,7 +126,7 @@ npm run typecheck && npm test
```
UI checks: `CODYNC_SHOW_INACTIVE=1` opens the window without taking focus,
-`CODYNC_DEBUG_OPEN=compose|group|plugins|computers|<bot name>` opens a screen, and
+`CODYNC_DEBUG_OPEN=newBot|newGroup|plugins|computers|<bot name>` opens a screen, and
`CODYNC_REMOTE_DEBUG=<port>` lets a script drive the renderer over the DevTools protocol.
Each packaging script names its environment:
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index f4f41d46..0a26dd0d 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -2,7 +2,7 @@
## iPhone navigation
-The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account button, centered computer status/filter menu, and new-chat button. Computer management is inside the centered menu. The conversation copies Grok Bot: the title pill is a native `Menu` (details and the bot's actions), the only trailing button is the computer (remote screen; it pulses while this bot operates the screen), and the call button sits in the composer as a filled waveform capsule while the box is empty. Menus opened from toolbar buttons (New, the computer filter, the title) are native `Menu`s, like every iOS menu; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.
+The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account button, centered computer status/filter menu, and New button (New bot, New group chat). Computer management is inside the centered menu. The conversation copies Grok Bot: the title pill is a native `Menu` (details and the bot's actions), the only trailing button is the computer (remote screen; it pulses while this bot operates the screen), and the call button sits in the composer as a filled waveform capsule while the box is empty. Menus opened from toolbar buttons (New, the computer filter, the title) are native `Menu`s, like every iOS menu; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.
The conversation keeps the native glass buttons over the chat with a soft top scroll-edge effect, so messages blur out under the header instead of running sharp behind it. Root error dialogs use an in-place, full-screen scrim so presenting them does not change the underlying glass controls' appearance.
@@ -95,15 +95,17 @@ Desktop conversations start with the details inspector closed; the title menu op
Preserve the original character avatar design: dotted shading, highlight-only color, silhouettes and animation. Desktop roster avatars remain 30 points and iPhone roster avatars remain 46 points. iPhone shares readable secondary text and message previews; its native navigation remains platform-specific. Terminal avatars already use solid color and the terminal has no persistent details inspector; its secondary text uses the same readable palette.
-The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model and fast mode), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the New bot and editor sheets show all of it. Memory is the memory card, its sections in the same tabs and the add/more actions beside each layer's note. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.
+The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model and fast mode), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Memory is the memory card, its sections in the same tabs and the add/more actions beside each layer's note. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.
Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the desktop the form card fits its content. The header's chat button asks the bot (puts "I want a routine that " in the composer); + opens the form, where When to run is a type choice (a segmented control on the desktop, the system menu on iPhone) and a schedule is a Repeat choice (Hourly, Daily, Weekdays, Weekly, Custom) with only the fields that choice needs (minute, time, weekday, or a typed cron for Custom) and a time zone picked from a searchable list. On the desktop these sit in one `CardSection` of labeled rows, Repeat and the weekday as `ChipChoice` chips with the chosen one on a light capsule. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as monospaced rows (in the same group on the desktop) with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.
On iPhone, the routine editor keeps the full-width save action in a fixed footer on the sheet background. When required fields are empty, the footer explains why saving is unavailable.
+New bot and New group chat (the + menu on every client) are one short sheet each, in the same layout: a large face on top (the avatar, or the picked members' group avatar), a centered optional name field, then the choices as wrapping centered grids (the avatar's shapes and colors; the computer's bots, each a face with its name under it), ringed when picked. The desktop puts Cancel and Create in a footer; the phones put Create in the sheet header. Everything else starts on the defaults and changes afterwards in Settings or the group editor; an unnamed bot is named by the host after its first conversations, an unnamed group after its bots. With more than one computer, the sheet also picks which one.
+
New bots use automatically allocated personal workspaces. Settings offer Personal or an optional project folder; see [bot workspaces](../features/bot-workspaces.md).
-Desktop menus (`AnchoredMenu` in `Overlay.tsx`) scroll vertically when their content exceeds 420 points or the available space beside the trigger. Menus open toward the side with more vertical room; short lists keep their content height. Menu width is capped at 320 points and constrained to the window, and long option titles remain available through help text. This applies to Agent, Model, and other choice menus on the desktop. On iOS every menu is the system one: `DropdownMenu` and `ChoicePicker` present the native `Menu` (choices as checkmarked toggles) and `.contextActions` the native `contextMenu` (reactions as a palette row), because an overlay anchored by global frame lands in the wrong place inside `.codyncSheet`, scroll views and the composer (the + menu opened mid-screen on iPhone, 2026-09-30). Each computer has its own marketplace; its header names the computer and, with several online, switches between them. A new bot's editor on iPhone has a Computer dropdown listing every computer in the current account, including computers hidden by the roster filter and offline computers. It remains a dropdown with one computer. Offline choices stay selectable and are labeled; creation waits until the selected computer is online. Switching computers resets the folder, model and connectors that belonged to the old computer.
+Desktop menus (`AnchoredMenu` in `Overlay.tsx`) scroll vertically when their content exceeds 420 points or the available space beside the trigger. Menus open toward the side with more vertical room; short lists keep their content height. Menu width is capped at 320 points and constrained to the window, and long option titles remain available through help text. This applies to Agent, Model, and other choice menus on the desktop. On iOS every menu is the system one: `DropdownMenu` and `ChoicePicker` present the native `Menu` (choices as checkmarked toggles) and `.contextActions` the native `contextMenu` (reactions as a palette row), because an overlay anchored by global frame lands in the wrong place inside `.codyncSheet`, scroll views and the composer (the + menu opened mid-screen on iPhone, 2026-09-30). Each computer has its own marketplace; its header names the computer and, with several online, switches between them. With more than one computer that can take a bot, the New bot sheet on iPhone has a Computer dropdown listing them (every computer in the current account that doesn't need an update, including computers hidden by the roster filter and offline computers). Offline choices stay selectable and are labeled; creation waits until the selected computer is online.
## Reading conversations
diff --git a/docs/features/bot-workspaces.md b/docs/features/bot-workspaces.md
index ca7183d6..4e5c3047 100644
--- a/docs/features/bot-workspaces.md
+++ b/docs/features/bot-workspaces.md
@@ -1,6 +1,6 @@
# Bot workspaces
-New agent bots get a personal, persistent workspace automatically. Creating a bot does not require choosing a project. An omitted or empty `cwd` in `createBot` allocates `<CODYNC_HOME>/bots/<bot-id>/workspace` (normally `~/.codync/bots/<bot-id>/workspace`). Groups do not allocate folders.
+New agent bots get a personal, persistent workspace automatically. Creating a bot does not require choosing a project. An omitted or empty `cwd` in `createBot` allocates `<CODYNC_HOME>/bots/<bot-id>/workspace` (normally `~/.codync/bots/<bot-id>/workspace`). Groups do not allocate folders. An omitted or empty `backend` gets Claude when it runs on the computer, else the first runnable agent Codync knows (the terminal UI relies on this; the apps still pick it themselves for older hosts), and omitted `connectors`/`skills` turn on every installed one.
The host persists the resolved absolute directory in `cwd` and exposes `managedWorkspace` in bot responses. Empty `cwd` in `updateBot` selects the same bot's personal workspace again. Existing explicit project directories remain unchanged, must already exist, and can still be selected in settings. Templates for personal bots send an empty cwd so a new bot gets its own directory.
diff --git a/docs/features/file-attachments.md b/docs/features/file-attachments.md
index 6572b03c..09d29dc7 100644
--- a/docs/features/file-attachments.md
+++ b/docs/features/file-attachments.md
@@ -8,8 +8,8 @@ Files travel in both directions: users attach inputs, and bots explicitly share
(`apps/desktop/src/renderer/views/thread/Composer.tsx`); on the iPhone through Paste in the
+ menu.
HEIC/TIFF/BMP become JPEG (`OutgoingFile.prepared`, `Thread/Attachments.swift`). Picked files show as chips above
- the text and can be removed; a message can be files only. Not in group chats (a group has no
- folder of its own). Up to 100 MB per file.
+ the text and can be removed; a message can be files only. Group chats take files too: they're
+ kept in the group's uploads folder and listed to each member under the message. Up to 100 MB per file.
- Upload: `upload {botId, uploadId, name, offset, data (base64), done}`, 384 KiB per call so each
stays under the channel's 1 MiB message limit. A repeated chunk is accepted (retry); anything out
of order is refused. Then `send {…, attachments: [uploadId]}`; the text may be empty.
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index b5ac7db9..aea9c974 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -29,14 +29,14 @@ Registry-backed package connectors follow their upstream release. The host check
## Commands
-Typing `/` at the start of a message to a bot (desktop, iPhone, terminal; not in a group, where each member has its own agent and skills) lists that bot's commands, filtered by what follows the `/` (a command's name or title): the built-in ones first, then the skills the bot has on. Each row shows an icon, the title and what it does. The list floats above the box on the desktop (↑/↓ move the highlight, Tab or Return picks it, Escape hides the list until the draft changes, hover and click work too), sits inline above the box on the iPhone (a tap picks; it isn't a menu, so the system-menu rule doesn't apply), and is the highlighted list over the transcript in the terminal (↑/↓, Tab or ↵).
+Typing `/` at the start of a message to a bot (desktop, iPhone, Android, terminal) lists that bot's commands, filtered by what follows the `/` (a command's name or title): the built-in ones first, then the skills the bot has on. A group chat lists its members' commands the same way: Fast mode for every member that offers it (on once all of them are; picking it turns each member's own Fast mode on or back off, so it also applies in their own chats), then every skill one of them has on. A `/skill …` message in a group reaches each member that has the skill on as "read this skill first"; the others read it as typed. Each row shows an icon, the title and what it does. The list floats above the box on the desktop (↑/↓ move the highlight, Tab or Return picks it, Escape hides the list until the draft changes, hover and click work too), sits inline above the box on the iPhone (a tap picks; it isn't a menu, so the system-menu rule doesn't apply), and is the highlighted list over the transcript in the terminal (↑/↓, Tab or ↵).
| Command | Title | Does |
| --- | --- | --- |
| `/fast` | Fast mode | Switches [Fast mode](#fast-mode) with `updateBot`; listed only while the bot offers it. Its detail says what picking it does, or why the agent refused it (warning color). |
| `/<skill id>` | the skill's name | Fills in `/<skill id> ` for the rest of the message. |
-Picking a built-in command, or sending a message that is just one (`/fast`), runs it in the client and clears the box; nothing reaches the agent. Return on a skill whose name is already typed out sends the message. The host sees a message starting with `/<id of a skill the bot has on>` and hands the agent `[Codync: the user picked the "<name>" skill for this message. Read <path> first and follow it.]` followed by the rest of the message; the chat keeps the text as typed. Any other `/command`, including `/fast` for a bot without Fast mode on offer, reaches the agent unchanged, so its own commands keep working. Clients list skills and load skill instructions only from hosts 2.14.1 and newer.
+Picking a built-in command, or sending a message that is just one (`/fast`), runs it in the client and clears the box; nothing reaches the agent. Return on a skill whose name is already typed out sends the message. The host sees a message starting with `/<id of a skill the bot has on>` and hands the agent `[Codync: the user picked the "<name>" skill for this message. Read <path> first and follow it.]` followed by the rest of the message; the chat keeps the text as typed. Any other `/command`, including `/fast` for a bot without Fast mode on offer, reaches the agent unchanged, so its own commands keep working. Clients list skills and load skill instructions only from hosts 2.14.1 and newer, and list skills in a group only from hosts 2.20.1 and newer.
## Sign-in for remote connectors (`host/src/market/oauth.rs`)
@@ -84,7 +84,7 @@ The bot's runtime carries what the agent says (`fastModeSupport`, `fastModeIssue
`offered` and `unsupported` are kept across host restarts (`fast-mode.<bot>` in the kv store); a refusal isn't, so a new host asks again.
-Clients show Fast mode for an agent bot unless its runtime says `unsupported` (an `unknown` bot may offer it; its first session settles it), and always while it's on (so it can be turned off); never for a group:
+Clients show Fast mode for an agent bot unless its runtime says `unsupported` (an `unknown` bot may offer it; its first session settles it), and always while it's on (so it can be turned off). A group has no Fast mode of its own: its `/fast` sets its members' (see [commands](#commands)). It shows in:
- Composer: the `/fast` [command](#commands), not a button. The terminal UI also shows `⚡ fast` or `⚡ refused` in the chat header.
- Bot settings: a Fast mode switch row under Model when the agent's model list offers it (never for a custom command), when the bot's own sessions do, or while it's on. While refused, its detail gives the reason. The terminal UI form always lists the field and notes when the agent doesn't offer it.
diff --git a/host/src/api/bots.rs b/host/src/api/bots.rs
index 42c865e9..48417313 100644
--- a/host/src/api/bots.rs
+++ b/host/src/api/bots.rs
@@ -85,6 +85,11 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
if b["skills"].is_null() && b["kind"] != "group" {
b["skills"] = json!(market::skills(&hub.store).into_iter().map(|s| s.id).collect::<Vec<_>>());
}
+ // And the agent, when the client names none.
+ if b["backend"].as_str().is_none_or(str::is_empty) && b["kind"] != "group" {
+ let agents = tokio::task::spawn_blocking(crate::agent::backends::list).await?;
+ b["backend"] = default_backend(&agents).into();
+ }
let cfg: BotConfig = serde_json::from_value(b).context("invalid bot")?;
let hub = hub.clone();
json!({"bot": tokio::task::spawn_blocking(move || hub.create_bot(cfg)).await??})
@@ -175,8 +180,6 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
attachments.push(crate::chat::uploads::resolve(&root, id)?.1);
}
}
- // `/skill …` reaches the agent as "read this skill first"; the chat keeps what was typed.
- let prompt = crate::chat::prompt::of_message(&hub.store, &row.config, text, &attachments);
let turn = hub.store.max_turn(bot) + 1;
// A group has no agent of its own to queue behind: its message is simply sent.
let status = if row.config.is_group() { "sent" } else { "queued" };
@@ -202,8 +205,12 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
tracing::warn!(%error, bot, "couldn't mark bot read after send");
}
if row.config.is_group() {
+ // Each member reads it in its room prompt (`chat::group`).
crate::chat::group::start(hub, &row.config, lane);
} else {
+ // `/skill …` reaches the agent as "read this skill first"; the chat keeps what was typed.
+ let root = crate::chat::uploads::root(&row.config);
+ let prompt = crate::chat::prompt::of_message(&hub.store, &row.config.skills, &root, text, &attachments);
hub.send_cmd(bot, Cmd::Send { lane, entry_id: e.id.clone(), text: prompt })?;
}
json!({"entry": e})
@@ -249,3 +256,31 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
_ => return Ok(ControlFlow::Continue(b)),
}))
}
+
+/// A new bot's agent (`agents` as `backends::list` gives them): Claude when it runs here, else the
+/// first one Codync knows that does. A registry agent nobody chose is never the default.
+fn default_backend(agents: &[Value]) -> &str {
+ let runnable = || agents.iter().filter(|a| a["available"] == true);
+ if runnable().any(|a| a["id"] == "claude") {
+ return "claude";
+ }
+ runnable().find(|a| a["curated"] == true).and_then(|a| a["id"].as_str()).unwrap_or("claude")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_default_agent_is_claude_then_the_first_known_one() {
+ assert_eq!(default_backend(&[]), "claude", "nothing installed");
+ let mut agents = vec![
+ json!({"id": "goose", "available": true, "curated": false}),
+ json!({"id": "codex", "available": true, "curated": true}),
+ json!({"id": "claude", "available": false, "curated": true}),
+ ];
+ assert_eq!(default_backend(&agents), "codex");
+ agents[2]["available"] = true.into();
+ assert_eq!(default_backend(&agents), "claude");
+ }
+}
diff --git a/host/src/chat/group.rs b/host/src/chat/group.rs
index c67e2fe5..51e57b2c 100644
--- a/host/src/chat/group.rs
+++ b/host/src/chat/group.rs
@@ -277,15 +277,13 @@ fn line(hub: &Hub, group: &BotConfig, e: &Entry, me: &BotConfig) -> String {
let text = e.data["text"].as_str().unwrap_or_default();
let reacted = crate::chat::reactions::describe(hub, e);
if e.kind == EntryKind::User.as_str() {
+ // As in the member's own chat (its skills), with the files the group keeps.
let root = crate::chat::uploads::root(group);
- let files: Vec<_> = e.data["attachments"]
- .as_array()
- .into_iter()
- .flatten()
- .filter_map(|a| crate::chat::uploads::path_of(&root, a))
- .collect();
- let files = if files.is_empty() { String::new() } else { crate::chat::uploads::prompt_suffix(&files) };
- return format!("User: {text}{reacted}{files}");
+ let attachments = e.data["attachments"].as_array().map_or(&[][..], Vec::as_slice);
+ return format!(
+ "User: {}{reacted}",
+ crate::chat::prompt::of_message(&hub.store, &me.skills, &root, text, attachments)
+ );
}
let author = e.data["author"].as_str().unwrap_or_default();
let text = crate::agent::acp::truncate(text, LINE_CHARS);
@@ -303,271 +301,4 @@ pub fn is_pass(text: &str) -> bool {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- fn bot(id: &str, name: &str) -> BotConfig {
- serde_json::from_value(json!({"id": id, "name": name, "backend": "claude", "cwd": "/tmp"})).expect("valid bot")
- }
-
- fn said(text: &str) -> Entry {
- Entry {
- id: "e".into(),
- seq: 1,
- bot_id: "g".into(),
- thread_id: None,
- rev: 1,
- kind: "user".into(),
- turn: 1,
- data: json!({"text": text}),
- created_at: 0,
- updated_at: 0,
- }
- }
-
- #[test]
- fn mentions_pick_responders_and_no_mention_means_everyone() {
- let members = [bot("a", "Alice Chen"), bot("b", "Bob"), bot("c", "尼采課")];
- let ids = |m: &[BotConfig], text: &str| -> Vec<String> {
- responders(m, &[said(text)]).into_iter().map(|b| b.id.clone()).collect()
- };
- assert_eq!(ids(&members, "hi all"), ["a", "b", "c"]);
- assert_eq!(ids(&members, "@bob can you look"), ["b"]);
- assert_eq!(ids(&members, "@alicechen and @Alice"), ["a"]);
- assert_eq!(ids(&members, "@尼采課幫我整理"), ["c"], "CJK names can run into the message");
- assert_eq!(ids(&members, "@bobby?"), ["a", "b", "c"], "a longer word isn't a mention");
- assert_eq!(ids(&members, "@all go"), ["a", "b", "c"]);
- }
-
- use crate::api::devices::Caller;
- use crate::hub::BotStatus;
- use std::path::PathBuf;
- use std::time::Duration;
-
- /// A host with agent bots `a` and `b` (the scripted fixture agent) and a group of both.
- struct Room {
- hub: Arc<Hub>,
- dir: PathBuf,
- group: String,
- }
-
- impl Room {
- fn new() -> Self {
- let dir = std::env::temp_dir().join(format!("codync-group-{}", uuid::Uuid::new_v4()));
- std::fs::create_dir_all(&dir).unwrap();
- let store = Store::open(&dir.join("test.db")).unwrap();
- let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
- for id in ["a", "b"] {
- let cwd = dir.join(id);
- std::fs::create_dir_all(&cwd).unwrap();
- let cfg: BotConfig = serde_json::from_value(json!({
- "id": id, "name": id, "backend": "fixture", "cwd": cwd,
- "command": crate::shell::python(&agent), "notify": false,
- }))
- .unwrap();
- store.save_bot(&cfg).unwrap();
- }
- let hub = Hub::new(
- store,
- "test-host".into(),
- crate::remote::identity::Identity::load_or_create(&dir).unwrap(),
- "test-token".into(),
- 19222,
- );
- hub.start().unwrap();
- let group = hub
- .create_bot(
- serde_json::from_value(
- json!({"id": "", "kind": "group", "name": "Crew", "description": "Ship the release", "members": ["a", "b", "a"]}),
- )
- .unwrap(),
- )
- .unwrap();
- let group = group["id"].as_str().unwrap().to_owned();
- Self { hub, dir, group }
- }
-
- async fn send(&self, text: &str, thread: Option<&str>) -> Entry {
- let sent = crate::api::dispatch(
- &self.hub,
- &Caller::Local,
- "send",
- json!({"botId": self.group, "text": text, "threadId": thread}),
- )
- .await
- .unwrap();
- serde_json::from_value::<serde_json::Value>(sent["entry"].clone())
- .ok()
- .and_then(|e| self.hub.store.entry(e["id"].as_str()?))
- .unwrap()
- }
-
- fn replies(&self, lane: &Lane) -> Vec<(String, String)> {
- self.hub
- .store
- .messages_after(lane, 0, 100)
- .unwrap()
- .into_iter()
- .filter(|e| e.kind == "agent")
- .map(|e| (e.data["author"].as_str().unwrap().to_owned(), e.data["text"].as_str().unwrap().to_owned()))
- .collect()
- }
-
- async fn settle(&self) {
- tokio::time::timeout(Duration::from_secs(10), async {
- loop {
- tokio::time::sleep(Duration::from_millis(300)).await;
- let idle = ["a", "b"].iter().all(|b| self.hub.runtime(b).status == BotStatus::Idle);
- if idle && self.hub.bots_json(0).unwrap().iter().all(|b| b["status"] == "idle") {
- break;
- }
- }
- })
- .await
- .expect("room settles");
- }
-
- async fn shutdown(self) {
- self.hub.shutdown().await;
- let _ = std::fs::remove_dir_all(self.dir);
- }
- }
-
- #[tokio::test]
- async fn room_turns_follow_mentions_and_end_when_everyone_passes() {
- let room = Room::new();
- let row = room.hub.store.bot(&room.group).unwrap().unwrap();
- assert_eq!(row.config.members, ["a", "b"], "members are deduplicated");
- let again = room
- .hub
- .create_bot(
- serde_json::from_value(json!({"id": "", "kind": "group", "name": "Dup", "members": ["b", "a"]}))
- .unwrap(),
- )
- .unwrap();
- assert_eq!(again["id"], room.group, "the same bots reopen their group");
-
- let main = Lane::main(&room.group);
- room.send("hello everyone", None).await;
- room.settle().await;
- // `a` answers the user; `b` then sees a bot spoke last and passes; round two is all passes.
- assert_eq!(room.replies(&main), [("a".to_owned(), "reply: group".to_owned())]);
-
- room.send("@b your turn", None).await;
- room.settle().await;
- assert_eq!(room.replies(&main).last().unwrap().0, "b", "only the mentioned bot answers");
- assert_eq!(room.replies(&main).len(), 2);
- let listed = room.hub.bot_value_for_test(&room.group);
- assert_eq!(listed["lastMessage"], "b: reply: group");
- let prompts = std::fs::read_to_string(room.dir.join("a/prompts.jsonl")).unwrap();
- assert!(
- prompts.contains("Ship the release) with the user"),
- "members are told what the room is for: {prompts}"
- );
- // The members' own chats stay private: the room's entries live in the group.
- assert!(room.hub.store.messages_after(&Lane::main("a"), 0, 100).unwrap().is_empty());
- room.shutdown().await;
- }
-
- #[tokio::test]
- async fn threads_stay_out_of_the_main_chat_and_summarize_on_their_root() {
- let room = Room::new();
- let first = room.send("@a start here", None).await;
- room.settle().await;
- room.send("@a in the thread", Some(&first.id)).await;
- room.settle().await;
- let thread = Lane::in_thread(&room.group, &first.id);
- assert_eq!(room.replies(&thread).len(), 1);
- assert_eq!(room.replies(&Lane::main(&room.group)).len(), 1, "the thread's reply isn't in the main chat");
- let summary = room.hub.store.entry(&first.id).unwrap().data["thread"].clone();
- assert_eq!(summary["count"], 2);
- assert_eq!(summary["authors"], json!(["user", "a"]));
-
- // Threads are read on their own (Slack's): reading the main chat leaves the thread's reply unread.
- let unread = || room.hub.bot_value_for_test(&room.group)["unread"].as_i64().unwrap();
- assert_eq!(summary["unread"], 1);
- assert_eq!(unread(), 2, "the main chat's reply and the thread's");
- let mark = |b: serde_json::Value| crate::api::dispatch(&room.hub, &Caller::Local, "markRead", b);
- mark(json!({"botId": room.group})).await.unwrap();
- assert_eq!(unread(), 1);
- mark(json!({"botId": room.group, "threadId": first.id})).await.unwrap();
- assert_eq!(unread(), 0);
- assert_eq!(room.hub.store.entry(&first.id).unwrap().data["thread"]["unread"], 0);
- assert!(mark(json!({"botId": "a", "threadId": first.id})).await.is_err(), "a thread of another chat");
-
- // Reactions toggle, and reacting to a read message doesn't make it unread.
- let reply = room.hub.store.messages_after(&Lane::main(&room.group), 0, 100).unwrap();
- let reply = reply.iter().find(|e| e.kind == "agent" && e.data["final"] == true).unwrap();
- let react = |emoji: &str| {
- crate::api::dispatch(&room.hub, &Caller::Local, "react", json!({"entryId": reply.id, "emoji": emoji}))
- };
- react("👍").await.unwrap();
- let reacted = react("✅").await.unwrap();
- assert_eq!(reacted["entry"]["data"]["reactions"], json!(["👍", "✅"]));
- assert_eq!(unread(), 0);
- let undone = react("👍").await.unwrap();
- assert_eq!(undone["entry"]["data"]["reactions"], json!(["✅"]));
- assert!(react("hi").await.is_err(), "only emoji");
-
- // A thread in a bot's own chat gets a session of its own, told where it branched off.
- let dm = crate::api::dispatch(&room.hub, &Caller::Local, "send", json!({"botId": "b", "text": "main"}))
- .await
- .unwrap();
- room.settle().await;
- let dm_root = dm["entry"]["id"].as_str().unwrap().to_owned();
- crate::api::dispatch(
- &room.hub,
- &Caller::Local,
- "send",
- json!({"botId": "b", "text": "aside", "threadId": dm_root}),
- )
- .await
- .unwrap();
- room.settle().await;
- let prompts = std::fs::read_to_string(room.dir.join("b/prompts.jsonl")).unwrap();
- assert!(prompts.lines().last().unwrap().contains("[Thread]"), "{prompts}");
- let replies = room.hub.store.thread("b", &dm_root, 10).unwrap();
- assert_eq!(replies.iter().filter(|e| e.data["final"] == true).count(), 1);
- assert!(
- crate::api::dispatch(
- &room.hub,
- &Caller::Local,
- "send",
- json!({"botId": "b", "text": "x", "threadId": replies[0].id})
- )
- .await
- .is_err(),
- "threads are flat"
- );
- room.shutdown().await;
- }
-
- #[tokio::test]
- async fn stop_ends_the_room_turn_before_the_next_speaker() {
- let room = Room::new();
- room.send("BLOCK everyone look", None).await;
- let hub = room.hub.clone();
- tokio::time::timeout(Duration::from_secs(10), async {
- while hub.runtime("a").status != BotStatus::Working {
- tokio::time::sleep(Duration::from_millis(20)).await;
- }
- })
- .await
- .expect("a starts");
- crate::api::dispatch(&room.hub, &Caller::Local, "stop", json!({"botId": room.group})).await.unwrap();
- room.settle().await;
- tokio::time::sleep(Duration::from_millis(500)).await;
- assert!(!room.dir.join("b/prompts.jsonl").exists(), "b never got a turn after Stop");
- assert!(room.replies(&Lane::main(&room.group)).iter().all(|(_, t)| t != "reply: group"));
- room.shutdown().await;
- }
-
- #[test]
- fn pass_is_recognized_loosely() {
- for t in ["(pass)", " (pass) ", "\"(pass)\"", "pass.", ""] {
- assert!(is_pass(t), "{t:?}");
- }
- assert!(!is_pass("I'll pass this to Bob"));
- }
-}
+mod tests;
diff --git a/host/src/chat/group/tests.rs b/host/src/chat/group/tests.rs
new file mode 100644
index 00000000..4aaecd26
--- /dev/null
+++ b/host/src/chat/group/tests.rs
@@ -0,0 +1,282 @@
+use super::*;
+use serde_json::json;
+
+fn bot(id: &str, name: &str) -> BotConfig {
+ serde_json::from_value(json!({"id": id, "name": name, "backend": "claude", "cwd": "/tmp"})).expect("valid bot")
+}
+
+fn said(text: &str) -> Entry {
+ Entry {
+ id: "e".into(),
+ seq: 1,
+ bot_id: "g".into(),
+ thread_id: None,
+ rev: 1,
+ kind: "user".into(),
+ turn: 1,
+ data: json!({"text": text}),
+ created_at: 0,
+ updated_at: 0,
+ }
+}
+
+#[test]
+fn mentions_pick_responders_and_no_mention_means_everyone() {
+ let members = [bot("a", "Alice Chen"), bot("b", "Bob"), bot("c", "尼采課")];
+ let ids = |m: &[BotConfig], text: &str| -> Vec<String> {
+ responders(m, &[said(text)]).into_iter().map(|b| b.id.clone()).collect()
+ };
+ assert_eq!(ids(&members, "hi all"), ["a", "b", "c"]);
+ assert_eq!(ids(&members, "@bob can you look"), ["b"]);
+ assert_eq!(ids(&members, "@alicechen and @Alice"), ["a"]);
+ assert_eq!(ids(&members, "@尼采課幫我整理"), ["c"], "CJK names can run into the message");
+ assert_eq!(ids(&members, "@bobby?"), ["a", "b", "c"], "a longer word isn't a mention");
+ assert_eq!(ids(&members, "@all go"), ["a", "b", "c"]);
+}
+
+use crate::api::devices::Caller;
+use crate::hub::BotStatus;
+use std::path::PathBuf;
+use std::time::Duration;
+
+/// A host with agent bots `a` and `b` (the scripted fixture agent) and a group of both.
+struct Room {
+ hub: Arc<Hub>,
+ dir: PathBuf,
+ group: String,
+}
+
+impl Room {
+ fn new() -> Self {
+ let dir = std::env::temp_dir().join(format!("codync-group-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("test.db")).unwrap();
+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
+ for id in ["a", "b"] {
+ let cwd = dir.join(id);
+ std::fs::create_dir_all(&cwd).unwrap();
+ let cfg: BotConfig = serde_json::from_value(json!({
+ "id": id, "name": id, "backend": "fixture", "cwd": cwd,
+ "command": crate::shell::python(&agent), "notify": false,
+ }))
+ .unwrap();
+ store.save_bot(&cfg).unwrap();
+ }
+ let hub = Hub::new(
+ store,
+ "test-host".into(),
+ crate::remote::identity::Identity::load_or_create(&dir).unwrap(),
+ "test-token".into(),
+ 19222,
+ );
+ hub.start().unwrap();
+ let group = hub
+ .create_bot(
+ serde_json::from_value(
+ json!({"id": "", "kind": "group", "name": "Crew", "description": "Ship the release", "members": ["a", "b", "a"]}),
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let group = group["id"].as_str().unwrap().to_owned();
+ Self { hub, dir, group }
+ }
+
+ async fn send(&self, text: &str, thread: Option<&str>) -> Entry {
+ let sent = crate::api::dispatch(
+ &self.hub,
+ &Caller::Local,
+ "send",
+ json!({"botId": self.group, "text": text, "threadId": thread}),
+ )
+ .await
+ .unwrap();
+ serde_json::from_value::<serde_json::Value>(sent["entry"].clone())
+ .ok()
+ .and_then(|e| self.hub.store.entry(e["id"].as_str()?))
+ .unwrap()
+ }
+
+ fn replies(&self, lane: &Lane) -> Vec<(String, String)> {
+ self.hub
+ .store
+ .messages_after(lane, 0, 100)
+ .unwrap()
+ .into_iter()
+ .filter(|e| e.kind == "agent")
+ .map(|e| (e.data["author"].as_str().unwrap().to_owned(), e.data["text"].as_str().unwrap().to_owned()))
+ .collect()
+ }
+
+ async fn settle(&self) {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let idle = ["a", "b"].iter().all(|b| self.hub.runtime(b).status == BotStatus::Idle);
+ if idle && self.hub.bots_json(0).unwrap().iter().all(|b| b["status"] == "idle") {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("room settles");
+ }
+
+ async fn shutdown(self) {
+ self.hub.shutdown().await;
+ let _ = std::fs::remove_dir_all(self.dir);
+ }
+}
+
+#[tokio::test]
+async fn room_turns_follow_mentions_and_end_when_everyone_passes() {
+ let room = Room::new();
+ let row = room.hub.store.bot(&room.group).unwrap().unwrap();
+ assert_eq!(row.config.members, ["a", "b"], "members are deduplicated");
+ let again = room
+ .hub
+ .create_bot(
+ serde_json::from_value(json!({"id": "", "kind": "group", "name": "Dup", "members": ["b", "a"]})).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(again["id"], room.group, "the same bots reopen their group");
+
+ let main = Lane::main(&room.group);
+ room.send("hello everyone", None).await;
+ room.settle().await;
+ // `a` answers the user; `b` then sees a bot spoke last and passes; round two is all passes.
+ assert_eq!(room.replies(&main), [("a".to_owned(), "reply: group".to_owned())]);
+
+ room.send("@b your turn", None).await;
+ room.settle().await;
+ assert_eq!(room.replies(&main).last().unwrap().0, "b", "only the mentioned bot answers");
+ assert_eq!(room.replies(&main).len(), 2);
+ let listed = room.hub.bot_value_for_test(&room.group);
+ assert_eq!(listed["lastMessage"], "b: reply: group");
+ let prompts = std::fs::read_to_string(room.dir.join("a/prompts.jsonl")).unwrap();
+ assert!(prompts.contains("Ship the release) with the user"), "members are told what the room is for: {prompts}");
+ // The members' own chats stay private: the room's entries live in the group.
+ assert!(room.hub.store.messages_after(&Lane::main("a"), 0, 100).unwrap().is_empty());
+ room.shutdown().await;
+}
+
+#[tokio::test]
+async fn a_skill_command_reaches_the_members_that_have_the_skill_on() {
+ let room = Room::new();
+ let pdf = json!([{"id": "pdf", "name": "PDF", "description": "", "source": "custom"}]);
+ room.hub.store.kv_set("skills", &pdf.to_string()).unwrap();
+ let mut a = room.hub.store.bot("a").unwrap().unwrap().config;
+ a.skills = vec!["pdf".into()];
+ room.hub.store.save_bot(&a).unwrap();
+
+ room.send("/pdf merge these", None).await;
+ room.settle().await;
+ let prompts = |id: &str| std::fs::read_to_string(room.dir.join(id).join("prompts.jsonl")).unwrap();
+ assert!(prompts("a").contains(r#"User: [Codync: the user picked the \"PDF\" skill"#), "{}", prompts("a"));
+ assert!(
+ prompts("b").contains("User: /pdf merge these"),
+ "a member without it reads what was typed: {}",
+ prompts("b")
+ );
+ room.shutdown().await;
+}
+
+#[tokio::test]
+async fn threads_stay_out_of_the_main_chat_and_summarize_on_their_root() {
+ let room = Room::new();
+ let first = room.send("@a start here", None).await;
+ room.settle().await;
+ room.send("@a in the thread", Some(&first.id)).await;
+ room.settle().await;
+ let thread = Lane::in_thread(&room.group, &first.id);
+ assert_eq!(room.replies(&thread).len(), 1);
+ assert_eq!(room.replies(&Lane::main(&room.group)).len(), 1, "the thread's reply isn't in the main chat");
+ let summary = room.hub.store.entry(&first.id).unwrap().data["thread"].clone();
+ assert_eq!(summary["count"], 2);
+ assert_eq!(summary["authors"], json!(["user", "a"]));
+
+ // Threads are read on their own (Slack's): reading the main chat leaves the thread's reply unread.
+ let unread = || room.hub.bot_value_for_test(&room.group)["unread"].as_i64().unwrap();
+ assert_eq!(summary["unread"], 1);
+ assert_eq!(unread(), 2, "the main chat's reply and the thread's");
+ let mark = |b: serde_json::Value| crate::api::dispatch(&room.hub, &Caller::Local, "markRead", b);
+ mark(json!({"botId": room.group})).await.unwrap();
+ assert_eq!(unread(), 1);
+ mark(json!({"botId": room.group, "threadId": first.id})).await.unwrap();
+ assert_eq!(unread(), 0);
+ assert_eq!(room.hub.store.entry(&first.id).unwrap().data["thread"]["unread"], 0);
+ assert!(mark(json!({"botId": "a", "threadId": first.id})).await.is_err(), "a thread of another chat");
+
+ // Reactions toggle, and reacting to a read message doesn't make it unread.
+ let reply = room.hub.store.messages_after(&Lane::main(&room.group), 0, 100).unwrap();
+ let reply = reply.iter().find(|e| e.kind == "agent" && e.data["final"] == true).unwrap();
+ let react = |emoji: &str| {
+ crate::api::dispatch(&room.hub, &Caller::Local, "react", json!({"entryId": reply.id, "emoji": emoji}))
+ };
+ react("👍").await.unwrap();
+ let reacted = react("✅").await.unwrap();
+ assert_eq!(reacted["entry"]["data"]["reactions"], json!(["👍", "✅"]));
+ assert_eq!(unread(), 0);
+ let undone = react("👍").await.unwrap();
+ assert_eq!(undone["entry"]["data"]["reactions"], json!(["✅"]));
+ assert!(react("hi").await.is_err(), "only emoji");
+
+ // A thread in a bot's own chat gets a session of its own, told where it branched off.
+ let dm =
+ crate::api::dispatch(&room.hub, &Caller::Local, "send", json!({"botId": "b", "text": "main"})).await.unwrap();
+ room.settle().await;
+ let dm_root = dm["entry"]["id"].as_str().unwrap().to_owned();
+ crate::api::dispatch(
+ &room.hub,
+ &Caller::Local,
+ "send",
+ json!({"botId": "b", "text": "aside", "threadId": dm_root}),
+ )
+ .await
+ .unwrap();
+ room.settle().await;
+ let prompts = std::fs::read_to_string(room.dir.join("b/prompts.jsonl")).unwrap();
+ assert!(prompts.lines().last().unwrap().contains("[Thread]"), "{prompts}");
+ let replies = room.hub.store.thread("b", &dm_root, 10).unwrap();
+ assert_eq!(replies.iter().filter(|e| e.data["final"] == true).count(), 1);
+ assert!(
+ crate::api::dispatch(
+ &room.hub,
+ &Caller::Local,
+ "send",
+ json!({"botId": "b", "text": "x", "threadId": replies[0].id})
+ )
+ .await
+ .is_err(),
+ "threads are flat"
+ );
+ room.shutdown().await;
+}
+
+#[tokio::test]
+async fn stop_ends_the_room_turn_before_the_next_speaker() {
+ let room = Room::new();
+ room.send("BLOCK everyone look", None).await;
+ let hub = room.hub.clone();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while hub.runtime("a").status != BotStatus::Working {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ })
+ .await
+ .expect("a starts");
+ crate::api::dispatch(&room.hub, &Caller::Local, "stop", json!({"botId": room.group})).await.unwrap();
+ room.settle().await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert!(!room.dir.join("b/prompts.jsonl").exists(), "b never got a turn after Stop");
+ assert!(room.replies(&Lane::main(&room.group)).iter().all(|(_, t)| t != "reply: group"));
+ room.shutdown().await;
+}
+
+#[test]
+fn pass_is_recognized_loosely() {
+ for t in ["(pass)", " (pass) ", "\"(pass)\"", "pass.", ""] {
+ assert!(is_pass(t), "{t:?}");
+ }
+ assert!(!is_pass("I'll pass this to Bob"));
+}
diff --git a/host/src/chat/prompt.rs b/host/src/chat/prompt.rs
index 520359fe..41e652ba 100644
--- a/host/src/chat/prompt.rs
+++ b/host/src/chat/prompt.rs
@@ -2,15 +2,15 @@
//! paths of the files attached to it.
use crate::chat::uploads;
-use crate::store::{BotConfig, Store};
+use crate::store::Store;
use serde_json::Value;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
-/// `attachments`: the message's `{id, name}` upload metadata, as saved in the chat.
-pub fn of_message(store: &Store, cfg: &BotConfig, text: &str, attachments: &[Value]) -> String {
- let asked = crate::market::expand_command(store, &cfg.skills, text);
+/// `skills`: the asked bot's skills on. `root`: the chat's uploads (`uploads::root`; a group's
+/// own in a group). `attachments`: the message's `{id, name}` upload metadata, as saved in the chat.
+pub fn of_message(store: &Store, skills: &[String], root: &Path, text: &str, attachments: &[Value]) -> String {
+ let asked = crate::market::expand_command(store, skills, text);
let asked = asked.as_deref().unwrap_or(text);
- let root = uploads::root(cfg);
- let paths: Vec<PathBuf> = attachments.iter().filter_map(|meta| uploads::path_of(&root, meta)).collect();
+ let paths: Vec<PathBuf> = attachments.iter().filter_map(|meta| uploads::path_of(root, meta)).collect();
if paths.is_empty() { asked.to_owned() } else { format!("{asked}{}", uploads::prompt_suffix(&paths)) }
}
diff --git a/host/src/market/requests.rs b/host/src/market/requests.rs
index eff9b604..98711dca 100644
--- a/host/src/market/requests.rs
+++ b/host/src/market/requests.rs
@@ -95,7 +95,8 @@ pub fn agent_signed_in(hub: &Hub, backend: &str) -> Result<()> {
for mut entry in ids.iter().filter_map(Value::as_str).filter_map(|id| hub.store.entry(id)) {
let attachments = entry.data["attachments"].as_array().cloned().unwrap_or_default();
let text = entry.data["text"].as_str().unwrap_or_default();
- let prompt = crate::chat::prompt::of_message(&hub.store, &bot.config, text, &attachments);
+ let root = crate::chat::uploads::root(&bot.config);
+ let prompt = crate::chat::prompt::of_message(&hub.store, &bot.config.skills, &root, text, &attachments);
entry.data["status"] = "queued".into();
hub.set_entry(&entry.id, &entry.data);
let lane = Lane { chat: entry.bot_id.clone(), thread: entry.thread_id.clone() };
diff --git a/host/src/tui/app/analytics.rs b/host/src/tui/app/analytics.rs
index 0856e5be..2cd831e1 100644
--- a/host/src/tui/app/analytics.rs
+++ b/host/src/tui/app/analytics.rs
@@ -64,7 +64,7 @@ impl App {
Overlay::Routines(_) => Some(Screen::Routines),
Overlay::Market(_) => Some(Screen::Marketplace),
Overlay::Help(_) => Some(Screen::Help),
- Overlay::Form(f) if f.bot_id.is_some() => Some(Screen::BotDetails),
+ Overlay::Form(_) => Some(Screen::BotDetails),
Overlay::Group(g) if g.group_id.is_some() => Some(Screen::BotDetails),
_ => None,
});
diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rs
index a7a8c8d9..1368bacc 100644
--- a/host/src/tui/app/events.rs
+++ b/host/src/tui/app/events.rs
@@ -175,6 +175,10 @@ impl App {
f.saving = false;
f.error = Some(e);
}
+ Some(Overlay::NewBot(n)) => {
+ n.saving = false;
+ n.error = Some(e);
+ }
Some(Overlay::Group(g)) => {
g.saving = false;
g.error = Some(e);
@@ -264,10 +268,13 @@ impl App {
}
}
After::Saved => {
- let saved = self.overlays.iter().rposition(|o| matches!(o, Overlay::Form(_) | Overlay::Group(_)));
+ let saved = self
+ .overlays
+ .iter()
+ .rposition(|o| matches!(o, Overlay::Form(_) | Overlay::NewBot(_) | Overlay::Group(_)));
// A new bot or group opens ready to type; an edit goes back to where it was.
let created = saved.is_some_and(|i| match &self.overlays[i] {
- Overlay::Form(f) => f.bot_id.is_none(),
+ Overlay::NewBot(_) => true,
Overlay::Group(g) => g.group_id.is_none(),
_ => false,
});
@@ -295,11 +302,10 @@ impl App {
}
for o in &mut self.overlays {
if let Overlay::Form(f) = o {
- // Connectors and skills start on for a new bot.
if connectors {
- merge_toggles(&mut f.connectors, &self.market.0, f.bot_id.is_none());
+ merge_toggles(&mut f.connectors, &self.market.0);
} else {
- merge_toggles(&mut f.skills, &self.market.1, f.bot_id.is_none());
+ merge_toggles(&mut f.skills, &self.market.1);
}
}
}
diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rs
index 4db74151..b125c2fb 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -1,12 +1,12 @@
-//! The new/edit bot and group chat forms.
+//! The bot settings form and the new/edit group chat form.
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use super::{
- After, AgentPicker, App, Bot, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, SHAPES, Toggle,
- cycle, merge_toggles,
+ After, App, Bot, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, SHAPES, Toggle, cycle,
+ merge_toggles,
};
use crate::tui::manage::Page;
@@ -16,13 +16,6 @@ impl App {
self.call("pairing", json!({}), After::Pairing);
}
- pub(super) fn new_bot(&mut self) {
- if self.backends.is_empty() {
- self.call("hello", json!({}), After::Hello);
- }
- self.overlays.push(Overlay::Agents(AgentPicker { query: Editor::default(), cursor: 0 }));
- }
-
pub(super) fn new_group(&mut self) {
self.overlays.push(Overlay::Group(GroupForm {
group_id: None,
@@ -52,16 +45,17 @@ impl App {
pub(super) fn group_key(&mut self, mut g: GroupForm, k: KeyEvent) -> Option<Overlay> {
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
let n = self.group_candidates(&g.members).len();
+ let about = g.group_id.is_some();
match k.code {
KeyCode::Esc => return None,
KeyCode::Enter => self.save_group(&mut g),
KeyCode::Char('s') if ctrl => self.save_group(&mut g),
- KeyCode::Tab => g.field = g.field.next(),
- KeyCode::BackTab => g.field = g.field.prev(),
- KeyCode::Down if g.field != GroupField::Bots => g.field = g.field.next(),
+ KeyCode::Tab => g.field = g.field.next(about),
+ KeyCode::BackTab => g.field = g.field.prev(about),
+ KeyCode::Down if g.field != GroupField::Bots => g.field = g.field.next(about),
KeyCode::Down => g.cursor = (g.cursor + 1).min(n.saturating_sub(1)),
KeyCode::Up if g.field == GroupField::About => g.field = GroupField::Name,
- KeyCode::Up if g.field == GroupField::Bots && g.cursor == 0 => g.field = GroupField::About,
+ KeyCode::Up if g.field == GroupField::Bots && g.cursor == 0 => g.field = g.field.prev(about),
KeyCode::Up if g.field == GroupField::Bots => g.cursor -= 1,
KeyCode::Char(' ') if g.field == GroupField::Bots => {
let id = self.group_candidates(&g.members).get(g.cursor).map(|b| b.id.clone());
@@ -124,7 +118,7 @@ impl App {
return;
}
let mut f = Form {
- bot_id: Some(b.id.clone()),
+ bot_id: b.id.clone(),
name: Editor::with(&b.name),
instructions: Editor::with(&b.description),
backend: b.backend.clone(),
@@ -145,8 +139,8 @@ impl App {
saving: false,
opened: Value::Null,
};
- merge_toggles(&mut f.connectors, &self.market.0, false);
- merge_toggles(&mut f.skills, &self.market.1, false);
+ merge_toggles(&mut f.connectors, &self.market.0);
+ merge_toggles(&mut f.skills, &self.market.1);
f.opened = f.body();
self.want_models(&b.backend);
self.overlays.push(Overlay::Form(Box::new(f)));
@@ -154,50 +148,8 @@ impl App {
self.call("skills", json!({}), After::Skills);
}
- /// Step 2 of a new bot: name and looks, prefilled, in a personal workspace.
- pub(super) fn new_bot_form(&mut self, backend: String) {
- if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Agents(_))) {
- self.overlays.truncate(i);
- }
- let n = self.bots.len() + usize::try_from(crate::store::now_ms() % 97).unwrap_or(0);
- let name = NAMES[n % NAMES.len()].to_owned();
- let f = Form {
- bot_id: None,
- name: Editor::with(&name),
- instructions: Editor::default(),
- backend,
- model: Editor::default(),
- model_options: (String::new(), BTreeMap::new()),
- fast: false,
- cwd: String::new(),
- auto: true,
- notify: true,
- computer: false,
- color: (n * 7) % COLORS.len(),
- shape: n % SHAPES.len(),
- connectors: self
- .market
- .0
- .iter()
- .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: true })
- .collect(),
- skills: self.market.1.iter().map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: true }).collect(),
- field: 0,
- sub: 0,
- error: None,
- saving: false,
- opened: Value::Null,
- };
- self.want_models(&f.backend);
- self.overlays.push(Overlay::Form(Box::new(f)));
- self.call("connectors", json!({}), After::Connectors);
- self.call("skills", json!({}), After::Skills);
- }
-
pub(super) fn form_key(&mut self, mut f: Box<Form>, k: KeyEvent) -> Option<Overlay> {
- if f.bot_id.is_some()
- && let Some(page) = Page::Settings.step(k)
- {
+ if let Some(page) = Page::Settings.step(k) {
if f.dirty() {
f.error = Some("Save with ^S first, or Esc to drop the changes.".into());
return Some(Overlay::Form(f));
@@ -275,8 +227,7 @@ impl App {
let space = k.code == KeyCode::Char(' ');
match field {
Field::Agent if !space => {
- let ids: Vec<String> =
- self.agent_choices("").iter().filter_map(|b| b["id"].as_str().map(str::to_owned)).collect();
+ let ids = self.agent_choices();
if !ids.is_empty() {
let i = ids.iter().position(|x| *x == f.backend).unwrap_or(0);
f.backend.clone_from(&ids[cycle(i, d, ids.len())]);
@@ -344,20 +295,26 @@ impl App {
if f.saving {
return;
}
- if f.bot_id.is_some() && f.name.text.trim().is_empty() {
+ if f.name.text.trim().is_empty() {
f.error = Some("Give the bot a name.".into());
return;
}
let mut body = f.body();
+ body["id"] = f.bot_id.clone().into();
f.saving = true;
f.error = None;
- match &f.bot_id {
- Some(id) => {
- body["id"] = id.clone().into();
- self.call("updateBot", body, After::Saved);
- }
- None => self.call("createBot", body, After::Saved),
- }
+ self.call("updateBot", body, After::Saved);
+ }
+
+ /// Agents a bot can switch to: runnable ones on this computer first.
+ fn agent_choices(&self) -> Vec<String> {
+ let mut v: Vec<&Value> = self
+ .backends
+ .iter()
+ .filter(|b| b["available"].as_bool().unwrap_or(false) || b["registry"].is_string())
+ .collect();
+ v.sort_by_key(|b| !b["installed"].as_bool().unwrap_or(false));
+ v.iter().filter_map(|b| b["id"].as_str().map(str::to_owned)).collect()
}
}
@@ -389,11 +346,6 @@ impl Form {
}
}
-const NAMES: [&str; 24] = [
- "Ada", "Rex", "Mia", "Sol", "Kit", "Oli", "Ivy", "Max", "Zoe", "Leo", "Ari", "Bea", "Cal", "Dot", "Eli", "Fay",
- "Gus", "Hal", "Ida", "Jin", "Kai", "Lux", "Nia", "Otto",
-];
-
#[cfg(test)]
mod tests {
use super::super::{AgentModel, test_app};
@@ -419,4 +371,34 @@ mod tests {
f.model = Editor::with("other");
assert!(f.model_options().is_none(), "another model starts without settings");
}
+
+ #[test]
+ fn a_new_group_has_no_about_and_an_edited_one_keeps_it() {
+ let mut app = test_app();
+ app.bots.insert("a".into(), Bot::parse(&json!({"id": "a", "name": "Ada"})).expect("a bot"));
+ app.new_group();
+ let Some(Overlay::Group(mut g)) = app.overlays.pop() else { panic!("the group form opens") };
+ let mut fields = vec![];
+ for code in [KeyCode::Tab, KeyCode::Tab, KeyCode::BackTab, KeyCode::Down, KeyCode::Up] {
+ let Some(Overlay::Group(next)) = app.group_key(g, KeyEvent::from(code)) else { panic!("stays open") };
+ g = next;
+ fields.push(g.field);
+ }
+ let (n, b) = (GroupField::Name, GroupField::Bots);
+ assert_eq!(fields, [n, b, n, b, n], "creating skips About");
+ let Some(Overlay::Group(g)) = app.group_key(g, KeyEvent::from(KeyCode::Char('x'))) else { panic!("stays") };
+ assert_eq!(g.name.text, "x");
+ let group = json!({"id": "g", "kind": "group", "name": "Team", "members": ["a"]});
+ app.bots.insert("g".into(), Bot::parse(&group).expect("a group"));
+ app.selected = Some("g".into());
+ app.edit_bot();
+ let Some(Overlay::Group(mut g)) = app.overlays.pop() else { panic!("the group editor opens") };
+ let mut fields = vec![];
+ for _ in 0..3 {
+ let Some(Overlay::Group(next)) = app.group_key(g, KeyEvent::from(KeyCode::Tab)) else { panic!("stays") };
+ g = next;
+ fields.push(g.field);
+ }
+ assert_eq!(fields, [GroupField::About, b, n]);
+ }
}
diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rs
index 57e2a9f3..edcdad2b 100644
--- a/host/src/tui/app/input.rs
+++ b/host/src/tui/app/input.rs
@@ -6,8 +6,8 @@ use serde_json::json;
use super::editor::move_line;
use super::{
- After, App, Click, Confirm, ConfirmAct, Editor, Field, Focus, Goto, GroupField, Kind, Mark, Overlay, PendingSend,
- Status, TraceMode, Width, mismatch_text, page, tilde,
+ After, App, Click, Confirm, ConfirmAct, Editor, Field, Focus, Goto, GroupField, Kind, Mark, NewBotField, Overlay,
+ PendingSend, Status, TraceMode, Width, mismatch_text, page, tilde,
};
impl App {
@@ -36,7 +36,7 @@ impl App {
match self.overlays.last_mut()? {
Overlay::Goto(g) => Some(&mut g.query),
Overlay::Help(e) => Some(e),
- Overlay::Agents(a) => Some(&mut a.query),
+ Overlay::NewBot(n) => (n.field == NewBotField::Name).then_some(&mut n.name),
Overlay::Folder(p) => Some(&mut p.query),
Overlay::Group(g) => match g.field {
GroupField::Name => Some(&mut g.name),
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index f9e02eae..13e85533 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -8,6 +8,7 @@ mod forms;
mod input;
mod model;
mod navigate;
+mod new_bot;
mod overlay_keys;
mod slash;
mod ui;
@@ -17,8 +18,8 @@ pub use exchange::{ConversationRow, Exchange, Item, Outcome, conversation, group
pub use model::{After, AgentModel, Bot, Entry, Kind, Mark, ModelOption, Msg, Status};
pub use slash::SlashAction;
pub use ui::{
- ACTIONS, Action, AgentPicker, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderPicker,
- Form, Goto, GotoItem, GroupField, GroupForm, Hits, NEW_GROUP, Overlay, SHAPES, Toast, Toggle, TraceMode, Width,
+ ACTIONS, Action, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderPicker, Form, Goto,
+ GotoItem, GroupField, GroupForm, Hits, NewBot, NewBotField, Overlay, SHAPES, Toast, Toggle, TraceMode, Width,
};
use serde_json::{Value, json};
@@ -430,11 +431,12 @@ pub(super) fn cycle(i: usize, d: isize, n: usize) -> usize {
usize::try_from((isize::try_from(i).unwrap_or(0) + d).rem_euclid(n)).unwrap_or(0)
}
-fn merge_toggles(have: &mut Vec<Toggle>, all: &[Toggle], on: bool) {
+/// Names the bot's connectors / skills, and lists the installed ones it doesn't use, off.
+fn merge_toggles(have: &mut Vec<Toggle>, all: &[Toggle]) {
for t in all {
match have.iter_mut().find(|h| h.id == t.id) {
Some(h) => h.name.clone_from(&t.name),
- None => have.push(Toggle { id: t.id.clone(), name: t.name.clone(), on }),
+ None => have.push(Toggle { id: t.id.clone(), name: t.name.clone(), on: false }),
}
}
}
diff --git a/host/src/tui/app/new_bot.rs b/host/src/tui/app/new_bot.rs
new file mode 100644
index 00000000..cbcfda84
--- /dev/null
+++ b/host/src/tui/app/new_bot.rs
@@ -0,0 +1,125 @@
+//! The new bot dialog: a name and looks. The agent and everything else take the host's defaults.
+
+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+use serde_json::{Value, json};
+
+use super::{After, App, COLORS, Editor, NewBot, NewBotField, Overlay, SHAPES, cycle};
+
+const ORDER: [NewBotField; 3] = [NewBotField::Name, NewBotField::Color, NewBotField::Shape];
+
+impl App {
+ pub(super) fn new_bot(&mut self) {
+ // A random look, out of every color with every shape.
+ let looks = COLORS.len() * SHAPES.len();
+ let n = usize::try_from(crate::store::now_ms()).unwrap_or(0) % looks;
+ self.overlays.push(Overlay::NewBot(NewBot {
+ name: Editor::default(),
+ color: n % COLORS.len(),
+ shape: n / COLORS.len(),
+ field: NewBotField::Name,
+ error: None,
+ saving: false,
+ }));
+ }
+
+ pub(super) fn new_bot_key(&mut self, mut n: NewBot, k: KeyEvent) -> Option<Overlay> {
+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
+ let step =
+ |f: NewBotField, d: isize| ORDER[cycle(ORDER.iter().position(|o| *o == f).unwrap_or(0), d, ORDER.len())];
+ let d: isize = if k.code == KeyCode::Left { -1 } else { 1 };
+ match (k.code, n.field) {
+ (KeyCode::Esc, _) => return None,
+ (KeyCode::Enter, _) => self.create_bot(&mut n),
+ (KeyCode::Char('s'), _) if ctrl => self.create_bot(&mut n),
+ (KeyCode::Tab | KeyCode::Down, f) => n.field = step(f, 1),
+ (KeyCode::BackTab | KeyCode::Up, f) => n.field = step(f, -1),
+ (KeyCode::Left | KeyCode::Right, NewBotField::Color) => n.color = cycle(n.color, d, COLORS.len()),
+ (KeyCode::Left | KeyCode::Right, NewBotField::Shape) => n.shape = cycle(n.shape, d, SHAPES.len()),
+ (_, NewBotField::Name) => {
+ n.name.key(k);
+ }
+ _ => {}
+ }
+ Some(Overlay::NewBot(n))
+ }
+
+ fn create_bot(&mut self, n: &mut NewBot) {
+ if n.saving {
+ return;
+ }
+ n.saving = true;
+ n.error = None;
+ self.call("createBot", n.body(), After::Saved);
+ }
+}
+
+impl NewBot {
+ /// A personal workspace, automatic approvals, notifications on. The agent, connectors and
+ /// skills are left unset: the host picks the agent and turns on every installed plugin.
+ fn body(&self) -> Value {
+ json!({
+ "name": self.name.text.trim(),
+ "cwd": "",
+ "permission": "auto",
+ "notify": true,
+ "avatarColor": COLORS[self.color],
+ "avatarShape": SHAPES[self.shape],
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::{Msg, test_app};
+ use super::*;
+
+ fn top(app: &mut App) -> NewBot {
+ let Some(Overlay::NewBot(n)) = app.overlays.pop() else { panic!("the new bot dialog is on top") };
+ n
+ }
+
+ #[tokio::test]
+ async fn typing_names_the_bot_and_arrows_change_its_looks() {
+ let mut app = test_app();
+ app.new_bot();
+ let mut n = top(&mut app);
+ assert!(n.name.text.is_empty(), "the host names an unnamed bot");
+ assert_eq!(n.field, NewBotField::Name);
+ let (color, shape) = (n.color, n.shape);
+ for k in [KeyCode::Char('R'), KeyCode::Char('e'), KeyCode::Char('x'), KeyCode::Tab, KeyCode::Right] {
+ let Some(Overlay::NewBot(next)) = app.new_bot_key(n, KeyEvent::from(k)) else { panic!("stays open") };
+ n = next;
+ }
+ assert_eq!(n.name.text, "Rex");
+ assert_eq!((n.field, n.color), (NewBotField::Color, cycle(color, 1, COLORS.len())));
+ for k in [KeyCode::Down, KeyCode::Left] {
+ let Some(Overlay::NewBot(next)) = app.new_bot_key(n, KeyEvent::from(k)) else { panic!("stays open") };
+ n = next;
+ }
+ assert_eq!((n.field, n.shape), (NewBotField::Shape, cycle(shape, -1, SHAPES.len())));
+ let body = n.body();
+ assert_eq!(body["name"], "Rex");
+ assert_eq!(body["avatarShape"], SHAPES[n.shape]);
+ assert!(body["backend"].is_null(), "the host picks the agent");
+ assert!(body["connectors"].is_null() && body["skills"].is_null(), "the host turns every one on");
+ let Some(Overlay::NewBot(n)) = app.new_bot_key(n, KeyEvent::from(KeyCode::Enter)) else { panic!("saving") };
+ assert!(n.saving);
+ }
+
+ #[tokio::test]
+ async fn a_created_bot_opens_and_a_refusal_stays_in_the_dialog() {
+ let mut app = test_app();
+ app.new_bot();
+ if let Some(Overlay::NewBot(n)) = app.overlays.last_mut() {
+ n.saving = true;
+ }
+ app.on_msg(Msg::Reply(After::Saved, Err("No agent".into())));
+ let n = top(&mut app);
+ assert_eq!((n.saving, n.error.as_deref()), (false, Some("No agent")));
+ app.overlays.push(Overlay::NewBot(n));
+ app.on_msg(Msg::Reply(After::Saved, Ok(json!({"bot": {"id": "b", "name": "Rex"}}))));
+ assert!(app.overlays.is_empty());
+ assert_eq!(app.selected.as_deref(), Some("b"));
+ assert!(app.typing);
+ }
+}
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 7854130d..305271bb 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -1,27 +1,15 @@
-//! Keys in the pickers: go-to, actions, agents and folders.
+//! Keys in the pickers: go-to, actions and folders.
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
-use serde_json::{Value, json};
+use serde_json::json;
use super::super::manage::{AnalyticsSheet, Reply};
use super::{
- ACTIONS, Action, After, AgentPicker, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderPicker, Goto, GotoItem,
- NEW_GROUP, Overlay, contains, fuzzy,
+ ACTIONS, Action, After, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderPicker, Goto, GotoItem, Overlay,
+ contains, fuzzy,
};
impl App {
- /// Agents offered for a new bot: runnable ones on this computer first.
- pub fn agent_choices(&self, query: &str) -> Vec<&Value> {
- let mut v: Vec<&Value> = self
- .backends
- .iter()
- .filter(|b| b["available"].as_bool().unwrap_or(false) || b["registry"].is_string())
- .filter(|b| fuzzy(query, &[b["name"].as_str().unwrap_or_default(), b["id"].as_str().unwrap_or_default()]))
- .collect();
- v.sort_by_key(|b| !b["installed"].as_bool().unwrap_or(false));
- v
- }
-
pub fn goto_items(&self, g: &Goto) -> Vec<GotoItem> {
let q = g.query.text.trim();
let want = FILTERS[g.filter].1;
@@ -107,7 +95,7 @@ impl App {
KeyCode::Esc | KeyCode::Char('q') => None,
_ => Some(Overlay::Confirm(c)),
},
- Overlay::Agents(a) => self.agents_key(a, k),
+ Overlay::NewBot(n) => self.new_bot_key(n, k),
Overlay::Folder(p) => self.folder_key(p, k),
Overlay::Form(f) => self.form_key(f, k),
Overlay::Group(g) => self.group_key(g, k),
@@ -174,40 +162,6 @@ impl App {
Some(Overlay::Goto(g))
}
- /// The agent picker's last row, "New group chat", when the filter matches it.
- pub fn agent_group_row(query: &str) -> bool {
- fuzzy(query, &[NEW_GROUP])
- }
-
- fn agents_key(&mut self, mut a: AgentPicker, k: KeyEvent) -> Option<Overlay> {
- let agents = self.agent_choices(&a.query.text).len();
- let n = agents + usize::from(Self::agent_group_row(&a.query.text));
- match k.code {
- KeyCode::Esc => return None,
- KeyCode::Down => a.cursor = (a.cursor + 1).min(n.saturating_sub(1)),
- KeyCode::Up => a.cursor = a.cursor.saturating_sub(1),
- KeyCode::Enter if a.cursor == agents && Self::agent_group_row(&a.query.text) => {
- self.new_group();
- return None;
- }
- KeyCode::Enter => {
- let backend =
- self.agent_choices(&a.query.text).get(a.cursor).and_then(|b| b["id"].as_str()).map(str::to_owned);
- if let Some(backend) = backend {
- self.overlays.push(Overlay::Agents(a));
- self.new_bot_form(backend);
- return None;
- }
- }
- _ => {
- if a.query.key(k) {
- a.cursor = 0;
- }
- }
- }
- Some(Overlay::Agents(a))
- }
-
pub(super) fn open_folder(&mut self, start: &str) {
self.overlays.push(Overlay::Folder(FolderPicker {
path: start.to_owned(),
diff --git a/host/src/tui/app/slash.rs b/host/src/tui/app/slash.rs
index fc6037da..ffc648f1 100644
--- a/host/src/tui/app/slash.rs
+++ b/host/src/tui/app/slash.rs
@@ -1,11 +1,11 @@
//! The composer's `/` commands, listed while the draft is just `/partial`: Fast mode runs here
//! (`updateBot`; a new session is `S`); a skill fills in `/<id> `, which the host turns into "read
-//! this skill first" (`market::expand_command`).
+//! this skill first" (`market::expand_command`). A group offers the same, over its members.
use crossterm::event::{KeyCode, KeyEvent};
use serde_json::json;
-use super::{After, App, Editor};
+use super::{After, App, Bot, Editor};
/// What picking a command does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -35,28 +35,38 @@ impl SlashCommand {
}
impl App {
- /// The selected bot's built-in commands; a group has none.
+ /// The bots the commands reach: the selected bot, or a group's members.
+ fn reached(&self) -> Vec<&Bot> {
+ let Some(bot) = self.bot() else { return vec![] };
+ if bot.group { bot.members.iter().filter_map(|m| self.bots.get(m)).collect() } else { vec![bot] }
+ }
+
+ /// The bots `/fast` sets: those reached that offer Fast mode.
+ fn fast_bots(&self) -> Vec<&Bot> {
+ self.reached().into_iter().filter(|b| b.fast_shown()).collect()
+ }
+
+ /// Fast mode, when the bot (or any member of a group) offers it.
fn built_in(&self) -> Vec<SlashCommand> {
- let Some(bot) = self.bot().filter(|b| !b.group) else { return vec![] };
- let fast = bot.fast_shown().then(|| SlashCommand {
- name: "fast".into(),
- title: "Fast mode".into(),
- detail: bot.fast_detail(),
- action: SlashAction::Fast,
- });
- fast.into_iter().collect()
+ let bots = self.fast_bots();
+ let detail = match bots.as_slice() {
+ [] => return vec![],
+ [bot] if self.bot().is_some_and(|b| !b.group) => bot.fast_detail(),
+ _ => group_fast_detail(&bots),
+ };
+ vec![SlashCommand { name: "fast".into(), title: "Fast mode".into(), detail, action: SlashAction::Fast }]
}
- /// Built-in commands, then the selected bot's skills, whose name or title holds the
- /// `/partial` being typed (none in a group).
+ /// Built-in commands, then the skills the bot (or any member of a group) has on, whose name
+ /// or title holds the `/partial` being typed.
pub fn slash_commands(&self) -> Vec<SlashCommand> {
- let Some(bot) = self.bot().filter(|b| !b.group) else { return vec![] };
let draft = self.draft();
let Some((query, None)) = crate::market::slash_command(&draft.text) else { return vec![] };
let query = query.to_lowercase();
+ let bots = self.reached();
let skills = self.plugins.1.iter().filter_map(|s| {
let id = s["id"].as_str()?;
- bot.skills.iter().any(|on| on == id).then(|| SlashCommand {
+ bots.iter().any(|b| b.skills.iter().any(|on| on == id)).then(|| SlashCommand {
name: id.to_owned(),
title: s["name"].as_str().unwrap_or(id).to_owned(),
detail: s["description"].as_str().unwrap_or_default().to_owned(),
@@ -111,11 +121,15 @@ impl App {
}
fn run_slash(&mut self, command: &SlashCommand) {
- let Some((id, fast)) = self.bot().map(|b| (b.id.clone(), b.fast_mode)) else { return };
let fill = match command.action {
+ // Each bot's own setting, so it holds in its own chat too.
SlashAction::Fast => {
- self.call("updateBot", json!({"id": id, "fastMode": !fast}), After::Nothing);
- self.flash(if fast { "Fast mode off" } else { "Fast mode on" });
+ let bots = self.fast_bots();
+ let on = !bots.is_empty() && bots.iter().all(|b| b.fast_mode);
+ for b in bots {
+ self.call("updateBot", json!({"id": b.id, "fastMode": !on}), After::Nothing);
+ }
+ self.flash(if on { "Fast mode off" } else { "Fast mode on" });
String::new()
}
SlashAction::Skill => format!("/{} ", command.name),
@@ -127,12 +141,23 @@ impl App {
/// Starting a draft with `/` loads the computer's skills again, so the menu is current.
pub(super) fn slash_typed(&self) {
- if self.bot().is_some_and(|b| !b.group) && self.draft().text == "/" {
+ if self.draft().text == "/" {
self.call("skills", json!({}), After::Skills);
}
}
}
+/// A group's Fast mode: on when every member offering it has it on; then the first member whose
+/// agent refused it says why.
+fn group_fast_detail(bots: &[&Bot]) -> String {
+ if !bots.iter().all(|b| b.fast_mode) {
+ return "Turn on for every bot here: faster replies and more usage".into();
+ }
+ bots.iter()
+ .find_map(|b| b.fast_refusal().map(|why| format!("{}: {why}", b.name)))
+ .unwrap_or_else(|| "Turn off for every bot here and return to standard speed".into())
+}
+
#[cfg(test)]
mod tests {
use super::super::{Bot, test_app};
@@ -190,6 +215,40 @@ mod tests {
assert_eq!(app.draft().text, "", "and the draft clears");
}
+ #[tokio::test]
+ async fn a_group_offers_its_members_fast_mode_and_skills() {
+ let mut app = app_with(&json!({"id": "b", "name": "Bea", "skills": ["docx"], "fastModeSupport": "offered"}));
+ let members = [("c", "Cal", json!(["xlsx", "docx"])), ("d", "Dot", json!([]))];
+ for (id, name, skills) in members {
+ let bot = json!({"id": id, "name": name, "skills": skills, "fastModeSupport": "offered"});
+ app.bots.insert(id.into(), Bot::parse(&bot).expect("a bot parses"));
+ }
+ let group = json!({"id": "g", "kind": "group", "members": ["b", "c", "d"]});
+ app.bots.insert("g".into(), Bot::parse(&group).expect("a group parses"));
+ app.selected = Some("g".into());
+ app.drafts.insert("g".into(), super::Editor::with("/"));
+ assert_eq!(names(&app), ["fast", "docx", "xlsx"], "every member's skills, once each");
+ let detail = |app: &super::App| app.slash_commands().remove(0).detail;
+ assert!(detail(&app).starts_with("Turn on for every bot here"));
+ app.bots.get_mut("b").expect("Bea").fast_mode = true;
+ assert!(detail(&app).starts_with("Turn on"), "on only when every member has it on");
+ app.bots.get_mut("d").expect("Dot").fast_support = "unsupported".into();
+ app.bots.get_mut("c").expect("Cal").fast_mode = true;
+ assert!(detail(&app).starts_with("Turn off for every bot here"), "Dot has no Fast mode to count");
+ let cal = app.bots.get_mut("c").expect("Cal");
+ (cal.fast_support, cal.fast_issue) = ("refused".into(), Some("requires extra usage".into()));
+ assert!(detail(&app).starts_with("Cal: The agent turned it off: requires extra usage"));
+ assert!(app.built_in_command("/fast"), "a bare /fast runs in a group too");
+ assert_eq!(app.hint.as_ref().map(|(text, _)| text.as_str()), Some("Fast mode off"));
+ for id in ["b", "c"] {
+ let bot = app.bots.get_mut(id).expect("a member");
+ (bot.fast_mode, bot.fast_support) = (false, "unsupported".into());
+ }
+ app.drafts.insert("g".into(), super::Editor::with("/"));
+ assert_eq!(names(&app), ["docx", "xlsx"], "no member offers Fast mode");
+ assert!(!app.built_in_command("/fast"), "then it reaches the bots as typed");
+ }
+
#[tokio::test]
async fn sending_just_a_built_in_command_runs_it() {
let mut app = app_with(&json!({"id": "b", "name": "Bot", "fastModeSupport": "offered"}));
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index fa1ffb58..97b6b7cf 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -60,8 +60,6 @@ pub enum Action {
Keys,
}
-pub const NEW_GROUP: &str = "New group chat";
-
pub const ACTIONS: [(&str, &str, Action); 12] = [
("New bot…", "n", Action::NewBot),
("New group chat…", "m", Action::NewGroup),
@@ -116,9 +114,22 @@ pub struct Confirm {
pub act: ConfirmAct,
}
-pub struct AgentPicker {
- pub query: Editor,
- pub cursor: usize,
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum NewBotField {
+ Name,
+ Color,
+ Shape,
+}
+
+/// A new bot: a name (optional: the host names it after its first conversations) and its looks.
+/// Everything else takes the defaults and is changed afterwards in Settings.
+pub struct NewBot {
+ pub name: Editor,
+ pub color: usize,
+ pub shape: usize,
+ pub field: NewBotField,
+ pub error: Option<String>,
+ pub saving: bool,
}
#[derive(Clone)]
@@ -184,7 +195,7 @@ pub struct Toggle {
#[allow(clippy::struct_excessive_bools, reason = "independent bot settings and save state")]
pub struct Form {
- pub bot_id: Option<String>,
+ pub bot_id: String,
pub name: Editor,
pub instructions: Editor,
pub backend: String,
@@ -228,16 +239,21 @@ pub enum GroupField {
}
impl GroupField {
- pub(super) fn next(self) -> Self {
+ /// The field after this one; a new group has no About (it is written afterwards, in the editor).
+ pub(super) fn next(self, about: bool) -> Self {
match self {
- Self::Name => Self::About,
- Self::About => Self::Bots,
+ Self::Name if about => Self::About,
+ Self::Name | Self::About => Self::Bots,
Self::Bots => Self::Name,
}
}
- pub(super) fn prev(self) -> Self {
- self.next().next()
+ pub(super) fn prev(self, about: bool) -> Self {
+ match self {
+ Self::Name => Self::Bots,
+ Self::Bots if about => Self::About,
+ Self::About | Self::Bots => Self::Name,
+ }
}
}
@@ -246,7 +262,8 @@ pub struct GroupForm {
/// The group being edited; `None` creates one.
pub group_id: Option<String>,
pub name: Editor,
- /// What the group is for; sent as `description`, shown to its members.
+ /// What the group is for; sent as `description`, shown to its members. Edited only:
+ /// a new group starts without one.
pub about: Editor,
/// Picked bot ids, in the order they were picked.
pub members: Vec<String>,
@@ -260,7 +277,7 @@ pub enum Overlay {
Goto(Goto),
Help(Editor),
Confirm(Confirm),
- Agents(AgentPicker),
+ NewBot(NewBot),
Folder(FolderPicker),
Form(Box<Form>),
Group(GroupForm),
diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rs
index 1fa5df33..2083436d 100644
--- a/host/src/tui/view/chat.rs
+++ b/host/src/tui/view/chat.rs
@@ -116,7 +116,7 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
} else if app.thread.is_some() {
"Reply…".to_owned()
} else if b.group {
- "Message everyone · @ to ask one bot".to_owned()
+ "Ask everyone · @ to ask one bot".to_owned()
} else {
format!("Message {}…", b.name)
};
diff --git a/host/src/tui/view/forms.rs b/host/src/tui/view/forms.rs
index 845e137e..f9d57311 100644
--- a/host/src/tui/view/forms.rs
+++ b/host/src/tui/view/forms.rs
@@ -1,4 +1,4 @@
-//! The new/edit bot and group chat forms.
+//! The bot settings form and the new/edit group chat form.
use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
@@ -16,13 +16,10 @@ use super::style::{FACE, avatar, bot_color, face_style, theme};
pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
let t = theme();
- let r = centered(area, 88, if f.bot_id.is_some() { 34 } else { 32 });
- let title = match &f.bot_id {
- Some(id) => app.bots.get(id).map_or_else(|| f.name.text.clone(), |b| b.name.clone()),
- None => "New bot · 2/2 name and looks".into(),
- };
+ let r = centered(area, 88, 34);
+ let title = app.bots.get(&f.bot_id).map_or_else(|| f.name.text.clone(), |b| b.name.clone());
let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));
- let inner = if f.bot_id.is_some() { page_tabs(buf, inner, Page::Settings) } else { inner };
+ let inner = page_tabs(buf, inner, Page::Settings);
let wide = inner.width >= 70;
let fx = if wide { inner.x + 18 } else { inner.x };
if wide {
@@ -85,11 +82,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
}
};
match field {
- Field::Name => {
- // A new bot may stay unnamed: the host names it after its first conversations.
- let placeholder = if f.bot_id.is_none() { "Named after a few chats" } else { "Name" };
- text_field(buf, &f.name, placeholder, y);
- }
+ Field::Name => text_field(buf, &f.name, "Name", y),
Field::Instructions => {
text_field(buf, &f.instructions, "e.g. Reviews PRs. Never pushes without asking.", y);
}
@@ -112,7 +105,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
Field::Fast => {
let s = if f.fast { "◉ On ○ Off" } else { "○ On ◉ Off" };
// Known once the agent's model list loads, or once the bot's own sessions say.
- let saved = f.bot_id.as_ref().and_then(|id| app.bots.get(id)).filter(|b| b.backend == f.backend);
+ let saved = app.bots.get(&f.bot_id).filter(|b| b.backend == f.backend);
let offered = match app.models.get(&f.backend) {
_ if saved.is_some_and(super::super::app::Bot::fast_shown) => "",
Some(Some(_)) if !app.fast_mode.contains(&f.backend) => " · not offered by this agent",
@@ -210,7 +203,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
if let Some(e) = &f.error {
put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));
} else if f.current() == Field::Fast {
- let refusal = f.bot_id.as_ref().and_then(|id| app.bots.get(id)).and_then(super::super::app::Bot::fast_refusal);
+ let refusal = app.bots.get(&f.bot_id).and_then(super::super::app::Bot::fast_refusal);
let (line, style) = match refusal {
Some(why) => (why, t.amber),
None => ("Faster replies for more usage, on models that offer it (Claude Code, Codex)".to_owned(), t.dim),
@@ -226,13 +219,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
t.dim.patch(t.panel),
);
}
- let save = if f.saving {
- " … Saving "
- } else if f.bot_id.is_some() {
- " ↵ Save "
- } else {
- " ↵ Create "
- };
+ let save = if f.saving { " … Saving " } else { " ↵ Save " };
let x = put(buf, inner.x, by, 14, save, t.btn_primary) + 1;
put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));
let hint = match f.current() {
@@ -254,14 +241,17 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
pub(super) fn group_view(buf: &mut Buffer, area: Rect, app: &App, g: &GroupForm) {
let t = theme();
let bots = app.group_candidates(&g.members);
- let r = centered(area, 74, u(bots.len() + 12).max(16));
- let title = if g.group_id.is_some() { "Group chat" } else { "New group chat" };
+ // A new group gets its About afterwards, in the editor.
+ let about = g.group_id.is_some();
+ let top = if about { 4 } else { 2 };
+ let r = centered(area, 74, u(bots.len() + 8).saturating_add(top).max(16));
+ let title = if about { "Group chat" } else { "New group chat" };
let inner = frame_box(buf, r, t.text, t.panel, Some((title, t.text)));
let label = |on: bool| if on { t.bold } else { t.secondary }.patch(t.panel);
let on_bots = g.field == GroupField::Bots;
put(buf, inner.x, inner.y, 8, "Name", label(g.field == GroupField::Name));
let default = app.group_default_name(&g.members);
- let placeholder = if default.is_empty() { "Name" } else { default.as_str() };
+ let placeholder = if default.is_empty() { "Name your group" } else { default.as_str() };
input_line(
buf,
Rect::new(inner.x + 8, inner.y, inner.width.saturating_sub(8), 1),
@@ -271,23 +261,25 @@ pub(super) fn group_view(buf: &mut Buffer, area: Rect, app: &App, g: &GroupForm)
g.field == GroupField::Name,
false,
);
- put(buf, inner.x, inner.y + 2, 8, "About", label(g.field == GroupField::About));
- input_line(
- buf,
- Rect::new(inner.x + 8, inner.y + 2, inner.width.saturating_sub(8), 1),
- inner.y + 2,
- &g.about,
- "What this group works on (optional)",
- g.field == GroupField::About,
- false,
- );
- put(buf, inner.x, inner.y + 4, inner.width, &format!("Bots · {}", g.members.len()), label(on_bots));
- let list_h = usize::from(inner.height.saturating_sub(9));
+ if about {
+ put(buf, inner.x, inner.y + 2, 8, "About", label(g.field == GroupField::About));
+ input_line(
+ buf,
+ Rect::new(inner.x + 8, inner.y + 2, inner.width.saturating_sub(8), 1),
+ inner.y + 2,
+ &g.about,
+ "What this group works on (optional)",
+ g.field == GroupField::About,
+ false,
+ );
+ }
+ put(buf, inner.x, inner.y + top, inner.width, &format!("Bots · {}", g.members.len()), label(on_bots));
+ let list_h = usize::from(inner.height.saturating_sub(top + 5));
let off = g.cursor.saturating_sub(list_h.saturating_sub(1));
if bots.is_empty() {
- put(buf, inner.x, inner.y + 5, inner.width, "No bots yet. n creates one.", t.dim.patch(t.panel));
+ put(buf, inner.x, inner.y + top + 1, inner.width, "No bots yet. Create a bot first.", t.dim.patch(t.panel));
}
- for (y, (i, b)) in (inner.y + 5..).zip(bots.iter().enumerate().skip(off).take(list_h)) {
+ for (y, (i, b)) in (inner.y + top + 1..).zip(bots.iter().enumerate().skip(off).take(list_h)) {
let sel = on_bots && i == g.cursor;
let base = if sel { t.sel } else { t.panel };
if sel {
@@ -319,7 +311,7 @@ pub(super) fn group_view(buf: &mut Buffer, area: Rect, app: &App, g: &GroupForm)
}
let save = if g.saving {
" … Saving "
- } else if g.group_id.is_some() {
+ } else if about {
" ↵ Save "
} else {
" ↵ Create "
diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rs
index 9cdc4612..72a99a5c 100644
--- a/host/src/tui/view/mod.rs
+++ b/host/src/tui/view/mod.rs
@@ -14,6 +14,7 @@ mod computer_access;
mod forms;
mod goto;
mod help;
+mod new_bot;
mod overlay;
mod pair;
mod permission;
diff --git a/host/src/tui/view/new_bot.rs b/host/src/tui/view/new_bot.rs
new file mode 100644
index 00000000..a2625335
--- /dev/null
+++ b/host/src/tui/view/new_bot.rs
@@ -0,0 +1,57 @@
+//! The new bot dialog: the bot's face in its color, a name, then color and shape.
+
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::{Modifier, Style};
+
+use super::super::app::{COLORS, NewBot, NewBotField, SHAPES};
+use super::super::md::width as w;
+use super::buffer::{centered, frame_box, put, rput, u};
+use super::overlay::input_line;
+use super::style::{FACE, bot_color, face_style, theme};
+
+/// "Color " + "‹ " + the swatches (2 cells and a gap each) + "›".
+const LOOKS_W: usize = 6 + 2 + COLORS.len() * 3 + 1;
+
+pub(super) fn new_bot_view(buf: &mut Buffer, area: Rect, n: &NewBot) {
+ let t = theme();
+ let r = centered(area, 56, 18);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("New bot", t.text)));
+ let mid = |width: usize| inner.x + inner.width.saturating_sub(u(width)) / 2;
+ for (y, row) in (inner.y + 1..).zip(FACE) {
+ put(buf, mid(w(row)), y, inner.width, row, face_style(COLORS[n.color]).patch(t.panel));
+ }
+ // Left empty, the host names the bot after its first conversations.
+ let placeholder = "Name your bot";
+ let shown = if n.name.text.is_empty() { placeholder } else { n.name.text.as_str() };
+ let name_w = u(w(shown) + 1).min(inner.width);
+ let y = inner.y + 9;
+ let field = Rect::new(mid(usize::from(name_w)), y, name_w, 1);
+ input_line(buf, field, y, &n.name, placeholder, n.field == NewBotField::Name, false);
+ // ‹ › mark the row the arrows change.
+ let label = |f: NewBotField| if n.field == f { t.bold } else { t.secondary }.patch(t.panel);
+ let on_color = n.field == NewBotField::Color;
+ let x0 = mid(LOOKS_W);
+ let y = inner.y + 11;
+ let mut x = put(buf, x0, y, 6, "Color ", label(NewBotField::Color));
+ x = put(buf, x, y, 2, if on_color { "‹ " } else { " " }, label(NewBotField::Color));
+ for (ci, c) in COLORS.iter().enumerate() {
+ let s = if t.color { Style::default().bg(bot_color(c)) } else { t.text };
+ let mark = if ci == n.color { "◆ " } else { " " };
+ x = put(buf, x, y, 2, mark, s.fg(t.on_color)) + 1;
+ }
+ put(buf, x, y, 1, if on_color { "›" } else { " " }, label(NewBotField::Color));
+ let shape = SHAPES[n.shape];
+ let shape = if n.field == NewBotField::Shape { format!("‹ {shape} ›") } else { format!(" {shape}") };
+ let x = put(buf, x0, y + 1, 6, "Shape ", label(NewBotField::Shape));
+ put(buf, x, y + 1, u(w(&shape)), &shape, label(NewBotField::Shape));
+ let by = inner.bottom() - 1;
+ if let Some(e) = &n.error {
+ put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));
+ }
+ let create = if n.saving { " … Saving " } else { " ↵ Create " };
+ let x = put(buf, inner.x, by, 14, create, t.btn_primary) + 1;
+ put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));
+ let hint = if n.field == NewBotField::Name { "tab color and shape" } else { "←→ change · tab next" };
+ rput(buf, inner.right(), by, hint, t.dim.patch(t.panel));
+}
diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rs
index bc6f7344..0d5abced 100644
--- a/host/src/tui/view/overlay.rs
+++ b/host/src/tui/view/overlay.rs
@@ -5,12 +5,13 @@ use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Modifier, Style};
-use super::super::app::{App, Editor, NEW_GROUP, Overlay, tilde};
+use super::super::app::{App, Editor, Overlay, tilde};
use super::super::md::{truncate, width as w};
use super::buffer::{centered, dim_all, frame_box, put, restyle, rput, u};
use super::forms::{form_view, group_view};
use super::goto::goto;
use super::help::help;
+use super::new_bot::new_bot_view;
use super::pair::pair;
use super::set_cursor;
use super::style::{rgb, theme};
@@ -54,75 +55,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay
let x = put(buf, inner.x, inner.y + 4, 30, &format!(" ↵ {} ", c.button), danger) + 1;
put(buf, x, inner.y + 4, 14, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));
}
- Overlay::Agents(a) => {
- let t = theme();
- let choices: Vec<serde_json::Value> = app.agent_choices(&a.query.text).into_iter().cloned().collect();
- let group_row = App::agent_group_row(&a.query.text);
- let h = u(choices.len() + usize::from(group_row) + 8).min(area.height.saturating_sub(2)).max(10);
- let r = centered(area, 74, h);
- let inner = frame_box(buf, r, t.text, t.panel, Some(("New bot · 1/2 agent", t.text)));
- field_line(buf, inner, inner.y, &a.query, "type to filter", true);
- let list_h = usize::from(inner.height.saturating_sub(4));
- let off = a.cursor.saturating_sub(list_h.saturating_sub(1));
- if choices.is_empty() && !group_row {
- put(
- buf,
- inner.x,
- inner.y + 2,
- inner.width,
- if app.backends.is_empty() { "Loading agents…" } else { "No agent matches" },
- t.dim.patch(t.panel),
- );
- }
- for (y, (i, c)) in (inner.y + 2..).zip(choices.iter().enumerate().skip(off).take(list_h)) {
- let row = Rect::new(inner.x - 1, y, inner.width + 2, 1);
- let sel = i == a.cursor;
- if sel {
- restyle(buf, row, t.sel);
- }
- let installed = c["installed"].as_bool().unwrap_or(false);
- let base = if sel { t.sel } else { t.panel };
- put(
- buf,
- inner.x,
- y,
- 2,
- if installed { "✓" } else { "↓" },
- if installed { t.green } else { t.dim }.patch(base),
- );
- put(
- buf,
- inner.x + 2,
- y,
- inner.width / 2,
- c["name"].as_str().unwrap_or_default(),
- if sel { t.bold } else { t.text }.patch(base),
- );
- let how = if installed { "on this computer".to_owned() } else { "fetched on first use".to_owned() };
- rput(buf, inner.right(), y, &how, t.dim.patch(base));
- }
- // Last row: a group chat instead of a bot.
- let gi = choices.len();
- if group_row && gi >= off && gi < off + list_h {
- let y = inner.y + 2 + u(gi - off);
- let sel = gi == a.cursor;
- let base = if sel { t.sel } else { t.panel };
- if sel {
- restyle(buf, Rect::new(inner.x - 1, y, inner.width + 2, 1), t.sel);
- }
- put(buf, inner.x, y, 2, "+", t.secondary.patch(base));
- put(buf, inner.x + 2, y, inner.width / 2, NEW_GROUP, if sel { t.bold } else { t.text }.patch(base));
- rput(buf, inner.right(), y, "several bots, one chat", t.dim.patch(base));
- }
- put(
- buf,
- inner.x,
- inner.bottom() - 1,
- inner.width,
- "↵ next: folder ↑↓ move esc cancel",
- t.dim.patch(t.panel),
- );
- }
+ Overlay::NewBot(n) => new_bot_view(buf, area, n),
Overlay::Folder(p) => {
let t = theme();
let matches = App::folder_matches(p);