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: roster sections on every client (#202)

Hakan Tapan57ab28d210a6
diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxproj
index 5cd6e89a..ffa06fbb 100644
--- a/apps/Codync.xcodeproj/project.pbxproj
+++ b/apps/Codync.xcodeproj/project.pbxproj
@@ -46,6 +46,7 @@
7E5F670CFFA0E4373F44DB41 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31BFDAD6DCCE1CC98642ACDD /* AccountSession.swift */; };
8157F3E9CFB390CBCB1A9F9A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4815867922559696EDCA47FD /* Assets.xcassets */; };
8517F8FC5AFAFF1527369829 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6932F782C1B87C9608359A6 /* NotificationService.swift */; };
+ 864E7C2DC7600E9DA58E2BD6 /* RosterSectionHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C62636FD789C49762696A3 /* RosterSectionHeader.swift */; };
89CA3972915769DBA315876F /* Push.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3BF4D3B82FE8274F610C703 /* Push.swift */; };
8B5CCF45DEE9149BB11333C4 /* CodyncBot-pebble-Ink.ttf in Resources */ = {isa = PBXBuildFile; fileRef = F4375A206703EC65F0D15BD6 /* CodyncBot-pebble-Ink.ttf */; };
8B78A34695AD94109AE82C0F /* CodyncBot-blob-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = D0E552136D473567E0C25ED4 /* CodyncBot-blob-Tint.ttf */; };
@@ -55,6 +56,8 @@
974A5D8D89758A61E7D8D1B6 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BA06CEE98A7CDED62678522 /* Input.swift */; };
980C29719BDE2E874C9AD53A /* CodyncBot-wedge-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = C3BB9F034194450254CE14EC /* CodyncBot-wedge-Tint.ttf */; };
9BBB2FAEDBD35A83EAB02981 /* AccountSwitcherView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */; };
+ 9C5F3D805E170CDF68EA4A19 /* SectionNameDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09B4BF594A570A303880D6E4 /* SectionNameDialog.swift */; };
+ 9E1D40B1216F6D46A615277E /* ComputerSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FB8080D4CB79347C36A7E75 /* ComputerSection.swift */; };
A1B7C7774E7FAF6D45D1BEF8 /* Permissions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FA78A055791BBBA79DF8C8B /* Permissions.swift */; };
AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };
ABE57DA1C72A08A22262AAB1 /* CodyncOrb-Ghost.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 8E783FFF5EC2697C16FA2E1B /* CodyncOrb-Ghost.ttf */; };
@@ -118,12 +121,14 @@
0582B6169BFC36E4BCD51C0D /* BotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotListView.swift; sourceTree = "<group>"; };
0814BD0C30F01A163FBDF896 /* AppearanceSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppearanceSettings.swift; sourceTree = "<group>"; };
0829A4FCADAC108E8C2DB2F1 /* Widgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Widgets.entitlements; sourceTree = "<group>"; };
+ 09B4BF594A570A303880D6E4 /* SectionNameDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SectionNameDialog.swift; sourceTree = "<group>"; };
0A87B0091DAF0E4807D62017 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
0C44BCF971511A5E94D073D5 /* CodyncOrb-Dot.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncOrb-Dot.ttf"; sourceTree = "<group>"; };
120FD9DBA315A6DD543463D8 /* CodyncBot-tablet-Ink.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-tablet-Ink.ttf"; sourceTree = "<group>"; };
1318104275E5BEC47B7088AD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
1BDF6A8F94A945065D4348F8 /* AppIcon.icon */ = {isa = PBXFileReference; path = AppIcon.icon; sourceTree = "<group>"; };
1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
+ 1FB8080D4CB79347C36A7E75 /* ComputerSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerSection.swift; sourceTree = "<group>"; };
1FECC371F3CD98687C0B69FA /* CodyncBot-pebble-Tint.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-pebble-Tint.ttf"; sourceTree = "<group>"; };
203A43D8DF8D3832F95FA837 /* CodyncBot-teardrop-Ink.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-teardrop-Ink.ttf"; sourceTree = "<group>"; };
28B2CB561A43ED9F2F1A4391 /* ScreenHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenHelper.swift; sourceTree = "<group>"; };
@@ -131,6 +136,7 @@
300202AE0BDAB4961D1E4423 /* BotShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotShortcuts.swift; sourceTree = "<group>"; };
305DDCC18BB8AA6CD9D19CEF /* WidgetPreviews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreviews.swift; sourceTree = "<group>"; };
31BFDAD6DCCE1CC98642ACDD /* AccountSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSession.swift; sourceTree = "<group>"; };
+ 36C62636FD789C49762696A3 /* RosterSectionHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RosterSectionHeader.swift; sourceTree = "<group>"; };
3F4C4D3B64C608AEF2F85F91 /* Kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Kit; path = ios/Kit; sourceTree = SOURCE_ROOT; };
445DB0A03CFBB5CC7A830139 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
4815867922559696EDCA47FD /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -309,6 +315,7 @@
DD3DE9A4EEB369C4F75C9448 /* ActivityGalleryView.swift */,
0814BD0C30F01A163FBDF896 /* AppearanceSettings.swift */,
0582B6169BFC36E4BCD51C0D /* BotListView.swift */,
+ 1FB8080D4CB79347C36A7E75 /* ComputerSection.swift */,
6BC00039A6C2C0D3F39A5F67 /* ComputerStatus.swift */,
E3E35BCE6E7037B78D22F927 /* ComputersView.swift */,
73D324231A9BCE79C84C0403 /* LanguageSettings.swift */,
@@ -316,7 +323,9 @@
ECD0B4EA4BBA2BB2826C4362 /* PairingView.swift */,
BB1B021A5F4CCAA3D180C2CB /* ReviewInvitationModifier.swift */,
B6E13F8EA6C7B0DA4D899FEE /* RootView.swift */,
+ 36C62636FD789C49762696A3 /* RosterSectionHeader.swift */,
B708DF60FB00E1724260BCD2 /* RowLabel.swift */,
+ 09B4BF594A570A303880D6E4 /* SectionNameDialog.swift */,
0A87B0091DAF0E4807D62017 /* SettingsView.swift */,
9AD0BD16672E128A4F26272B /* SignInButtons.swift */,
CFEBE2E6A9D0AF0A0D89FFE7 /* UsageView.swift */,
@@ -699,6 +708,7 @@
E0D116BF893B81AEC0D2135A /* BotShortcuts.swift in Sources */,
AF04355DFF3452C3ED0CA641 /* CallControlIntents.swift in Sources */,
7C20764DC05D499075BC5E8C /* CodyncApp.swift in Sources */,
+ 9E1D40B1216F6D46A615277E /* ComputerSection.swift in Sources */,
2002C16E427B4E4E7279E1C4 /* ComputerStatus.swift in Sources */,
AC044B31C0B4A68463B9024E /* ComputersView.swift in Sources */,
5A56EF5D36D12ACCEA100642 /* LanguageSettings.swift in Sources */,
@@ -708,7 +718,9 @@
89CA3972915769DBA315876F /* Push.swift in Sources */,
CF8160C37D98BD7C1472CF49 /* ReviewInvitationModifier.swift in Sources */,
0631979397E0D6822747E03A /* RootView.swift in Sources */,
+ 864E7C2DC7600E9DA58E2BD6 /* RosterSectionHeader.swift in Sources */,
1302DAC1A6D9AE9E33654B84 /* RowLabel.swift in Sources */,
+ 9C5F3D805E170CDF68EA4A19 /* SectionNameDialog.swift in Sources */,
BF77DD7946621D8818EDAB9B /* SettingsView.swift in Sources */,
76E77CC8A2B7C74213512FAB /* SignInButtons.swift in Sources */,
684F7F77EECBA0BD95BDD658 /* UsageView.swift in Sources */,
diff --git a/apps/android/README.md b/apps/android/README.md
index ef099fe8..e9e764cc 100644
--- a/apps/android/README.md
+++ b/apps/android/README.md
@@ -76,8 +76,9 @@ current pairing in Computer management before pairing another. Multiple-computer
support is tracked in the checklist. Accounts have separate device keys, mirrors,
files, image caches and composer drafts.
-The roster shows activity, previews, unread counts, groups and pin/hide actions;
-touch and hold a bot, then move it, to reorder (the order syncs through the host). Cached bots remain readable offline and are labeled as saved. An
+The roster shows activity, previews, unread counts, groups, pin/hide actions and sections
+(Move to section in a bot's menu; tap a section's header to fold it on this phone, touch and hold it to rename or remove it; bots in none sit under a "Bots" label);
+touch and hold a bot, then move it, to reorder within its section (the order syncs through the host). Cached bots remain readable offline and are labeled as saved. An
unreachable computer is distinguished from an empty online roster. Chat supports
final replies, Markdown/code, permissions, reactions, quote replies (touch and hold a
message, then Reply), history and Full conversation.
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 2f6dc761..9bf7ba54 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -7,14 +7,10 @@ released version's section; a version without one gets the PRs' "What's New: And
else a generic "Bug fixes and improvements" line. Delete old sections.
-->
-## 2.31.2
+## 2.32.0
### zh-Hant
-- 從手機更新電腦時,電腦重新啟動的期間會顯示「正在更新…」,不會再要你申請訪問。
-- Codex bot 現在拿得到和你 Codex 設定裡同名的聯結器(例如 Notion),不會再看不到它的工具。
-- Codex bot 傳訊息和整理記憶的動作,不會再出現在工作步驟裡。
+- Bot 清單可以分成自己的分組,例如「工作」和「個人」:長按 Bot 選「移到分組」,點分組標題即可收合,收合時會顯示裡面的未讀數。
### en-US
-- While a computer restarts for an update you started from your phone, it shows Updating… instead of asking you for access.
-- Codex bots now get a connector that shares its name with a server in your Codex config, such as Notion, instead of missing its tools.
-- A Codex bot's own messages and memory upkeep no longer show among its working steps.
+- Sort the bot list into your own sections, like Work and Personal: touch and hold a bot and choose Move to section, then tap a section's heading to fold it, with its unread count showing while it's folded.
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
index b9a3c6e2..b0e679df 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
@@ -52,6 +52,10 @@ class AppStore(application: Application) : AndroidViewModel(application) {
internal val transportRequired: Boolean get() = foreground || state.value.voice != null
internal val sends = mutableSetOf<String>()
internal val actions = mutableMapOf<String, Job>()
+ /** The bots as the mirror last had them; the state shows them with [pendingSectionMoves] laid over (`withMoves`). */
+ internal var mirrorBots: List<Bot> = emptyList()
+ /** Section moves shown but not answered yet, oldest first. */
+ internal val pendingSectionMoves = mutableListOf<SectionMove>()
internal var pluginsRefreshAgain = false
internal var widgetOwner: WidgetOwner? = null
/** The host version an undecodable event already made the mirror fetch everything again for. */
@@ -135,6 +139,8 @@ class AppStore(application: Application) : AndroidViewModel(application) {
channel?.close(); channel = null
connectionJob = null; pairingJob = null; graceJob = null
actions.clear(); sends.clear(); downloadLocks.clear(); cloud = null
+ // A cancelled section move never heard back: it would lie over the next mirror for good.
+ pendingSectionMoves.clear(); mirrorBots = emptyList()
pluginsRefreshAgain = false
rewoundFor = null
draftWriter = null; draftBook = null; savedDrafts = emptyMap()
@@ -182,7 +188,8 @@ class AppStore(application: Application) : AndroidViewModel(application) {
withContext(Dispatchers.IO) { retired.forEach(attachments::discard) }
// Like iOS, a screen state this app can't read is a host without remote screen.
val screen = snapshot.screen?.let { runCatching { ScreenState.decode(it) }.getOrNull() }
- mutableState.update { current -> current.copy(bots = snapshot.bots, entries = snapshot.entries,
+ mirrorBots = snapshot.bots
+ mutableState.update { current -> current.copy(bots = withMoves(snapshot.bots, pendingSectionMoves), entries = snapshot.entries,
pending = snapshot.pending, usage = snapshot.usage, screen = screen, mirrorRevision = snapshot.rev,
selectedBot = current.selectedBot?.takeIf { id -> snapshot.bots.any { it.id == id } }) }
if (voiceBinding != null && snapshot.bots.none { it.id == voiceBinding?.botId && !it.deleted }) endVoice("Voice chat ended because its bot was removed.")
@@ -209,8 +216,9 @@ class AppStore(application: Application) : AndroidViewModel(application) {
@Suppress("UNREACHABLE_CODE") error("Unreachable")
}
- internal fun action(key: String, operation: suspend () -> Unit) {
- if (state.value.loading || key in state.value.busy) return
+ /** Runs [operation] as [key], its error shown; not while loading or while [key] still runs. Whether it started. */
+ internal fun action(key: String, operation: suspend () -> Unit): Boolean {
+ if (state.value.loading || key in state.value.busy) return false
mutableState.update { it.copy(busy = it.busy + key, error = null) }
val job = contextScope.launch(start = CoroutineStart.LAZY) {
try { operation() }
@@ -220,6 +228,7 @@ class AppStore(application: Application) : AndroidViewModel(application) {
}
actions[key] = job
job.start()
+ return true
}
internal fun showError(error: Exception) { mutableState.update { it.copy(loading = false, error = error.message ?: "Couldn't complete the action.") } }
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 d30d3810..df603eab 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
@@ -7,19 +7,54 @@ import kotlinx.serialization.json.*
// Bots and groups, their routines, usage, and the host queries the screens make.
-fun AppStore.command(method: String, body: JsonObject = JsonObject(emptyMap()), key: String = method, onSuccess: () -> Unit = {}) = action(key) {
- val active = ready()
- val response = active.call(method, body)
- response.jsonObject["bot"]?.let { value ->
- withContext(Dispatchers.IO) { requireNotNull(database).receive(HostClient.decode(value.jsonObject)) }
- }
- response.jsonObject["entry"]?.let { value ->
- withContext(Dispatchers.IO) { requireNotNull(database).receive(listOf(Entry.decode(value.jsonObject))) }
+/** [onFailure] runs when the computer didn't take it (unreachable or refused, before the error shows) or it never went (still loading, or [key] under way). */
+fun AppStore.command(method: String, body: JsonObject = JsonObject(emptyMap()), key: String = method, onFailure: () -> Unit = {},
+ onSuccess: () -> Unit = {}) {
+ val started = action(key) {
+ val response = try { ready().call(method, body) }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) { onFailure(); throw error }
+ response.jsonObject["bot"]?.let { value ->
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(HostClient.decode(value.jsonObject)) }
+ }
+ response.jsonObject["entry"]?.let { value ->
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(listOf(Entry.decode(value.jsonObject))) }
+ }
+ refresh()
+ onSuccess()
}
- refresh()
- onSuccess()
+ if (!started) onFailure()
+}
+
+/** Moves a bot into the roster section [section], or out of any (null). */
+fun AppStore.setSection(botId: String, section: String?) = moveSections(listOf(botId), section, "updateBot", sectionUpdate(botId, section))
+
+/**
+ * Moves every bot of the section [from] into [to] (merging into a section of that name), or out of any (null: removes the section);
+ * [onRefused] when the computer doesn't take it.
+ */
+fun AppStore.renameSection(from: String, to: String?, onRefused: () -> Unit) =
+ moveSections(state.value.bots.filter { it.section == from }.map(Bot::id), to, "renameSection", sectionRename(from, to), onRefused)
+
+/**
+ * Shows bots [ids] in [section] at once, then sends [method] (iOS `BotStore.show`): each move shows over the mirror until it's
+ * answered, so a refused one leaves the bot where the computer has it, or where a later move put it.
+ */
+private fun AppStore.moveSections(ids: List<String>, section: String?, method: String, body: JsonObject, onRefused: () -> Unit = {}) {
+ val moves = ids.map { SectionMove(it, section) }
+ pendingSectionMoves += moves
+ showSectionMoves()
+ // A key of its own: a later move of the same bot goes while this one is answered.
+ command(method, body, "section:" + java.util.UUID.randomUUID(), onFailure = {
+ pendingSectionMoves.removeAll(moves)
+ // The bots and the caller's folds go back in one update.
+ showSectionMoves()
+ onRefused()
+ }) { pendingSectionMoves.removeAll(moves) }
}
+private fun AppStore.showSectionMoves() = mutableState.update { it.copy(bots = withMoves(mirrorBots, pendingSectionMoves)) }
+
fun AppStore.saveBot(draft: BotDraft, onSaved: () -> Unit) = action("editor") {
val active = ready()
val result = active.call(if (draft.id == null) "createBot" else "updateBot", draft.body())
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
index ce162bbe..1cc1659f 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
@@ -33,6 +33,7 @@ import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.zIndex
import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.semantics.CustomAccessibilityAction
@@ -58,11 +59,25 @@ import kotlinx.serialization.json.putJsonArray
@Composable internal fun BotListView(state: AppState, store: AppStore, account: () -> Unit, manage: () -> Unit,
newBot: () -> Unit, newGroup: () -> Unit, edit: (Bot) -> Unit, bottomInset: androidx.compose.ui.unit.Dp) {
var confirmDelete by remember { mutableStateOf<Bot?>(null) }
+ var naming by remember { mutableStateOf<SectionNaming?>(null) }
+ val context = LocalContext.current
+ var folded by remember { mutableStateOf(FoldedSections.load(context)) }
+ // A folded section renamed or removed here stays folded under its new name, at once, like its bots; a refusal puts the
+ // folds back, reading and writing the stored ones, as the list may have left the screen.
+ val renameSection = { from: String, to: String? ->
+ val before = folded
+ val renamed = foldsAfterRename(before, from, to)
+ folded = renamed
+ FoldedSections.save(context, renamed)
+ store.renameSection(from, to) {
+ folded = foldsAfterRefusal(FoldedSections.load(context), renamed, before).also { FoldedSections.save(context, it) }
+ }
+ }
var confirmNewSession by remember { mutableStateOf<Bot?>(null) }
val roster = roster(state.bots)
+ val sections = menuSections(state.bots)
val reorder = remember { RosterReorder() }
- reorder.roster = roster.map(Bot::id)
- reorder.lead = roster.firstOrNull { it.lead }?.id
+ reorder.roster = roster
val online = state.actualConnection is LinkState.Ready
// A computer that turned this phone away, or this computer's older identity, counts as none (iOS `availableStores`).
val usable = state.computers.isNotEmpty() && !state.isStale
@@ -84,13 +99,28 @@ import kotlinx.serialization.json.putJsonArray
if (roster.isEmpty() && state.mismatch == null) item {
EmptyRoster(canCreate = usable, hasComputer = usable, create = newBot, showComputers = manage)
}
- items(reorder.shown(roster), key = Bot::id) { bot ->
- val lifted = reorder.dragged == bot.id
- Box(Modifier.onSizeChanged { reorder.heights[bot.id] = it.height }
- .then(if (lifted) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.offset; scaleX = 1.02f; scaleY = 1.02f }
- else Modifier.animateItem())) {
- BotRowItem(bot, state, store, reorder.handle(bot.id) { store.reorder(it) }, edit = { edit(bot) },
- newSession = { confirmNewSession = bot }, delete = { confirmDelete = bot })
+ items(rosterLines(reorder.shown(roster), folded), key = RosterLine::key) { line ->
+ when (line) {
+ // Folding drops the section's rows from the list; animateItem fades them out and slides the rest up.
+ is RosterLine.Header -> SectionHeader(line, toggle = {
+ folded = if (line.name in folded) folded - line.name else folded + line.name
+ FoldedSections.save(context, folded)
+ }, actions = if (state.supportsSections) sectionActions(
+ rename = { naming = SectionNaming("Rename section", line.name) { renameSection(line.name, it) } },
+ remove = { renameSection(line.name, null) }) else emptyList(),
+ modifier = Modifier.animateItem())
+ RosterLine.Label -> SectionLabel(Modifier.animateItem())
+ is RosterLine.Row -> {
+ val bot = line.bot
+ val lifted = reorder.dragged == bot.id
+ Box(Modifier.onSizeChanged { reorder.heights[bot.id] = it.height }
+ .then(if (lifted) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.offset; scaleX = 1.02f; scaleY = 1.02f }
+ else Modifier.animateItem())) {
+ BotRowItem(bot, state, store, reorder.handle(bot.id) { store.reorder(it) }, sections, edit = { edit(bot) },
+ newSession = { confirmNewSession = bot }, delete = { confirmDelete = bot },
+ newSection = { naming = SectionNaming("New section", "") { store.setSection(bot.id, it) } })
+ }
+ }
}
}
}
@@ -108,6 +138,7 @@ import kotlinx.serialization.json.putJsonArray
deleting?.let { store.deleteBot(it) {} }
})
}
+ SectionNameDialog(naming) { naming = null }
}
/**
@@ -115,40 +146,38 @@ import kotlinx.serialization.json.putJsonArray
* shown follows the finger until the host's synced order catches up.
*/
private class RosterReorder {
- var roster: List<String> = emptyList()
- /** Stays on top: nothing takes its place. */
- var lead: String? = null
+ var roster: List<Bot> = emptyList()
var order by mutableStateOf<List<String>?>(null)
var dragged by mutableStateOf<String?>(null)
var offset by mutableFloatStateOf(0f)
val heights = mutableMapOf<String, Int>()
private val handles = mutableMapOf<String, ContextDrag>()
+ private val synced: List<String> get() = roster.map(Bot::id)
fun shown(bots: List<Bot>): List<Bot> {
val ids = order ?: return bots
// Dropped and synced: the host's order is the one to show again.
- if (dragged == null && ids == roster) { order = null; return bots }
+ if (dragged == null && ids == synced) { order = null; return bots }
return ids.mapNotNull { id -> bots.firstOrNull { it.id == id } } + bots.filter { it.id !in ids }
}
fun handle(id: String, save: (List<String>) -> Unit): ContextDrag = handles.getOrPut(id) {
- ContextDrag(start = { order = order ?: roster; dragged = id; offset = 0f }, move = { step -> offset += step; swap(id) }, end = {
+ ContextDrag(start = { order = order ?: synced; dragged = id; offset = 0f }, move = { step -> offset += step; swap(id) }, end = {
val dropped = order
dragged = null; offset = 0f
- if (dropped != null && dropped != roster) save(dropped) else order = null
+ if (dropped != null && dropped != synced) save(dropped) else order = null
})
}
- /** Past half the neighbor's height, the row takes the neighbor's place. */
+ /** Past half its height, the row takes the place of the next bot it may pass ([moved]): headers and other sections stay put. */
private fun swap(id: String) {
- val list = order ?: return
- val at = list.indexOf(id)
- val next = if (offset > 0) at + 1 else at - 1
- if (list.getOrNull(next) == lead) return
- val height = list.getOrNull(next)?.let(heights::get) ?: return
+ val bots = shown(roster)
+ val direction = if (offset > 0) 1 else -1
+ val swapped = moved(bots, id, direction) ?: return
+ val height = heights[swapped[bots.indexOfFirst { it.id == id }]] ?: return
if (kotlin.math.abs(offset) < height / 2f) return
- order = list.toMutableList().apply { add(next, removeAt(at)) }
- offset -= if (offset > 0) height else -height
+ order = swapped
+ offset -= direction * height
}
}
@@ -156,17 +185,24 @@ private class RosterReorder {
internal fun roster(bots: List<Bot>): List<Bot> = bots.filter { !it.deleted && !it.hidden }
.sortedWith(compareBy<Bot> { it.band }.thenBy { it.position }.thenByDescending { it.lastAt })
-/** The roster order with a bot one place up (-1) or down (+1) within its band (`Bot.band`), or null when it can't move. */
+/**
+ * The roster order with a bot swapped with the next bot up (-1) or down (+1) that shows beside it, or null when there's none:
+ * a bot stays in its band (`Bot.band`: the lead, pinned bots, the rest); pinned bots move among all the pinned, the others
+ * among bots of their section (or of none), skipping the bots between.
+ */
internal fun moved(roster: List<Bot>, id: String, offset: Int): List<String>? {
val at = roster.indexOfFirst { it.id == id }
- val neighbor = roster.getOrNull(at + offset)
- if (at < 0 || neighbor == null || neighbor.band != roster[at].band) return null
- return roster.map(Bot::id).toMutableList().apply { this[at] = neighbor.id; this[at + offset] = id }
+ if (at < 0) return null
+ val next = generateSequence(at + offset) { it + offset }.takeWhile { it in roster.indices }
+ .firstOrNull { roster[it].movesWith(roster[at]) } ?: return null
+ return roster.map(Bot::id).toMutableList().apply { this[at] = roster[next].id; this[next] = id }
}
-@Composable private fun BotRowItem(bot: Bot, state: AppState, store: AppStore, drag: ContextDrag, edit: () -> Unit, newSession: () -> Unit,
- delete: () -> Unit) {
- // The lead stays on top and in the list: no drag, pin, hide or delete.
+private fun Bot.movesWith(other: Bot) = band == other.band && (staysOnTop || section == other.section)
+
+@Composable private fun BotRowItem(bot: Bot, state: AppState, store: AppStore, drag: ContextDrag, sections: List<String>, edit: () -> Unit,
+ newSession: () -> Unit, delete: () -> Unit, newSection: () -> Unit) {
+ // The lead stays on top and in the list: no drag, pin, section, hide or delete.
Box(Modifier.fillMaxWidth().contextActions(onClick = { store.openBot(bot.id) }, reorder = drag.takeUnless { bot.lead }, preview = {
Box(Modifier.padding(horizontal = 8.dp)) { BotRow(bot, state) }
}) {
@@ -174,6 +210,7 @@ internal fun moved(roster: List<Bot>, id: String, offset: Int): List<String>? {
MenuItem(if (bot.pinned) "Unpin" else "Pin", icon = if (bot.pinned) "pin.slash" else "pin") {
store.command("updateBot", buildJsonObject { put("id", bot.id); put("pinned", !bot.pinned) }, "roster:" + bot.id)
}.takeUnless { bot.lead },
+ if (state.supportsSections && !bot.lead) sectionMenu(bot, sections, { store.setSection(bot.id, it) }, newSection) else null,
if (bot.kind == "group") MenuItem("Edit group", icon = "person.2", action = edit)
else MenuItem("Edit profile", icon = "pencil", action = edit),
MenuItem("Mark as read", icon = "checkmark.message") {
@@ -215,15 +252,20 @@ internal fun moved(roster: List<Bot>, id: String, offset: Int): List<String>? {
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.weight(1f)) { Preview(bot, state) }
- if (bot.unread > 0) Box(Modifier.height(18.dp).widthIn(min = 18.dp).clip(Capsule()).background(Palette.accentFill)
- .padding(horizontal = 6.dp).semantics { contentDescription = "${bot.unread} unread" }, contentAlignment = Alignment.Center) {
- Text("${bot.unread}", style = Type.caption2.bold, color = Palette.onAccent)
- }
+ if (bot.unread > 0) UnreadBadge(bot.unread)
}
}
}
}
+/** A count of unread messages in the accent capsule (a row, a folded section). */
+@Composable internal fun UnreadBadge(count: Int) {
+ Box(Modifier.height(18.dp).widthIn(min = 18.dp).clip(Capsule()).background(Palette.accentFill)
+ .padding(horizontal = 6.dp).semantics { contentDescription = "$count unread" }, contentAlignment = Alignment.Center) {
+ Text("$count", style = Type.caption2.bold, color = Palette.onAccent)
+ }
+}
+
/** Live activity while working, otherwise the last message (Grok Bot row behavior). */
@Composable private fun Preview(bot: Bot, state: AppState) {
when {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt
new file mode 100644
index 00000000..e0371488
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt
@@ -0,0 +1,129 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+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.draw.rotate
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.heading
+import androidx.compose.ui.semantics.role
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import androidx.compose.ui.text.TextRange
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.TextFieldValue
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.design.*
+
+/**
+ * A section's heading, drawn like iOS `ComputerSection`: its name and bot count, their unread while
+ * folded, and the chevron. Tap folds it; touch and hold opens [actions] (none for a host without sections).
+ */
+@Composable internal fun SectionHeader(header: RosterLine.Header, toggle: () -> Unit, actions: List<MenuItem>, modifier: Modifier = Modifier) {
+ val turn by animateFloatAsState(if (header.folded) -90f else 0f, Motion.layout(), label = "Chevron")
+ val state = if (header.folded) tr("Collapsed") else tr("Expanded")
+ // "Work, 2 bots, 3 unread", its phrase translated before the name goes in: last, so one that reads "{count}" stays as typed.
+ val unread = header.folded && header.unread > 0
+ val spoken = when {
+ header.count == 1 && !unread -> tr("{name}, 1 bot")
+ !unread -> tr("{name}, {count} bots")
+ header.count == 1 -> tr("{name}, 1 bot, {unread} unread")
+ else -> tr("{name}, {count} bots, {unread} unread")
+ }.replace("{count}", "${header.count}").replace("{unread}", "${header.unread}").replace("{name}", header.name)
+ val tap = if (actions.isEmpty()) Modifier.clickable(role = Role.Button, onClick = toggle)
+ else Modifier.contextActions(onClick = toggle) { actions }.semantics { role = Role.Button }
+ Row(modifier.fillMaxWidth().padding(top = 14.dp, bottom = 2.dp).then(tap)
+ // One spoken line for the whole header (the count and the badge say nothing alone): clear the parts, then describe it.
+ .clearAndSetSemantics {
+ heading()
+ stateDescription = state
+ contentDescription = spoken
+ }
+ .padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) {
+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(header.name, Modifier.weight(1f, fill = false), style = Type.footnote.semibold, color = Palette.secondary,
+ maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text("${header.count}", style = Type.footnote, color = Palette.tertiary)
+ }
+ Spacer(Modifier.width(8.dp))
+ // The badge sits at the trailing edge, next to the chevron, as on iPhone and the desktop.
+ AnimatedVisibility(header.folded && header.unread > 0, Modifier.padding(end = 6.dp), enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
+ UnreadBadge(header.unread)
+ }
+ Symbol("chevron.down", Modifier.rotate(turn), size = 14.dp, tint = Palette.tertiary)
+ }
+}
+
+/** The plain "Bots" label over the bots in no section: a header's name, where its row starts; it folds nothing. */
+@Composable internal fun SectionLabel(modifier: Modifier = Modifier) {
+ Text(tr("Bots"), modifier.fillMaxWidth().padding(top = 14.dp, bottom = 2.dp).semantics { heading() }.padding(vertical = 6.dp),
+ style = Type.footnote.semibold, color = Palette.secondary)
+}
+
+/**
+ * The row's "Move to section" submenu: each other section there is (by the name the user gave it, never translated), a new one,
+ * and none when the bot is in one; [move] puts the bot in a section (null: out of its own).
+ */
+internal fun sectionMenu(bot: Bot, sections: List<String>, move: (String?) -> Unit, newSection: () -> Unit): MenuItem {
+ val others = sections.filter { it != bot.section }.map { name -> MenuItem(name, verbatim = true) { move(name) } }
+ return MenuItem("Move to section", icon = "arrow.turn.down.right", children = others + listOfNotNull(
+ MenuItem("New section…", icon = "plus", divider = true, action = newSection),
+ if (bot.section != null) MenuItem("Remove from section", icon = "xmark.circle") { move(null) } else null,
+ ))
+}
+
+/** The header's menu: rename the section, or remove it (its bots stay, without a section). */
+internal fun sectionActions(rename: () -> Unit, remove: () -> Unit): List<MenuItem> = listOf(
+ MenuItem("Rename section…", icon = "pencil", action = rename),
+ MenuItem("Remove section", icon = "xmark.circle", action = remove),
+)
+
+/** An open section name dialog (desktop `SectionNaming`): its title, the name it opens with, and what Save does with the typed one. */
+internal class SectionNaming(val title: String, val name: String, val save: (String) -> Unit)
+
+/**
+ * "New section" / "Rename section": a name, then Save. A name of nothing saves nothing; the host says what else it refuses.
+ * Each opening ([naming] is a new object every time) starts from its own name; the last one stays on show while the dialog fades out.
+ */
+@Composable internal fun SectionNameDialog(naming: SectionNaming?, dismiss: () -> Unit) {
+ var opened by remember { mutableStateOf<SectionNaming?>(null) }
+ var name by remember { mutableStateOf(TextFieldValue()) }
+ if (naming != null && naming !== opened) {
+ opened = naming
+ name = TextFieldValue(naming.name, TextRange(naming.name.length))
+ }
+ val submit = { if (naming != null) sectionName(name.text)?.let(naming.save) }
+ val focus = remember { FocusRequester() }
+ CodyncDialog(opened?.title.orEmpty(), naming != null, dismiss, field = {
+ LaunchedEffect(Unit) { focus.requestFocus() }
+ PlainTextField(name, { name = it.copy(text = limitSectionName(it.text)) }, Modifier.fillMaxWidth().pill().focusRequester(focus),
+ "Section name", singleLine = true, keyboard = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Done),
+ actions = KeyboardActions(onDone = { dismiss(); submit() }))
+ }) { listOf(DialogAction("Save", action = submit)) }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt b/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
new file mode 100644
index 00000000..90b41a0c
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
@@ -0,0 +1,111 @@
+package com.codync.android
+
+import android.content.Context
+import androidx.core.content.edit
+import com.codync.android.core.AppVersion
+import com.codync.android.core.Bot
+import java.text.Collator
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+
+/** One line of the roster as it shows: a bot, a section's header, or the "Bots" label (docs/plans/roster-sections.md). */
+internal sealed interface RosterLine {
+ val key: String
+
+ data class Row(val bot: Bot) : RosterLine {
+ override val key: String get() = bot.id
+ }
+
+ /** [count] and [unread] cover the section's unpinned bots, the ones shown under it. */
+ data class Header(val name: String, val count: Int, val unread: Int, val folded: Boolean) : RosterLine {
+ override val key: String get() = "section:$name"
+ }
+
+ /** The plain "Bots" label over the bots in no section. */
+ data object Label : RosterLine {
+ override val key: String get() = "label:bots"
+ }
+}
+
+/** The lead and pinned bots stay on top, outside sections. */
+internal val Bot.staysOnTop get() = lead || pinned
+
+/**
+ * The sorted [roster] as it shows: the lead and pinned bots, then each section by name (its header,
+ * then its bots in roster order unless it's [folded]), then bots without a section, under
+ * [RosterLine.Label] when there are sections. The lead and a pinned bot show only on top.
+ */
+internal fun rosterLines(roster: List<Bot>, folded: Set<String>): List<RosterLine> = buildList {
+ val (pinned, unpinned) = roster.partition { it.staysOnTop }
+ val sections = unpinned.groupBy(Bot::section)
+ pinned.forEach { add(RosterLine.Row(it)) }
+ val names = sectionNames(unpinned)
+ for (name in names) {
+ val bots = sections.getValue(name)
+ val header = RosterLine.Header(name, bots.size, bots.sumOf { it.unread }, name in folded)
+ add(header)
+ if (!header.folded) bots.forEach { add(RosterLine.Row(it)) }
+ }
+ val loose = sections[null].orEmpty()
+ if (names.isNotEmpty() && loose.isNotEmpty()) add(RosterLine.Label)
+ loose.forEach { add(RosterLine.Row(it)) }
+}
+
+/** The sections [bots] are in, sorted the way the phone's language sorts ("İş" where Turkish puts it). */
+internal fun sectionNames(bots: List<Bot>): List<String> = bots.mapNotNull(Bot::section).distinct().sortedWith(Collator.getInstance())
+
+/** The sections a row's "Move to section" offers: hidden bots' too, though the roster leaves those out (iOS `BotStore.sections`). */
+internal fun menuSections(bots: List<Bot>): List<String> = sectionNames(bots.filterNot(Bot::deleted))
+
+/** The first host version that keeps sections (`section` on bots, `renameSection`). */
+private const val SECTIONS_HOST = "2.32.0"
+
+/** Section controls show only for a host that keeps sections; before its `hello` (offline) they stay hidden. */
+internal val AppState.supportsSections: Boolean
+ get() = hello?.text("version")?.let { !AppVersion.isBelow(it, SECTIONS_HOST) } == true
+
+/** `updateBot`'s section patch: null goes as JSON null, which clears it (a missing key keeps it). */
+internal fun sectionUpdate(id: String, section: String?): JsonObject = buildJsonObject { put("id", id); put("section", section) }
+
+/** `renameSection`: every bot in [from] moves to [to], merging into a section of that name; null removes the section. */
+internal fun sectionRename(from: String, to: String?): JsonObject = buildJsonObject { put("from", from); put("to", to) }
+
+/** The most characters a section name may have (the host refuses more). */
+private const val SECTION_NAME_LIMIT = 40
+
+/** What a name field holds: at most [SECTION_NAME_LIMIT] characters (code points, as the host counts them), never cut inside a surrogate pair. */
+internal fun limitSectionName(input: String): String =
+ if (input.codePointCount(0, input.length) <= SECTION_NAME_LIMIT) input else input.substring(0, input.offsetByCodePoints(0, SECTION_NAME_LIMIT))
+
+/** The section a typed [input] names: trimmed, or null when nothing but whitespace or control characters was typed (the host would clear or remove). */
+internal fun sectionName(input: String): String? =
+ input.trim().takeIf { name -> name.any { !it.isWhitespace() && !it.isISOControl() } }
+
+/**
+ * This device's folded sections after it renames section [from] to [to] (null removes it): a folded [from] stays folded
+ * as [to], so a merge folds the section it joins; an unfolded one changes nothing.
+ */
+internal fun foldsAfterRename(folded: Set<String>, from: String, to: String?): Set<String> =
+ if (from in folded) folded - from + listOfNotNull(to) else folded
+
+/** This device's folded sections after the computer refused a rename that changed them from [before] to [set]: [before] again, unless they changed since. */
+internal fun foldsAfterRefusal(current: Set<String>, set: Set<String>, before: Set<String>): Set<String> = if (current == set) before else current
+
+/** A section change shown before the computer answered it (iOS `SectionMove`): bot [bot] into [to] (null: none). Told apart by identity. */
+internal class SectionMove(val bot: String, val to: String?)
+
+/** [bots] as they show while [pending] (oldest first) waits for the computer: each bot in the section its latest move put it in. */
+internal fun withMoves(bots: List<Bot>, pending: List<SectionMove>): List<Bot> {
+ if (pending.isEmpty()) return bots
+ val sections = pending.associate { it.bot to it.to }
+ return bots.map { bot -> if (bot.id in sections) bot.copy(section = sections[bot.id]) else bot }
+}
+
+/** The sections folded on this device (iOS `@AppStorage("collapsedRosterSections")`); not synced. */
+internal object FoldedSections {
+ private const val KEY = "collapsedRosterSections"
+ private fun prefs(context: Context) = context.getSharedPreferences("codync-roster", Context.MODE_PRIVATE)
+ fun load(context: Context): Set<String> = prefs(context).getStringSet(KEY, null).orEmpty().toSet()
+ fun save(context: Context, names: Set<String>) { prefs(context).edit { putStringSet(KEY, names) } }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt
index 9b13e52b..e66641df 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/RosterMoveTest.kt
@@ -19,6 +19,16 @@ class RosterMoveTest {
assertNull(moved(roster, "missing", 1))
}
+ @Test fun aBotMovesPastOtherSectionsToTheNextBotInItsOwn() {
+ val sectioned = listOf(Bot("pin", pinned = true, section = "Work"), Bot("pin2", pinned = true), Bot("a", section = "Work"),
+ Bot("b"), Bot("c", section = "Work"))
+ assertEquals(listOf("pin", "pin2", "c", "b", "a"), moved(sectioned, "a", 1))
+ assertNull(moved(sectioned, "b", -1))
+ assertNull(moved(sectioned, "b", 1))
+ // Pinned bots show together whatever their section, so they move among each other.
+ assertEquals(listOf("pin2", "pin", "a", "b", "c"), moved(sectioned, "pin", 1))
+ }
+
@Test fun theLeadComesFirstAndStaysThere() {
val bots = listOf(Bot("pin", pinned = true, lastAt = 9), Bot("a", lastAt = 5), Bot("lead", lead = true, position = 3, lastAt = 1))
val sorted = roster(bots)
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.kt
new file mode 100644
index 00000000..48033a4b
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.kt
@@ -0,0 +1,145 @@
+package com.codync.android
+
+import com.codync.android.core.Bot
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import org.junit.Assert.*
+import org.junit.Test
+
+class RosterSectionsTest {
+ private val pinned = Bot("pin", pinned = true, section = "Work", unread = 7)
+ private val work1 = Bot("w1", section = "Work", unread = 2)
+ private val loose = Bot("loose")
+ private val personal = Bot("p1", section = "Personal")
+ private val work2 = Bot("w2", section = "Work", unread = 3)
+ private val roster = listOf(pinned, work1, loose, personal, work2)
+
+ @Test fun pinnedBotsComeFirstThenEachSectionByNameThenBotsWithoutOneUnderTheLabel() {
+ assertEquals(listOf(
+ RosterLine.Row(pinned),
+ RosterLine.Header("Personal", count = 1, unread = 0, folded = false), RosterLine.Row(personal),
+ RosterLine.Header("Work", count = 2, unread = 5, folded = false), RosterLine.Row(work1), RosterLine.Row(work2),
+ RosterLine.Label, RosterLine.Row(loose),
+ ), rosterLines(roster, folded = emptySet()))
+ }
+
+ @Test fun theLeadStaysOnTopOutsideItsSection() {
+ val lead = Bot("lead", lead = true, section = "Work")
+ assertEquals(listOf(
+ RosterLine.Row(lead), RosterLine.Row(pinned),
+ RosterLine.Header("Work", count = 1, unread = 2, folded = false), RosterLine.Row(work1),
+ RosterLine.Label, RosterLine.Row(loose),
+ ), rosterLines(listOf(lead, pinned, work1, loose), folded = emptySet()))
+ assertNull(moved(listOf(lead, work1), "w1", -1))
+ }
+
+ @Test fun aFoldedSectionKeepsItsHeaderAndUnreadAndHidesItsBots() {
+ assertEquals(listOf(
+ RosterLine.Row(pinned),
+ RosterLine.Header("Personal", count = 1, unread = 0, folded = false), RosterLine.Row(personal),
+ RosterLine.Header("Work", count = 2, unread = 5, folded = true),
+ RosterLine.Label, RosterLine.Row(loose),
+ ), rosterLines(roster, folded = setOf("Work")))
+ }
+
+ @Test fun sectionsSortTheWayTheLanguageDoesNotByCharacterCode() {
+ val bots = listOf(Bot("a", section = "fig"), Bot("b", section = "Éclair"), Bot("c", section = "Cherry"), Bot("d", section = "banana"))
+ val sorted = listOf("banana", "Cherry", "Éclair", "fig")
+ assertEquals(sorted, sectionNames(bots))
+ assertEquals(sorted, rosterLines(bots, emptySet()).filterIsInstance<RosterLine.Header>().map { it.name })
+ }
+
+ @Test fun namesAlikeButForCaseOrAccentsKeepOneOrderAsOnEveryClient() {
+ for (names in listOf(listOf("Work", "work", "Café", "Cafe"), listOf("Cafe", "work", "Café", "Work"))) {
+ assertEquals(listOf("Cafe", "Café", "work", "Work"), sectionNames(names.mapIndexed { i, name -> Bot("$i", section = name) }))
+ }
+ }
+
+ @Test fun moveToSectionOffersAHiddenBotsSectionButNotADeletedOnes() {
+ val bots = listOf(work1, Bot("archived", section = "Archive", hidden = true), Bot("gone", section = "Old", deleted = true))
+ assertEquals(listOf("Archive", "Work"), menuSections(bots))
+ }
+
+ @Test fun withoutSectionsTheRosterShowsAsItIs() {
+ val plain = listOf(Bot("pin", pinned = true), Bot("a"), Bot("b"))
+ assertEquals(plain.map { RosterLine.Row(it) }, rosterLines(plain, emptySet()))
+ // Only a pinned bot is in a section: no header, so no label.
+ assertEquals(listOf(RosterLine.Row(pinned), RosterLine.Row(loose)), rosterLines(listOf(pinned, loose), emptySet()))
+ }
+
+ @Test fun theLabelNeedsABotInNoSection() {
+ assertEquals(listOf(RosterLine.Header("Work", count = 1, unread = 2, folded = false), RosterLine.Row(work1)),
+ rosterLines(listOf(work1), emptySet()))
+ }
+
+ @Test fun clearingASectionSendsNullRatherThanLeavingTheKeyOut() {
+ assertEquals(buildJsonObject { put("id", "b"); put("section", "Work") }, sectionUpdate("b", "Work"))
+ assertEquals(JsonNull, sectionUpdate("b", null)["section"])
+ assertEquals(buildJsonObject { put("from", "Work"); put("to", "Jobs") }, sectionRename("Work", "Jobs"))
+ assertEquals(JsonNull, sectionRename("Work", null)["to"])
+ }
+
+ @Test fun aTypedSectionNameIsTrimmedAndANameOfNothingIsNoName() {
+ assertEquals("Work", sectionName(" Work \n"))
+ assertEquals("Side projects", sectionName("Side projects"))
+ listOf("", " ", "\t\n", "\u00A0", "\u0000", " \u0000 \t").forEach { assertNull(it, sectionName(it)) }
+ }
+
+ @Test fun aNameFieldStopsAtFortyCharactersAsTheHostCountsThemNeverInsideAnEmoji() {
+ val forty = "a".repeat(40)
+ assertEquals(forty, limitSectionName(forty))
+ assertEquals(forty, limitSectionName(forty + "b"))
+ // An emoji is two UTF-16 units but one character: 40 of them fit, a 41st is cut whole.
+ val emoji = "\uD83D\uDE00"
+ assertEquals(emoji.repeat(40), limitSectionName(emoji.repeat(40)))
+ assertEquals(emoji.repeat(40), limitSectionName(emoji.repeat(41)))
+ assertEquals("a".repeat(39) + emoji, limitSectionName("a".repeat(39) + emoji + "b"))
+ }
+
+ @Test fun aFoldedSectionRenamedOrRemovedHereStaysFoldedUnderItsNewName() {
+ assertEquals(setOf("Home", "Jobs"), foldsAfterRename(setOf("Home", "Work"), "Work", "Jobs"))
+ assertEquals(setOf("Home"), foldsAfterRename(setOf("Home"), "Work", "Jobs")) // Unfolded: nothing changes.
+ assertEquals(setOf("Home"), foldsAfterRename(setOf("Home"), "Work", "Home")) // Never unfolds the target.
+ assertEquals(setOf("Home"), foldsAfterRename(setOf("Home", "Work"), "Work", null)) // Removed: its name goes.
+ assertEquals(setOf("Home"), foldsAfterRename(setOf("Work"), "Work", "Home")) // A merge folds the section it joins.
+ assertEquals(setOf("Work"), foldsAfterRename(setOf("Work"), "Work", "Work")) // The same name: still folded.
+ }
+
+ @Test fun aMoveShowsAtOnceAndARefusedOneLeavesTheBotWhereTheComputerOrALaterMovePutIt() {
+ val first = SectionMove("w1", "Home")
+ val second = SectionMove("w1", "Play")
+ val out = SectionMove("p1", null)
+ val section = { pending: List<SectionMove>, id: String -> withMoves(roster, pending).first { it.id == id }.section }
+ assertEquals("Home", section(listOf(first), "w1"))
+ assertEquals("Play", section(listOf(first, second), "w1")) // The latest move shows.
+ assertEquals("Play", section(listOf(second), "w1")) // The first refused: the later one still shows.
+ assertEquals("Work", section(emptyList(), "w1")) // Both refused: where the computer has it.
+ assertNull(section(listOf(out), "p1"))
+ assertEquals(roster, withMoves(roster, listOf(SectionMove("gone", "Home")))) // A bot not there: nothing changes.
+ }
+
+ @Test fun aRefusedRenamePutsTheFoldsBackUnlessOneChangedMeanwhile() {
+ val before = setOf("Home", "Work")
+ val moved = setOf("Home", "Jobs")
+ assertEquals(before, foldsAfterRefusal(moved, moved, before))
+ assertEquals(setOf("Jobs"), foldsAfterRefusal(setOf("Jobs"), moved, before)) // "Home" unfolded meanwhile: kept.
+ }
+
+ @Test fun moveToSectionShowsEachSectionByTheNameTheUserTypedNeverTranslated() {
+ val translate = { title: String -> "translated $title" }
+ val menu = sectionMenu(Bot("b", section = "Work"), listOf("Settings", "Work"), move = {}, newSection = {})
+ assertEquals("translated Move to section", menu.shownTitle(translate))
+ // A section named "Settings" stays "Settings"; the app's own rows translate.
+ assertEquals(listOf("Settings", "translated New section…", "translated Remove from section"),
+ menu.children.orEmpty().map { it.shownTitle(translate) })
+ }
+
+ @Test fun sectionControlsWaitForAHostThatKeepsSections() {
+ fun host(version: String?) = AppState(hello = version?.let { buildJsonObject { put("version", it) } })
+ assertFalse(host("2.31.2").supportsSections)
+ assertTrue(host("2.32.0").supportsSections)
+ assertTrue(host("2.32.1-dev").supportsSections)
+ assertFalse(host(null).supportsSections)
+ }
+}
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 4512dcbf..af7cb03d 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
@@ -53,6 +53,8 @@ data class Bot(
val pinned: Boolean = false,
/** The computer's lead bot, which the host makes: first in the roster, never deleted, hidden or pinned. */
val lead: Boolean = false,
+ /** The roster section the user put it in; null for none (or a host without sections). Kept while pinned or hidden. */
+ val section: String? = null,
/** Where the user dragged it in the roster, synced by the host to every device. */
val position: Int = 0,
val hidden: Boolean = false,
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
index 9ad1f4f8..88ee2f47 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
@@ -72,15 +72,22 @@ class ConversationTest {
@Test fun `templates preserve portable settings and exclude identity and runtime flags`() {
val bot = Bot("identity", "Reviewer", description = "Review carefully", model = "chosen", connectors = listOf("c"),
- skills = listOf("s"), pinned = true, hidden = true, managedWorkspace = true, cwd = "/host/workspace", rev = 77)
+ skills = listOf("s"), pinned = true, hidden = true, managedWorkspace = true, cwd = "/host/workspace", rev = 77, section = "Work")
val template = WireJson.parseToJsonElement(BotDraft.from(bot).template()).jsonObject
- for (key in listOf("id", "pinned", "hidden", "rev", "status", "autoName", "createdAt")) assertFalse(key in template)
+ for (key in listOf("id", "pinned", "hidden", "rev", "status", "autoName", "createdAt", "section")) assertFalse(key in template)
+ // Saving the editor leaves the section to the roster's menu: updateBot keeps a field it isn't sent.
+ assertFalse("section" in BotDraft.from(bot).body())
assertEquals("", template.getValue("cwd").jsonPrimitive.content)
assertEquals("chosen", template.getValue("model").jsonPrimitive.content)
assertEquals(listOf(JsonPrimitive("c")), template.getValue("connectors").jsonArray.toList())
assertEquals(JsonNull, BotDraft.from(bot).copy(model = null).body()["model"])
}
+ @Test fun `a bot decodes its roster section, and an older host's without one`() {
+ assertEquals("Work", HostClient.decode(WireJson.parseToJsonElement("""{"id":"b","name":"Scout","section":"Work"}""").jsonObject).section)
+ assertNull(HostClient.decode(WireJson.parseToJsonElement("""{"id":"b","name":"Scout"}""").jsonObject).section)
+ }
+
@Test fun `a settings draft takes changes made elsewhere and keeps its own edits`() {
val base = BotDraft.from(Bot("b", "Lead", model = "sonnet"))
val fresh = base.copy(model = "opus", name = "Boss", manageTeam = true)
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 edb56945..55073b60 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
@@ -73,6 +73,7 @@ import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@@ -337,14 +338,25 @@ val LocalCardStyle = staticCompositionLocalOf { CardStyle.Filled }
actions: KeyboardActions = KeyboardActions.Default) {
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 ->
- 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(tr(prompt), style = style, color = Palette.tertiary, maxLines = if (singleLine) 1 else Int.MAX_VALUE)
- field()
- }
- })
+ decorationBox = plainDecoration(text.isEmpty(), prompt, style, singleLine))
+}
+
+/** [PlainTextField] over a [TextFieldValue], for a field that starts with its cursor somewhere (a name to edit: at its end). */
+@Composable fun PlainTextField(value: TextFieldValue, onChange: (TextFieldValue) -> Unit, modifier: Modifier = Modifier, prompt: String = "",
+ singleLine: Boolean = false, style: TextStyle = Type.body, imeAction: ImeAction = ImeAction.Default,
+ keyboard: KeyboardOptions = KeyboardOptions(imeAction = imeAction), actions: KeyboardActions = KeyboardActions.Default) {
+ BasicTextField(value, onChange, modifier, singleLine = singleLine, textStyle = style.copy(color = Palette.text),
+ cursorBrush = SolidColor(Palette.accent), keyboardOptions = keyboard, keyboardActions = actions,
+ decorationBox = plainDecoration(value.text.isEmpty(), prompt, style, singleLine))
+}
+
+private fun plainDecoration(empty: Boolean, prompt: String, style: TextStyle, singleLine: Boolean): @Composable (@Composable () -> Unit) -> Unit = { field ->
+ 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 (empty) Text(tr(prompt), style = style, color = Palette.tertiary, maxLines = if (singleLine) 1 else Int.MAX_VALUE)
+ field()
+ }
}
/** A row that expands to show more: the replacement for `DisclosureGroup`. */
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt
index 56768443..65c96a96 100644
--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt
@@ -79,8 +79,13 @@ class MenuItem(
val divider: Boolean = false,
val enabled: Boolean = true,
val children: List<MenuItem>? = null,
+ /** Shows [title] as it is, never translated: a name the user gave (a section's). */
+ val verbatim: Boolean = false,
val action: () -> Unit = {},
-)
+) {
+ /** [title] as the row shows it: through [translate], unless [verbatim]. */
+ fun shownTitle(translate: (String) -> String): String = if (verbatim) title else translate(title)
+}
/** A row of emoji above a message's menu (Slack's quick reactions). */
class ReactionPick(val emoji: List<String>, val chosen: List<String>, val toggle: (String) -> Unit)
@@ -134,13 +139,17 @@ class ContextDrag(val start: () -> Unit, val move: (Float) -> Unit, val end: ()
hold()
var moved = 0f
var started = false
- drag(held.id) { change ->
- val step = change.positionChange().y
- moved += step
- if (!started && abs(moved) > viewConfiguration.touchSlop) { started = true; open = false; reorder.start() }
- if (started) { reorder.move(step); change.consume() }
+ // finally: a cancelled gesture (the row left the list, the handler restarted) still ends the drag.
+ try {
+ drag(held.id) { change ->
+ val step = change.positionChange().y
+ moved += step
+ if (!started && abs(moved) > viewConfiguration.touchSlop) { started = true; open = false; reorder.start() }
+ if (started) { reorder.move(step); change.consume() }
+ }
+ } finally {
+ if (started) reorder.end()
}
- if (started) reorder.end()
}
}
return onGloballyPositioned { anchor = it.boundsInRoot() }.then(gestures)
@@ -250,7 +259,7 @@ private val MenuShape = RoundedRectangle(26.dp)
Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {
if (leading != null) Symbol(leading, size = 21.dp, tint = ink)
}
- Text(tr(item.title), Modifier.weight(1f), style = if (bold) Type.body.semibold else Type.body, color = ink)
+ Text(item.shownTitle(translator()), Modifier.weight(1f), style = if (bold) Type.body.semibold else Type.body, color = ink)
if (item.children != null) Symbol("chevron.right", size = 16.dp, tint = Palette.secondary)
}
}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 42a3d574..6ee938a0 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -16,7 +16,7 @@
"build": "electron-vite build",
"build:demo": "vite build --config vite.demo.config.ts && mv ../../web/public/demo/desktop/index.html ../../web/public/demo/desktop.html",
"typecheck": "tsc --noEmit -p tsconfig.json",
- "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/lib/*.test.ts src/renderer/views/thread/*.test.ts src/renderer/views/routines/*.test.ts src/renderer/views/call/*.test.ts src/renderer/views/marketplace/*.test.ts",
+ "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/lib/*.test.ts src/renderer/store/*.test.ts src/renderer/views/*.test.ts src/renderer/views/thread/*.test.ts src/renderer/views/routines/*.test.ts src/renderer/views/call/*.test.ts src/renderer/views/marketplace/*.test.ts",
"icons": "swift tools/export-symbols.swift",
"dist:mac:dev": "node tools/account-config.mjs dev && node tools/native-host.mjs dev && node tools/native-screen.mjs dev && electron-vite build && CSC_NAME=\"Pokai Lee (6KFK5J2LB4)\" electron-builder --mac --config tools/dev-builder.cjs",
"dist:mac:main": "node tools/account-config.mjs main && node tools/native-host.mjs main && node tools/native-screen.mjs main && electron-vite build && electron-builder --mac",
diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsx
index 6dcf9cea..e2694d91 100644
--- a/apps/desktop/src/renderer/components/Overlay.tsx
+++ b/apps/desktop/src/renderer/components/Overlay.tsx
@@ -143,20 +143,22 @@ export interface DialogAction {
}
/** A centered card over a dimmed screen with the actions and Cancel (`.codyncDialog`). */
-export function Dialog({ open, title, message, actions, cancel = 'Cancel', onClose }: {
+export function Dialog({ open, title, message, actions, cancel = 'Cancel', onClose, children }: {
open: boolean
title: string
message?: string | null
actions: DialogAction[]
cancel?: string | null
onClose: () => void
+ /** A field between the text and the buttons (a name to type); `data-autofocus` on it takes the focus. */
+ children?: ReactNode
}) {
const { mounted, shown } = usePresence(open, 120)
const tr = useTr()
- const last = useRef({ title, message, actions })
+ const last = useRef({ title, message, actions, children })
const layer = useRef<HTMLDivElement>(null)
const id = useId()
- if (open) last.current = { title, message, actions }
+ if (open) last.current = { title, message, actions, children }
useEscape(open && cancel !== null, onClose)
useModalFocus(open, mounted, layer)
if (!mounted) return null
@@ -170,6 +172,7 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onClo
<Text as="h2" id={`${id}-title`} size="title3" weight="semibold">{shownContent.title}</Text>
{shownContent.message ? <Text as="div" id={`${id}-message`} size="body" tone="secondary">{shownContent.message}</Text> : null}
</div>
+ {shownContent.children}
<div className="dialog-buttons">
{cancel !== null ? (
<button className="dialog-button" data-autofocus onClick={onClose}>
@@ -204,6 +207,8 @@ export interface MenuItem {
selected?: boolean
destructive?: boolean
divider?: boolean
+ /** The title is a name the user gave (a section): shown as typed, never translated. */
+ verbatim?: boolean
action: () => void
}
@@ -271,7 +276,7 @@ export function MenuPanel({ items, reactions, dismiss, maxHeight }: { items: Men
className={`menu-row ${item.destructive ? 'destructive' : ''} ${highlight === i ? 'highlight' : ''}`}
role={item.selected === undefined ? 'menuitem' : 'menuitemradio'}
aria-checked={item.selected}
- title={tr(item.title)}
+ title={item.verbatim ? item.title : tr(item.title)}
onMouseEnter={() => setHighlight(i)}
onClick={() => {
dismiss()
@@ -283,7 +288,7 @@ export function MenuPanel({ items, reactions, dismiss, maxHeight }: { items: Men
{item.leading ?? (item.icon ? <Icon name={item.icon} size={12} /> : null)}
</span>
) : null}
- <span className="menu-title">{tr(item.title)}</span>
+ <span className="menu-title">{item.verbatim ? item.title : tr(item.title)}</span>
{item.selected !== undefined ? (
<span className={`check-slot${item.selected ? ' on' : ''}`}>
<Icon name="checkmark" size={10} weight="semibold" />
diff --git a/apps/desktop/src/renderer/components/overlay.css b/apps/desktop/src/renderer/components/overlay.css
index d9d4aba7..b15ff4e2 100644
--- a/apps/desktop/src/renderer/components/overlay.css
+++ b/apps/desktop/src/renderer/components/overlay.css
@@ -138,6 +138,20 @@
line-height: 1.45;
overflow-wrap: anywhere;
}
+/* A text field in a dialog (a name to type). */
+.dialog-field {
+ width: 100%;
+ padding: 8px 10px;
+ background: var(--field);
+ border-radius: var(--radius-m);
+ color: var(--text);
+ font-size: var(--text-body);
+ user-select: text;
+ cursor: text;
+}
+.dialog-field:focus {
+ outline: 2px solid var(--secondary);
+}
.dialog-buttons {
display: flex;
flex-wrap: wrap;
diff --git a/apps/desktop/src/renderer/demo/fake-host.ts b/apps/desktop/src/renderer/demo/fake-host.ts
index 3bcfaf1b..8ab127b6 100644
--- a/apps/desktop/src/renderer/demo/fake-host.ts
+++ b/apps/desktop/src/renderer/demo/fake-host.ts
@@ -227,6 +227,11 @@ export class FakeHost {
})
return {}
}
+ case 'renameSection': {
+ const to = typeof b.to === 'string' ? b.to.trim() || undefined : undefined
+ for (const bot of this.bots.values()) if (bot.section === str('from')) this.emitBot(Object.assign(bot, { section: to }))
+ return {}
+ }
case 'deleteBot': {
const id = str('botId')
this.bots.delete(id)
diff --git a/apps/desktop/src/renderer/lib/prefs.ts b/apps/desktop/src/renderer/lib/prefs.ts
index 006f02b1..4d222f59 100644
--- a/apps/desktop/src/renderer/lib/prefs.ts
+++ b/apps/desktop/src/renderer/lib/prefs.ts
@@ -61,6 +61,8 @@ export const prefs = {
hiddenComputers: pref('hiddenComputers', ''),
computerOrder: pref<string[]>('computerOrder', []),
collapsedComputers: pref<string[]>('collapsedComputerSections', []),
+ /** Folded roster sections, by name: on this device only. */
+ collapsedRosterSections: pref<string[]>('collapsedRosterSections', []),
usageIconStyle: pref<'character' | 'original'>('usageIconStyle', 'character'),
onboardingDone: pref('macAccountOnboardingCompleted', false),
computerAccessSetup: pref<'ready' | 'later' | null>('computerAccessSetup', null),
diff --git a/apps/desktop/src/renderer/lib/roster-sections.test.ts b/apps/desktop/src/renderer/lib/roster-sections.test.ts
new file mode 100644
index 00000000..a242a558
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/roster-sections.test.ts
@@ -0,0 +1,164 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { chainedMoves, foldsAfterRename, hostHasSections, limitSectionName, placedBots, restoredBots, rosterLines, sameRosterGroup, sectionMembers, sectionName, sectionNames, sectionRename, shownRows, type RosterLine } from './roster-sections.ts'
+
+const item = (id: string, section?: string, { lead = false, pinned = false, unread = 0 } = {}) => ({ id, bot: { lead, pinned, section, unread } })
+type Item = ReturnType<typeof item>
+
+/** Each line as text: a row's id, the "Bots" label, or a header's name, count, unread and fold. */
+const outline = (lines: RosterLine<Item>[]) =>
+ lines.map((line) => (line.kind === 'row' ? line.item.id : line.kind === 'label' ? 'BOTS'
+ : `${line.name} ${line.count} ${line.unread}${line.folded ? ' folded' : ''}: ${line.items.map((i) => i.id).join(' ')}`))
+
+test('pinned rows first, then sections by name, then rows without a section under the label', () => {
+ const roster = [
+ item('pinned-work', 'Work', { pinned: true }),
+ item('loose'),
+ item('work-1', 'Work', { unread: 2 }),
+ item('home', 'personal'),
+ item('work-2', 'Work', { unread: 3 }),
+ item('apps', 'apps'),
+ ]
+ assert.deepEqual(outline(rosterLines(roster, [])), [
+ 'pinned-work',
+ 'apps 1 0: apps',
+ 'personal 1 0: home',
+ 'Work 2 5: work-1 work-2',
+ 'BOTS',
+ 'loose',
+ ])
+})
+
+test('a folded section keeps its rows for the fold, but only its header is on screen', () => {
+ const roster = [item('a', 'Work'), item('b', 'Work'), item('c')]
+ const lines = rosterLines(roster, ['Work'])
+ assert.deepEqual(outline(lines), ['Work 2 0 folded: a b', 'BOTS', 'c'])
+ assert.deepEqual(shownRows(lines).map((i) => i.id), ['c'])
+ assert.deepEqual(shownRows(rosterLines(roster, [])).map((i) => i.id), ['a', 'b', 'c'])
+})
+
+test('a section only its pinned bots are in has no header, and no header means no label', () => {
+ assert.deepEqual(outline(rosterLines([item('p', 'Work', { pinned: true }), item('c')], [])), ['p', 'c'])
+})
+
+test('the label shows only with a section header and a bot in none', () => {
+ assert.deepEqual(outline(rosterLines([item('a'), item('b')], [])), ['a', 'b'])
+ assert.deepEqual(outline(rosterLines([item('p', undefined, { pinned: true }), item('a', 'Work')], [])), ['p', 'Work 1 0: a'])
+})
+
+test('the lead stays on top, outside its section', () => {
+ const items = [item('l', 'Work', { lead: true }), item('p', undefined, { pinned: true }), item('w', 'Work'), item('c')]
+ assert.deepEqual(outline(rosterLines(items, [])), ['l', 'p', 'Work 1 0: w', 'BOTS', 'c'])
+})
+
+test('a bot moves past bots with the same pin state and section; pinned bots ignore sections', () => {
+ const bot = (section?: string, pinned = false, lead = false) => ({ lead, pinned, section })
+ assert.equal(sameRosterGroup(bot('Work'), bot('Work')), true)
+ assert.equal(sameRosterGroup(bot('Work'), bot('Home')), false)
+ assert.equal(sameRosterGroup(bot('Work'), bot()), false)
+ assert.equal(sameRosterGroup(bot(), bot('')), true)
+ assert.equal(sameRosterGroup(bot('Work', true), bot('Home', true)), true)
+ assert.equal(sameRosterGroup(bot('Work', true), bot('Work')), false)
+ assert.equal(sameRosterGroup(bot('Work', false, true), bot('Work')), false, 'the lead moves past no one')
+ assert.equal(sameRosterGroup(bot(undefined, false, true), bot(undefined, true)), false)
+})
+
+test('every section once, sorted by name', () => {
+ assert.deepEqual(sectionNames([{ section: 'Work' }, {}, { section: 'apps' }, { section: 'Work' }, { section: '' }]), ['apps', 'Work'])
+ // Names that differ only in case or accents keep one order, whatever order the bots come in.
+ for (const names of [['Work', 'work', 'Café', 'Cafe'], ['Cafe', 'work', 'Café', 'Work']]) {
+ assert.deepEqual(sectionNames(names.map((section) => ({ section }))), ['Cafe', 'Café', 'work', 'Work'])
+ }
+})
+
+test('a typed name is trimmed of whitespace and control characters, nothing left being none', () => {
+ assert.equal(sectionName(' Work\t\u0001'), 'Work')
+ assert.equal(sectionName('Side projects'), 'Side projects')
+ for (const typed of [null, '', ' \n\t', '\u00a0', '\u0000', ' \u0000 \t']) assert.equal(sectionName(typed), null)
+})
+
+test('removing a section sends `to` as null, which JSON keeps', () => {
+ assert.equal(JSON.stringify(sectionRename('Work', null)), '{"from":"Work","to":null}')
+ assert.equal(JSON.stringify(sectionRename('Work', ' ')), '{"from":"Work","to":null}')
+ assert.deepEqual(sectionRename('Work', ' Jobs '), { from: 'Work', to: 'Jobs' })
+})
+
+test('a name field stops at 40 characters as the host counts them, never inside an emoji', () => {
+ const forty = 'a'.repeat(40)
+ assert.equal(limitSectionName(forty + 'b'), forty)
+ assert.equal(limitSectionName('😀'.repeat(41)), '😀'.repeat(40))
+ assert.equal(limitSectionName('a'.repeat(39) + '😀b'), 'a'.repeat(39) + '😀')
+})
+
+test('a folded section renamed or removed here takes its fold along; an unfolded one changes nothing', () => {
+ assert.deepEqual(foldsAfterRename(['Home', 'Work'], 'Work', 'Jobs'), ['Home', 'Jobs'])
+ assert.deepEqual(foldsAfterRename(['Home'], 'Work', 'Jobs'), ['Home'])
+ assert.deepEqual(foldsAfterRename(['Home'], 'Work', 'Home'), ['Home']) // Never unfolds the target.
+ assert.deepEqual(foldsAfterRename(['Home', 'Work'], 'Work', null), ['Home'])
+ assert.deepEqual(foldsAfterRename(['Work'], 'Work', 'Home'), ['Home']) // A merge folds the section it joins.
+ assert.deepEqual(foldsAfterRename(['Home', 'Work'], 'Work', 'Home'), ['Home'])
+})
+
+type Placeable = { id: string; section?: string; unread: number }
+/** A computer's bots by id. */
+const computerBots = (...bots: Placeable[]) => new Map(bots.map((bot) => [bot.id, bot]))
+/** Shows placed bots as `BotStore.place` does. */
+const apply = (bots: Map<string, Placeable>, placed: [string, Placeable][]) => {
+ for (const [id, bot] of placed) bots.set(id, bot)
+}
+
+test('a refused section change for one bot puts back only its section', () => {
+ const bots = computerBots({ id: 'a', section: 'Work', unread: 0 }, { id: 'b', section: 'Work', unread: 0 })
+ apply(bots, placedBots(bots, ['a'], 'Home')) // The move shows at once…
+ bots.set('a', { ...bots.get('a')!, unread: 3 }) // …and a message arrives meanwhile.
+ const undo = restoredBots(bots, [{ id: 'a', from: 'Work', to: 'Home' }])
+ assert.deepEqual(undo, [['a', { id: 'a', section: 'Work', unread: 3 }]])
+ apply(bots, undo)
+ assert.deepEqual([...bots.values()], [{ id: 'a', section: 'Work', unread: 3 }, { id: 'b', section: 'Work', unread: 0 }])
+})
+
+test('a refused rename puts back exactly the bots it moved, not those already in the target', () => {
+ const bots = computerBots({ id: 'w1', section: 'Work', unread: 0 }, { id: 'h', section: 'Home', unread: 0 }, { id: 'w2', section: 'Work', unread: 0 }, { id: 'n', unread: 0 })
+ for (const to of ['Home', undefined]) { // Merged into Home, or removed.
+ const moved = sectionMembers(bots.values(), 'Work')
+ assert.deepEqual(moved, ['w1', 'w2'])
+ apply(bots, placedBots(bots, moved, to))
+ assert.deepEqual([...bots.values()].map((bot) => bot.section), [to, 'Home', to, undefined])
+ apply(bots, restoredBots(bots, moved.map((id) => ({ id, from: 'Work', to }))))
+ assert.deepEqual([...bots.values()].map((bot) => bot.section), ['Work', 'Home', 'Work', undefined])
+ }
+})
+
+test('a refused move leaves a bot moved again since where it is now', () => {
+ const bots = computerBots({ id: 'a', section: 'Side', unread: 0 }, { id: 'b', unread: 0 }, { id: 'c', section: 'Home', unread: 0 })
+ // a went Work → Home, then on to Side; b Work → Home, then out of sections on another device; c is still where its move put it.
+ const moves = ['a', 'b', 'c'].map((id) => ({ id, from: 'Work', to: 'Home' }))
+ assert.deepEqual(restoredBots(bots, moves), [['c', { id: 'c', section: 'Work', unread: 0 }]])
+ // A refused removal: only a bot still in no section goes back.
+ assert.deepEqual(restoredBots(bots, [{ id: 'a', from: 'Work', to: undefined }, { id: 'b', from: 'Work', to: undefined }]), [['b', { id: 'b', section: 'Work', unread: 0 }]])
+})
+
+test('a bot deleted before the move shows or the refusal comes back stays deleted', () => {
+ const bots = computerBots({ id: 'a', unread: 0 })
+ assert.deepEqual(placedBots(bots, ['gone', 'a'], 'Work'), [['a', { id: 'a', section: 'Work', unread: 0 }]])
+ assert.deepEqual(restoredBots(bots, [{ id: 'gone', from: 'Work', to: undefined }]), [])
+})
+
+test('a refused move chains only the later moves of its bot that started where it put it', () => {
+ const first = { id: 'a', from: 'Work', to: 'Home' }
+ const second = { id: 'a', from: 'Home', to: 'Side' }
+ const pending = [
+ { id: 'a', from: 'Home', to: 'Work' }, // Earlier: not chained.
+ first,
+ second,
+ { id: 'b', from: 'Home', to: 'Side' }, // Another bot.
+ { id: 'a', from: 'Side', to: 'X' }, // Chained to `second`, not to `first`.
+ ]
+ assert.deepEqual(chainedMoves(pending, first), [second])
+})
+
+test('sections show only on hosts from 2.32.0, dev builds included', () => {
+ assert.equal(hostHasSections('2.31.2'), false)
+ assert.equal(hostHasSections('2.32.0'), true)
+ assert.equal(hostHasSections('2.32.1-dev'), true)
+})
diff --git a/apps/desktop/src/renderer/lib/roster-sections.ts b/apps/desktop/src/renderer/lib/roster-sections.ts
new file mode 100644
index 00000000..937b9f2f
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/roster-sections.ts
@@ -0,0 +1,138 @@
+import { isBelow } from '../../shared/compat.ts'
+import { rosterBand } from './computer-roster.ts'
+
+/** The first host with roster sections. */
+const ROSTER_SECTIONS_HOST = '2.32.0'
+
+/** Whether a host of `version` keeps roster sections (an older one leaves them out). */
+export function hostHasSections(version: string): boolean {
+ return !isBelow(version, ROSTER_SECTIONS_HOST)
+}
+
+/** What placing a bot in the roster reads: lead, its pin, the section the user put it in, its unread count. */
+interface Placed {
+ lead: boolean
+ pinned: boolean
+ section?: string
+ unread: number
+}
+
+/** One line of a computer's roster: a bot's row, a section header holding its rows, or the "Bots" label. */
+export type RosterLine<T> =
+ | { kind: 'row'; item: T }
+ | { kind: 'section'; name: string; count: number; unread: number; folded: boolean; items: T[] }
+ | { kind: 'label' }
+
+/** The lead and pinned bots stay on top, outside sections. */
+const onTop = (bot: Omit<Placed, 'unread' | 'section'>) => bot.lead || bot.pinned
+
+/**
+ * A computer's roster (already in roster order, hidden bots left out) as lines: the lead and pinned
+ * rows, then each section by name with its rows, then rows without a section, under a "Bots" label
+ * when there are sections. The lead and a pinned bot show only on top. A folded section still holds
+ * its rows, so its fold can animate.
+ */
+export function rosterLines<T extends { bot: Placed }>(items: T[], folded: readonly string[]): RosterLine<T>[] {
+ const row = (item: T): RosterLine<T> => ({ kind: 'row', item })
+ const unpinned = items.filter((item) => !onTop(item.bot))
+ const sections = sectionNames(unpinned.map((item) => item.bot)).map((name): RosterLine<T> => {
+ const rows = unpinned.filter((item) => item.bot.section === name)
+ const unread = rows.reduce((sum, item) => sum + item.bot.unread, 0)
+ return { kind: 'section', name, count: rows.length, unread, folded: folded.includes(name), items: rows }
+ })
+ const loose = unpinned.filter((item) => !item.bot.section).map(row)
+ const label: RosterLine<T>[] = sections.length && loose.length ? [{ kind: 'label' }] : []
+ return [...items.filter((item) => onTop(item.bot)).map(row), ...sections, ...label, ...loose]
+}
+
+/** The rows on screen, top to bottom: a folded section's rows are left out. */
+export function shownRows<T>(lines: RosterLine<T>[]): T[] {
+ return lines.flatMap((line) => (line.kind === 'row' ? [line.item] : line.kind === 'label' || line.folded ? [] : line.items))
+}
+
+/** The section a bot shows in: none for the lead and pinned bots, which stay on top (terminal `Bot::shown_section`). */
+export function shownSection(bot: Omit<Placed, 'unread'>): string | undefined {
+ return onTop(bot) ? undefined : bot.section || undefined
+}
+
+/** Whether a drag (or Alt+↑/↓) may move one bot past another: the same band (lead, pinned, the rest) and the same section shown. */
+export function sameRosterGroup(a: Omit<Placed, 'unread'>, b: Omit<Placed, 'unread'>): boolean {
+ return rosterBand(a) === rosterBand(b) && shownSection(a) === shownSection(b)
+}
+
+/** Every section among `bots` once, by name as the user's language sorts it ("İş" too; "work" before "Work", as on the phones). */
+export function sectionNames(bots: Iterable<{ section?: string }>): string[] {
+ const names = new Set<string>()
+ for (const bot of bots) if (bot.section) names.add(bot.section)
+ return [...names].sort((a, b) => a.localeCompare(b))
+}
+
+/** The section a typed name names: trimmed of whitespace and control characters, null when nothing is left (iOS `RosterSection.name(typed:)`). */
+export function sectionName(typed: string | null): string | null {
+ return typed?.replace(/^[\s\p{Cc}]+|[\s\p{Cc}]+$/gu, '') || null
+}
+
+/** `renameSection`'s payload: `to` as `sectionName` reads it, and null (sent, not left out) to remove the section. */
+export function sectionRename(from: string, to: string | null): { from: string; to: string | null } {
+ return { from, to: sectionName(to) }
+}
+
+/**
+ * This device's folded sections after it renames section `from` to `to` (null: removes it): a folded
+ * `from` stays folded under `to`, so a merge folds the section it joins; an unfolded one changes nothing.
+ */
+export function foldsAfterRename(folded: readonly string[], from: string, to: string | null): string[] {
+ if (!folded.includes(from)) return [...folded]
+ const rest = folded.filter((name) => name !== from)
+ return to === null || rest.includes(to) ? rest : [...rest, to]
+}
+
+/** The ids of the bots in section `name`: what renaming or removing it moves, and a refusal moves back (never bots already in the target). */
+export function sectionMembers(bots: Iterable<{ id: string; section?: string }>, name: string): string[] {
+ return [...bots].filter((bot) => bot.section === name).map((bot) => bot.id)
+}
+
+/** The bots with these ids still there, each put in `section` (none: undefined) and otherwise as they are now: a section change shown before the host confirms it. */
+export function placedBots<T extends { section?: string }>(bots: ReadonlyMap<string, T>, ids: readonly string[], section: string | undefined): [string, T][] {
+ return ids.flatMap((id): [string, T][] => {
+ const bot = bots.get(id)
+ return bot ? [[id, { ...bot, section }]] : []
+ })
+}
+
+/** A section change shown before the host accepted it: bot `id` from section `from` to `to` (none: undefined). */
+export interface SectionMove {
+ id: string
+ from: string | undefined
+ to: string | undefined
+}
+
+/**
+ * Taking back `moves` the host refused: each bot still in the section its move put it in goes back to
+ * the one it left, otherwise as it is now. A bot moved again since (here or on another device) keeps
+ * its newer section, and a deleted one stays deleted.
+ */
+export function restoredBots<T extends { section?: string }>(bots: ReadonlyMap<string, T>, moves: readonly SectionMove[]): [string, T][] {
+ return moves.flatMap(({ id, from, to }): [string, T][] => {
+ const bot = bots.get(id)
+ return bot && bot.section === to ? [[id, { ...bot, section: from }]] : []
+ })
+}
+
+/**
+ * The moves still waiting (`pending`, oldest first) that started where `refused` put its bot: later
+ * moves of the same bot from its `to`. They start where `refused` began instead, so taking one of
+ * them back too lands where the host still has the bot.
+ */
+export function chainedMoves(pending: readonly SectionMove[], refused: SectionMove): SectionMove[] {
+ return pending.slice(pending.indexOf(refused) + 1).filter((move) => move.id === refused.id && move.from === refused.to)
+}
+
+/** The most characters a section name may have, counted as the host counts them (code points). */
+const SECTION_NAME_LIMIT = 40
+
+/** What a name field holds: at most `SECTION_NAME_LIMIT` characters, never cut inside an emoji. */
+export function limitSectionName(typed: string): string {
+ const chars = [...typed]
+ return chars.length > SECTION_NAME_LIMIT ? chars.slice(0, SECTION_NAME_LIMIT).join('') : typed
+}
diff --git a/apps/desktop/src/renderer/lib/undo-on-failure.test.ts b/apps/desktop/src/renderer/lib/undo-on-failure.test.ts
new file mode 100644
index 00000000..63d7e42f
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/undo-on-failure.test.ts
@@ -0,0 +1,23 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { undoOnFailure } from './undo-on-failure.ts'
+
+/** What happens, in order, when `action` settles, then whether it went through. */
+async function settle(action: Promise<unknown>, withUndo = true) {
+ const log: string[] = []
+ const accepted = await undoOnFailure(action, withUndo ? () => log.push('undo') : undefined, (message) => log.push(`error: ${message}`))
+ return [...log, accepted ? 'accepted' : 'refused']
+}
+
+test('a refused action is taken back before its error shows', async () => {
+ assert.deepEqual(await settle(Promise.reject(new Error('Section names are 40 characters at most'))), ['undo', 'error: Section names are 40 characters at most', 'refused'])
+ assert.deepEqual(await settle(Promise.reject('timed out')), ['undo', 'error: timed out', 'refused'])
+})
+
+test('an accepted action keeps what it showed', async () => {
+ assert.deepEqual(await settle(Promise.resolve()), ['accepted'])
+})
+
+test('an action with nothing to take back still shows its error', async () => {
+ assert.deepEqual(await settle(Promise.reject(new Error('offline')), false), ['error: offline', 'refused'])
+})
diff --git a/apps/desktop/src/renderer/lib/undo-on-failure.ts b/apps/desktop/src/renderer/lib/undo-on-failure.ts
new file mode 100644
index 00000000..ab75bafc
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/undo-on-failure.ts
@@ -0,0 +1,11 @@
+/** Waits for `action` and resolves to whether it went through; when it fails (refused, or the link gave up), `undo` takes back what it already showed before `fail` reports why. */
+export async function undoOnFailure(action: Promise<unknown>, undo: (() => void) | undefined, fail: (message: string) => void): Promise<boolean> {
+ try {
+ await action
+ return true
+ } catch (error) {
+ undo?.()
+ fail(error instanceof Error ? error.message : String(error))
+ return false
+ }
+}
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.ts
index 8a0a106f..8f8af610 100644
--- a/apps/desktop/src/renderer/store/bot-mirror.ts
+++ b/apps/desktop/src/renderer/store/bot-mirror.ts
@@ -14,6 +14,7 @@ import type { HostClient, HostRoute, HostTransport } from '../client/host-client
import { rosterOrder } from '../lib/computer-roster'
import { HOST_UPDATE_WAIT, hostVersionLine, offerHostUpdate, type HostUpdate, type HostUpdateOffer, type HostVersionLine } from '../lib/host-update'
import { Observable } from '../lib/observable'
+import { hostHasSections } from '../lib/roster-sections'
import { ComposerDrafts } from '@shared/composer-drafts'
import { canLoadHistory } from '@shared/mirror-window'
@@ -111,6 +112,11 @@ export class BotMirror extends Observable {
return null
}
+ /** The host keeps roster sections (an older one leaves them out): the menus offer them only then. */
+ get hasRosterSections() {
+ return this.hostVersion !== null && hostHasSections(this.hostVersion.version)
+ }
+
/** What the update notice offers while this computer is behind this app. */
get hostUpdateOffer(): HostUpdateOffer {
return offerHostUpdate(this.hostUpdate, this.hello?.canUpdate === true)
diff --git a/apps/desktop/src/renderer/store/bot-sections.test.ts b/apps/desktop/src/renderer/store/bot-sections.test.ts
new file mode 100644
index 00000000..edbabb77
--- /dev/null
+++ b/apps/desktop/src/renderer/store/bot-sections.test.ts
@@ -0,0 +1,101 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import type { Bot } from '@shared/models'
+import type { HostClient } from '../client/host-client'
+import { BotSections } from './bot-sections.ts'
+
+/**
+ * A computer's sections over bots in `placed` (id → section), with a host that answers each call only
+ * when the test says: `answer(i, false)` refuses call `i` as `perform` does (undo, then settle).
+ */
+function computer(placed: Record<string, string>) {
+ const bots = new Map(Object.entries(placed).map(([id, section]) => [id, { id, section } as Bot]))
+ const sent: unknown[][] = []
+ const answers: ((accepted: boolean) => void)[] = []
+ const sections = new BotSections(() => bots, () => {}, (op, undo) => new Promise<boolean>((resolve) => {
+ void op({ call: async (method: string, body: unknown) => sent.push([method, body]) } as unknown as HostClient)
+ answers.push((accepted) => {
+ if (!accepted) undo()
+ resolve(accepted)
+ })
+ }))
+ return {
+ sections, sent,
+ bot: (id: string) => bots.get(id)!,
+ where: () => Object.fromEntries([...bots.values()].map((bot) => [bot.id, bot.section])),
+ answer: (i: number, accepted: boolean) => answers[i]!(accepted),
+ }
+}
+
+test('a move sends only the section and shows at once; a refusal puts it back', async () => {
+ const { sections, sent, bot, where, answer } = computer({ a: 'Work' })
+ const moved = sections.move(bot('a'), ' Home ')
+ assert.deepEqual(sent, [['updateBot', { id: 'a', section: 'Home' }]])
+ assert.deepEqual(where(), { a: 'Home' })
+ answer(0, false)
+ assert.equal(await moved, false)
+ assert.deepEqual(where(), { a: 'Work' })
+})
+
+test('chained moves refused in order end where the host still has the bot', async () => {
+ // With the link down: a goes Work → Home, then Home → Side; both are refused after the wait.
+ const { sections, bot, where, answer } = computer({ a: 'Work', b: 'Home' })
+ const first = sections.move(bot('a'), 'Home')
+ const second = sections.move(bot('a'), 'Side')
+ const other = sections.move(bot('b'), 'Side') // Another bot's move from Home is not chained.
+ answer(0, false)
+ await first
+ assert.deepEqual(where(), { a: 'Side', b: 'Side' }) // Moved again since: left alone.
+ answer(1, false)
+ await second
+ assert.deepEqual(where(), { a: 'Work', b: 'Side' }) // Not Home, which the host never had.
+ answer(2, false)
+ await other
+ assert.deepEqual(where(), { a: 'Work', b: 'Home' })
+})
+
+test('chained moves refused out of order end where the host still has the bot', async () => {
+ const { sections, bot, where, answer } = computer({ a: 'Work' })
+ const moves = [sections.move(bot('a'), 'Home'), sections.move(bot('a'), 'Side'), sections.move(bot('a'), 'X')]
+ for (const i of [1, 0, 2]) {
+ answer(i, false)
+ await moves[i]
+ }
+ assert.deepEqual(where(), { a: 'Work' })
+})
+
+test('a refused rename followed by a refused move of one of its bots puts both bots back', async () => {
+ const { sections, bot, where, answer } = computer({ w1: 'Work', w2: 'Work', h: 'Home' })
+ const renamed = sections.rename('Work', 'Home')
+ const moved = sections.move(bot('w1'), 'Side')
+ answer(0, false)
+ await renamed
+ assert.deepEqual(where(), { w1: 'Side', w2: 'Work', h: 'Home' })
+ answer(1, false)
+ await moved
+ assert.deepEqual(where(), { w1: 'Work', w2: 'Work', h: 'Home' })
+})
+
+test('a refused rename runs its callback while its bots are still moved, then puts them back; an accepted one never does', async () => {
+ const { sections, where, answer } = computer({ w: 'Work' })
+ const seen: Record<string, string | undefined>[] = []
+ const refused = sections.rename('Work', 'Jobs', () => seen.push(where()))
+ answer(0, false)
+ await refused
+ assert.deepEqual(where(), { w: 'Work' })
+ const accepted = sections.rename('Work', 'Jobs', () => seen.push(where()))
+ answer(1, true)
+ await accepted
+ assert.deepEqual(seen, [{ w: 'Jobs' }])
+})
+
+test('an accepted move stays, and later refusals no longer chain to it', async () => {
+ const { sections, bot, where, answer } = computer({ a: 'Work' })
+ const first = sections.move(bot('a'), 'Home')
+ answer(0, true)
+ assert.equal(await first, true)
+ const second = sections.move(bot('a'), 'Side')
+ answer(1, false)
+ await second
+ assert.deepEqual(where(), { a: 'Home' })
+})
diff --git a/apps/desktop/src/renderer/store/bot-sections.ts b/apps/desktop/src/renderer/store/bot-sections.ts
new file mode 100644
index 00000000..d329798c
--- /dev/null
+++ b/apps/desktop/src/renderer/store/bot-sections.ts
@@ -0,0 +1,61 @@
+import type { Bot } from '@shared/models'
+import type { HostClient } from '../client/host-client'
+import { chainedMoves, placedBots, restoredBots, sectionMembers, sectionName, sectionRename, type SectionMove } from '../lib/roster-sections.ts'
+
+/** A host call that, when refused, runs `undo` before the error shows; resolves to whether it went through. */
+type Perform = (op: (c: HostClient) => Promise<unknown>, undo: () => void) => Promise<boolean>
+
+/** One computer's roster sections: moves and renames shown at once, then sent; a refusal takes them back. */
+export class BotSections {
+ private bots: () => Map<string, Bot>
+ private changed: () => void
+ private perform: Perform
+ /** Moves shown but not answered yet, oldest first. */
+ private pending: SectionMove[] = []
+ constructor(bots: () => Map<string, Bot>, changed: () => void, perform: Perform) {
+ this.bots = bots
+ this.changed = changed
+ this.perform = perform
+ }
+
+ /** Puts the bot in roster section `name`, or takes it out of its section (null). Sends only the section, so a setting changed on another device meanwhile stays. Resolves to whether the host did it. */
+ move(bot: Bot, name: string | null): Promise<boolean> {
+ const section = sectionName(name)
+ return this.moveBots([bot.id], section ?? undefined, (c) => c.call('updateBot', { id: bot.id, section }))
+ }
+
+ /**
+ * Renames a section on this computer (onto another one's name merges them); null removes it, its bots
+ * stay. A refusal runs `onRefused` as its bots go back, in the same update. Resolves to whether the host did it.
+ */
+ rename(from: string, to: string | null, onRefused?: () => void): Promise<boolean> {
+ const rename = sectionRename(from, to)
+ return this.moveBots(sectionMembers(this.bots().values(), from), rename.to ?? undefined, (c) => c.call('renameSection', rename), onRefused)
+ }
+
+ /**
+ * Shows bots `ids` in section `to` (none: undefined) before the host's bot events confirm it, then
+ * sends `op`; a refusal takes back the moves nothing changed since. Resolves to whether the host accepted.
+ */
+ private async moveBots(ids: string[], to: string | undefined, op: (c: HostClient) => Promise<unknown>, onRefused?: () => void): Promise<boolean> {
+ const moves = ids.map((id) => ({ id, from: this.bots().get(id)?.section, to }))
+ this.pending.push(...moves)
+ this.place(placedBots(this.bots(), ids, to))
+ try {
+ return await this.perform(op, () => {
+ onRefused?.()
+ // A later move that started where a refused one put the bot now starts where the host still has it.
+ for (const move of moves) for (const later of chainedMoves(this.pending, move)) later.from = move.from
+ this.place(restoredBots(this.bots(), moves))
+ })
+ } finally {
+ this.pending = this.pending.filter((move) => !moves.includes(move))
+ }
+ }
+
+ private place(placed: [string, Bot][]) {
+ const bots = this.bots()
+ for (const [id, bot] of placed) bots.set(id, bot)
+ this.changed()
+ }
+}
diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.ts
index 1cf19233..1d4c44c6 100644
--- a/apps/desktop/src/renderer/store/bot-store.ts
+++ b/apps/desktop/src/renderer/store/bot-store.ts
@@ -17,6 +17,7 @@ import type { CallLine } from '@shared/calls'
import type { HostClient } from '../client/host-client'
import { readSharedFile } from '../../shared/files.ts'
import { FileDownloads } from './file-downloads'
+import { BotSections } from './bot-sections'
import { BotSync, sleep } from './bot-sync'
export { builtInBackendName, type Connection } from './bot-mirror'
@@ -49,6 +50,7 @@ export const QUICK_REACTIONS = ['👍', '❤️', '😂', '🎉', '👀', '✅']
*/
export class BotStore extends BotSync {
readonly fileDownloads = new FileDownloads(() => this.changed())
+ readonly sections = new BotSections(() => this.bots, () => this.changed(), (op, undo) => this.perform(op, true, undo))
override retire() { this.fileDownloads.retire(); super.retire() }
diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.ts
index dbc26721..25f0c81f 100644
--- a/apps/desktop/src/renderer/store/bot-sync.ts
+++ b/apps/desktop/src/renderer/store/bot-sync.ts
@@ -1,6 +1,7 @@
import { isChat, type AccessRequest, type CloudStatus, type Entry } from '@shared/models'
import { isOutsideLoadedWindow, snapshotFloors } from '@shared/mirror-window'
import { HostClient, HostError, type HostEvent } from '../client/host-client'
+import { undoOnFailure } from '../lib/undo-on-failure'
import { BotMirror, type Connection } from './bot-mirror'
import { Artifacts } from './artifacts'
import type { CallCue } from '@shared/calls'
@@ -392,9 +393,10 @@ export class BotSync extends BotMirror {
}
}
- protected perform(op: (c: HostClient) => Promise<unknown>, replay = false) {
- void this.withLink(op, replay).catch((error: unknown) => {
- this.lastError = error instanceof Error ? error.message : String(error)
+ /** Fire and forget (resolving to whether it went through): what waiting and retrying couldn't settle reaches the dialog, after `undo` takes back what the action already showed. */
+ protected perform(op: (c: HostClient) => Promise<unknown>, replay = false, undo?: () => void): Promise<boolean> {
+ return undoOnFailure(this.withLink(op, replay), undo, (message) => {
+ this.lastError = message
this.changed()
})
}
diff --git a/apps/desktop/src/renderer/store/computer-roster.ts b/apps/desktop/src/renderer/store/computer-roster.ts
index 3343ce73..be8eedef 100644
--- a/apps/desktop/src/renderer/store/computer-roster.ts
+++ b/apps/desktop/src/renderer/store/computer-roster.ts
@@ -1,6 +1,7 @@
-import { computerSections, moveInOrder, orderedComputers, rosterBand } from '../lib/computer-roster'
+import { computerSections, moveInOrder, orderedComputers } from '../lib/computer-roster'
import { prefs, usePref } from '../lib/prefs'
import { useModel } from '../lib/observable'
+import { foldsAfterRename, rosterLines, sameRosterGroup, sectionRename, shownRows, shownSection } from '../lib/roster-sections'
import type { BotStore } from './bot-store'
import type { AppModel, BotRef } from './app-model'
@@ -8,6 +9,7 @@ import type { AppModel, BotRef } from './app-model'
export function useComputerRoster(app: AppModel, shown: Set<string>) {
const order = useModel(app.computerOrder).ids
const [collapsed, setCollapsed] = usePref(prefs.collapsedComputers)
+ const [folded, setFolded] = usePref(prefs.collapsedRosterSections)
const computers = orderedComputers(app.computers, order)
const sections = computerSections(computers.filter((c) => shown.has(c.id)), app.roster)
.map((section) => ({ ...section, store: app.store(section.computer.id) }))
@@ -17,22 +19,47 @@ export function useComputerRoster(app: AppModel, shown: Set<string>) {
sections,
grouped,
collapsed,
+ folded,
items: sections.flatMap((section) => section.items),
- navigable: sections.flatMap((section) => grouped && collapsed.includes(section.computer.id) ? [] : section.items),
+ /** The rows on screen, top to bottom, for ↑/↓. */
+ navigable: sections.flatMap((section) => grouped && collapsed.includes(section.computer.id) ? [] : shownRows(rosterLines(section.items, folded))),
toggle(id: string) {
- setCollapsed(collapsed.includes(id) ? collapsed.filter((value) => value !== id) : [...collapsed, id])
+ setCollapsed(toggled(collapsed, id))
+ },
+ /** Folds or unfolds roster section `name` on this device. */
+ toggleFold(name: string) {
+ setFolded(toggled(folded, name))
+ },
+ /** Renames or removes (null) a section on `store`'s computer; a folded one stays folded under its new name, on this device, unless the host refuses. */
+ renameSection(store: BotStore, from: string, to: string | null) {
+ // Read now: a name dialog saves after the render that built its menu.
+ const before = prefs.collapsedRosterSections.get()
+ const after = foldsAfterRename(before, from, sectionRename(from, to).to)
+ setFolded(after)
+ // Refused: the folds go back with the bots (one render, no open-then-fold), unless they were toggled while the host answered.
+ void store.sections.rename(from, to, () => {
+ if (prefs.collapsedRosterSections.get() === after) setFolded(before)
+ })
},
move(id: string, target: string) {
app.computerOrder.move(id, target, computers.map((c) => c.id))
},
- /** One place up (-1) or down (+1) among its computer's bots in the same band (lead, pinned, the rest). */
+ /** One place up (-1) or down (+1) among its computer's bots in the same band (lead, pinned, the rest) and, for the rest, the same section. */
moveBot(ref: BotRef, offset: number) {
const section = sections.find((s) => s.computer.id === ref.computerId)
const items = section?.items ?? []
- const index = items.findIndex((item) => item.bot.id === ref.botId)
- const target = items[index + offset]
- if (!section || index < 0 || !target || rosterBand(target.bot) !== rosterBand(items[index]!.bot)) return
- section.store.reorder(moveInOrder(items.map((item) => item.bot.id), ref.botId, target.bot.id))
+ const moved = items.find((item) => item.bot.id === ref.botId)
+ const shown = moved && shownSection(moved.bot)
+ // A folded section shows no order to change.
+ if (!section || !moved || (shown && folded.includes(shown))) return
+ const group = items.filter((item) => sameRosterGroup(item.bot, moved.bot))
+ const target = group[group.indexOf(moved) + offset]
+ if (target) section.store.reorder(moveInOrder(items.map((item) => item.bot.id), ref.botId, target.bot.id))
},
}
}
+
+/** `list` with `value` added, or taken out when it's there. */
+function toggled(list: string[], value: string) {
+ return list.includes(value) ? list.filter((v) => v !== value) : [...list, value]
+}
diff --git a/apps/desktop/src/renderer/views/BotRoster.tsx b/apps/desktop/src/renderer/views/BotRoster.tsx
index 8b4fd925..1a3b815b 100644
--- a/apps/desktop/src/renderer/views/BotRoster.tsx
+++ b/apps/desktop/src/renderer/views/BotRoster.tsx
@@ -1,8 +1,9 @@
import { useRef, useState, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
import { isGroup, type Bot } from '@shared/models'
-import { moveInOrder, rosterBand } from '../lib/computer-roster'
+import { moveInOrder } from '../lib/computer-roster'
import { pointerDrag, type Point } from '../lib/pointer-drag'
+import { rosterLines, sameRosterGroup } from '../lib/roster-sections'
import { reduceMotion } from '../lib/theme'
import { useSlide } from '../lib/slide'
import { sameRef, refKey, type RosterItem } from '../store/app-model'
@@ -11,6 +12,7 @@ import type { useComputerRoster } from '../store/computer-roster'
import { StoreContext, useApp } from '../store/context'
import { BotRow } from './BotRow'
import { ComputerHeadingLabel, ComputerRosterSection } from './ComputerRosterSection'
+import { RosterLabel, RosterSection } from './RosterSection'
import { UpdateNeededCard } from './UpdateNeededCard'
/** A bot being dragged among its computer's bots, and the order it has made so far. */
@@ -34,10 +36,11 @@ interface Lift {
seq: number
}
-export function BotRoster({ roster, compact, onContext, openExtensions }: {
+export function BotRoster({ roster, compact, onContext, onSectionContext, openExtensions }: {
roster: ReturnType<typeof useComputerRoster>
compact: boolean
onContext: (bot: Bot, store: BotStore, x: number, y: number) => void
+ onSectionContext: (section: string, store: BotStore, x: number, y: number) => void
/** A computer's own Extensions, from its heading. */
openExtensions: (computerId: string) => void
}) {
@@ -138,14 +141,14 @@ export function BotRoster({ roster, compact, onContext, openExtensions }: {
edgeScroll.current = requestAnimationFrame(scrollAtEdge)
}
- // Any row of the same computer is a target; only rows in the same band (lead, pinned, the rest) make room.
+ // Any row of the same computer is a target; only rows in the same band (lead, pinned, the rest) and, for the rest, the same section make room.
const makeRoom = (under: Element | null) => {
const current = drag.current
const row = under?.closest<HTMLElement>('[data-roster-row]')
const item = row && itemsByKey.current.get(row.dataset.rosterRow!)
if (!current || !row || !item || current.item.ref.computerId !== item.ref.computerId) return
// A row still sliding out of the way would be hit again where it was.
- if (item.bot.id === current.item.bot.id || rosterBand(item.bot) !== rosterBand(current.item.bot) || row.getAnimations().length) return
+ if (item.bot.id === current.item.bot.id || !sameRosterGroup(item.bot, current.item.bot) || row.getAnimations().length) return
setBotDrag({ ...current, ids: moveInOrder(current.ids, current.item.bot.id, item.bot.id) })
}
@@ -211,7 +214,12 @@ export function BotRoster({ roster, compact, onContext, openExtensions }: {
const sections = sectionOrder.map(({ computer, store, items }) => {
const index = roster.sections.findIndex((s) => s.computer.id === computer.id)
const notice = store.mismatch && !compact ? <StoreContext.Provider value={store}><UpdateNeededCard /></StoreContext.Provider> : null
- const rows = ordered(computer.id, items).map((item) => row(item, items))
+ const rows = rosterLines(ordered(computer.id, items), roster.folded).map((line) => line.kind === 'row' ? row(line.item, items) : line.kind === 'label' ? <RosterLabel key="label" compact={compact} /> : (
+ <RosterSection key={`section/${line.name}`} name={line.name} count={line.count} unread={line.unread} folded={line.folded} compact={compact}
+ toggle={() => roster.toggleFold(line.name)} onContext={(x, y) => onSectionContext(line.name, store, x, y)}>
+ {line.items.map((item) => row(item, items))}
+ </RosterSection>
+ ))
if (!roster.grouped) return <div key={computer.id}>{notice}{rows}</div>
return (
<ComputerRosterSection key={computer.id} store={store} compact={compact}
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 98fa3b51..6b157188 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -36,7 +36,9 @@ export { EmptyState } from './HostStateView'
import { RefreshIndicator } from './RefreshIndicator'
import { StarPrompt } from './StarPrompt'
import { OpenVoiceSettings } from './call/CallView'
-import { AccountPanelLayer, DesktopActionMenu, ProfileAvatar } from './PanelMenus'
+import { AccountPanelLayer, DesktopActionMenu, ProfileAvatar, type ActionItem } from './PanelMenus'
+import { moveToSectionItems, sectionHeaderItems, type SectionNaming } from './section-menus'
+import { SectionNameDialog } from './SectionNameDialog'
import { useTraySummary } from './tray-summary'
import { useIslandSummary } from './island-summary'
import { useSSH, useSSHAttachments } from './settings/ssh-model'
@@ -199,7 +201,8 @@ function ChatSplitView() {
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)
+ const [context, setContext] = useState<{ items: ActionItem[]; x: number; y: number } | null>(null)
+ const [naming, setNaming] = useState<SectionNaming | null>(null)
const [editing, setEditing] = useState<EditTarget | null>(null)
const [confirmDelete, setConfirmDelete] = useState<BotTarget | null>(null)
const [newSessionBot, setNewSessionBot] = useState<BotTarget | null>(null)
@@ -286,9 +289,10 @@ function ChatSplitView() {
const openMarketplace = () => setMarketplace((selectedStore ?? app.local ?? onlineStores[0])?.computer.id ?? null)
- // The lead stays on top and can't go: no pin, hide or delete.
- const botActions = (bot: Bot, store: BotStore): MenuItem[] => [
+ // The lead stays on top and can't go: no pin, section, hide or delete.
+ const botActions = (bot: Bot, store: BotStore): ActionItem[] => [
...(bot.lead ? [] : [{ title: bot.pinned ? 'Unpin' : 'Pin', icon: 'pin', action: () => store.setPinned(bot, !bot.pinned) }]),
+ ...moveToSectionItems(bot, store, setNaming),
{ title: 'Mark as Read', icon: 'bell.badge', action: () => store.markAllRead(bot.id) },
{ title: 'Edit Profile…', icon: 'square.and.pencil', divider: true, action: () => setEditing({ id: crypto.randomUUID(), draft: draftOf(bot), store }) },
{ title: 'Copy conversation ID', icon: 'square.on.square', divider: true, action: () => window.codync.app.copy(bot.id) },
@@ -359,7 +363,7 @@ function ChatSplitView() {
const width = compact ? 76 : sidebarWidth
return (
- <div className={`split ${showAccount || contextBot ? 'covered' : ''}`}>
+ <div className={`split ${showAccount || context ? 'covered' : ''}`}>
<aside className={`sidebar ${compact ? 'compact' : ''} ${resizing ? 'resizing' : ''}`} style={{ width }}>
<div className="sidebar-header drag" inert={compact}>
<Spacer />
@@ -379,11 +383,17 @@ function ChatSplitView() {
) : null}
<div className="roster" ref={listRef} tabIndex={0} onKeyDown={onListKey}>
{roster.grouped && !compact ? <ExtensionsMovedTip /> : null}
- <BotRoster roster={roster} compact={compact} onContext={(bot, store, x, y) => setContextBot({ target: { bot, store }, x, y })} openExtensions={(id) => {
- // Found it: the tip about where Extensions went has done its job.
- prefs.extensionsMovedTipSeen.set(true)
- setMarketplace(id)
- }} />
+ <BotRoster roster={roster} compact={compact}
+ onContext={(bot, store, x, y) => setContext({ items: botActions(bot, store), x, y })}
+ onSectionContext={(section, store, x, y) => {
+ const items = sectionHeaderItems(section, store, setNaming, (to) => roster.renameSection(store, section, to))
+ if (items.length) setContext({ items, x, y })
+ }}
+ openExtensions={(id) => {
+ // Found it: the tip about where Extensions went has done its job.
+ prefs.extensionsMovedTipSeen.set(true)
+ setMarketplace(id)
+ }} />
{visibleRoster.length === 0 && !roster.grouped && !compact && mismatchStores.length === 0 ? (
<div className="roster-empty">
<Text as="div" size="body" weight="medium">{onlineStores.length ? tr(`No bots yet`) : tr(`Waiting for a computer`)}</Text>
@@ -428,12 +438,13 @@ function ChatSplitView() {
}}
/>
) : null}
- {contextBot ? (
- <div className="context-layer" onMouseDown={(e) => e.target === e.currentTarget && setContextBot(null)}>
+ {context ? (
+ <div className="context-layer" onMouseDown={(e) => e.target === e.currentTarget && setContext(null)}>
<DesktopActionMenu
- items={botActions(contextBot.target.bot, contextBot.target.store)}
- onDismiss={() => setContextBot(null)}
- style={{ left: Math.min(Math.max(8, contextBot.x), windowSize.width - 268), top: Math.min(Math.max(8, contextBot.y), Math.max(8, windowSize.height - 344)) }}
+ items={context.items}
+ onDismiss={() => setContext(null)}
+ x={context.x}
+ y={context.y}
/>
</div>
) : null}
@@ -478,6 +489,7 @@ function ChatSplitView() {
actions={confirmDelete ? [{ title: 'Delete bot and its conversation', destructive: true, action: () => confirmDelete.store.delete(confirmDelete.bot) }] : []}
onClose={() => setConfirmDelete(null)}
/>
+ <SectionNameDialog naming={naming} onClose={() => setNaming(null)} />
<Dialog open={errorMessage !== null} title={tr('Something went wrong')} message={errorMessage} actions={[]} cancel="OK" onClose={() => app.clearErrors()} />
</div>
)
diff --git a/apps/desktop/src/renderer/views/PanelMenus.tsx b/apps/desktop/src/renderer/views/PanelMenus.tsx
index 49b7a560..c1bacbd0 100644
--- a/apps/desktop/src/renderer/views/PanelMenus.tsx
+++ b/apps/desktop/src/renderer/views/PanelMenus.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, type ReactNode } from 'react'
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
import { Spinner } from '../components/Controls'
import { Icon } from '../components/Icon'
import type { MenuItem } from '../components/Overlay'
@@ -41,6 +41,8 @@ interface PanelItem {
chevron?: boolean
disabled?: boolean
destructive?: boolean
+ /** A name the user gave: shown as typed, never translated. */
+ verbatim?: boolean
action: () => void
}
@@ -110,9 +112,15 @@ export function AccountPanelLayer({ compact, approvals, onDismiss, onUsage, onSe
)
}
-function PanelRows({ items, onDismiss, after, dismissOnActivate = false }: { items: PanelItem[]; onDismiss: () => void; after?: (i: number) => ReactNode; dismissOnActivate?: boolean }) {
+function PanelRows({ items, onDismiss, after }: { items: PanelItem[]; onDismiss: () => void; after?: (i: number) => ReactNode }) {
const tr = useTr()
const [highlighted, setHighlighted] = useState(0)
+ const highlightedRow = useRef<HTMLButtonElement>(null)
+ // A long list scrolls: ↑/↓ and Tab bring the row Enter would run into view.
+ // A block, not an arrow's value: Chromium's scrollIntoView returns a promise, which React would call as the clean-up.
+ useEffect(() => {
+ highlightedRow.current?.scrollIntoView({ block: 'nearest' })
+ }, [highlighted])
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
@@ -127,32 +135,28 @@ function PanelRows({ items, onDismiss, after, dismissOnActivate = false }: { ite
} else if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
const item = items[highlighted]
- if (item && !item.disabled) {
- if (dismissOnActivate) onDismiss()
- item.action()
- }
+ if (item && !item.disabled) item.action()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
- }, [items, highlighted, onDismiss, dismissOnActivate])
+ }, [items, highlighted, onDismiss])
return (
<VStack gap={2}>
{items.map((item, i) => (
<div key={item.title}>
<button
+ ref={highlighted === i ? highlightedRow : undefined}
className={`panel-row ${highlighted === i ? 'highlight' : ''} ${item.destructive ? 'destructive' : ''}`}
disabled={item.disabled}
- onMouseEnter={() => setHighlighted(i)}
- onClick={() => {
- if (dismissOnActivate) onDismiss()
- item.action()
- }}
+ // Movement, not enter: Chromium re-enters the row under a resting pointer after a scroll, which would undo ↑/↓.
+ onMouseMove={() => setHighlighted(i)}
+ onClick={item.action}
>
<IconSlot width={20}>
{item.image ? <img src={item.image} alt="" width={14} height={14} /> : <Icon name={item.icon} size={14} />}
</IconSlot>
- <Text size="callout" truncate grow>{tr(item.title)}</Text>
+ <Text size="callout" truncate grow>{item.verbatim ? item.title : tr(item.title)}</Text>
{item.detail ? <Text size="body" tone="secondary">{item.detail}</Text> : null}
{item.chevron ? <Icon name="chevron.right" size={11} color="var(--secondary)" /> : null}
</button>
@@ -163,17 +167,32 @@ function PanelRows({ items, onDismiss, after, dismissOnActivate = false }: { ite
)
}
-/** The roster's right-click actions, shared by pointer and keyboard. */
-export function DesktopActionMenu({ items, onDismiss, style }: { items: MenuItem[]; onDismiss: () => void; style: React.CSSProperties }) {
- const rows = items.map<PanelItem>((m) => ({ title: m.title, icon: m.icon ?? 'circle', destructive: m.destructive, action: m.action }))
+/** A roster menu row: an action, or with `submenu`, rows that open in the menu's place (as the account menu opens Support). */
+export type ActionItem = MenuItem | (Omit<MenuItem, 'action'> & { submenu: MenuItem[] })
+
+/** The roster's right-click actions at `x`, `y`, shared by pointer and keyboard; kept inside the window, a long list scrolling. */
+export function DesktopActionMenu({ items, onDismiss, x, y }: { items: ActionItem[]; onDismiss: () => void; x: number; y: number }) {
+ const [submenu, setSubmenu] = useState<{ title: string; items: MenuItem[] } | null>(null)
+ const menu = useRef<HTMLDivElement>(null)
+ // Measured after every render: a submenu, or a window resized under it, changes its height.
+ const [height, setHeight] = useState(0)
+ useLayoutEffect(() => setHeight(menu.current?.offsetHeight ?? 0))
+ const row = (m: ActionItem): PanelItem => 'submenu' in m
+ ? { title: m.title, icon: m.icon ?? 'circle', chevron: true, action: () => setSubmenu({ title: m.title, items: m.submenu }) }
+ : { title: m.title, icon: m.icon ?? 'circle', destructive: m.destructive, verbatim: m.verbatim, action: () => { onDismiss(); m.action() } }
+ const rows: { row: PanelItem; divider?: boolean }[] = submenu
+ ? [{ row: { title: submenu.title, icon: 'chevron.left', action: () => setSubmenu(null) } }, ...submenu.items.map((m, i) => ({ row: row(m), divider: i === 0 || m.divider }))]
+ : items.map((m) => ({ row: row(m), divider: m.divider }))
return (
- <div className="action-menu" style={style}>
- <PanelRows
- items={rows}
- onDismiss={onDismiss}
- dismissOnActivate
- after={(i) => (items[i + 1]?.divider ? <div className="panel-divider" /> : null)}
- />
+ <div ref={menu} className="action-menu" style={{ left: Math.min(Math.max(8, x), window.innerWidth - 268), top: Math.max(8, Math.min(y, window.innerHeight - 8 - height)) }}>
+ <div className="action-menu-rows">
+ <PanelRows
+ key={submenu?.title}
+ items={rows.map((r) => r.row)}
+ onDismiss={onDismiss}
+ after={(i) => (rows[i + 1]?.divider ? <div className="panel-divider" /> : null)}
+ />
+ </div>
</div>
)
}
diff --git a/apps/desktop/src/renderer/views/RosterSection.tsx b/apps/desktop/src/renderer/views/RosterSection.tsx
new file mode 100644
index 00000000..a68d53aa
--- /dev/null
+++ b/apps/desktop/src/renderer/views/RosterSection.tsx
@@ -0,0 +1,54 @@
+import { useRef, type ReactNode } from 'react'
+import { Icon } from '../components/Icon'
+import { HStack } from '../components/Stack'
+import { Text } from '../components/Text'
+import { useSlide } from '../lib/slide'
+import { useTr } from '../lib/use-language'
+import './computer-roster.css'
+
+interface Props {
+ name: string
+ count: number
+ /** Its bots' unread messages, shown while it's folded. */
+ unread: number
+ folded: boolean
+ compact: boolean
+ toggle: () => void
+ onContext: (x: number, y: number) => void
+ children: ReactNode
+}
+
+/** A section the user made (Slack's custom sidebar sections): its header folds its rows. */
+export function RosterSection({ name, count, unread, folded, compact, toggle, onContext, children }: Props) {
+ const section = useRef<HTMLElement>(null)
+ useSlide(section)
+ return (
+ <section ref={section} aria-label={name}>
+ <button className="roster-section-toggle" aria-expanded={!folded} aria-label={name} title={name} onClick={toggle}
+ onContextMenu={(e) => {
+ e.preventDefault()
+ onContext(e.clientX, e.clientY)
+ }}>
+ <HStack gap={5} justify={compact ? 'center' : undefined}>
+ <span className={`computer-roster-chevron ${folded ? 'collapsed' : ''}`}><Icon name="chevron.down" size={9} /></span>
+ {!compact ? <Text size="caption" weight="semibold" truncate grow>{name}</Text> : null}
+ {!compact ? <Text size="caption" tone="tertiary" tabular>{count}</Text> : null}
+ {folded && unread > 0 ? <span className="unread-badge">{unread}</span> : null}
+ </HStack>
+ </button>
+ <div className={`computer-roster-content ${folded ? 'collapsed' : ''}`} inert={folded} aria-hidden={folded}>
+ <div>{children}</div>
+ </div>
+ </section>
+ )
+}
+
+/** The plain "Bots" label over the bots in no section, set like a section's name; it folds nothing.
+ * The narrow rail drops its text, as headers drop their names, and keeps the gap. */
+export function RosterLabel({ compact }: { compact: boolean }) {
+ const tr = useTr()
+ const label = useRef<HTMLDivElement>(null)
+ useSlide(label)
+ if (compact) return <div ref={label} className="roster-label" role="heading" aria-level={3} aria-label={tr('Bots')} />
+ return <div ref={label} className="roster-label"><Text as="h3" size="caption" weight="semibold" tone="secondary">{tr('Bots')}</Text></div>
+}
diff --git a/apps/desktop/src/renderer/views/SectionNameDialog.tsx b/apps/desktop/src/renderer/views/SectionNameDialog.tsx
new file mode 100644
index 00000000..a31c415d
--- /dev/null
+++ b/apps/desktop/src/renderer/views/SectionNameDialog.tsx
@@ -0,0 +1,34 @@
+import { useState } from 'react'
+import { Dialog } from '../components/Overlay'
+import { limitSectionName, sectionName } from '../lib/roster-sections'
+import { useTr } from '../lib/use-language'
+import type { SectionNaming } from './section-menus'
+
+/** Asks for a section's name: a new section for a bot, or a section's new name. */
+export function SectionNameDialog({ naming, onClose }: { naming: SectionNaming | null; onClose: () => void }) {
+ const tr = useTr()
+ const [name, setName] = useState('')
+ const [opened, setOpened] = useState<SectionNaming | null>(null)
+ // Each opening starts from its own name: empty for a new section, the current one for a rename.
+ if (naming && naming !== opened) {
+ setOpened(naming)
+ setName(naming.name)
+ }
+ const save = () => {
+ const typed = sectionName(name)
+ if (naming && typed) naming.save(typed)
+ }
+ return (
+ <Dialog open={naming !== null} title={naming ? tr(naming.title) : ''} actions={[{ title: 'Save', action: save }]} onClose={onClose}>
+ {/* The host refuses longer names; the field stops there first. */}
+ <input className="dialog-field" data-autofocus value={name} placeholder={tr('Section name')} aria-label={tr('Section name')} spellCheck={false}
+ onChange={(e) => setName(limitSectionName(e.target.value))}
+ onKeyDown={(e) => {
+ if (e.key !== 'Enter' || e.nativeEvent.isComposing || e.keyCode === 229) return
+ e.preventDefault()
+ onClose()
+ save()
+ }} />
+ </Dialog>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/chat-window.css b/apps/desktop/src/renderer/views/chat-window.css
index c7cfa097..2296b129 100644
--- a/apps/desktop/src/renderer/views/chat-window.css
+++ b/apps/desktop/src/renderer/views/chat-window.css
@@ -397,6 +397,11 @@ html[data-platform="darwin"] .sidebar-header {
width: 260px;
border-radius: var(--radius-l);
}
+/* Rows past the window's height scroll; the menu's outline stays put. */
+.action-menu-rows {
+ max-height: calc(100vh - 30px);
+ overflow-y: auto;
+}
@keyframes panel-in {
from {
opacity: 0;
diff --git a/apps/desktop/src/renderer/views/computer-roster.css b/apps/desktop/src/renderer/views/computer-roster.css
index 6fa8be6f..736dc69b 100644
--- a/apps/desktop/src/renderer/views/computer-roster.css
+++ b/apps/desktop/src/renderer/views/computer-roster.css
@@ -99,6 +99,22 @@
overflow: hidden;
}
+/* A section the user made: a quieter header than a computer's, its rows folding the same way. The
+ "Bots" label over the rows in no section sits where a header's chevron starts. */
+.roster-section-toggle,
+.roster-label {
+ width: 100%;
+ margin-top: 8px;
+ padding: 5px 8px;
+ color: var(--secondary);
+ border-radius: var(--radius-s);
+ text-align: left;
+}
+
+.roster-section-toggle:hover {
+ background: var(--bubble-agent);
+}
+
.computer-roster-empty {
padding: 8px 10px 12px;
color: var(--tertiary);
diff --git a/apps/desktop/src/renderer/views/section-menus.test.ts b/apps/desktop/src/renderer/views/section-menus.test.ts
new file mode 100644
index 00000000..5ac95b28
--- /dev/null
+++ b/apps/desktop/src/renderer/views/section-menus.test.ts
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import type { Bot } from '@shared/models'
+import type { BotStore } from '../store/bot-store'
+import type { ActionItem } from './PanelMenus'
+import { moveToSectionItems, sectionHeaderItems, type SectionNaming } from './section-menus.ts'
+
+/** A computer's store as the menus read it (`archived` is hidden, its section still counts), logging what they ask of it. */
+function computer(hasRosterSections = true) {
+ const calls: unknown[][] = []
+ const bots = [{ id: 'work', section: 'Work' }, { id: 'loose' }, { id: 'home', section: 'Home' }, { id: 'archived', section: 'archive', hidden: true }] as Bot[]
+ const store = {
+ hasRosterSections,
+ bots: new Map(bots.map((bot) => [bot.id, bot])),
+ sections: { move: (bot: Bot, name: string | null) => calls.push(['move', bot.id, name]) },
+ } as unknown as BotStore
+ const naming: SectionNaming[] = []
+ return { store, calls, naming, bot: (id: string) => store.bots.get(id)! }
+}
+
+/** The "Move to section" submenu. */
+function submenu(items: ActionItem[]) {
+ assert.equal(items.length, 1)
+ const [move] = items
+ assert.ok(move && 'submenu' in move && move.title === 'Move to section')
+ return move.submenu
+}
+
+test('Move to section offers the other sections (hidden bots\' too), a new one, and out of its own', () => {
+ const { store, calls, naming, bot } = computer()
+ const rows = submenu(moveToSectionItems(bot('work'), store, (n) => naming.push(n)))
+ assert.deepEqual(rows.map((r) => r.title), ['archive', 'Home', 'New section…', 'Remove from section'])
+ // Section names show as the user typed them ("Home" stays "Home" in any language); the rest is translated.
+ assert.deepEqual(rows.map((r) => r.verbatim === true), [true, true, false, false])
+ rows[1]!.action()
+ rows[3]!.action()
+ rows[2]!.action()
+ assert.deepEqual(naming.map((n) => [n.title, n.name]), [['New section', '']])
+ naming[0]!.save('Side')
+ assert.deepEqual(calls, [['move', 'work', 'Home'], ['move', 'work', null], ['move', 'work', 'Side']])
+})
+
+test('a bot in no section has nothing to be removed from', () => {
+ const { store, bot } = computer()
+ assert.deepEqual(submenu(moveToSectionItems(bot('loose'), store, () => {})).map((r) => r.title), ['archive', 'Home', 'Work', 'New section…'])
+})
+
+test('a header renames its section from its name, or removes it', () => {
+ const { store, calls, naming } = computer()
+ const items = sectionHeaderItems('Work', store, (n) => naming.push(n), (to) => calls.push(['rename', to]))
+ assert.deepEqual(items.map((i) => i.title), ['Rename section…', 'Remove section'])
+ items[0]!.action()
+ assert.deepEqual(naming.map((n) => [n.title, n.name]), [['Rename section', 'Work']])
+ naming[0]!.save('Jobs')
+ items[1]!.action()
+ assert.deepEqual(calls, [['rename', 'Jobs'], ['rename', null]])
+})
+
+test('the lead gets no Move to section: it stays on top, outside sections', () => {
+ const { store, bot } = computer()
+ assert.deepEqual(moveToSectionItems({ ...bot('work'), lead: true }, store, () => {}), [])
+})
+
+test('a host without sections gets no section menus', () => {
+ const { store, bot } = computer(false)
+ assert.deepEqual(moveToSectionItems(bot('work'), store, () => {}), [])
+ assert.deepEqual(sectionHeaderItems('Work', store, () => {}, () => {}), [])
+})
diff --git a/apps/desktop/src/renderer/views/section-menus.ts b/apps/desktop/src/renderer/views/section-menus.ts
new file mode 100644
index 00000000..528e7b59
--- /dev/null
+++ b/apps/desktop/src/renderer/views/section-menus.ts
@@ -0,0 +1,33 @@
+import type { Bot } from '@shared/models'
+import type { MenuItem } from '../components/Overlay'
+import { sectionNames } from '../lib/roster-sections.ts'
+import type { BotStore } from '../store/bot-store'
+import type { ActionItem } from './PanelMenus'
+
+/** An open section name dialog: its title, the name it starts with, and what Save does with the typed one. */
+export interface SectionNaming {
+ title: string
+ name: string
+ save: (name: string) => void
+}
+
+/** A bot row's "Move to section"; none for the lead (it stays on top, outside sections) or while its computer runs a host without sections. */
+export function moveToSectionItems(bot: Bot, store: BotStore, askName: (naming: SectionNaming) => void): ActionItem[] {
+ if (bot.lead || !store.hasRosterSections) return []
+ const others = sectionNames(store.bots.values()).filter((name) => name !== bot.section)
+ const submenu: MenuItem[] = [
+ ...others.map((name) => ({ title: name, icon: 'tray', verbatim: true, action: () => store.sections.move(bot, name) })),
+ { title: 'New section…', icon: 'plus', divider: others.length > 0, action: () => askName({ title: 'New section', name: '', save: (name) => store.sections.move(bot, name) }) },
+ ...(bot.section ? [{ title: 'Remove from section', icon: 'minus.circle', action: () => store.sections.move(bot, null) }] : []),
+ ]
+ return [{ title: 'Move to section', icon: 'tray', submenu }]
+}
+
+/** A section header's right-click menu, `rename` taking the new name (null: remove it, its bots staying without one). None while the computer runs a host without sections. */
+export function sectionHeaderItems(section: string, store: BotStore, askName: (naming: SectionNaming) => void, rename: (to: string | null) => void): MenuItem[] {
+ if (!store.hasRosterSections) return []
+ return [
+ { title: 'Rename section…', icon: 'pencil', action: () => askName({ title: 'Rename section', name: section, save: rename }) },
+ { title: 'Remove section', icon: 'xmark.circle', action: () => rename(null) },
+ ]
+}
diff --git a/apps/desktop/src/shared/models.test.ts b/apps/desktop/src/shared/models.test.ts
index 545ab285..1ed4c39e 100644
--- a/apps/desktop/src/shared/models.test.ts
+++ b/apps/desktop/src/shared/models.test.ts
@@ -8,6 +8,12 @@ test('a bot keeps its Fast mode through the settings draft', () => {
assert.equal(draftOf(bot).fastMode, true)
})
+test('a bot without a section, or with a cleared one, has none', () => {
+ assert.equal(normalizeBot({ id: 'b', section: 'Work' }).section, 'Work')
+ assert.equal(normalizeBot({ id: 'b' }).section, undefined)
+ assert.equal(normalizeBot({ id: 'b', section: '' }).section, undefined)
+})
+
test('a host without Fast mode reads as off', () => {
assert.equal(normalizeBot({ id: 'b' }).fastMode, false)
})
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 74150653..20b8dc82 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -44,6 +44,8 @@ export interface Bot {
lead: boolean
/** Where the user dragged it, lowest first within its band (`rosterBand`); ties sort by recent activity. */
position: number
+ /** The roster section the user put it in (`Work`, `Personal`); none when absent. */
+ section?: string
hidden: boolean
notify?: boolean | null
connectors: string[]
@@ -106,6 +108,8 @@ export function normalizeBot(raw: Partial<Bot> & { id: string }): Bot {
pinned: raw.pinned ?? false,
lead: raw.lead ?? false,
position: raw.position ?? 0,
+ // A cleared section (null, or an empty name) reads as none.
+ section: raw.section || undefined,
hidden: raw.hidden ?? false,
notify: raw.notify ?? null,
connectors: raw.connectors ?? [],
@@ -592,6 +596,8 @@ export interface BotDraft {
fallbacks?: Fallback[]
selfFallbacks?: boolean
pinned?: boolean
+ /** A name puts the bot in that roster section, null takes it out; left out, the host keeps it. */
+ section?: string | null
hidden?: boolean
notify?: boolean | null
connectors?: string[]
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 85842ac5..f05c0ce4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -199,6 +199,12 @@ public extension HostClient {
return res.bot
}
+ /// Puts the bot in `section`, or takes it out of its own (nil, sent as null); nothing else changes.
+ func setSection(_ botId: String, to section: String?) async throws {
+ let body: [String: String?] = ["id": botId, "section": section]
+ let _: Empty = try await call("updateBot", body)
+ }
+
func deleteBot(_ id: String) async throws {
let _: Empty = try await call("deleteBot", ["botId": id])
}
@@ -208,6 +214,13 @@ public extension HostClient {
let _: Empty = try await call("reorderBots", ["ids": ids])
}
+ /// Moves every bot of the computer in section `from` to `to` (a name already in use merges the
+ /// two); nil removes the section, its bots staying without one.
+ func renameSection(from: String, to: String?) async throws {
+ let body: [String: String?] = ["from": from, "to": to]
+ let _: Empty = try await call("renameSection", body)
+ }
+
/// The chat read; a no-op when nothing there is unread.
func markRead(_ id: String) async throws {
let _: Empty = try await call("markRead", ["botId": id])
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
index 63dc7ba5..01c4e80e 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
@@ -38,6 +38,8 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
public var lead: Bool = false
/// Where the user dragged it, lowest first within its `band`; ties sort by recent activity.
public var position: Int = 0
+ /// The user's section in the roster ("Work"); nil in none.
+ public var section: String?
public var hidden: Bool
public var notify: Bool?
/// Installed connector / skill ids this bot uses (see `Market.swift`).
@@ -121,6 +123,7 @@ extension Bot {
pinned = try c.decodeIfPresent(Bool.self, forKey: .pinned) ?? false
lead = try c.decodeIfPresent(Bool.self, forKey: .lead) ?? false
position = try c.decodeIfPresent(Int.self, forKey: .position) ?? 0
+ section = try c.decodeIfPresent(String.self, forKey: .section)
hidden = try c.decodeIfPresent(Bool.self, forKey: .hidden) ?? false
notify = try c.decodeIfPresent(Bool.self, forKey: .notify)
connectors = try c.decodeIfPresent([String].self, forKey: .connectors) ?? []
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 5e845c57..06555d5b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "Ihr leitender Agent ist Ihre erste Anlaufstelle. Er verfolgt Ihre Ziele und offenen Aufgaben, schlägt hilfreiche nächste Schritte vor und koordiniert die Arbeit mit Ihren anderen Bots. Seine Check in-Routine läuft standardmäßig zweimal täglich; unter Routinen können Sie sie ändern oder pausieren.",
"The lead bot can't be deleted": "Der Haupt-Bot kann nicht gelöscht werden",
"The lead bot always stays on top": "Der Haupt-Bot bleibt immer oben",
+ "Move to section": "In Abschnitt verschieben",
+ "New section…": "Neuer Abschnitt…",
+ "Remove from section": "Aus Abschnitt entfernen",
+ "Rename section…": "Abschnitt umbenennen…",
+ "Remove section": "Abschnitt entfernen",
+ "New section": "Neuer Abschnitt",
+ "Rename section": "Abschnitt umbenennen",
+ "Section": "Abschnitt",
+ "Section name": "Abschnittsname",
+ "Empty takes it out of its section; a new name makes one.": "Leer lassen, um ihn aus seinem Abschnitt zu nehmen; ein neuer Name legt einen neuen an.",
+ "Empty removes the section; its bots stay. A name in use merges them.": "Leer lassen, um den Abschnitt zu entfernen; seine Bots bleiben. Ein vergebener Name führt beide zusammen.",
+ " Sections: {list}": " Abschnitte: {list}",
+ "This bot isn't in a section": "Dieser Bot ist in keinem Abschnitt",
+ "Still connecting: try again in a moment.": "Verbindung wird noch hergestellt: Versuche es gleich noch einmal.",
+ "Update Codync on {host}: sections need {version} or newer.": "Aktualisiere Codync auf {host}: Abschnitte brauchen {version} oder neuer.",
+ "{name}, 1 bot": "{name}, 1 Bot",
+ "{name}, {count} bots": "{name}, {count} Bots",
+ "{name}, 1 bot, {unread} unread": "{name}, 1 Bot, {unread} ungelesen",
+ "{name}, {count} bots, {unread} unread": "{name}, {count} Bots, {unread} ungelesen",
+ "Double-tap to fold or expand.": "Zum Ein- oder Ausklappen doppeltippen.",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "Zum Ein- oder Ausklappen doppeltippen. Gedrückt halten, um den Abschnitt umzubenennen oder zu entfernen.",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "Live-Aktivitäten sind in den iOS-Einstellungen deaktiviert.",
"Live Activity": "Live-Aktivität",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 19a4743b..a3f606b6 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "Tu agente principal es tu primer punto de contacto. Sigue tus objetivos y tareas pendientes, sugiere próximos pasos útiles y coordina el trabajo con tus otros bots. Su rutina Check in se ejecuta dos veces al día de forma predeterminada; puedes cambiarla o pausarla en Rutinas.",
"The lead bot can't be deleted": "El bot principal no se puede eliminar",
"The lead bot always stays on top": "El bot principal siempre queda arriba",
+ "Move to section": "Mover a una sección",
+ "New section…": "Nueva sección…",
+ "Remove from section": "Quitar de la sección",
+ "Rename section…": "Cambiar nombre de la sección…",
+ "Remove section": "Eliminar sección",
+ "New section": "Nueva sección",
+ "Rename section": "Cambiar nombre de la sección",
+ "Section": "Sección",
+ "Section name": "Nombre de la sección",
+ "Empty takes it out of its section; a new name makes one.": "Déjalo vacío para sacarlo de su sección; un nombre nuevo crea una.",
+ "Empty removes the section; its bots stay. A name in use merges them.": "Déjalo vacío para eliminar la sección; sus bots se quedan. Un nombre que ya existe las une.",
+ " Sections: {list}": " Secciones: {list}",
+ "This bot isn't in a section": "Este bot no está en ninguna sección",
+ "Still connecting: try again in a moment.": "Todavía conectando: inténtalo de nuevo en un momento.",
+ "Update Codync on {host}: sections need {version} or newer.": "Actualiza Codync en {host}: las secciones necesitan {version} o una versión más reciente.",
+ "{name}, 1 bot": "{name}, 1 bot",
+ "{name}, {count} bots": "{name}, {count} bots",
+ "{name}, 1 bot, {unread} unread": "{name}, 1 bot, {unread} sin leer",
+ "{name}, {count} bots, {unread} unread": "{name}, {count} bots, {unread} sin leer",
+ "Double-tap to fold or expand.": "Toca dos veces para contraer o expandir.",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "Toca dos veces para contraer o expandir. Mantén pulsado para cambiar el nombre de la sección o eliminarla.",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "Las actividades en vivo están desactivadas en la configuración de iOS.",
"Live Activity": "Actividad en vivo",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index ecaee33a..5a281733 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "Votre agent principal est votre premier interlocuteur. Il suit vos objectifs et vos tâches inachevées, propose les prochaines étapes utiles et coordonne le travail avec vos autres bots. Sa routine Check in s’exécute deux fois par jour par défaut ; vous pouvez la modifier ou la suspendre dans Routines.",
"The lead bot can't be deleted": "Le bot principal ne peut pas être supprimé",
"The lead bot always stays on top": "Le bot principal reste toujours en haut",
+ "Move to section": "Déplacer vers une section",
+ "New section…": "Nouvelle section…",
+ "Remove from section": "Retirer de la section",
+ "Rename section…": "Renommer la section…",
+ "Remove section": "Supprimer la section",
+ "New section": "Nouvelle section",
+ "Rename section": "Renommer la section",
+ "Section": "Section",
+ "Section name": "Nom de la section",
+ "Empty takes it out of its section; a new name makes one.": "Laissez vide pour le retirer de sa section ; un nouveau nom en crée une.",
+ "Empty removes the section; its bots stay. A name in use merges them.": "Laissez vide pour supprimer la section ; ses bots restent. Un nom déjà utilisé fusionne les deux.",
+ " Sections: {list}": " Sections : {list}",
+ "This bot isn't in a section": "Ce bot n’est dans aucune section",
+ "Still connecting: try again in a moment.": "Connexion en cours : réessayez dans un instant.",
+ "Update Codync on {host}: sections need {version} or newer.": "Mettez à jour Codync sur {host} : les sections nécessitent {version} ou une version plus récente.",
+ "{name}, 1 bot": "{name}, 1 bot",
+ "{name}, {count} bots": "{name}, {count} bots",
+ "{name}, 1 bot, {unread} unread": "{name}, 1 bot, non lus : {unread}",
+ "{name}, {count} bots, {unread} unread": "{name}, {count} bots, non lus : {unread}",
+ "Double-tap to fold or expand.": "Touchez deux fois pour réduire ou développer.",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "Touchez deux fois pour réduire ou développer. Maintenez le doigt pour renommer ou supprimer la section.",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "Les activités en direct sont désactivées dans les paramètres iOS.",
"Live Activity": "Activité en direct",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 086140d0..f725be26 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "リードエージェントは最初の相談相手です。目標や未完了のタスクを追跡し、役立つ次の一歩を提案して、他のボットとの作業を調整します。「Check in」ルーチンは初期設定で1日2回実行されます。ルーチンで変更または一時停止できます。",
"The lead bot can't be deleted": "メインボットは削除できません",
"The lead bot always stays on top": "メインボットは常に一番上です",
+ "Move to section": "セクションに移動",
+ "New section…": "新しいセクション…",
+ "Remove from section": "セクションから外す",
+ "Rename section…": "セクション名を変更…",
+ "Remove section": "セクションを削除",
+ "New section": "新しいセクション",
+ "Rename section": "セクション名を変更",
+ "Section": "セクション",
+ "Section name": "セクション名",
+ "Empty takes it out of its section; a new name makes one.": "空欄にするとセクションから外れます。新しい名前を入れるとセクションを作成します。",
+ "Empty removes the section; its bots stay. A name in use merges them.": "空欄にするとセクションを削除します。ボットはそのまま残ります。使用中の名前にすると 2 つを統合します。",
+ " Sections: {list}": "セクション: {list}",
+ "This bot isn't in a section": "このボットはどのセクションにも入っていません",
+ "Still connecting: try again in a moment.": "まだ接続中です。少し待ってからもう一度お試しください。",
+ "Update Codync on {host}: sections need {version} or newer.": "{host} の Codync をアップデートしてください。セクションには {version} 以降が必要です。",
+ "{name}, 1 bot": "{name}、ボット 1 個",
+ "{name}, {count} bots": "{name}、ボット {count} 個",
+ "{name}, 1 bot, {unread} unread": "{name}、ボット 1 個、未読 {unread} 件",
+ "{name}, {count} bots, {unread} unread": "{name}、ボット {count} 個、未読 {unread} 件",
+ "Double-tap to fold or expand.": "ダブルタップして折りたたむか展開します。",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "ダブルタップして折りたたむか展開します。長押しするとセクション名の変更や削除ができます。",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "iOS 設定でライブ アクティビティがオフになっています。",
"Live Activity": "ライブアクティビティ",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index bdb371a8..0b660f90 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "리드 에이전트는 가장 먼저 연락할 도우미입니다. 목표와 미완료 작업을 추적하고 유용한 다음 단계를 제안하며 다른 봇과 작업을 조율합니다. Check in 루틴은 기본적으로 하루 두 번 실행되며, 루틴에서 변경하거나 일시 중지할 수 있습니다.",
"The lead bot can't be deleted": "메인 봇은 삭제할 수 없습니다",
"The lead bot always stays on top": "메인 봇은 항상 맨 위에 있습니다",
+ "Move to section": "섹션으로 이동",
+ "New section…": "새 섹션…",
+ "Remove from section": "섹션에서 제거",
+ "Rename section…": "섹션 이름 변경…",
+ "Remove section": "섹션 제거",
+ "New section": "새 섹션",
+ "Rename section": "섹션 이름 변경",
+ "Section": "섹션",
+ "Section name": "섹션 이름",
+ "Empty takes it out of its section; a new name makes one.": "비워 두면 섹션에서 빠지고, 새 이름을 입력하면 새 섹션이 만들어집니다.",
+ "Empty removes the section; its bots stay. A name in use merges them.": "비워 두면 섹션이 제거되며 봇은 그대로 남습니다. 이미 있는 이름을 입력하면 두 섹션이 합쳐집니다.",
+ " Sections: {list}": " 섹션: {list}",
+ "This bot isn't in a section": "이 봇은 섹션에 속해 있지 않습니다",
+ "Still connecting: try again in a moment.": "아직 연결 중입니다. 잠시 후 다시 시도하세요.",
+ "Update Codync on {host}: sections need {version} or newer.": "{host}에서 Codync를 업데이트하세요. 섹션을 쓰려면 {version} 이상이 필요합니다.",
+ "{name}, 1 bot": "{name}, 봇 1개",
+ "{name}, {count} bots": "{name}, 봇 {count}개",
+ "{name}, 1 bot, {unread} unread": "{name}, 봇 1개, 읽지 않은 메시지 {unread}개",
+ "{name}, {count} bots, {unread} unread": "{name}, 봇 {count}개, 읽지 않은 메시지 {unread}개",
+ "Double-tap to fold or expand.": "두 번 탭하여 접거나 펼칩니다.",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "두 번 탭하여 접거나 펼칩니다. 길게 누르면 섹션 이름을 변경하거나 섹션을 제거할 수 있습니다.",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "iOS 설정에서 실시간 활동이 꺼져 있습니다.",
"Live Activity": "라이브 활동",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index 803e6e42..41736532 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "主助理是你优先联系的 agent。它会跟进你的目标与未完成的任务、建议实用的下一步,并协调其他 bots 一起完成工作。它的「Check in」例行任务默认每天执行两次;你可以在「例行任务」中调整或暂停。",
"The lead bot can't be deleted": "主助理不能删除",
"The lead bot always stays on top": "主助理固定在最上面",
+ "Move to section": "移到分组",
+ "New section…": "新建分组…",
+ "Remove from section": "移出分组",
+ "Rename section…": "重命名分组…",
+ "Remove section": "移除分组",
+ "New section": "新建分组",
+ "Rename section": "重命名分组",
+ "Section": "分组",
+ "Section name": "分组名称",
+ "Empty takes it out of its section; a new name makes one.": "留空会把它移出分组;输入新名称会新建一个分组。",
+ "Empty removes the section; its bots stay. A name in use merges them.": "留空会移除这个分组,里面的 Bot 会保留。用已有的名称会把两个分组合并。",
+ " Sections: {list}": "现有分组:{list}",
+ "This bot isn't in a section": "这个 Bot 不在任何分组里",
+ "Still connecting: try again in a moment.": "还在连接中,请稍后再试。",
+ "Update Codync on {host}: sections need {version} or newer.": "请在 {host} 上更新 Codync:分组需要 {version} 或更高版本。",
+ "{name}, 1 bot": "{name},1 个 Bot",
+ "{name}, {count} bots": "{name},{count} 个 Bot",
+ "{name}, 1 bot, {unread} unread": "{name},1 个 Bot,{unread} 条未读",
+ "{name}, {count} bots, {unread} unread": "{name},{count} 个 Bot,{unread} 条未读",
+ "Double-tap to fold or expand.": "连按两次可收起或展开。",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "连按两次可收起或展开。按住可重命名或移除这个分组。",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "iOS 设置里已关闭实时活动。",
"Live Activity": "实时活动",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index 72665bb6..e5f5df56 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -102,6 +102,27 @@
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. Its Check in routine runs twice a day by default; you can change or pause it in Routines.": "主助理是你優先聯絡的 agent。它會追蹤你的目標與未完成的任務、建議實用的下一步,並協調其他 bots 一起完成工作。它的「Check in」例行任務預設每天執行兩次;你可以在「例行任務」中調整或暫停。",
"The lead bot can't be deleted": "主助理不能刪除",
"The lead bot always stays on top": "主助理固定在最上面",
+ "Move to section": "移到分組",
+ "New section…": "新建分組…",
+ "Remove from section": "移出分組",
+ "Rename section…": "重新命名分組…",
+ "Remove section": "移除分組",
+ "New section": "新建分組",
+ "Rename section": "重新命名分組",
+ "Section": "分組",
+ "Section name": "分組名稱",
+ "Empty takes it out of its section; a new name makes one.": "留空會把它移出分組;輸入新名稱會新建一個分組。",
+ "Empty removes the section; its bots stay. A name in use merges them.": "留空會移除這個分組,裡面的 Bot 會保留。用已有的名稱會把兩個分組合併。",
+ " Sections: {list}": "現有分組:{list}",
+ "This bot isn't in a section": "這個 Bot 不在任何分組裡",
+ "Still connecting: try again in a moment.": "還在連線中,請稍後再試。",
+ "Update Codync on {host}: sections need {version} or newer.": "請在 {host} 上更新 Codync:分組需要 {version} 或更新的版本。",
+ "{name}, 1 bot": "{name},1 個 Bot",
+ "{name}, {count} bots": "{name},{count} 個 Bot",
+ "{name}, 1 bot, {unread} unread": "{name},1 個 Bot,{unread} 則未讀",
+ "{name}, {count} bots, {unread} unread": "{name},{count} 個 Bot,{unread} 則未讀",
+ "Double-tap to fold or expand.": "連按兩次可收起或展開。",
+ "Double-tap to fold or expand. Touch and hold to rename or remove the section.": "連按兩次可收起或展開。按住可重新命名或移除這個分組。",
"Linux": "Linux",
"Live Activities are turned off in iOS Settings.": "iOS 設定裡已關閉實時活動。",
"Live Activity": "實時活動",
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swift
index 03c61c99..f16ac155 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swift
@@ -37,14 +37,7 @@ public struct BotRow: View {
HStack(alignment: .firstTextBaseline, spacing: 6) {
preview
Spacer(minLength: 4)
- if bot.unread > 0 {
- Text(L10n.tr("\(bot.unread)"))
- .font(.caption2.bold())
- .foregroundStyle(Palette.onAccent)
- .padding(.horizontal, 6)
- .frame(minWidth: 18, minHeight: 18)
- .background(Palette.accentFill, in: Capsule())
- }
+ if bot.unread > 0 { UnreadBadge(count: bot.unread) }
}
}
}
@@ -86,3 +79,19 @@ public struct BotRow: View {
}
}
}
+
+/// An unread count in an accent capsule: a bot's, or a folded section's.
+public struct UnreadBadge: View {
+ let count: Int
+
+ public init(count: Int) { self.count = count }
+
+ public var body: some View {
+ Text("\(count)")
+ .font(.caption2.bold())
+ .foregroundStyle(Palette.onAccent)
+ .padding(.horizontal, 6)
+ .frame(minWidth: 18, minHeight: 18)
+ .background(Palette.accentFill, in: Capsule())
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Controls.swift b/apps/ios/Kit/Sources/CodyncUI/Controls.swift
index eb87164c..3812f447 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Controls.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Controls.swift
@@ -125,119 +125,6 @@ public struct Spinner: View {
// MARK: - Menus
-/// One row in a Codync menu: an action, or a choice when `selected` is set.
-public struct MenuItem: Identifiable {
- public let id = UUID()
- public var title: String
- public var icon: String?
- /// A picture in the icon's place (an agent's logo).
- public var image: Image?
- public var selected: Bool?
- public var destructive: Bool
- public var divider: Bool
- public var action: () -> Void
-
- public init(_ title: String, icon: String? = nil, image: Image? = nil, selected: Bool? = nil, destructive: Bool = false,
- divider: Bool = false, action: @escaping () -> Void) {
- self.title = title
- self.icon = icon
- self.image = image
- self.selected = selected
- self.destructive = destructive
- self.divider = divider
- self.action = action
- }
-}
-
-/// A row of emoji above a message's menu (Slack's quick reactions).
-public struct ReactionPick {
- public var emoji: [String]
- public var chosen: [String]
- public var toggle: (String) -> Void
-
- public init(emoji: [String], chosen: [String], toggle: @escaping (String) -> Void) {
- self.emoji = emoji
- self.chosen = chosen
- self.toggle = toggle
- }
-}
-
-public extension View {
- /// Long-press opens the system context menu; `reactions` puts a quick-reaction row on top.
- func contextActions(reactions: ReactionPick? = nil, _ items: @escaping () -> [MenuItem]) -> some View {
- modifier(ContextActions(items: items, reactions: reactions))
- }
-}
-
-private struct ContextActions: ViewModifier {
- let items: () -> [MenuItem]
- let reactions: ReactionPick?
-
- func body(content: Content) -> some View {
- content.contextMenu {
- if let reactions {
- ControlGroup {
- ForEach(reactions.emoji, id: \.self) { emoji in
- let chosen = reactions.chosen.contains(emoji)
- Toggle(isOn: Binding(get: { chosen }, set: { _ in reactions.toggle(emoji) })) { Text(emoji) }
- }
- }
- .controlGroupStyle(.palette)
- }
- ForEach(items()) { item in
- if item.divider { Divider() }
- systemMenuRow(item)
- }
- }
- }
-}
-
-/// A `MenuItem` inside a system `Menu` or `contextMenu`: choices as checkmarked toggles.
-@ViewBuilder private func systemMenuRow(_ item: MenuItem) -> some View {
- let role: ButtonRole? = item.destructive ? .destructive : nil
- if let selected = item.selected {
- // The binding's setter must be Sendable, but SwiftUI only calls it from the menu, on the
- // main thread where the action was made.
- nonisolated(unsafe) let action = item.action
- Toggle(isOn: Binding(get: { selected }, set: { _ in action() })) { menuLabel(item) }
- } else {
- Button(role: role, action: item.action) { menuLabel(item) }
- }
-}
-
-@ViewBuilder private func menuLabel(_ item: MenuItem) -> some View {
- if let image = item.image {
- SwiftUI.Label { Text(L10n.tr(item.title)) } icon: { image }
- } else if let icon = item.icon {
- SwiftUI.Label(L10n.tr(item.title), systemImage: icon)
- } else {
- Text(L10n.tr(item.title))
- }
-}
-
-/// A button that opens the system menu.
-public struct DropdownMenu<Label: View>: View {
- let items: () -> [MenuItem]
- let label: Label
-
- public init(items: @escaping () -> [MenuItem], @ViewBuilder label: () -> Label) {
- self.items = items
- self.label = label()
- }
-
- public var body: some View {
- // The system menu: it anchors correctly inside sheets and scroll views, where an overlay can't.
- Menu {
- ForEach(items()) { item in
- if item.divider { Divider() }
- systemMenuRow(item)
- }
- } label: { label }
- .buttonStyle(.plain)
- .menuIndicator(.hidden)
- }
-}
-
/// Picks one value: shows the current choice in a pill with a chevron, opens the system menu.
public struct ChoicePicker<ID: Hashable>: View {
@Binding var selection: ID
diff --git a/apps/ios/Kit/Sources/CodyncUI/Dialog.swift b/apps/ios/Kit/Sources/CodyncUI/Dialog.swift
index 96c31e83..67349dd8 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Dialog.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Dialog.swift
@@ -18,14 +18,26 @@ public struct DialogAction: Identifiable {
}
}
+/// A text box above a dialog's actions (a name to type), focused as the dialog opens.
+public struct DialogField {
+ public var placeholder: String
+ public var text: Binding<String>
+
+ public init(_ placeholder: String, text: Binding<String>) {
+ self.placeholder = placeholder
+ self.text = text
+ }
+}
+
public extension View {
/// A centered card over a dimmed screen with the actions and Cancel:
- /// the replacement for `confirmationDialog` and `alert`.
+ /// the replacement for `confirmationDialog` and `alert`. A `field` sits above the actions;
+ /// Return in it runs the first action.
/// Set `inPlace` only at the navigation root to keep underlying glass unchanged.
- func codyncDialog(_ title: String, isPresented: Binding<Bool>, message: String? = nil,
+ func codyncDialog(_ title: String, isPresented: Binding<Bool>, message: String? = nil, field: DialogField? = nil,
cancel: String? = "Cancel", inPlace: Bool = false,
actions: @escaping () -> [DialogAction]) -> some View {
- modifier(CodyncDialog(title: title, message: message, cancel: cancel, inPlace: inPlace,
+ modifier(CodyncDialog(title: title, message: message, field: field, cancel: cancel, inPlace: inPlace,
isPresented: isPresented, actions: actions))
.reviewInterruption(active: isPresented.wrappedValue)
}
@@ -34,11 +46,15 @@ public extension View {
private struct CodyncDialog: ViewModifier {
let title: String
let message: String?
+ let field: DialogField?
let cancel: String?
/// Use only above the navigation container so the scrim also covers its toolbar.
let inPlace: Bool
@Binding var isPresented: Bool
let actions: () -> [DialogAction]
+ /// Counts the dismissals: each opening of the in-place card is a fresh card, so one that closed
+ /// and reopened before a redraw can't keep its `closed` flag.
+ @State private var opening = 0
@Environment(\.accessibilityReduceMotion) private var reduceMotion
func body(content: Content) -> some View {
@@ -48,12 +64,16 @@ private struct CodyncDialog: ViewModifier {
.accessibilityHidden(isPresented)
.overlay {
if isPresented {
- DialogCard(title: title, message: message, cancel: cancel, actions: actions()) {
+ DialogCard(title: title, message: message, field: field, cancel: cancel, actions: actions()) {
isPresented = false
+ opening += 1
}
+ .id(opening)
.ignoresSafeArea(.container)
.transition(.opacity)
.onAppear {
+ // A field takes the focus on the next update: don't race it with a keyboard drop.
+ guard field == nil else { return }
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),
to: nil, from: nil, for: nil)
}
@@ -62,7 +82,7 @@ private struct CodyncDialog: ViewModifier {
.animation(Motion.reduced(Motion.fade, reduceMotion), value: isPresented)
} else {
content.codyncOverlay(isPresented: $isPresented) { close in
- DialogCard(title: title, message: message, cancel: cancel, actions: actions(), dismiss: close)
+ DialogCard(title: title, message: message, field: field, cancel: cancel, actions: actions(), dismiss: close)
}
}
}
@@ -71,14 +91,18 @@ private struct CodyncDialog: ViewModifier {
private struct DialogCard: View {
let title: String
let message: String?
+ let field: DialogField?
let cancel: String?
let actions: [DialogAction]
let dismiss: () -> Void
+ @FocusState private var typing: Bool
+ /// Set once the card begins to close: a second tap or Return during the fade runs nothing.
+ @State private var closed = false
var body: some View {
ZStack {
Color.black.opacity(0.35).ignoresSafeArea()
- .onTapGesture { if cancel != nil { dismiss() } }
+ .onTapGesture { if cancel != nil { close() } }
VStack(spacing: 14) {
VStack(spacing: 6) {
Text(L10n.tr(title)).font(.headline).foregroundStyle(Palette.text)
@@ -87,18 +111,30 @@ private struct DialogCard: View {
}
}
.multilineTextAlignment(.center)
+ if let field {
+ TextField(L10n.tr(field.placeholder), text: field.text)
+ .textFieldStyle(.plain)
+ .font(.body)
+ .foregroundStyle(Palette.text)
+ .submitLabel(.done)
+ .focused($typing)
+ .onSubmit { if let first = actions.first { run(first) } }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 12)
+ .background(Palette.background, in: Capsule())
+ .task { typing = true }
+ }
VStack(spacing: 8) {
ForEach(actions) { action in
Button {
- dismiss()
- action.action()
+ run(action)
} label: {
Text(L10n.tr(action.title)).frame(maxWidth: .infinity)
}
.buttonStyle(DialogButtonStyle(destructive: action.destructive, prominent: true))
}
if let cancel {
- Button(action: dismiss) { Text(L10n.tr(cancel)).frame(maxWidth: .infinity) }
+ Button(action: close) { Text(L10n.tr(cancel)).frame(maxWidth: .infinity) }
.buttonStyle(DialogButtonStyle(destructive: false, prominent: false))
.keyboardShortcut(.cancelAction)
}
@@ -112,6 +148,18 @@ private struct DialogCard: View {
}
.accessibilityAddTraits(.isModal)
}
+
+ private func close() {
+ guard !closed else { return }
+ closed = true
+ dismiss()
+ }
+
+ private func run(_ action: DialogAction) {
+ guard !closed else { return }
+ close()
+ action.action()
+ }
}
private struct DialogButtonStyle: ButtonStyle {
diff --git a/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift b/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
new file mode 100644
index 00000000..6f209a2e
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
@@ -0,0 +1,147 @@
+import CodyncKit
+import SwiftUI
+
+/// One row in a Codync menu: an action, a choice when `selected` is set, or a submenu.
+public struct MenuItem: Identifiable {
+ public let id = UUID()
+ public var title: String
+ public var icon: String?
+ /// A picture in the icon's place (an agent's logo).
+ public var image: Image?
+ public var selected: Bool?
+ public var destructive: Bool
+ public var divider: Bool
+ /// Shows `title` as it is, never translated: a name the user gave (a section's).
+ public var verbatim: Bool
+ /// The rows of the submenu this row opens ("Move to section ▸") instead of running `action`;
+ /// one level deep: a row inside it can't open another.
+ public var submenu: [MenuItem] = []
+ public var action: () -> Void
+
+ public init(_ title: String, icon: String? = nil, image: Image? = nil, selected: Bool? = nil, destructive: Bool = false,
+ divider: Bool = false, verbatim: Bool = false, action: @escaping () -> Void) {
+ self.title = title
+ self.icon = icon
+ self.image = image
+ self.selected = selected
+ self.destructive = destructive
+ self.divider = divider
+ self.verbatim = verbatim
+ self.action = action
+ }
+
+ /// A row that opens a submenu of `rows`.
+ public init(_ title: String, icon: String? = nil, divider: Bool = false, submenu rows: [MenuItem]) {
+ self.init(title, icon: icon, divider: divider) {}
+ submenu = rows
+ }
+
+ /// `title` as the row shows it: in the app's language, unless `verbatim`.
+ func shownTitle(_ translate: (String) -> String = { L10n.tr($0) }) -> String { verbatim ? title : translate(title) }
+}
+
+/// A row of emoji above a message's menu (Slack's quick reactions).
+public struct ReactionPick {
+ public var emoji: [String]
+ public var chosen: [String]
+ public var toggle: (String) -> Void
+
+ public init(emoji: [String], chosen: [String], toggle: @escaping (String) -> Void) {
+ self.emoji = emoji
+ self.chosen = chosen
+ self.toggle = toggle
+ }
+}
+
+public extension View {
+ /// Long-press opens the system context menu; `reactions` puts a quick-reaction row on top.
+ func contextActions(reactions: ReactionPick? = nil, _ items: @escaping () -> [MenuItem]) -> some View {
+ modifier(ContextActions(items: items, reactions: reactions))
+ }
+}
+
+private struct ContextActions: ViewModifier {
+ let items: () -> [MenuItem]
+ let reactions: ReactionPick?
+
+ func body(content: Content) -> some View {
+ content.contextMenu {
+ if let reactions {
+ ControlGroup {
+ ForEach(reactions.emoji, id: \.self) { emoji in
+ let chosen = reactions.chosen.contains(emoji)
+ Toggle(isOn: Binding(get: { chosen }, set: { _ in reactions.toggle(emoji) })) { Text(emoji) }
+ }
+ }
+ .controlGroupStyle(.palette)
+ }
+ ForEach(items()) { item in
+ if item.divider { Divider() }
+ systemMenuRow(item)
+ }
+ }
+ }
+}
+
+/// A `MenuItem` inside a system `Menu` or `contextMenu`; a submenu opens its rows in a system
+/// `Menu`, one level deep (an opaque row type can't contain itself).
+@ViewBuilder private func systemMenuRow(_ item: MenuItem) -> some View {
+ if item.submenu.isEmpty {
+ systemMenuAction(item)
+ } else {
+ Menu {
+ ForEach(item.submenu) { row in
+ let _ = assert(row.submenu.isEmpty, "A submenu is one level deep: this row would be a dead button")
+ if row.divider { Divider() }
+ systemMenuAction(row)
+ }
+ } label: { menuLabel(item) }
+ }
+}
+
+/// A `MenuItem` that runs its action: choices as checkmarked toggles.
+@ViewBuilder private func systemMenuAction(_ item: MenuItem) -> some View {
+ let role: ButtonRole? = item.destructive ? .destructive : nil
+ if let selected = item.selected {
+ // The binding's setter must be Sendable, but SwiftUI only calls it from the menu, on the
+ // main thread where the action was made.
+ nonisolated(unsafe) let action = item.action
+ Toggle(isOn: Binding(get: { selected }, set: { _ in action() })) { menuLabel(item) }
+ } else {
+ Button(role: role, action: item.action) { menuLabel(item) }
+ }
+}
+
+@ViewBuilder private func menuLabel(_ item: MenuItem) -> some View {
+ let title = item.shownTitle()
+ if let image = item.image {
+ SwiftUI.Label { Text(title) } icon: { image }
+ } else if let icon = item.icon {
+ SwiftUI.Label(title, systemImage: icon)
+ } else {
+ Text(title)
+ }
+}
+
+/// A button that opens the system menu.
+public struct DropdownMenu<Label: View>: View {
+ let items: () -> [MenuItem]
+ let label: Label
+
+ public init(items: @escaping () -> [MenuItem], @ViewBuilder label: () -> Label) {
+ self.items = items
+ self.label = label()
+ }
+
+ public var body: some View {
+ // The system menu: it anchors correctly inside sheets and scroll views, where an overlay can't.
+ Menu {
+ ForEach(items()) { item in
+ if item.divider { Divider() }
+ systemMenuRow(item)
+ }
+ } label: { label }
+ .buttonStyle(.plain)
+ .menuIndicator(.hidden)
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
index e220ee53..22508314 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
@@ -58,12 +58,21 @@ extension BotStore {
/// Fire-and-forget actions; only what waiting and retrying couldn't settle reaches the dialog.
private func perform(replay: Bool = false, _ op: @escaping @MainActor (HostClient) async throws -> Void) {
- Task {
- do {
- try await withLink(replay: replay, op)
- } catch {
- lastError = error.localizedDescription
- }
+ Task { await attempt(replay: replay, op) }
+ }
+
+ /// `perform` for a caller that waits: whether the computer took it. A refusal runs `undo`, taking
+ /// back what the action already showed, before it reaches the dialog.
+ @discardableResult
+ private func attempt(replay: Bool = false, undo: @MainActor () -> Void = {},
+ _ op: @MainActor (HostClient) async throws -> Void) async -> Bool {
+ do {
+ try await withLink(replay: replay, op)
+ return true
+ } catch {
+ undo()
+ lastError = error.localizedDescription
+ return false
}
}
@@ -250,13 +259,63 @@ extension BotStore {
perform(replay: true) { try await $0.reorderBots(ids) }
}
- /// One place up (-1) or down (+1) among bots of the same band (VoiceOver).
+ /// One place up (-1) or down (+1) among the bots it moves with (`isRosterPeer`: its band and, below the top, its section; VoiceOver).
public func move(_ botId: String, by offset: Int) {
- var ids = roster.map(\.id)
- guard let i = ids.firstIndex(of: botId), ids.indices.contains(i + offset),
- bots[ids[i + offset]]?.band == bots[botId]?.band else { return }
- ids.swapAt(i, i + offset)
- reorder(ids)
+ guard let bot = bots[botId] else { return }
+ var peers = roster.filter { $0.isRosterPeer(of: bot) }.map(\.id)
+ guard let i = peers.firstIndex(of: botId), peers.indices.contains(i + offset) else { return }
+ peers.swapAt(i, i + offset)
+ drop(botId, in: peers)
+ }
+
+ /// A drop of `botId` where `order` (the rows on screen, top first) puts it among the bots it
+ /// moves with; every other bot keeps its place. Dropped among others (another section, the
+ /// pinned bots), it goes first or last of its own. Nothing moves unless `order` holds all of them.
+ public func drop(_ botId: String, in order: [String]) {
+ guard let bot = bots[botId] else { return }
+ let ids = roster.map(\.id)
+ let isPeer = { (id: String) in self.bots[id]?.isRosterPeer(of: bot) == true }
+ let placed = order.filter(isPeer)
+ guard Set(placed) == Set(ids.filter(isPeer)) else { return }
+ var next = placed.makeIterator()
+ reorder(ids.map { isPeer($0) ? next.next() ?? $0 : $0 })
+ }
+
+ // MARK: sections
+
+ /// Puts the bot in `section` (nil: out of its own), shown at once and taken back if the
+ /// computer refuses the name (it allows 40 characters, no control characters).
+ public func setSection(_ bot: Bot, to section: String?) {
+ let moves = show([bot.id], in: section)
+ Task { await send(moves) { try await $0.setSection(bot.id, to: section) } }
+ }
+
+ /// Moves every bot of this computer in section `name` to `newName` (a name already in use
+ /// merges the two); nil removes the section, its bots staying without one. Whether the
+ /// computer took it: a refusal is taken back and shown.
+ @discardableResult
+ public func renameSection(from name: String, to newName: String?) async -> Bool {
+ let moves = show(bots.values.filter { $0.section == name }.map(\.id), in: newName)
+ return await send(moves) { try await $0.renameSection(from: name, to: newName) }
+ }
+
+ /// Shows the bots `ids` in `section` before the computer confirms it (its `bot` events follow),
+ /// each move kept as pending until it's answered.
+ private func show(_ ids: [String], in section: String?) -> [SectionMove] {
+ let moves = ids.map { SectionMove(bot: $0, from: bots[$0]?.section, to: section) }
+ pendingSectionMoves += moves
+ Motion.animate { for id in ids { bots[id]?.section = section } }
+ return moves
+ }
+
+ /// Sends `op` for the `moves` shown; a refusal takes back each one nothing changed since.
+ private func send(_ moves: [SectionMove], _ op: @MainActor (HostClient) async throws -> Void) async -> Bool {
+ let ids = Set(moves.map(\.id))
+ defer { pendingSectionMoves.removeAll { ids.contains($0.id) } }
+ return await attempt(replay: true, undo: {
+ let back = RosterSection.takeBack(ids, pending: &pendingSectionMoves, sections: bots.compactMapValues(\.section))
+ Motion.animate { for (id, section) in back { bots[id]?.section = section } }
+ }, op)
}
public func delete(_ bot: Bot) {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
index 235c7af6..cbe1b3e8 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
@@ -107,6 +107,8 @@ public final class BotStore {
var retired = false
/// Files of messages not delivered yet (by client nonce), kept for a retry.
@ObservationIgnored var outgoingFiles: [String: [OutgoingFile]] = [:]
+ /// Section moves shown but not answered yet, oldest first.
+ @ObservationIgnored var pendingSectionMoves: [SectionMove] = []
var rev: Int64 = 0
var hostId: String?
@@ -208,6 +210,17 @@ public final class BotStore {
}
}
+ /// Every section on this computer by name, hidden and pinned bots' too (a row's "Move to section").
+ public var sections: [String] { RosterSection.sorted(Set(bots.values.compactMap(\.section))) }
+
+ /// Roster sections came with host 2.32.0: an older one drops a bot's `section` and has no
+ /// `renameSection`, so its bots offer no "Move to section". Unknown until the host answers.
+ public var supportsSections: Bool {
+ hostVersion.map { !AppVersion.isBelow($0.version, Self.sectionsHost) } ?? false
+ }
+
+ static let sectionsHost = "2.32.0"
+
/// Display name for a harness id, as the host reports it (falls back to the built-in list).
public func backendName(_ id: String) -> String {
hello?.backends.first { $0.id == id }?.name ?? BackendInfo.name(id)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift
new file mode 100644
index 00000000..95690921
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift
@@ -0,0 +1,129 @@
+import CodyncKit
+import Foundation
+
+/// A user-made section's heading in a computer's roster ("Work"): how many of its bots it lists,
+/// their unread messages (shown while it's folded) and whether it's folded on this device.
+public struct RosterSection: Sendable {
+ public let name: String
+ public let count: Int
+ public let unread: Int
+ public let folded: Bool
+
+ /// Section names as the roster lists them: the way the user's language sorts ("İş" in Turkish),
+ /// "work" before "Work", digits one by one ("Sprint 10" before "Sprint 2"), as every client does.
+ static func sorted(_ names: some Sequence<String>) -> [String] {
+ names.sorted {
+ let order = $0.localizedCompare($1)
+ return order == .orderedSame ? $0 < $1 : order == .orderedAscending
+ }
+ }
+
+ /// The section a typed name names: trimmed, nil when nothing but whitespace or control
+ /// characters was typed (the host would clear the section or refuse it).
+ public static func name(typed: String) -> String? {
+ let name = typed.trimmingCharacters(in: .whitespacesAndNewlines.union(.controlCharacters))
+ return name.isEmpty ? nil : name
+ }
+
+ /// The most Unicode scalars a section name may have, as the host counts them.
+ static let maxNameLength = 40
+
+ /// What a name box may hold: at most `maxNameLength` scalars; a name within that (one the host
+ /// accepted) is never cut.
+ public static func limited(_ typed: String) -> String {
+ typed.unicodeScalars.count > maxNameLength
+ ? String(String.UnicodeScalarView(typed.unicodeScalars.prefix(maxNameLength))) : typed
+ }
+
+ /// This device's folded sections after it renames section `from` to `to` (nil removes it): a
+ /// folded `from` stays folded as `to`, so a merge folds the section it joins; an unfolded one
+ /// changes nothing.
+ public static func folds(_ folded: Set<String>, renaming from: String, to: String?) -> Set<String> {
+ guard folded.contains(from) else { return folded }
+ var names = folded
+ names.remove(from)
+ if let to { names.insert(to) }
+ return names
+ }
+
+ /// Taking back the refused moves `refused` (desktop `restoredBots` and `chainedMoves`): each bot
+ /// still in the section its move put it in (`sections`: each bot's, if it's in one) goes back
+ /// to where that move began, as `pending` (oldest first) has it now. A bot moved since (here or on
+ /// another device) keeps its newer section. Each later pending move of the same bot that began
+ /// where a refused one put it now begins where that one did, so taking it back too lands where
+ /// the computer still has the bot.
+ static func takeBack(_ refused: Set<UUID>, pending: inout [SectionMove],
+ sections: [String: String]) -> [(bot: String, section: String?)] {
+ var back: [(bot: String, section: String?)] = []
+ for i in pending.indices where refused.contains(pending[i].id) {
+ let move = pending[i]
+ if sections[move.bot] == move.to { back.append((move.bot, move.from)) }
+ for later in pending.indices.dropFirst(i + 1) where pending[later].bot == move.bot && pending[later].from == move.to {
+ pending[later].from = move.from
+ }
+ }
+ return back
+ }
+
+ /// This device's folded sections after the computer refused a rename that changed them from
+ /// `before` to `set`: `before` again, unless they changed since (a section folded meanwhile).
+ public static func folds(_ current: Set<String>, refused set: Set<String>, before: Set<String>) -> Set<String> {
+ current == set ? before : current
+ }
+
+ /// A computer's roster (in `BotStore.roster` order) as the rows on screen: the lead and pinned
+ /// bots, then each section by name with its bots (none while folded), then the bots in no
+ /// section, under the "Bots" label when there are sections. The lead and a pinned bot show only
+ /// on top, whatever their section; every part keeps the roster's order.
+ public static func lines<Item>(_ roster: [Item], folded: Set<String>, bot: (Item) -> Bot) -> [RosterSectionLine<Item>] {
+ var pinned: [Item] = [], loose: [Item] = [], bySection: [String: [Item]] = [:]
+ for item in roster {
+ let placed = bot(item)
+ if placed.staysOnTop {
+ pinned.append(item)
+ } else if let name = placed.section {
+ bySection[name, default: []].append(item)
+ } else {
+ loose.append(item)
+ }
+ }
+ var lines = pinned.map { RosterSectionLine.bot($0) }
+ for name in sorted(bySection.keys) {
+ let items = bySection[name] ?? []
+ let isFolded = folded.contains(name)
+ let unread = items.reduce(0) { $0 + bot($1).unread }
+ lines.append(.header(RosterSection(name: name, count: items.count, unread: unread, folded: isFolded)))
+ if !isFolded { lines += items.map { RosterSectionLine.bot($0) } }
+ }
+ if !bySection.isEmpty && !loose.isEmpty { lines.append(.label) }
+ return lines + loose.map { RosterSectionLine.bot($0) }
+ }
+}
+
+/// A section change shown before the computer took it: bot `bot` from section `from` to `to` (nil:
+/// none); `id` tells it from another move of the same bot.
+struct SectionMove: Sendable {
+ let id = UUID()
+ let bot: String
+ var from: String?
+ let to: String?
+}
+
+/// One row of a computer's roster split into sections; `label` is the "Bots" label over the bots in none.
+public enum RosterSectionLine<Item> {
+ case header(RosterSection)
+ case label
+ case bot(Item)
+}
+
+extension Bot {
+ /// The lead and pinned bots stay on top, outside sections.
+ var staysOnTop: Bool { lead || pinned }
+
+ /// Whether the user can drag this bot past `other`: the same `band`, where pinned bots share
+ /// the top whatever their sections; the rest move within their own section, or among the bots
+ /// in none.
+ func isRosterPeer(of other: Bot) -> Bool {
+ band == other.band && (staysOnTop || section == other.section)
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/BotSectionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/BotSectionTests.swift
new file mode 100644
index 00000000..57c80fe6
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/BotSectionTests.swift
@@ -0,0 +1,49 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+/// Answers every call with `{}` and keeps each method's last body.
+private actor Recorder: HostTransport {
+ private(set) var bodies: [String: Data] = [:]
+
+ func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {
+ bodies[method] = body
+ return Data("{}".utf8)
+ }
+
+ nonisolated func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> { AsyncThrowingStream { $0.finish() } }
+ nonisolated func states() -> AsyncStream<LinkState> { AsyncStream { $0.finish() } }
+}
+
+private func json(_ data: Data?) throws -> [String: Any] {
+ let data = try #require(data)
+ return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
+}
+
+@Test func botSectionDecodesAndSavingSettingsLeavesItAlone() throws {
+ let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"b","section":"Work"}"#.utf8))
+ #expect(bot.section == "Work")
+ #expect(try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"b"}"#.utf8)).section == nil) // An older host.
+ let body = try json(JSONEncoder().encode(BotUpdate(draft: BotDraft(bot))))
+ #expect(body["section"] == nil)
+}
+
+@Test func sectionCallsSendOnlyTheSectionAndNullToClear() async throws {
+ let recorder = Recorder()
+ let client = HostClient(transport: recorder)
+ try await client.setSection("b", to: "Work")
+ var sent = try json(await recorder.bodies["updateBot"])
+ #expect(sent["id"] as? String == "b")
+ #expect(sent["section"] as? String == "Work")
+ #expect(sent.count == 2)
+ try await client.setSection("b", to: nil)
+ sent = try json(await recorder.bodies["updateBot"])
+ #expect(sent["section"] is NSNull)
+ try await client.renameSection(from: "Work", to: "Home")
+ sent = try json(await recorder.bodies["renameSection"])
+ #expect(sent["from"] as? String == "Work")
+ #expect(sent["to"] as? String == "Home")
+ try await client.renameSection(from: "Home", to: nil)
+ sent = try json(await recorder.bodies["renameSection"])
+ #expect(sent["to"] is NSNull)
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
index 3dcc6652..3642b909 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/RosterOrderTests.swift
@@ -35,3 +35,244 @@ import Testing
store.reorder(["p", "c", "l", "a", "b"])
#expect(order().first == "l")
}
+
+/// A bot as the host sends it.
+private func rosterBot(_ id: String, pinned: Bool = false, lead: Bool = false, hidden: Bool = false, section: String? = nil,
+ unread: Int = 0, lastAt: Int = 0) throws -> Bot {
+ var json: [String: Any] = ["id": id, "pinned": pinned, "lead": lead, "hidden": hidden, "unread": unread, "lastAt": lastAt]
+ if let section { json["section"] = section }
+ return try JSONDecoder().decode(Bot.self, from: JSONSerialization.data(withJSONObject: json))
+}
+
+/// A store holding `bots` that never connects; `done` retires it and drops its defaults.
+@MainActor private func rosterStore(_ bots: [Bot]) -> (store: BotStore, done: () -> Void) {
+ let suite = "RosterOrderTests.\(UUID().uuidString)"
+ let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)
+ let store = BotStore(computer: Computer(id: UUID().uuidString, name: "Mac", signKey: "test"), storage: storage) { _ in
+ FakeRemote(.connecting)
+ }
+ for item in bots { store.bots[item.id] = item }
+ return (store, {
+ store.retire()
+ UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
+ })
+}
+
+@Test func sectionsListPinnedBotsThenSectionsByNameThenTheRest() throws {
+ let roster = try [
+ rosterBot("p", pinned: true, section: "Work"),
+ rosterBot("w1", section: "Work", unread: 2),
+ rosterBot("loose"),
+ rosterBot("i", section: "İş"),
+ rosterBot("h", section: "home"),
+ rosterBot("w2", section: "Work", unread: 3),
+ ]
+ func shown(_ folded: Set<String>) -> [String] {
+ RosterSection.lines(roster, folded: folded) { $0 }.map { line in
+ switch line {
+ case let .header(section): "\(section.folded ? "▸" : "▾") \(section.name) \(section.count) \(section.unread)"
+ case .label: "BOTS"
+ case let .bot(item): item.id
+ }
+ }
+ }
+ // A pinned bot shows only on top; its section counts the rest.
+ #expect(shown([]) == ["p", "▾ home 1 0", "h", "▾ İş 1 0", "i", "▾ Work 2 5", "w1", "w2", "BOTS", "loose"])
+ #expect(shown(["Work"]) == ["p", "▾ home 1 0", "h", "▾ İş 1 0", "i", "▸ Work 2 5", "BOTS", "loose"])
+ // A section only pinned bots are in has no heading, and with no heading no label.
+ #expect(RosterSection.lines([roster[0], roster[2]], folded: []) { $0 }.count == 2)
+ // The label needs a bot in no section too.
+ #expect(RosterSection.lines([roster[1]], folded: []) { $0 }.count == 2)
+}
+
+@MainActor @Test func theLeadStaysOnTopOutsideItsSection() throws {
+ let (store, done) = try rosterStore([
+ rosterBot("l", lead: true, section: "Work"), rosterBot("p", pinned: true, lastAt: 3),
+ rosterBot("w", section: "Work", lastAt: 2), rosterBot("x", lastAt: 1),
+ ])
+ defer { done() }
+ let lines = RosterSection.lines(store.roster, folded: []) { $0 }.map { line in
+ switch line {
+ case let .header(section): "▾ \(section.name) \(section.count)"
+ case .label: "BOTS"
+ case let .bot(bot): bot.id
+ }
+ }
+ #expect(lines == ["l", "p", "▾ Work 1", "w", "BOTS", "x"])
+ let lead = try #require(store.bots["l"]), p = try #require(store.bots["p"]), w = try #require(store.bots["w"])
+ #expect(!lead.isRosterPeer(of: p) && !lead.isRosterPeer(of: w))
+}
+
+@Test func sectionsSortTheSameWhateverOrderTheyComeIn() {
+ // As the other clients sort them: lowercase first, unaccented first, digits one by one.
+ for names in [["Work", "work", "Café", "Cafe", "Sprint 2", "Sprint 10"], ["Sprint 10", "Cafe", "work", "Sprint 2", "Café", "Work"]] {
+ #expect(RosterSection.sorted(names) == ["Cafe", "Café", "Sprint 10", "Sprint 2", "work", "Work"])
+ }
+}
+
+@Test func typedSectionNamesAreTrimmedAndCappedLikeTheHost() {
+ #expect(RosterSection.name(typed: "") == nil)
+ #expect(RosterSection.name(typed: " \n\t ") == nil)
+ #expect(RosterSection.name(typed: "\u{1}\u{7F} ") == nil) // Control characters only.
+ #expect(RosterSection.name(typed: " Work ") == "Work")
+ // 40 Unicode scalars, as the host counts them: "é" written as e + accent is two.
+ let forty = String(repeating: "e\u{301}", count: 20)
+ #expect(RosterSection.limited(forty) == forty)
+ #expect(RosterSection.limited(forty + "x") == forty)
+ #expect(RosterSection.limited("Work") == "Work")
+}
+
+@Test func aFoldedSectionRenamedOrRemovedHereTakesItsFoldAlong() {
+ #expect(RosterSection.folds(["Home", "Work"], renaming: "Work", to: "Jobs") == ["Home", "Jobs"])
+ #expect(RosterSection.folds(["Home"], renaming: "Work", to: "Jobs") == ["Home"]) // Unfolded: nothing changes.
+ #expect(RosterSection.folds(["Home"], renaming: "Work", to: "Home") == ["Home"]) // Never unfolds the target.
+ #expect(RosterSection.folds(["Home", "Work"], renaming: "Work", to: nil) == ["Home"]) // Removed: its name goes.
+ #expect(RosterSection.folds(["Work"], renaming: "Work", to: "Home") == ["Home"]) // A merge folds the section it joins.
+ #expect(RosterSection.folds(["Home", "Work"], renaming: "Work", to: "Home") == ["Home"])
+}
+
+@Test func aRefusedRenamePutsTheFoldsBackUnlessOneChangedMeanwhile() {
+ let before: Set = ["Home", "Work"], moved: Set = ["Home", "Jobs"]
+ #expect(RosterSection.folds(moved, refused: moved, before: before) == before)
+ #expect(RosterSection.folds(["Jobs"], refused: moved, before: before) == ["Jobs"]) // "Home" unfolded meanwhile: kept.
+}
+
+@Test func aSectionsNameInAMenuShowsAsTheUserTypedIt() {
+ let translate = { (_: String) in "Einstellungen" }
+ #expect(MenuItem("Settings", verbatim: true) {}.shownTitle(translate) == "Settings") // A section named "Settings".
+ #expect(MenuItem("Settings") {}.shownTitle(translate) == "Einstellungen") // The app's own Settings.
+}
+
+@MainActor @Test func sectionMenuListsEverySectionOnTheComputer() throws {
+ let (store, done) = try rosterStore([
+ rosterBot("a", section: "Work"), rosterBot("p", pinned: true, section: "Pinned"),
+ rosterBot("h", hidden: true, section: "Hidden"), rosterBot("b", section: "Work"), rosterBot("c"),
+ ])
+ defer { done() }
+ #expect(store.sections == ["Hidden", "Pinned", "Work"]) // Hidden and pinned bots keep theirs.
+}
+
+@MainActor @Test func sectionMenusNeedAHostThatKnowsSections() throws {
+ let (store, done) = rosterStore([])
+ defer { done() }
+ #expect(!store.supportsSections) // The host hasn't answered yet.
+ store.hostVersion = HostVersion(version: "2.31.2")
+ #expect(!store.supportsSections)
+ store.hostVersion = HostVersion(version: "2.32.0")
+ #expect(store.supportsSections)
+ store.hostVersion = HostVersion(version: "2.32.1-dev")
+ #expect(store.supportsSections)
+}
+
+@MainActor @Test func sectionChangesShowAtOnceAndUndoWhenRefused() async throws {
+ let (store, done) = try rosterStore([rosterBot("a"), rosterBot("b", section: "Work"), rosterBot("c", section: "Home")])
+ defer { done() }
+ store.connection = .unauthorized("No access") // Every call fails at once.
+ store.setSection(try #require(store.bots["a"]), to: "Work")
+ #expect(store.bots["a"]?.section == "Work")
+ #expect(await until { store.bots["a"]?.section == nil })
+ #expect(store.lastError != nil)
+ store.connection = .connecting // The next call waits for the link…
+ let merge = Task { await store.renameSection(from: "Work", to: "Home") } // Onto a name in use: the two merge.
+ #expect(await until { store.sections == ["Home"] })
+ store.connection = .unauthorized("No access") // …which turns it away.
+ #expect(await merge.value == false) // So this device's folds go back.
+ #expect(store.bots["b"]?.section == "Work")
+ #expect(store.bots["c"]?.section == "Home") // Already in "Home": the undo leaves it.
+ #expect(await store.renameSection(from: "Home", to: nil) == false)
+ #expect(store.bots["c"]?.section == "Home")
+}
+
+@MainActor @Test func aRefusedRenameKeepsWhatAnotherDeviceMovedMeanwhile() async throws {
+ let (store, done) = try rosterStore([rosterBot("b", section: "Work"), rosterBot("c", section: "Work")])
+ defer { done() }
+ let rename = Task { await store.renameSection(from: "Work", to: "Jobs") } // Waits for the link (the store never connects).
+ #expect(await until { store.sections == ["Jobs"] })
+ store.bots["b"]?.section = "Home" // Another device moves one; then the computer turns the rename away.
+ store.connection = .unauthorized("No access")
+ #expect(await rename.value == false)
+ #expect(store.bots["b"]?.section == "Home")
+ #expect(store.bots["c"]?.section == "Work") // Still where the refused rename put it: taken back.
+}
+
+@MainActor @Test func aRefusedMoveKeepsWhatAnotherDeviceMovedMeanwhile() async throws {
+ let (store, done) = try rosterStore([rosterBot("a")])
+ defer { done() }
+ store.setSection(try #require(store.bots["a"]), to: "Work") // Waits for the link.
+ store.bots["a"]?.section = "Home" // Another device moves it; then the computer turns the move away.
+ store.connection = .unauthorized("No access")
+ #expect(await until { store.lastError != nil }) // The undo has run.
+ #expect(store.bots["a"]?.section == "Home")
+ #expect(store.pendingSectionMoves.isEmpty)
+}
+
+/// Bot "x" through `moves` shown one after another, then each refused in `order` (indices into
+/// `moves`), as `BotStore` takes them back: where "x" ends up.
+private func refused(_ moves: [SectionMove], in order: [Int]) -> String? {
+ var pending = moves, section = moves.last?.to
+ for i in order {
+ let back = RosterSection.takeBack([moves[i].id], pending: &pending, sections: section.map { ["x": $0] } ?? [:])
+ for (_, to) in back { section = to }
+ pending.removeAll { $0.id == moves[i].id }
+ }
+ return section
+}
+
+@Test func refusedMovesInARowGoBackToWhereTheComputerHasTheBot() {
+ let toHome = SectionMove(bot: "x", from: "Work", to: "Home"), toSide = SectionMove(bot: "x", from: "Home", to: "Side")
+ #expect(refused([toHome, toSide], in: [0, 1]) == "Work") // In order: not left in Home.
+ #expect(refused([toHome, toSide], in: [1, 0]) == "Work") // Out of order.
+ #expect(refused([toHome, toSide], in: [0]) == "Side") // The later move went through.
+ #expect(refused([toHome, toSide], in: [1]) == "Home") // The earlier one did.
+ // A rename (Work → Jobs), then the bot moved on to Side; both refused, either way round.
+ let rename = SectionMove(bot: "x", from: "Work", to: "Jobs"), toSideAfter = SectionMove(bot: "x", from: "Jobs", to: "Side")
+ #expect(refused([rename, toSideAfter], in: [0, 1]) == "Work")
+ #expect(refused([rename, toSideAfter], in: [1, 0]) == "Work")
+ // Out of a section (nil) and into another, both refused.
+ let out = SectionMove(bot: "x", from: "Work", to: nil), into = SectionMove(bot: "x", from: nil, to: "Side")
+ #expect(refused([out, into], in: [0, 1]) == "Work")
+}
+
+@MainActor @Test func aRenameTheComputerTakesReportsIt() async throws {
+ let (storage, suite) = context()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let fake = FakeRemote(.ready(.direct))
+ let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }
+ defer { store.retire() }
+ store.setActive(true)
+ #expect(await until { await fake.subscribed })
+ await fake.emit(#"{"type":"bot","bot":{"id":"b1","name":"Bot","rev":1,"lastAt":1,"section":"Work"}}"#)
+ #expect(await until { store.connection == .online })
+ #expect(await store.renameSection(from: "Work", to: "Jobs")) // So a folded "Work" stays folded as "Jobs".
+ #expect(await fake.calls.contains("renameSection"))
+ #expect(store.bots["b1"]?.section == "Jobs")
+}
+
+@MainActor @Test func botsMoveOnlyAmongTheirPinStateAndSection() throws {
+ let (store, done) = try rosterStore([
+ rosterBot("p1", pinned: true, section: "Work", lastAt: 9), rosterBot("p2", pinned: true, lastAt: 8),
+ rosterBot("w1", section: "Work", lastAt: 7), rosterBot("a", lastAt: 6),
+ rosterBot("w2", section: "Work", lastAt: 5), rosterBot("b", lastAt: 4),
+ ])
+ defer { done() }
+ let order = { store.roster.map(\.id) }
+ let p1 = try #require(store.bots["p1"]), p2 = try #require(store.bots["p2"])
+ let w1 = try #require(store.bots["w1"]), w2 = try #require(store.bots["w2"]), a = try #require(store.bots["a"])
+ #expect(p1.isRosterPeer(of: p2)) // Pinned bots share the top, whatever their sections.
+ #expect(!p1.isRosterPeer(of: w1))
+ #expect(w1.isRosterPeer(of: w2))
+ #expect(!w1.isRosterPeer(of: a)) // Another section: none.
+ #expect(order() == ["p1", "p2", "w1", "a", "w2", "b"])
+ store.move("w2", by: -1) // Past "a", which is in no section: above w1.
+ #expect(order() == ["p1", "p2", "w2", "a", "w1", "b"])
+ store.move("w2", by: -1) // Already first in Work.
+ #expect(order() == ["p1", "p2", "w2", "a", "w1", "b"])
+ store.drop("a", in: ["p1", "p2", "w2", "b", "a", "w1"]) // Dropped below "b", among Work's bots.
+ #expect(order() == ["p1", "p2", "w2", "b", "w1", "a"])
+ store.drop("w1", in: ["w1", "p1", "p2", "w2", "b", "a"]) // Above the pinned bots: first of Work.
+ #expect(order() == ["p1", "p2", "w1", "b", "w2", "a"])
+ store.drop("p1", in: ["p2", "p1", "w1", "b", "w2", "a"])
+ #expect(order() == ["p2", "p1", "w1", "b", "w2", "a"])
+ store.drop("w1", in: ["p2", "p1", "w1", "b", "a"]) // A bot of its section isn't on screen: nothing moves.
+ #expect(order() == ["p2", "p1", "w1", "b", "w2", "a"])
+}
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index 7a10ec87..559ed4c1 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -4,8 +4,9 @@ import SwiftUI
/// The roster: every bot on every computer is a person you can message (Grok Bot sidebar, phone-sized).
/// A `List` with its styling taken away, for the system's reordering: touch and hold opens a bot's
-/// menu, and dragging it (before or after the menu shows) moves it among its computer's bots.
-/// Dragging a computer's heading moves the computer with its bots.
+/// menu, and dragging it (before or after the menu shows) moves it among its computer's bots with
+/// the same pin state and section. Dragging a computer's heading moves the computer with its bots;
+/// a section's heading folds its bots away and holds its menu.
struct BotListView: View {
@Environment(AppStore.self) private var app
@Environment(AccountStore.self) private var accounts
@@ -13,6 +14,8 @@ struct BotListView: View {
@State private var editing: EditTarget?
@State private var editingGroup: GroupTarget?
@State private var confirmDelete: RosterItem?
+ /// What the section name dialog names while it's open.
+ @State private var naming: SectionNaming?
/// A bot whose agent starts over with a fresh context, once confirmed.
@State private var confirmNewSession: RosterItem?
/// The row that's lifted (a `RosterLine` id): a bot to drag or for its menu, or a computer's heading.
@@ -22,6 +25,9 @@ struct BotListView: View {
@AppStorage("hiddenComputers") private var hiddenComputers = ""
/// Computers whose bots are folded away on this device, comma-separated IDs.
@AppStorage("collapsedComputers") private var collapsedComputers = ""
+ /// Sections folded away on this device, by name, one per line: a name never holds a line break.
+ // ponytail: one name folds that section on every computer; key it by computer if they must fold apart.
+ @AppStorage("collapsedRosterSections") private var collapsedRosterSections = ""
private var collapsedIDs: Set<ComputerID> { Set(collapsedComputers.split(separator: ",").map(String.init)) }
@@ -31,6 +37,31 @@ struct BotListView: View {
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { collapsedComputers = ids.sorted().joined(separator: ",") }
}
+ private var foldedSections: Set<String> {
+ get { Set(collapsedRosterSections.split(separator: "\n").map(String.init)) }
+ nonmutating set { collapsedRosterSections = newValue.sorted().joined(separator: "\n") }
+ }
+
+ private func toggleSection(_ name: String) {
+ var names = foldedSections
+ if names.remove(name) == nil { names.insert(name) }
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { foldedSections = names }
+ }
+
+ /// Renames or removes (nil) a section on `store`'s computer; a folded one stays folded under its
+ /// new name, on this device, at once. A refusal puts the folds back, unless one was folded or
+ /// unfolded meanwhile.
+ private func renameSection(_ name: String, to newName: String?, on store: BotStore) {
+ Task {
+ // Right before the call, which moves the bots before it waits: one update shows both.
+ let before = foldedSections
+ let moved = RosterSection.folds(before, renaming: name, to: newName)
+ foldedSections = moved
+ if await store.renameSection(from: name, to: newName) { return }
+ foldedSections = RosterSection.folds(foldedSections, refused: moved, before: before)
+ }
+ }
+
private var shownIDs: Set<ComputerID> {
Set(ComputerSelection(all: accounts.computers.map(\.id), hidden: hiddenComputers).shown)
}
@@ -60,14 +91,27 @@ struct BotListView: View {
accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.mismatch == nil && !accounts.isStale($0.computer.id) }
}
- /// The rows the user can drag: each shown computer's heading (with several computers), in the
- /// order they were dragged into, followed by its bots unless it's folded away.
+ /// The roster's rows: each shown computer's heading (with several computers), in the order
+ /// they were dragged into, followed by its bots and sections unless it's folded away.
private var lines: [RosterLine] {
shownStores.flatMap { store -> [RosterLine] in
let id = store.computer.id
- let bots = grouped && collapsedIDs.contains(id)
- ? [] : accounts.roster.filter { $0.ref.computerId == id }.map { RosterLine.bot($0, store) }
- return grouped ? [.computer(id, store)] + bots : bots
+ let rows = grouped && collapsedIDs.contains(id) ? [] : sectionLines(store)
+ return grouped ? [.computer(id, store)] + rows : rows
+ }
+ }
+
+ /// A computer's bots: pinned ones, then each section's heading with its bots (none while
+ /// folded), then the bots in no section (under the "Bots" label when there are sections).
+ private func sectionLines(_ store: BotStore) -> [RosterLine] {
+ let id = store.computer.id
+ let items = accounts.roster.filter { $0.ref.computerId == id }
+ return RosterSection.lines(items, folded: foldedSections) { $0.bot }.map { line -> RosterLine in
+ switch line {
+ case let .header(section): .section(section, id, store)
+ case .label: .label(id)
+ case let .bot(item): .bot(item, store)
+ }
}
}
@@ -93,6 +137,10 @@ struct BotListView: View {
ForEach(lines) { line in
switch line {
case let .computer(_, store): computerHeading(store, roster: roster, folded: movingComputer)
+ case let .section(section, _, store):
+ if movingComputer { Color.clear.frame(height: 0) } else { sectionHeading(section, store: store) }
+ case .label:
+ if movingComputer { Color.clear.frame(height: 0) } else { RosterBotsLabel().moveDisabled(true) }
case let .bot(item, store):
// A dragged heading folds every computer's bots into their headings. Each
// row stays, empty: taking it out would move the lifted heading's place in
@@ -184,6 +232,7 @@ struct BotListView: View {
if let item { accounts.store(for: item.ref.computerId)?.delete(item.bot) }
}]
}
+ .sectionNameDialog($naming)
.codyncDialog("Start a new session?",
isPresented: Binding(get: { confirmNewSession != nil }, set: { if !$0 { confirmNewSession = nil } }),
message: "The conversation stays here, but the agent starts with a fresh context.") {
@@ -195,8 +244,9 @@ struct BotListView: View {
}
/// A row the system's reordering dropped. A heading moves its computer and its bots (an order
- /// kept on this device); a bot moves only among its computer's bots, an order the host syncs to
- /// every device: dropped above or below them (on another computer), it goes first or last.
+ /// kept on this device); a bot moves only among its computer's bots with the same pin state and
+ /// section, an order the host syncs to every device: dropped among others (another section,
+ /// another computer), it goes first or last of its own. Section headings don't move.
private func moveLines(from source: IndexSet, to destination: Int) {
let before = lines
guard let from = source.first, before.indices.contains(from) else { return }
@@ -208,7 +258,9 @@ struct BotListView: View {
guard let to = new.firstIndex(of: id), old[to] != id else { return }
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { accounts.move(id, to: old[to]) }
case let .bot(item, store):
- store.reorder(after.compactMap { $0.botId(on: item.ref.computerId) })
+ store.drop(item.bot.id, in: after.compactMap { $0.botId(on: item.ref.computerId) })
+ case .section, .label:
+ break
}
}
@@ -236,6 +288,27 @@ struct BotListView: View {
.itemProvider { lift(.computer(id, store)) }
}
+ /// A section's heading: tap folds its bots away (on this device); touch and hold to rename or
+ /// remove it, its bots staying without one. An older computer has no section menu.
+ @ViewBuilder private func sectionHeading(_ section: RosterSection, store: BotStore) -> some View {
+ let header = RosterSectionHeader(section: section, hasMenu: store.supportsSections) { toggleSection(section.name) }
+ .moveDisabled(true)
+ if store.supportsSections {
+ header.contextActions {
+ [
+ MenuItem("Rename section…", icon: "pencil") {
+ naming = SectionNaming(title: "Rename section", name: section.name) {
+ renameSection(section.name, to: $0, on: store)
+ }
+ },
+ MenuItem("Remove section", icon: "xmark.circle") { renameSection(section.name, to: nil, on: store) },
+ ]
+ }
+ } else {
+ header
+ }
+ }
+
private func row(_ item: RosterItem, store: BotStore) -> some View {
let bot = item.bot
let line = RosterLine.bot(item, store)
@@ -260,8 +333,10 @@ struct BotListView: View {
// The lead stays on top.
.moveDisabled(bot.lead)
.contextActions {
- // The lead is always on top and always there: no pin, hide or delete.
+ // The lead is always on top and always there: no pin, section, hide or delete.
var items = bot.lead ? [] : [MenuItem(bot.pinned ? "Unpin" : "Pin", icon: bot.pinned ? "pin.slash" : "pin") { store.setPinned(bot, !bot.pinned) }]
+ // Below Pin, like the desktop; an older computer has no sections.
+ if !bot.lead && store.supportsSections { items.append(sectionMenu(bot, store: store)) }
if !bot.isGroup {
items.append(MenuItem("New session", icon: "arrow.counterclockwise") { confirmNewSession = item })
}
@@ -281,6 +356,21 @@ struct BotListView: View {
}
}
+ /// "Move to section ▸": the computer's other sections (by the names the user gave them, never
+ /// translated), a new one, and out of its own.
+ private func sectionMenu(_ bot: Bot, store: BotStore) -> MenuItem {
+ var rows = store.sections.filter { $0 != bot.section }.map { name in
+ MenuItem(name, icon: "tray", verbatim: true) { store.setSection(bot, to: name) }
+ }
+ rows.append(MenuItem("New section…", icon: "plus", divider: !rows.isEmpty) {
+ naming = SectionNaming(title: "New section", name: "") { store.setSection(bot, to: $0) }
+ })
+ if bot.section != nil {
+ rows.append(MenuItem("Remove from section", icon: "minus.circle") { store.setSection(bot, to: nil) })
+ }
+ return MenuItem("Move to section", icon: "tray", submenu: rows)
+ }
+
/// The system asks for a row's item as it lifts; the row shows as lifted until it lets go.
/// A heading folds the bots away and back with an animation.
private func lift(_ line: RosterLine) -> NSItemProvider {
@@ -320,14 +410,19 @@ private final class LiftItem: NSItemProvider {
deinit { ended() }
}
-/// One row the user can drag in the roster: a computer's heading or a bot.
+/// One row in the roster: a computer's heading or a bot, which the user can drag, or a section's
+/// heading or the "Bots" label on a computer (its id carried along: `id` can't read the main-actor store).
private enum RosterLine: Identifiable {
case computer(ComputerID, BotStore)
+ case section(RosterSection, ComputerID, BotStore)
+ case label(ComputerID)
case bot(RosterItem, BotStore)
var id: String {
switch self {
case let .computer(id, _): "computer:\(id)"
+ case let .section(section, computerId, _): "section:\(computerId):\(section.name)"
+ case let .label(computerId): "label:\(computerId)"
case let .bot(item, _): "bot:\(item.ref.computerId):\(item.bot.id)"
}
}
@@ -342,88 +437,6 @@ private enum RosterLine: Identifiable {
}
}
-/// A computer's heading above its bots: badge, name and connection. Tap folds its bots away;
-/// touch and hold, then drag, moves the computer (on this device).
-private struct ComputerSection: View {
- let store: BotStore
- let empty: Bool
- let collapsed: Bool
- let toggle: () -> Void
- let move: (ComputerID, Int) -> Void
- /// This computer's own Extensions; nil while it can't be reached.
- let extensions: (() -> Void)?
-
- var body: some View {
- VStack(alignment: .leading, spacing: 6) {
- heading
- if empty && !collapsed {
- Text(L10n.tr("No bots yet"))
- .font(.footnote)
- .foregroundStyle(Palette.tertiary)
- .padding(.horizontal, 8)
- .padding(.bottom, 4)
- .transition(.opacity)
- }
- }
- .padding(.top, 14)
- .padding(.bottom, 2)
- .padding(.horizontal, -8)
- .accessibilityElement(children: .combine)
- .accessibilityAddTraits([.isHeader, .isButton])
- .accessibilityLabel("\(store.hostName), \(store.statusText)")
- .accessibilityValue(collapsed ? "Collapsed" : "Expanded")
- .accessibilityHint("Double-tap to fold or expand. Touch and hold, then drag to reorder on this device.")
- .accessibilityAction(named: collapsed ? "Expand" : "Collapse", toggle)
- .accessibilityAction(.default) { toggle() }
- .accessibilityActions {
- Button(L10n.tr("Move up")) { move(store.computer.id, -1) }
- Button(L10n.tr("Move down")) { move(store.computer.id, 1) }
- if let extensions { Button(L10n.tr("Extensions"), action: extensions) }
- }
- }
-
- private var heading: some View {
- HStack(spacing: 6) {
- ComputerBadge(store.computer, size: 18)
- Text(store.hostName)
- .font(.footnote.weight(.semibold))
- .foregroundStyle(Palette.secondary)
- .lineLimit(1)
- // The connection sits at the trailing edge, before the heading's buttons.
- Spacer(minLength: 8)
- Text(L10n.tr(store.statusText))
- .font(.footnote)
- .foregroundStyle(store.isOffline && !store.isUpdating ? Palette.warning : Palette.tertiary)
- .lineLimit(1)
- .contentTransition(.opacity)
- if store.connection == .online {
- RouteIcon(route: store.hostRoute, cloud: store.computer.cloud).font(.caption2).foregroundStyle(Palette.tertiary)
- }
- Image(systemName: "chevron.down")
- .font(.caption.weight(.semibold))
- .foregroundStyle(Palette.tertiary)
- .rotationEffect(.degrees(collapsed ? -90 : 0))
- .accessibilityHidden(true)
- if let extensions {
- // After the chevron, as on the desktop; sized like it so the heading stays one light line.
- Button(action: extensions) {
- Image(systemName: "square.grid.2x2")
- .font(.caption.weight(.semibold))
- .foregroundStyle(Palette.secondary)
- .frame(width: 28, height: 22)
- .contentShape(Rectangle())
- }
- .buttonStyle(.borderless)
- .accessibilityLabel(L10n.tr("Extensions"))
- .help(L10n.tr("Extensions"))
- }
- }
- .padding(.vertical, 6)
- .padding(.horizontal, 8)
- .contentShape(Rectangle())
- }
-}
-
private struct NewTarget: Identifiable {
enum Kind { case bot, group }
let id = UUID()
diff --git a/apps/ios/Views/ComputerSection.swift b/apps/ios/Views/ComputerSection.swift
new file mode 100644
index 00000000..ceb6fab3
--- /dev/null
+++ b/apps/ios/Views/ComputerSection.swift
@@ -0,0 +1,85 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// A computer's heading above its bots: badge, name and connection. Tap folds its bots away;
+/// touch and hold, then drag, moves the computer (on this device).
+struct ComputerSection: View {
+ let store: BotStore
+ let empty: Bool
+ let collapsed: Bool
+ let toggle: () -> Void
+ let move: (ComputerID, Int) -> Void
+ /// This computer's own Extensions; nil while it can't be reached.
+ let extensions: (() -> Void)?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ heading
+ if empty && !collapsed {
+ Text(L10n.tr("No bots yet"))
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ .padding(.horizontal, 8)
+ .padding(.bottom, 4)
+ .transition(.opacity)
+ }
+ }
+ .padding(.top, 14)
+ .padding(.bottom, 2)
+ .padding(.horizontal, -8)
+ .accessibilityElement(children: .combine)
+ .accessibilityAddTraits([.isHeader, .isButton])
+ .accessibilityLabel("\(store.hostName), \(store.statusText)")
+ .accessibilityValue(collapsed ? "Collapsed" : "Expanded")
+ .accessibilityHint("Double-tap to fold or expand. Touch and hold, then drag to reorder on this device.")
+ .accessibilityAction(named: collapsed ? "Expand" : "Collapse", toggle)
+ .accessibilityAction(.default) { toggle() }
+ .accessibilityActions {
+ Button(L10n.tr("Move up")) { move(store.computer.id, -1) }
+ Button(L10n.tr("Move down")) { move(store.computer.id, 1) }
+ if let extensions { Button(L10n.tr("Extensions"), action: extensions) }
+ }
+ }
+
+ private var heading: some View {
+ HStack(spacing: 6) {
+ ComputerBadge(store.computer, size: 18)
+ Text(store.hostName)
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(Palette.secondary)
+ .lineLimit(1)
+ // The connection sits at the trailing edge, before the heading's buttons.
+ Spacer(minLength: 8)
+ Text(L10n.tr(store.statusText))
+ .font(.footnote)
+ .foregroundStyle(store.isOffline && !store.isUpdating ? Palette.warning : Palette.tertiary)
+ .lineLimit(1)
+ .contentTransition(.opacity)
+ if store.connection == .online {
+ RouteIcon(route: store.hostRoute, cloud: store.computer.cloud).font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ Image(systemName: "chevron.down")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(Palette.tertiary)
+ .rotationEffect(.degrees(collapsed ? -90 : 0))
+ .accessibilityHidden(true)
+ if let extensions {
+ // After the chevron, as on the desktop; sized like it so the heading stays one light line.
+ Button(action: extensions) {
+ Image(systemName: "square.grid.2x2")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(Palette.secondary)
+ .frame(width: 28, height: 22)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.borderless)
+ .accessibilityLabel(L10n.tr("Extensions"))
+ .help(L10n.tr("Extensions"))
+ }
+ }
+ .padding(.vertical, 6)
+ .padding(.horizontal, 8)
+ .contentShape(Rectangle())
+ }
+}
diff --git a/apps/ios/Views/RosterSectionHeader.swift b/apps/ios/Views/RosterSectionHeader.swift
new file mode 100644
index 00000000..68bcfe84
--- /dev/null
+++ b/apps/ios/Views/RosterSectionHeader.swift
@@ -0,0 +1,84 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// A user-made section's heading in the roster, in `ComputerSection`'s look (name, bot count, a
+/// trailing chevron): tap folds its bots away on this device; folded, it shows how many unread
+/// messages its bots hold.
+struct RosterSectionHeader: View {
+ let section: RosterSection
+ /// Whether touch and hold opens its menu (rename, remove): not on a computer without sections.
+ let hasMenu: Bool
+ let toggle: () -> Void
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ private var showsUnread: Bool { section.folded && section.unread > 0 }
+
+ var body: some View {
+ HStack(spacing: 6) {
+ // The name gives way first: the count, badge and chevron keep their room.
+ Text(section.name)
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(Palette.secondary)
+ .lineLimit(1)
+ Text("\(section.count)")
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ .layoutPriority(1)
+ Spacer(minLength: 8)
+ // Fades however it changes: a message arriving while folded isn't animated by the store.
+ ZStack {
+ if showsUnread { UnreadBadge(count: section.unread).transition(.opacity) }
+ }
+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: showsUnread)
+ .layoutPriority(1)
+ Image(systemName: "chevron.down")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(Palette.tertiary)
+ .rotationEffect(.degrees(section.folded ? -90 : 0))
+ .accessibilityHidden(true)
+ }
+ // `ComputerSection`'s 14 + 6 points above and 2 + 6 below: about 46 points to tap.
+ .padding(.top, 20)
+ .padding(.bottom, 8)
+ .contentShape(Rectangle())
+ .onTapGesture(perform: toggle)
+ .accessibilityElement(children: .ignore)
+ .accessibilityAddTraits([.isHeader, .isButton])
+ .accessibilityLabel(spoken)
+ .accessibilityValue(section.folded ? L10n.tr("Collapsed") : L10n.tr("Expanded"))
+ .accessibilityHint(hasMenu ? L10n.tr("Double-tap to fold or expand. Touch and hold to rename or remove the section.")
+ : L10n.tr("Double-tap to fold or expand."))
+ .accessibilityAction(named: section.folded ? L10n.tr("Expand") : L10n.tr("Collapse"), toggle)
+ .accessibilityAction(.default) { toggle() }
+ }
+
+ /// "Work, 2 bots, 3 unread": what the count and the badge stand for, its phrase translated
+ /// before the name goes in.
+ private var spoken: String {
+ let phrase = switch (section.count == 1, showsUnread) {
+ case (true, false): L10n.tr("{name}, 1 bot")
+ case (false, false): L10n.tr("{name}, {count} bots")
+ case (true, true): L10n.tr("{name}, 1 bot, {unread} unread")
+ case (false, true): L10n.tr("{name}, {count} bots, {unread} unread")
+ }
+ // The name goes in last, so one that reads "{count}" stays as the user typed it.
+ return phrase.replacingOccurrences(of: "{count}", with: String(section.count))
+ .replacingOccurrences(of: "{unread}", with: String(section.unread))
+ .replacingOccurrences(of: "{name}", with: section.name)
+ }
+}
+
+/// The plain "Bots" label over the bots in no section, set like a section heading's name so the
+/// rows line up; it folds nothing and has no menu.
+struct RosterBotsLabel: View {
+ var body: some View {
+ Text(L10n.tr("Bots"))
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(Palette.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.top, 20)
+ .padding(.bottom, 8)
+ .accessibilityAddTraits(.isHeader)
+ }
+}
diff --git a/apps/ios/Views/SectionNameDialog.swift b/apps/ios/Views/SectionNameDialog.swift
new file mode 100644
index 00000000..9df32366
--- /dev/null
+++ b/apps/ios/Views/SectionNameDialog.swift
@@ -0,0 +1,43 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// An open section name dialog (desktop and Android `SectionNaming`): its title, the name it opens
+/// with, and what Save does with the typed one.
+struct SectionNaming {
+ let title: String
+ let name: String
+ let save: @MainActor (String) -> Void
+}
+
+extension View {
+ /// Asks for a section's name while `naming` is set (desktop and Android `SectionNameDialog`).
+ func sectionNameDialog(_ naming: Binding<SectionNaming?>) -> some View {
+ modifier(SectionNameDialog(naming: naming))
+ }
+}
+
+private struct SectionNameDialog: ViewModifier {
+ @Binding var naming: SectionNaming?
+ @State private var name = ""
+
+ func body(content: Content) -> some View {
+ content
+ .codyncDialog(naming?.title ?? "", isPresented: Binding(get: { naming != nil }, set: { if !$0 { naming = nil } }),
+ field: DialogField("Section name", text: $name)) {
+ // Read as the dialog shows: closing clears `naming`.
+ let target = naming
+ return [DialogAction("Save") {
+ guard let target, let typed = RosterSection.name(typed: name) else { return }
+ target.save(typed)
+ }]
+ }
+ // Each opening starts from its own name.
+ .onChange(of: naming?.name) { if let start = naming?.name { name = start } }
+ // Typing stops where the computer's limit is.
+ .onChange(of: name) {
+ let limited = RosterSection.limited(name)
+ if limited != name { name = limited }
+ }
+ }
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 7b8989a6..cc836d60 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -6,14 +6,10 @@ any left). tools/asc-submit.py reads the released version's section;
a version without one gets a generic "Bug fixes and improvements" line. Delete old sections.
-->
-## 2.31.2
+## 2.32.0
### zh-Hant
-- 從手機更新電腦時,電腦重新啟動的期間會顯示「正在更新…」,不會再要你申請訪問。
-- Codex bot 現在拿得到和你 Codex 設定裡同名的聯結器(例如 Notion),不會再看不到它的工具。
-- Codex bot 傳訊息和整理記憶的動作,不會再出現在工作步驟裡。
+- Bot 清單可以分成自己的分組,例如「工作」和「個人」:長按 Bot 選「移到分組」,點分組標題即可收合,收合時會顯示裡面的未讀數。
### en-US
-- While a computer restarts for an update you started from your phone, it shows Updating… instead of asking you for access.
-- Codex bots now get a connector that shares its name with a server in your Codex config, such as Notion, instead of missing its tools.
-- A Codex bot's own messages and memory upkeep no longer show among its working steps.
+- Sort the bot list into your own sections, like Work and Personal: touch and hold a bot and choose Move to section, then tap a section's heading to fold it, with its unread count showing while it's folded.
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index fb5cf165..711c82d2 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -45,10 +45,16 @@ pointer), every section folds into its heading, the others make room as it passe
they unfold on release (`BotRoster.tsx`). Click a heading to fold its bots.
Order and folded sections stay on this device; the iPhone and other computers keep
independent orders even when signed in to the same account. Filtering a computer out
-does not discard its position. One selected computer keeps a flat roster. Bots stay within
-their computer's section; drag a bot row or press Alt+Up/Down on the selected bot to reorder
+does not discard its position. One selected computer gets no heading. Inside each computer,
+the lead bot comes first, then pinned rows, then foldable section headers sorted by name (name,
+bot count, and the unread total while folded; folded state saved on this device), then rows in no
+section (under a "Bots" label when there are sections). A row's right-click menu has Move to
+section (not the lead's), a section header's has Rename section and Remove section (both only for
+a host at 2.32.0 or newer); a move or rename the host refuses is put back. Bots stay among their
+computer's bots (the lead stays on top, pinned bots move among all pinned bots, an unpinned bot
+also stays inside its section); drag a bot row or press Alt+Up/Down on the selected bot to reorder
it ([bot order](../features/computer-order.md#bot-order), synced through the host), and
-arrow-key navigation skips folded sections.
+Up/Down navigation skips folded computers and sections.
Search still includes their bots. The compact sidebar uses computer badges for the same
section controls. Ordering is saved locally immediately and survives restart, with separate
preferences per account and cloud environment. See [computer ordering](../features/computer-order.md).
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index a3b89261..2863d4b0 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -107,7 +107,7 @@ Codync/
| Swift transport and cloud API | `apps/ios/Kit/Sources/CodyncKit/Client/` |
| Account aggregation / one host mirror | `apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift` / `BotStore.swift` (+ `BotStore+Connection`, `+Sync`, `+Sending`, `+Actions`, `+Plugins`, `+Cache`, `+Shortcuts`) |
| iPhone chat, replies, composer and trace | `apps/ios/Kit/Sources/CodyncUI/Thread/` |
-| Reusable iPhone UI chrome | `apps/ios/Kit/Sources/CodyncUI/Chrome.swift`, `Controls.swift`, `Platform.swift` |
+| Reusable iPhone UI chrome | `apps/ios/Kit/Sources/CodyncUI/Chrome.swift`, `Controls.swift`, `MenuItem.swift` (system menus: `MenuItem`, `.contextActions`, `DropdownMenu`), `Platform.swift` |
| iOS navigation, pairing, account, settings, computer management | `apps/ios/Views/RootView.swift`, `BotListView.swift`, `PairingView.swift`, `AccountSwitcherView.swift`, `SettingsView.swift`, `ComputersView.swift` |
| Apple account sessions / public environment config | `apps/ios/App/AccountSession.swift`, `apps/shared/Config/` |
| Desktop local host / SSH lifecycle | `apps/desktop/src/main/host-controller.ts`, `ssh.ts` |
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 555675a7..4f27c475 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -10,7 +10,7 @@ iPhone conversation scrolling leaves dragging, deceleration, and bottom rubber-b
Do not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.
-Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The desktop app's `BotStore` (link handling in `apps/desktop/src/renderer/store/bot-sync.ts`) applies the same graces and 20-second wait. The TUI follows the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind its "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and its permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort in bands, the [lead bot](../features/lead-bot.md) (starred, never dragged) first, then pinned bots, then the rest; within a band, in the order the user dragged them into, then by recency ([bot order](../features/computer-order.md#bot-order)). On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Tapping a heading folds that computer's bots away (chevron; saved on the device). Long-press a heading to drag the computer with its bots up or down: while it is lifted every computer's bots fold into their headings, they unfold on release, and the order is saved on the device (`AccountStore.move`; VoiceOver: Move up / Move down). A bot moves only among its own computer's bots. The desktop app's sidebar has the same headings, folding and heading drag (a lifted copy follows the pointer, plus Alt+Up/Down). There are no connection banners. The compact desktop rail uses a computer icon for the same menu. Conversation headers show a small connection label; the desktop names the computer in its help text, the phones in the bot details' Settings (Workspace → Computer). Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers; a phone asks an account computer for access only when the user taps Ask for access, never on its own.
+Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. An action taken during a reconnect (back in the foreground, a new network, a drop still inside its grace) waits for the link, up to 20 seconds, instead of failing; while one waits, headers read `Connecting…` and the conversation's connection label shows a spinner. Calls that are safe to repeat (send, stop, approvals, pin, hide, mark as read, delete) are tried again when the link drops under them. Tapping while the header says Offline because the computer can't be reached starts a fresh connection attempt and waits for it, instead of failing until the backoff gets there; a computer the relay reports as off fails at once, since the relay says when it is back. A permission card shows a spinner on the chosen option, dims the others and takes no second answer until the computer has it. The desktop app's `BotStore` (link handling in `apps/desktop/src/renderer/store/bot-sync.ts`) applies the same graces and 20-second wait. The TUI follows the same rule over loopback: a command the host can't be reached for is retried for up to 20 seconds behind its "Reconnecting…" indicator (the `hello` probe that explains an unreachable host still answers at once), and its permission cards spin on the chosen option. The "Something went wrong" dialog is left for a computer that is off, a refused device, the computer's own answers, and reconnects that outlast the wait. Background work (cloud refresh, device registration) logs connection, busy-cloud and stale-token failures instead of showing them. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort in bands, the [lead bot](../features/lead-bot.md) (starred, never dragged) first, then pinned bots, then the rest; within a band, in the order the user dragged them into, then by recency ([bot order](../features/computer-order.md#bot-order)). Bots the user put in a section sit under a foldable section heading (name, count, and the unread total while folded; folded state saved on the device), with sections sorted by name after the lead and pinned bots and before bots without one (under a plain "Bots" label then). A bot's long-press menu has Move to section (not the lead's); a heading's has Rename section and Remove section; a move or rename the computer refuses is put back. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Tapping a heading folds that computer's bots away (chevron; saved on the device). Long-press a heading to drag the computer with its bots up or down: while it is lifted every computer's bots fold into their headings, they unfold on release, and the order is saved on the device (`AccountStore.move`; VoiceOver: Move up / Move down). A bot moves only among its own computer's bots, within its band, and an unpinned bot only inside its section (pinned bots ignore sections). The desktop app's sidebar has the same headings, folding and heading drag (a lifted copy follows the pointer, plus Alt+Up/Down), and the same section headings. There are no connection banners. The compact desktop rail uses a computer icon for the same menu. Conversation headers show a small connection label; the desktop names the computer in its help text, the phones in the bot details' Settings (Workspace → Computer). Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers; a phone asks an account computer for access only when the user taps Ask for access, never on its own.
Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Bots/ComputerFilterHeader.swift`, `Store/ComputerSelection.swift`, `Bots/BotRow.swift`; desktop: `apps/desktop/src/renderer/views/ChatWindow.tsx`, `ComputerFilterHeader.tsx`, `BotRow.tsx`.
diff --git a/docs/features/computer-order.md b/docs/features/computer-order.md
index 9c255f14..a2842e97 100644
--- a/docs/features/computer-order.md
+++ b/docs/features/computer-order.md
@@ -7,8 +7,8 @@ name without being merged. Resetting the host's data/keys makes a new identity:
its old offline entry may need removing. Signing in with Apple and Google shares
this state only when both reach the same Codync account.
-Desktop and iOS show one section per selected computer, or a flat list when only
-one is selected. Drag a section heading to reorder it. Desktop also supports
+Desktop and iOS show one section per selected computer, or no computer headings when
+only one is selected. Drag a section heading to reorder it. Desktop also supports
Alt+Up/Down on the heading; iOS exposes Move up/down accessibility actions.
Filtering, folding and ordering are device-local preferences. The iPhone and each
desktop installation keep their own order, even when signed in to the same account.
@@ -43,17 +43,38 @@ A computer's bots (and group chats) keep the order the user drags them into, on
device: the host stores it as each bot's `position` (`reorderBots`, `host/src/hub/order.rs`)
and syncs it like any bot change. Every client sorts in bands: the [lead bot](lead-bot.md)
first (it can't be dragged, and nothing drops above it), then pinned bots, then the rest;
-a bot moves only within its band. Until a computer's bots are first arranged, every
-position is 0 and they sort by recent activity; after that they stay put and a new bot
-appears at the top of its band. Hidden bots keep their position for when they return.
+a bot moves only within its band, and an unpinned bot also stays in its section (the lead and
+pinned rows show no sections, so pinned bots reorder among all pinned bots). Until a computer's
+bots are first arranged, every position is 0 and they sort by recent activity; after that they
+stay put and a new bot appears at the top of its band. Hidden bots keep their position for when
+they return.
+
+A bot or group chat can be in one section, a name the user picks (`section`, set with `updateBot`;
+`renameSection` renames, merges into another section's name, or removes one; `host/src/hub/sections.rs`).
+The host trims the name, treats an empty one as none, and refuses one over 40 characters or with a
+control character. The roster shows the lead and pinned rows first, then each section under its header
+sorted by name (the way the device's language sorts; the terminal UI sets case and accents aside but
+has no per-language rules, so Swedish "å" sorts as "a" there), then rows in no section (under a "Bots"
+label when there are sections); inside a section rows keep the order above. A section exists while
+a bot is in it. A bot's menu has Move to section and a section header's menu has Rename section and
+Remove section, offered only for a host at 2.32.0 or newer; the apps show the change at once and put
+it back when the host refuses it. The lead stays on top, outside sections, and its menus offer no
+Move to section. A
+pinned bot keeps its section and shows in it again once unpinned; hidden bots keep
+theirs. Each device folds sections for itself, by name: renaming or removing a folded section on
+this device takes its fold along (a merge folds the section it joins; an unfolded section changes
+nothing), while a rename made on another device arrives unfolded.
- **iPhone:** touch and hold a row, then drag it. The roster is a `List` with its styling
removed, so the system does the reordering: holding still opens the row's menu, and dragging
the lifted row moves it, also once the menu shows, unless the finger goes into the menu. Lifted,
the row is a rounded card: it fills while the system holds its drag item (`BotListView.lift`). A bot
- moves only among its own computer's bots: dropped above or below them, among another computer's,
- it goes first or last. The drop saves the order (`BotListView.moveLines`,
- `BotStore.reorder`). VoiceOver: Move up / Move down. SwiftUI's own drag and drop can't do this:
+ moves only among its own computer's bots with the same pin state and, unpinned, the same section:
+ dropped among others (another section, another computer's), it goes first or last of its own. The
+ drop saves the order (`BotListView.moveLines`, `BotStore.drop`). Section headings don't move.
+ VoiceOver: Move up / Move down. SwiftUI's own drag and drop can't do this:
with a context menu on the row, a drag never starts on iPhone.
- **Desktop:** drag a row, or Alt+Up/Down on the selected bot (macOS, Linux, Windows).
-- **Terminal UI:** `J` / `K` move the selected bot down / up.
+- **Terminal UI:** `J` / `K` move the selected bot down / up. `w` moves it to a section (empty takes
+ it out), `W` renames its section (empty removes it), `z` or a click on a section's label folds or
+ unfolds it (in the compact strip a click on a folded section unfolds it).
diff --git a/docs/features/groups-and-replies.md b/docs/features/groups-and-replies.md
index b6ab406b..d184d0d2 100644
--- a/docs/features/groups-and-replies.md
+++ b/docs/features/groups-and-replies.md
@@ -34,9 +34,10 @@ quotes itself.
|---|---|---|
| `send` | `botId, text, clientNonce, replyTo?` | `botId` is a bot or a group. `replyTo`: the id of a user message or final reply in that chat; anything else is refused. Works in the relay mailbox too. |
| `createBot` | `{kind:"group", name, description?, members}` | Returns the existing group when these exact bots already share one. |
-| `updateBot` | `{id, name?, members?, pinned?, hidden?}` | A group can't become a bot or the reverse. |
+| `updateBot` | `{id, name?, members?, pinned?, hidden?, section?}` | A group can't become a bot or the reverse. `section`: a name, or `null` for none. |
| `deleteBot` | `botId` | A group's bots stay. A deleted bot leaves its groups. |
| `reorderBots` | `ids` | The roster as the user dragged it, top first; groups count as rows. See [bot order](computer-order.md#bot-order). |
+| `renameSection` | `from, to` | Every row in section `from` moves to `to`, groups too; an existing name merges them, `null` removes the section. See [bot order](computer-order.md#bot-order). |
| `stop` | `botId` | For a group: ends its room turn and stops members working in it. |
| `react` | `entryId, emoji` | Toggles the user's reaction on a chat message (`data.reactions`, oldest first, at most 8). A reacted-to message never turns unread again. The bot isn't told, except in a group, where members see reactions on the room lines they're shown. Bots react themselves with the `chat` server's `react` ([bot reactions](chat-messages.md#bot-reactions)). |
| `respondPermission` | `entryId, optionId?` | Routed to `data.author`, so cards in a group reach the bot that asked. |
diff --git a/docs/features/lead-bot.md b/docs/features/lead-bot.md
index 2b85e004..f234abad 100644
--- a/docs/features/lead-bot.md
+++ b/docs/features/lead-bot.md
@@ -18,7 +18,7 @@ to be asked. Everything about it lives in the host (`host/src/chat/lead.rs`); th
shows a gold `star.fill` badge at the avatar’s bottom-right, with unread/approval badges at the top-right.
The larger badge in details opens the lead agent role explanation. TUI shows a gold `★` below the avatar;
click it or press `I` on the lead to read the same explanation, scroll with arrow keys, and close with `Esc`. Its menus have no
- Pin, Hide or Delete (TUI: `p` and `x` say why).
+ Pin, Move to section, Hide or Delete, and it shows in no roster section (TUI: `p`, `w` and `x` say why).
## Initiative
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index 46f52072..2ddeb629 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -16,7 +16,7 @@ emulator against a real host; device acceptance is listed separately.
| --- | --- | --- |
| Welcome/pairing | Ported: welcome crew and chat glimpse, Install (Mac/Linux) and Scan pages with the camera on the page, paste link, Tailscale note, sign-in | Physical optical scan, camera permission denial |
| Accounts/access | Ported: account sheet and switcher, Computer management (connection status, badge color, Revoke this phone's access, older copies removed from the account), account computer access with its code, access banner, `codync-dev://computers` and `codync-dev://plugins` | Provider browser round trip on a device; Revoke and older copies against a signed-in account (covered by cloud request tests only); one computer per phone ([multiple computers are future work](../architecture/overview.md)) |
-| Roster | Ported: rows, menus, pin/hide/delete, New session (bots only), groups, drag to reorder (host-synced order) and TalkBack Move up/down, computer header, pull to refresh (also in Computer management) | Multiple computers |
+| Roster | Ported: rows, menus, pin/hide/delete, New session (bots only), groups, sections (move to, fold per device, rename, remove), drag to reorder (host-synced order) and TalkBack Move up/down, computer header, pull to refresh (also in Computer management) | Multiple computers |
| Conversation | Ported: bubbles, Markdown/code, permissions, reactions, quote replies, Full conversation, bot-to-bot exchange lines and their conversation, routine notices that open their routine, files a bot shares (verified download, then the share sheet), sent images full size, pull down to reconnect, jump to latest, read receipts for every conversation on screen | Physical keyboard and TalkBack |
| Composer | Ported: files/photos/paste (groups too, image thumbnails, Paste only when the clipboard holds files), `/` commands (Fast mode, skills listed fresh on `/`), @mentions in groups, call/send/stop/interrupt button | Dictation ([voice call](../features/voice-call.md)): the mic, its recording pill, the engine menu beside it (On device, or OpenAI / Gemini transcribed on the user's key with *Transcribing…*) and the *Couldn't dictate* dialog |
| Bot and group editors | Ported: avatar, profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills (with their details); the bot details sheet (`BotDetailsView`, from the chat's title, a routine notice or Add a fallback): Details (instructions, agent, Use the computer, Routines), Library, Settings (Codync's skill and connector switches), saved as you edit, Create template; a group's title opens its editor. An agent's own skills, connectors, rules and plugins are on its sheet in Extensions, under Sign in | The details' Memory tab (see Memory) |
diff --git a/docs/plans/roster-sections.md b/docs/plans/roster-sections.md
new file mode 100644
index 00000000..5b5580bf
--- /dev/null
+++ b/docs/plans/roster-sections.md
@@ -0,0 +1,95 @@
+# Roster sections
+
+User-made sections in the bot roster, like Slack's custom sidebar sections: "Work", "Personal",
+each folding open and shut. Every client (desktop, iPhone, Android, terminal) gets them in the
+same change. "Folder" is not used for this anywhere: it already means a bot's project folder
+(`folder`, "Choose project folder…").
+
+## What the user sees
+
+```
+ ★ Assistant the lead bot: always first, outside sections
+ 📌 Reviewer pinned rows next, also outside sections
+▾ Personal (2)
+ 🤖 Notes Bot
+ 🤖 Mail Bot
+▸ Work (3) ●4 folded: the unread count of everything inside
+Bots a plain label (no fold, count or menu), only when there are sections
+ 🤖 Scratch Bot rows without a section
+```
+
+- A bot or group chat is in at most one section, or none.
+- **Order:** the lead bot, then pinned rows, then sections sorted by name (the way the device's
+ language sorts, so "İş" sorts as Turkish expects; the terminal sets case and accents aside), then
+ rows without a section, under a "Bots" label when there are sections. Inside a section rows keep
+ the roster order (position, then recent activity).
+- **Row menu:** "Move to section ▸" lists the existing sections, "New section…" and "Remove from
+ section"; the lead bot has none. **Header menu:** "Rename section…" and "Remove section" (its
+ bots stay, without a section).
+- A section exists while a bot is in it: moving its last bot out removes the header.
+- A pinned bot keeps its section and shows in it again once unpinned.
+- Tapping a header folds or unfolds it (animated, `Motion`). Folded state is per device, not
+ synced; renaming or removing a folded section on this device takes its fold along.
+- Dragging moves a bot only within its band: the lead can't be dragged and nothing drops above it;
+ pinned bots reorder among all pinned bots (pinned rows show no sections); an unpinned bot also
+ stays in its section.
+- Moves and renames show at once; one the host refuses is put back.
+- Hidden bots keep their section.
+
+Not in this change: dropping a bot onto a section by drag, reordering sections by drag, nested
+sections.
+
+## Host
+
+- `BotConfig` (`host/src/store/model.rs`) gains `section: Option<String>`
+ (`#[serde(default, skip_serializing_if = "Option::is_none")]`). The config is stored as one JSON
+ blob, so there is no schema migration; `bot_json` carries it in `bot` events.
+- `updateBot {id, section}`: a string sets it, `null` clears it. `Hub::update_bot` merges the patch,
+ so clients that don't send `section` (older apps) leave it alone. The name is trimmed; an empty
+ result clears the section; over 40 characters or containing a control character is refused.
+ Validation runs for groups too (today `validate()` returns early for them).
+- New method `renameSection {from, to}` (`host/src/api/bots.rs`, hub logic
+ in `hub/sections.rs`): moves every bot of this computer in `from` to `to` under one
+ `emit_lock`, then emits each changed bot. `to: null` removes the section. Renaming onto an
+ existing name merges the two. `to` is validated like `updateBot`'s `section`.
+- Bots can't set sections: `section` stays out of `chat/manage.rs` `FIELDS`.
+- Analytics: `bot_updated` lists `section` among changed fields; `renameSection` gets an event
+ (`analytics/observe.rs`, `docs/reference/analytics-events.md`). Names are never sent.
+- Compatibility: additive (a new optional field and a new method), so `MIN_APP` / `MIN_HOST` stay.
+ Clients show the section controls only when the host's version (from `hello`) is at least
+ 2.32.0, the release that ships this.
+
+## Clients
+
+Each client gets one pure function that turns the sorted roster into lines (the lead and pinned
+rows, section headers with their rows, the "Bots" label, rows without a section) and is
+unit-tested. The drag guards compare the band (lead, pinned, the rest), and for unpinned bots the
+section too.
+
+| Client | Model | Header | Menus | Name entry | Folded state |
+|---|---|---|---|---|---|
+| Desktop | `shared/models.ts` `Bot.section`, `normalizeBot` | modeled on `ComputerRosterSection` | `DesktopActionMenu` (`PanelMenus.tsx`), items from `views/section-menus.ts` (Move to section as submenu rows) | `Dialog` | `prefs.ts`, `collapsedRosterSections` |
+| iPhone | `Bot.swift` `Bot.section: String?`; `HostClient.setSection` sends `null` to clear | modeled on `ComputerSection` | system `contextMenu` submenu (`.contextActions`) | `.codyncDialog` | `@AppStorage("collapsedRosterSections")` |
+| Android | `HostClient.kt` `Bot.section`; `BotDraft.template()` leaves it out | modeled on iOS `ComputerSection` (`RosterSectionViews.kt`) | `contextActions` | `CodyncDialog` | `SharedPreferences` |
+| Terminal | `tui/app/bot.rs` `Bot.section` | labels beside `PINNED` / `BOTS` in `view/roster.rs` | keys, listed in `view/help.rs` | `section_fields` sheet (`manage/fields.rs`) | in memory |
+
+Desktop drag guards: `makeRoom` (`BotRoster.tsx`) and `moveBot` (`store/computer-roster.ts`), both
+through `sameRosterGroup` (`lib/roster-sections.ts`); iPhone `BotStore.move` and `BotStore.drop`; Android `moved()`; terminal `reorder_bot`. The desktop demo host
+(`demo/fake-host.ts`) handles `renameSection`.
+
+## Tests
+
+- Host: set and clear; trimming, length and control-character refusal; groups validated;
+ `renameSection` rename, merge and remove; re-record `tests/fixtures/wire-shape.json`
+ (`CODYNC_UPDATE_WIRE_SHAPE=1 cargo test --test e2e wire_shape`).
+- Desktop: the grouping function and the drag guard (`src/renderer/lib/*.test.ts`).
+- iPhone: `RosterOrderTests`. Android: `RosterMoveTest` plus grouping. Terminal: `navigate.rs`.
+- End to end on each client: create a section, move bots in, fold it with an unread message
+ inside, rename it onto another section's name, remove it.
+
+## Release
+
+This change bumps every version file to 2.32.0, the first host with sections, and clients gate the
+section controls on a 2.32.0 host. Its What's New bullets are in the `## 2.32.0` sections of
+`apps/ios/WhatsNew.md` and `apps/android/WhatsNew.md`. [Bot order](../features/computer-order.md#bot-order)
+and the scope table in [remote relay](../reference/remote-relay.md) cover `renameSection`.
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index 99ae7c84..ceb8d082 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -64,8 +64,9 @@ host answers and sends it once the host is up.
|---|---|---|---|
| `screen_viewed` | host `track` (desktop, TUI), iOS, Android | A screen, sheet or tab is shown | `screen` (see *Screens*) |
| `bot_created` | host | `createBot` | `kind` (`bot`/`group`), `agent`, `model` or `members` (count) |
-| `bot_updated` | host | `updateBot` | `fields`: the settings that changed, as the bot config's own camelCase keys (`model`, `permission`, `pinned`, `modelOptions`, `fastMode`, …), never their values |
+| `bot_updated` | host | `updateBot` | `fields`: the settings that changed, as the bot config's own camelCase keys (`model`, `permission`, `pinned`, `section`, `modelOptions`, `fastMode`, …), never their values |
| `bots_reordered` | host | `reorderBots` | — |
+| `section_renamed` | host | `renameSection` | `removed`: whether it removed the section (`to` empty or `null`); never the names |
| `bot_deleted` | host | `deleteBot` | — |
| `message_sent` | host | `send` (a resend counts once) | `kind`, `agent`, `reply` (whether it quotes a message), `attachments` (count) |
| `turn_stopped` | host | `stop` | — |
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 5a3ecd43..7e3259d1 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -315,7 +315,7 @@ blob = epk(32) ‖ sig(64) ‖ ct
| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `cloudStatus`, `setCloud`, `setCloudUrl` | `Caller::Local`(loopback + token) |
| 配對中 | `pair` | 只在 pairing 狀態的 channel;配對完成後不可再呼叫 |
| screen scope | `screenPrepare`, `screenOffer`, `screenClose`, `screenTakeover` | Local,或 scopes 含 `screen` 的裝置 |
-| control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |
+| control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `renameSection`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |
v1 發出的 grant 一律 `["control","screen"]`。
diff --git a/host/Cargo.lock b/host/Cargo.lock
index d9072010..5ef2dfee 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -732,6 +732,7 @@ dependencies = [
"hkdf 0.13.0",
"hmac 0.13.0",
"iana-time-zone",
+ "icu_normalizer",
"if-addrs",
"keyring",
"libc",
diff --git a/host/Cargo.toml b/host/Cargo.toml
index e3cdcdd0..5033e91f 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -48,6 +48,8 @@ serde = { version = "1.0.229", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["preserve_order"] }
sha2 = "0.11.0"
hmac = "0.13.0"
+# Already built for reqwest's URL handling; the TUI folds accents out of section names to sort them.
+icu_normalizer = { version = "2.3.0", default-features = false, features = ["compiled_data"] }
shlex = "2.0.1"
tar = "0.4.46"
tokio = { version = "1.53.1", features = ["full"] }
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 22c29b35..9735b450 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -61,6 +61,7 @@ pub enum Event {
BotCreated,
BotUpdated,
BotsReordered,
+ SectionRenamed,
BotDeleted,
MessageSent,
TurnStopped,
@@ -126,6 +127,7 @@ impl Event {
Self::BotCreated => "bot_created",
Self::BotUpdated => "bot_updated",
Self::BotsReordered => "bots_reordered",
+ Self::SectionRenamed => "section_renamed",
Self::BotDeleted => "bot_deleted",
Self::MessageSent => "message_sent",
Self::TurnStopped => "turn_stopped",
diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rs
index 3ad3976a..e7d3f110 100644
--- a/host/src/analytics/observe.rs
+++ b/host/src/analytics/observe.rs
@@ -83,6 +83,11 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Eve
}
"updateBot" => Event::BotUpdated,
"reorderBots" => Event::BotsReordered,
+ "renameSection" => {
+ // Whether it took the section away; the names never leave the computer.
+ p.insert("removed".into(), b["to"].as_str().is_none_or(|t| t.trim().is_empty()).into());
+ Event::SectionRenamed
+ }
"deleteBot" => Event::BotDeleted,
"send" => {
let reply = b["replyTo"].as_str().is_some_and(|t| !t.is_empty());
@@ -261,263 +266,4 @@ fn choice(card: Option<&Value>, option: &Value) -> &'static str {
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::store::{Device, DeviceSource, Store};
- use serde_json::json;
-
- fn temp_hub() -> (std::sync::Arc<Hub>, std::path::PathBuf) {
- let dir = std::env::temp_dir().join(format!("codync-analytics-{}", uuid::Uuid::new_v4()));
- std::fs::create_dir_all(&dir).unwrap();
- let store = Store::open(std::path::Path::new(":memory:")).unwrap();
- let identity = crate::remote::identity::Identity::load_or_create(&dir).unwrap();
- (Hub::new(store, "h".into(), identity, "t".into(), 0), dir)
- }
-
- fn props(method: &str, b: &Value) -> Option<(Event, Value)> {
- observe(&Caller::Local, method, b).map(|(e, p)| (e, Value::Object(p)))
- }
-
- #[test]
- fn observed_events_carry_no_content() {
- let b = json!({"botId": "b1", "text": "secret plan", "replyTo": "e1", "attachments": ["u1", "u2"]});
- let (event, p) = props("send", &b).expect("send is tracked");
- assert_eq!(event, Event::MessageSent);
- assert_eq!(p, json!({"reply": true, "attachments": 2, "client": "local"}));
- assert!(!p.to_string().contains("secret"));
-
- let custom = json!({"name": "mine", "command": "/Users/me/bin/server"});
- let (_, p) = props("installConnector", &custom).expect("tracked");
- assert_eq!(p["connector"], "custom");
- assert!(props("history", &json!({})).is_none());
- assert!(props("memory", &json!({"botId": "b1"})).is_none(), "reading memory is not an edit");
- assert!(props("memoryFile", &json!({"name": "notes.md"})).is_none());
- }
-
- #[test]
- fn handoff_and_credentials_name_a_fixed_action() {
- assert_eq!(
- props("keepConversation", &json!({})),
- Some((Event::HandoffAnswered, json!({"action": "keep", "client": "local"})))
- );
- assert_eq!(props("editHandoff", &json!({"text": "x"})).map(|(_, p)| p["action"].clone()), Some(json!("edit")));
-
- let login = json!({"site": "example.com", "username": "me", "password": "hunter2"});
- assert_eq!(
- props("credentialSaveLogin", &login),
- Some((Event::CredentialSaved, json!({"kind": "login", "client": "local"})))
- );
- assert_eq!(
- props("setVoiceKey", &json!({"provider": "openai", "key": "sk-1"})).map(|(_, p)| p["kind"].clone()),
- Some(json!("voice"))
- );
- assert_eq!(
- props("setAgentEnv", &json!({"backend": "codex", "vars": {"K": "v"}})).map(|(_, p)| p["kind"].clone()),
- Some(json!("agent_env"))
- );
- assert!(props("setComposioKey", &json!({"key": " "})).is_none(), "an empty key removes it");
- assert!(props("credentialSetOnePassword", &json!({"token": ""})).is_none());
- }
-
- #[test]
- fn settings_routines_screen_and_devices() {
- let setting = |m: &str, b: Value| props(m, &b).map(|(e, p)| (e, p["setting"].clone(), p["on"].clone()));
- assert_eq!(
- setting("setCloud", json!({"enabled": true})),
- Some((Event::SettingChanged, json!("remote_access"), json!(true)))
- );
- assert_eq!(setting("setApproval", json!({"approval": "auto"})).map(|s| s.2), Some(json!(true)));
- assert_eq!(setting("setApproval", json!({"approval": "code"})).map(|s| s.2), Some(json!(false)));
- assert_eq!(
- setting("setHostAutomaticUpdates", json!({"enabled": false})).map(|s| s.1),
- Some(json!("automatic_updates"))
- );
- assert_eq!(setting("setScreenEnabled", json!({"enabled": true})).map(|s| s.1), Some(json!("remote_screen")));
- assert_eq!(
- setting("setAssistants", json!({"enabled": true})),
- Some((Event::SettingChanged, json!("cloud_assistants"), json!(true)))
- );
- assert_eq!(
- props("networkJoin", &json!({"invite": "codync-network:…", "name": "laptop"})),
- Some((Event::NetworkJoined, json!({"via": "invite", "client": "local"})))
- );
- let saved = props("setCloudUrl", &json!({"url": "https://relay.example.com"}));
- assert_eq!(
- saved.as_ref().map(|(e, p)| (*e, p["setting"].clone(), p["on"].clone())),
- Some((Event::SettingChanged, json!("remote_access_url"), json!(true)))
- );
- assert!(!saved.unwrap().1.to_string().contains("relay.example.com"), "the URL is not a property");
- assert_eq!(setting("setCloudUrl", json!({"url": " "})).map(|s| s.2), Some(json!(false)));
-
- assert_eq!(
- props("setRoutineEnabled", &json!({"botId": "b", "id": "r", "enabled": false})),
- Some((Event::RoutineToggled, json!({"enabled": false, "client": "local"})))
- );
- assert_eq!(props("screenTakeover", &json!({"on": true})).map(|(e, _)| e), Some(Event::ScreenTakenOver));
- assert!(props("screenTakeover", &json!({"on": false})).is_none(), "handing it back");
- assert_eq!(props("pairing", &json!({})), Some((Event::PairingCodeCreated, json!({"client": "local"}))));
- assert_eq!(
- props("decideAccessRequest", &json!({"requestId": "req_1", "approve": false})).map(|(e, _)| e),
- Some(Event::AccessRequestDenied)
- );
- assert!(
- props("decideAccessRequest", &json!({"requestId": "req_1", "approve": true})).is_none(),
- "approval is device_paired"
- );
- assert_eq!(
- props("revokeDevice", &json!({"key": "k"})),
- Some((Event::DeviceRevoked, json!({"client": "local"})))
- );
- assert_eq!(
- props("installHostUpdate", &json!({"force": true})).map(|(e, _)| e),
- Some(Event::HostUpdateInstalled)
- );
- }
-
- #[test]
- fn connectors_skills_and_agents() {
- assert_eq!(
- props("removeConnector", &json!({"id": "github"})),
- Some((Event::ConnectorRemoved, json!({"client": "local"})))
- );
- assert_eq!(props("removeSkill", &json!({"id": "s"})).map(|(e, _)| e), Some(Event::SkillRemoved));
- let written =
- |arguments: Value| props("chatCall", &json!({"botId": "b", "name": "save_skill", "arguments": arguments}));
- assert_eq!(
- written(json!({"name": "Deploy", "instructions": "never sent"})),
- Some((Event::SkillWritten, json!({"change": "new", "client": "local"})))
- );
- assert_eq!(written(json!({"id": "deploy"})).map(|(_, p)| p["change"].clone()), Some(json!("update")));
- assert_eq!(props("chatCall", &json!({"name": "send_message"})), None, "other chat tools aren't events");
- let published = |arguments: Value| {
- observe(
- &Caller::Local,
- "chatCall",
- &json!({"botId": "b", "name": "publish_artifact", "arguments": arguments}),
- )
- .expect("a publish is tracked")
- };
- let (event, p) = published(json!({"path": "/secret/report.html", "title": "Salaries"}));
- let p = answered(event, p, &json!({"published": true})).expect("published");
- assert_eq!(
- (event, Value::Object(p)),
- (Event::ArtifactPublished, json!({"change": "new", "card": true, "client": "local"}))
- );
- let (event, p) = published(json!({"path": "r.html", "artifact": "a1"}));
- let p = answered(event, p, &json!({"published": true, "card": "not posted"})).expect("published");
- assert_eq!(
- (p["change"].clone(), p["card"].clone()),
- (json!("update"), json!(false)),
- "a routine's has no card"
- );
- assert_eq!(props("connectorSignIn", &json!({"id": "c"})).map(|(e, _)| e), Some(Event::ConnectorSigninStarted));
- let setup = props("agentSetup", &json!({"backend": "claude-acp", "step": "install"}));
- assert_eq!(setup, Some((Event::AgentSetupStarted, json!({"agent": "claude-acp", "client": "local"}))));
- assert_eq!(props("agentSetup", &json!({"step": "node"})).map(|(_, p)| p), Some(json!({"client": "local"})));
- let signed = props("agentAuthenticate", &json!({"backend": "codex", "method": "chatgpt"}));
- assert_eq!(signed, Some((Event::AgentSignedIn, json!({"agent": "codex", "client": "local"}))));
-
- let (event, p) = observe(&Caller::Local, "importConnectors", &json!({"config": "{\"secret\": 1}"})).unwrap();
- let p = answered(event, p, &json!({"items": [{"id": "a"}, {"id": "b"}]})).expect("an import");
- assert_eq!(Value::Object(p), json!({"count": 2, "client": "local"}));
-
- let (event, p) = observe(&Caller::Local, "composioConnection", &json!({"id": "ca_1"})).unwrap();
- assert!(answered(event, p.clone(), &json!({"status": "initiated"})).is_none(), "still signing in");
- let p = answered(event, p, &json!({"status": "active", "toolkit": "gmail"})).expect("connected");
- assert_eq!(
- (event, Value::Object(p)),
- (Event::ConnectorInstalled, json!({"connector": "composio", "client": "local"}))
- );
- }
-
- #[test]
- fn a_bot_edit_names_the_settings_it_changes() {
- let stored: BotConfig = serde_json::from_value(
- json!({"id": "b1", "name": "Ada", "backend": "codex", "cwd": "/tmp", "model": "gpt-5"}),
- )
- .unwrap();
- let patch = json!({"id": "b1", "name": "Ada", "model": "gpt-6", "pinned": true, "harnessMemory": null,
- "sharedMemory": true, "secret": "x", "createdAt": 5});
- assert_eq!(changed_fields(&stored, &patch), ["model", "pinned", "sharedMemory"]);
- assert_eq!(changed_fields(&stored, &json!({"id": "b1", "name": "Ada"})), Vec::<String>::new());
-
- // Clients send `""` for the bot's own workspace, which the store keeps as its path.
- let own = crate::agent::workspace::path("b1").to_string_lossy().into_owned();
- let stored: BotConfig =
- serde_json::from_value(json!({"id": "b1", "name": "Ada", "backend": "codex", "cwd": own})).unwrap();
- assert_eq!(changed_fields(&stored, &json!({"id": "b1", "cwd": "", "fastMode": true})), ["fastMode"]);
- assert_eq!(changed_fields(&stored, &json!({"id": "b1", "cwd": "/tmp"})), ["cwd"]);
- }
-
- #[test]
- fn a_permission_answer_names_the_kind_picked() {
- let card = json!({"title": "rm -rf", "options": [
- {"optionId": "a", "name": "Allow", "kind": "allow_once"},
- {"optionId": "r", "name": "Always reject", "kind": "reject_always"},
- {"optionId": "x", "name": "Odd", "kind": "something_new"}]});
- assert_eq!(choice(Some(&card), &json!("a")), "allow_once");
- assert_eq!(choice(Some(&card), &json!("r")), "reject_always");
- assert_eq!(choice(Some(&card), &json!("x")), "other");
- assert_eq!(choice(Some(&card), &Value::Null), "other");
- assert_eq!(choice(None, &json!("a")), "other");
- }
-
- #[tokio::test]
- async fn a_resent_message_counts_once_and_names_its_agent() {
- let (hub, dir) = temp_hub();
- let cfg = serde_json::from_value(json!({"id": "b1", "name": "b", "backend": "codex", "cwd": "/tmp"})).unwrap();
- hub.store.save_bot(&cfg).unwrap();
- let send = json!({"botId": "b1", "text": "hi", "clientNonce": "n1"});
-
- let (_, p) = observe_call(&hub, &Caller::Local, "send", &send).expect("a new message is tracked");
- assert_eq!((p["agent"].as_str(), p["kind"].as_str()), (Some("codex"), Some("bot")));
- let lane = crate::store::Lane::main("b1");
- hub.store
- .insert_entry(&lane, crate::store::EntryKind::User, 1, &json!({"text": "hi", "clientNonce": "n1"}))
- .unwrap();
- assert!(observe_call(&hub, &Caller::Local, "send", &send).is_none(), "a replay is the same message");
- std::fs::remove_dir_all(&dir).unwrap();
- }
-
- #[tokio::test]
- async fn store_lookups_add_fields_choice_and_platform() {
- let (hub, dir) = temp_hub();
- let cfg = serde_json::from_value(json!({"id": "b1", "name": "b", "backend": "codex", "cwd": "/tmp"})).unwrap();
- hub.store.save_bot(&cfg).unwrap();
- let (_, p) =
- observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "permission": "ask"})).unwrap();
- assert_eq!(p["fields"], json!(["permission"]));
-
- let card =
- json!({"status": "pending", "options": [{"optionId": "o1", "name": "Allow", "kind": "allow_always"}]});
- let e = hub
- .store
- .insert_entry(&crate::store::Lane::main("b1"), crate::store::EntryKind::Permission, 1, &card)
- .unwrap();
- let answer = json!({"entryId": e.id, "optionId": "o1"});
-
- let phone = Caller::Device { key: "k1".into(), scopes: vec![] };
- hub.store
- .put_device(&Device {
- key: "k1".into(),
- name: "Kevin's phone".into(),
- platform: "android".into(),
- source: DeviceSource::Local,
- grant_id: None,
- scopes: vec![],
- lease_until: None,
- created_at: 0,
- last_seen_at: None,
- })
- .unwrap();
- let (event, p) = observe_call(&hub, &phone, "respondPermission", &answer).unwrap();
- assert_eq!(
- (event, Value::Object(p)),
- (Event::PermissionAnswered, json!({"choice": "allow_always", "client": "remote", "platform": "android"}))
- );
- let stranger = Caller::Device { key: "gone".into(), scopes: vec![] };
- let (_, p) = observe_call(&hub, &stranger, "stop", &json!({"botId": "b1"})).unwrap();
- assert_eq!(p["platform"], "other");
- std::fs::remove_dir_all(&dir).unwrap();
- }
-}
+mod tests;
diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rs
new file mode 100644
index 00000000..0d0e714e
--- /dev/null
+++ b/host/src/analytics/observe/tests.rs
@@ -0,0 +1,256 @@
+use super::*;
+use crate::store::{Device, DeviceSource, Store};
+use serde_json::json;
+
+fn temp_hub() -> (std::sync::Arc<Hub>, std::path::PathBuf) {
+ let dir = std::env::temp_dir().join(format!("codync-analytics-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let identity = crate::remote::identity::Identity::load_or_create(&dir).unwrap();
+ (Hub::new(store, "h".into(), identity, "t".into(), 0), dir)
+}
+
+fn props(method: &str, b: &Value) -> Option<(Event, Value)> {
+ observe(&Caller::Local, method, b).map(|(e, p)| (e, Value::Object(p)))
+}
+
+#[test]
+fn observed_events_carry_no_content() {
+ let b = json!({"botId": "b1", "text": "secret plan", "replyTo": "e1", "attachments": ["u1", "u2"]});
+ let (event, p) = props("send", &b).expect("send is tracked");
+ assert_eq!(event, Event::MessageSent);
+ assert_eq!(p, json!({"reply": true, "attachments": 2, "client": "local"}));
+ assert!(!p.to_string().contains("secret"));
+
+ let custom = json!({"name": "mine", "command": "/Users/me/bin/server"});
+ let (_, p) = props("installConnector", &custom).expect("tracked");
+ assert_eq!(p["connector"], "custom");
+ assert!(props("history", &json!({})).is_none());
+ assert!(props("memory", &json!({"botId": "b1"})).is_none(), "reading memory is not an edit");
+ assert!(props("memoryFile", &json!({"name": "notes.md"})).is_none());
+}
+
+#[test]
+fn handoff_and_credentials_name_a_fixed_action() {
+ assert_eq!(
+ props("keepConversation", &json!({})),
+ Some((Event::HandoffAnswered, json!({"action": "keep", "client": "local"})))
+ );
+ assert_eq!(props("editHandoff", &json!({"text": "x"})).map(|(_, p)| p["action"].clone()), Some(json!("edit")));
+
+ let login = json!({"site": "example.com", "username": "me", "password": "hunter2"});
+ assert_eq!(
+ props("credentialSaveLogin", &login),
+ Some((Event::CredentialSaved, json!({"kind": "login", "client": "local"})))
+ );
+ assert_eq!(
+ props("setVoiceKey", &json!({"provider": "openai", "key": "sk-1"})).map(|(_, p)| p["kind"].clone()),
+ Some(json!("voice"))
+ );
+ assert_eq!(
+ props("setAgentEnv", &json!({"backend": "codex", "vars": {"K": "v"}})).map(|(_, p)| p["kind"].clone()),
+ Some(json!("agent_env"))
+ );
+ assert!(props("setComposioKey", &json!({"key": " "})).is_none(), "an empty key removes it");
+ assert!(props("credentialSetOnePassword", &json!({"token": ""})).is_none());
+}
+
+#[test]
+fn settings_routines_screen_and_devices() {
+ let setting = |m: &str, b: Value| props(m, &b).map(|(e, p)| (e, p["setting"].clone(), p["on"].clone()));
+ assert_eq!(
+ setting("setCloud", json!({"enabled": true})),
+ Some((Event::SettingChanged, json!("remote_access"), json!(true)))
+ );
+ assert_eq!(setting("setApproval", json!({"approval": "auto"})).map(|s| s.2), Some(json!(true)));
+ assert_eq!(setting("setApproval", json!({"approval": "code"})).map(|s| s.2), Some(json!(false)));
+ assert_eq!(
+ setting("setHostAutomaticUpdates", json!({"enabled": false})).map(|s| s.1),
+ Some(json!("automatic_updates"))
+ );
+ assert_eq!(setting("setScreenEnabled", json!({"enabled": true})).map(|s| s.1), Some(json!("remote_screen")));
+ assert_eq!(
+ setting("setAssistants", json!({"enabled": true})),
+ Some((Event::SettingChanged, json!("cloud_assistants"), json!(true)))
+ );
+ assert_eq!(
+ props("networkJoin", &json!({"invite": "codync-network:…", "name": "laptop"})),
+ Some((Event::NetworkJoined, json!({"via": "invite", "client": "local"})))
+ );
+ let saved = props("setCloudUrl", &json!({"url": "https://relay.example.com"}));
+ assert_eq!(
+ saved.as_ref().map(|(e, p)| (*e, p["setting"].clone(), p["on"].clone())),
+ Some((Event::SettingChanged, json!("remote_access_url"), json!(true)))
+ );
+ assert!(!saved.unwrap().1.to_string().contains("relay.example.com"), "the URL is not a property");
+ assert_eq!(setting("setCloudUrl", json!({"url": " "})).map(|s| s.2), Some(json!(false)));
+
+ assert_eq!(
+ props("setRoutineEnabled", &json!({"botId": "b", "id": "r", "enabled": false})),
+ Some((Event::RoutineToggled, json!({"enabled": false, "client": "local"})))
+ );
+ assert_eq!(props("screenTakeover", &json!({"on": true})).map(|(e, _)| e), Some(Event::ScreenTakenOver));
+ assert!(props("screenTakeover", &json!({"on": false})).is_none(), "handing it back");
+ assert_eq!(props("pairing", &json!({})), Some((Event::PairingCodeCreated, json!({"client": "local"}))));
+ assert_eq!(
+ props("decideAccessRequest", &json!({"requestId": "req_1", "approve": false})).map(|(e, _)| e),
+ Some(Event::AccessRequestDenied)
+ );
+ assert!(
+ props("decideAccessRequest", &json!({"requestId": "req_1", "approve": true})).is_none(),
+ "approval is device_paired"
+ );
+ assert_eq!(props("revokeDevice", &json!({"key": "k"})), Some((Event::DeviceRevoked, json!({"client": "local"}))));
+ assert_eq!(props("installHostUpdate", &json!({"force": true})).map(|(e, _)| e), Some(Event::HostUpdateInstalled));
+}
+
+#[test]
+fn connectors_skills_and_agents() {
+ assert_eq!(
+ props("removeConnector", &json!({"id": "github"})),
+ Some((Event::ConnectorRemoved, json!({"client": "local"})))
+ );
+ assert_eq!(props("removeSkill", &json!({"id": "s"})).map(|(e, _)| e), Some(Event::SkillRemoved));
+ let written =
+ |arguments: Value| props("chatCall", &json!({"botId": "b", "name": "save_skill", "arguments": arguments}));
+ assert_eq!(
+ written(json!({"name": "Deploy", "instructions": "never sent"})),
+ Some((Event::SkillWritten, json!({"change": "new", "client": "local"})))
+ );
+ assert_eq!(written(json!({"id": "deploy"})).map(|(_, p)| p["change"].clone()), Some(json!("update")));
+ assert_eq!(props("chatCall", &json!({"name": "send_message"})), None, "other chat tools aren't events");
+ let published = |arguments: Value| {
+ observe(&Caller::Local, "chatCall", &json!({"botId": "b", "name": "publish_artifact", "arguments": arguments}))
+ .expect("a publish is tracked")
+ };
+ let (event, p) = published(json!({"path": "/secret/report.html", "title": "Salaries"}));
+ let p = answered(event, p, &json!({"published": true})).expect("published");
+ assert_eq!(
+ (event, Value::Object(p)),
+ (Event::ArtifactPublished, json!({"change": "new", "card": true, "client": "local"}))
+ );
+ let (event, p) = published(json!({"path": "r.html", "artifact": "a1"}));
+ let p = answered(event, p, &json!({"published": true, "card": "not posted"})).expect("published");
+ assert_eq!((p["change"].clone(), p["card"].clone()), (json!("update"), json!(false)), "a routine's has no card");
+ assert_eq!(props("connectorSignIn", &json!({"id": "c"})).map(|(e, _)| e), Some(Event::ConnectorSigninStarted));
+ let setup = props("agentSetup", &json!({"backend": "claude-acp", "step": "install"}));
+ assert_eq!(setup, Some((Event::AgentSetupStarted, json!({"agent": "claude-acp", "client": "local"}))));
+ assert_eq!(props("agentSetup", &json!({"step": "node"})).map(|(_, p)| p), Some(json!({"client": "local"})));
+ let signed = props("agentAuthenticate", &json!({"backend": "codex", "method": "chatgpt"}));
+ assert_eq!(signed, Some((Event::AgentSignedIn, json!({"agent": "codex", "client": "local"}))));
+
+ let (event, p) = observe(&Caller::Local, "importConnectors", &json!({"config": "{\"secret\": 1}"})).unwrap();
+ let p = answered(event, p, &json!({"items": [{"id": "a"}, {"id": "b"}]})).expect("an import");
+ assert_eq!(Value::Object(p), json!({"count": 2, "client": "local"}));
+
+ let (event, p) = observe(&Caller::Local, "composioConnection", &json!({"id": "ca_1"})).unwrap();
+ assert!(answered(event, p.clone(), &json!({"status": "initiated"})).is_none(), "still signing in");
+ let p = answered(event, p, &json!({"status": "active", "toolkit": "gmail"})).expect("connected");
+ assert_eq!(
+ (event, Value::Object(p)),
+ (Event::ConnectorInstalled, json!({"connector": "composio", "client": "local"}))
+ );
+}
+
+#[test]
+fn a_bot_edit_names_the_settings_it_changes() {
+ let stored: BotConfig =
+ serde_json::from_value(json!({"id": "b1", "name": "Ada", "backend": "codex", "cwd": "/tmp", "model": "gpt-5"}))
+ .unwrap();
+ let patch = json!({"id": "b1", "name": "Ada", "model": "gpt-6", "pinned": true, "harnessMemory": null,
+ "sharedMemory": true, "secret": "x", "createdAt": 5});
+ assert_eq!(changed_fields(&stored, &patch), ["model", "pinned", "sharedMemory"]);
+ assert_eq!(changed_fields(&stored, &json!({"id": "b1", "name": "Ada"})), Vec::<String>::new());
+
+ // Clients send `""` for the bot's own workspace, which the store keeps as its path.
+ let own = crate::agent::workspace::path("b1").to_string_lossy().into_owned();
+ let stored: BotConfig =
+ serde_json::from_value(json!({"id": "b1", "name": "Ada", "backend": "codex", "cwd": own})).unwrap();
+ assert_eq!(changed_fields(&stored, &json!({"id": "b1", "cwd": "", "fastMode": true})), ["fastMode"]);
+ assert_eq!(changed_fields(&stored, &json!({"id": "b1", "cwd": "/tmp"})), ["cwd"]);
+}
+
+#[test]
+fn sections_count_without_their_names() {
+ assert_eq!(
+ props("renameSection", &json!({"from": "Work", "to": "Play"})),
+ Some((Event::SectionRenamed, json!({"removed": false, "client": "local"})))
+ );
+ let removed = props("renameSection", &json!({"from": "Work", "to": null}));
+ assert_eq!(removed.map(|(_, p)| p["removed"].clone()), Some(json!(true)));
+
+ let stored: BotConfig = serde_json::from_value(
+ json!({"id": "b1", "name": "Ada", "backend": "codex", "cwd": "/tmp", "section": "Work"}),
+ )
+ .unwrap();
+ assert_eq!(changed_fields(&stored, &json!({"id": "b1", "section": null})), ["section"]);
+ assert_eq!(changed_fields(&stored, &json!({"id": "b1", "section": "Work"})), Vec::<String>::new());
+}
+
+#[test]
+fn a_permission_answer_names_the_kind_picked() {
+ let card = json!({"title": "rm -rf", "options": [
+ {"optionId": "a", "name": "Allow", "kind": "allow_once"},
+ {"optionId": "r", "name": "Always reject", "kind": "reject_always"},
+ {"optionId": "x", "name": "Odd", "kind": "something_new"}]});
+ assert_eq!(choice(Some(&card), &json!("a")), "allow_once");
+ assert_eq!(choice(Some(&card), &json!("r")), "reject_always");
+ assert_eq!(choice(Some(&card), &json!("x")), "other");
+ assert_eq!(choice(Some(&card), &Value::Null), "other");
+ assert_eq!(choice(None, &json!("a")), "other");
+}
+
+#[tokio::test]
+async fn a_resent_message_counts_once_and_names_its_agent() {
+ let (hub, dir) = temp_hub();
+ let cfg = serde_json::from_value(json!({"id": "b1", "name": "b", "backend": "codex", "cwd": "/tmp"})).unwrap();
+ hub.store.save_bot(&cfg).unwrap();
+ let send = json!({"botId": "b1", "text": "hi", "clientNonce": "n1"});
+
+ let (_, p) = observe_call(&hub, &Caller::Local, "send", &send).expect("a new message is tracked");
+ assert_eq!((p["agent"].as_str(), p["kind"].as_str()), (Some("codex"), Some("bot")));
+ let lane = crate::store::Lane::main("b1");
+ hub.store
+ .insert_entry(&lane, crate::store::EntryKind::User, 1, &json!({"text": "hi", "clientNonce": "n1"}))
+ .unwrap();
+ assert!(observe_call(&hub, &Caller::Local, "send", &send).is_none(), "a replay is the same message");
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
+#[tokio::test]
+async fn store_lookups_add_fields_choice_and_platform() {
+ let (hub, dir) = temp_hub();
+ let cfg = serde_json::from_value(json!({"id": "b1", "name": "b", "backend": "codex", "cwd": "/tmp"})).unwrap();
+ hub.store.save_bot(&cfg).unwrap();
+ let (_, p) = observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "permission": "ask"})).unwrap();
+ assert_eq!(p["fields"], json!(["permission"]));
+
+ let card = json!({"status": "pending", "options": [{"optionId": "o1", "name": "Allow", "kind": "allow_always"}]});
+ let e =
+ hub.store.insert_entry(&crate::store::Lane::main("b1"), crate::store::EntryKind::Permission, 1, &card).unwrap();
+ let answer = json!({"entryId": e.id, "optionId": "o1"});
+
+ let phone = Caller::Device { key: "k1".into(), scopes: vec![] };
+ hub.store
+ .put_device(&Device {
+ key: "k1".into(),
+ name: "Kevin's phone".into(),
+ platform: "android".into(),
+ source: DeviceSource::Local,
+ grant_id: None,
+ scopes: vec![],
+ lease_until: None,
+ created_at: 0,
+ last_seen_at: None,
+ })
+ .unwrap();
+ let (event, p) = observe_call(&hub, &phone, "respondPermission", &answer).unwrap();
+ assert_eq!(
+ (event, Value::Object(p)),
+ (Event::PermissionAnswered, json!({"choice": "allow_always", "client": "remote", "platform": "android"}))
+ );
+ let stranger = Caller::Device { key: "gone".into(), scopes: vec![] };
+ let (_, p) = observe_call(&hub, &stranger, "stop", &json!({"botId": "b1"})).unwrap();
+ assert_eq!(p["platform"], "other");
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/host/src/api/bots.rs b/host/src/api/bots.rs
index 279e98e3..40f11963 100644
--- a/host/src/api/bots.rs
+++ b/host/src/api/bots.rs
@@ -95,6 +95,16 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
tokio::task::spawn_blocking(move || hub.reorder_bots(&ids)).await??;
json!({})
}
+ // Every bot in section `from` moves to `to`; `null` or an empty name removes the section.
+ "renameSection" => {
+ const TO: &str = "`to` must be a section name or null";
+ let from = str_arg(&b, "from")?.to_owned();
+ // A missing `to` is refused, not read as null: a client bug must not strip every section.
+ let to: Option<String> = serde_json::from_value(b.get("to").cloned().context(TO)?).context(TO)?;
+ let hub = hub.clone();
+ tokio::task::spawn_blocking(move || hub.rename_section(&from, to.as_deref())).await??;
+ json!({})
+ }
"deleteBot" => {
hub.delete_bot(str_arg(&b, "botId")?)?;
json!({})
diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rs
index c647fb81..e9f1f3ff 100644
--- a/host/src/chat/calls/context.rs
+++ b/host/src/chat/calls/context.rs
@@ -368,6 +368,7 @@ pub(super) mod tests {
pinned: false,
position: 0,
hidden: false,
+ section: None,
notify: None,
connectors: vec!["github".into()],
skills: vec![],
diff --git a/host/src/compat.rs b/host/src/compat.rs
index 0d2f76f1..22587a52 100644
--- a/host/src/compat.rs
+++ b/host/src/compat.rs
@@ -42,6 +42,11 @@ fn below(version: &str, minimum: &str) -> bool {
matches!((parse(version), parse(minimum)), (Some(v), Some(m)) if v < m)
}
+/// Whether `version` is `minimum` or newer; unreadable versions count as newer.
+pub fn at_least(version: &str, minimum: &str) -> bool {
+ !below(version, minimum)
+}
+
/// Checks a client of version `app` with floor `min_host` against a host's `hello`.
/// Hosts that predate `minApp` only get the floor check.
pub fn check(app: &str, min_host: &str, hello: &Value) -> Option<Mismatch> {
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 70479a89..e70b17bd 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -18,8 +18,11 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{broadcast, watch};
+mod groups;
mod order;
+mod patch;
mod reactions;
+mod sections;
mod sync;
mod validate;
pub(crate) use validate::validate;
@@ -204,22 +207,6 @@ impl Hub {
self.store.bot(id).ok().flatten().map_or_else(|| "A deleted bot".into(), |b| b.config.name)
}
- /// A group is busy while one of its members works in it: that member's status and activity.
- pub fn group_runtime(&self, group: &BotConfig) -> Runtime {
- let busy = {
- let runtime = self.runtime.locked();
- group.members.iter().find_map(|m| {
- let r = runtime.get(m)?;
- (r.status != BotStatus::Idle && r.lane.as_ref().is_some_and(|l| l.chat == group.id))
- .then(|| (m.clone(), r.clone()))
- })
- };
- let Some((member, mut r)) = busy else { return Runtime::default() };
- let name = self.bot_name(&member);
- r.activity = if r.activity.is_empty() { name } else { format!("{name}: {}", r.activity) };
- r
- }
-
pub fn create_bot(self: &Arc<Self>, mut cfg: BotConfig) -> Result<Value> {
cfg.id = uuid::Uuid::new_v4().to_string();
cfg.created_at = crate::store::now_ms();
@@ -237,6 +224,7 @@ impl Hub {
}
}
crate::agent::fallback::tidy(&mut cfg);
+ cfg.section = sections::normalize_section(cfg.section.as_deref())?;
validate(&cfg)?;
crate::agent::workspace::prepare(&mut cfg)?;
{
@@ -254,42 +242,29 @@ impl Hub {
pub fn update_bot(&self, patch: &Value) -> Result<Value> {
let id = patch["id"].as_str().ok_or_else(|| anyhow!("id required"))?.to_owned();
- let row = self.store.bot(&id)?.filter(|b| !b.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
- let mut merged = serde_json::to_value(&row.config)?;
- for (k, v) in patch.as_object().into_iter().flatten() {
- if !matches!(k.as_str(), "id" | "createdAt" | "createdBy" | "lead") {
- merged[k] = v.clone();
- }
- }
- let mut cfg: BotConfig = serde_json::from_value(merged)?;
- if cfg.name.trim().is_empty() {
- cfg.name.clone_from(&row.config.name);
- }
- // A name the user picked ends automatic naming; the namer passes `autoName` itself.
- if cfg.name != row.config.name && patch.get("autoName").is_none() {
- cfg.auto_name = false;
- }
- // Options belong to one model; an app that doesn't know them can't clear them itself.
- if (cfg.model != row.config.model || cfg.backend != row.config.backend) && patch.get("modelOptions").is_none() {
- cfg.model_options.clear();
- }
- if cfg.kind != row.config.kind {
- bail!("a bot can't become a group, or a group a bot");
- }
- if cfg.is_group() {
- cfg.members = crate::chat::group::valid_members(&self.store, &cfg.id, &cfg.members)?;
- }
- crate::agent::fallback::tidy(&mut cfg);
- validate(&cfg)?;
- crate::agent::workspace::prepare(&mut cfg)?;
- crate::agent::own_memory::settle(&mut cfg, &row.config, patch);
- {
+ // Read, merge and save under one lock: a section rename in between would otherwise be written back.
+ let (before, cfg) = {
let _g = self.emit_lock.locked();
+ let row = self.store.bot(&id)?.filter(|b| !b.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ let mut cfg = patch::patched(&row.config, patch)?;
+ if cfg.is_group() {
+ cfg.members = crate::chat::group::valid_members(&self.store, &cfg.id, &cfg.members)?;
+ }
+ crate::agent::fallback::tidy(&mut cfg);
+ cfg.section = sections::normalize_section(cfg.section.as_deref())?;
+ // ponytail: validated under the lock, so a workspace folder on a hung network share (its
+ // `is_dir`) stalls every bot's events until it answers. Upgrade: build and validate outside the
+ // lock from a snapshot, then save under it only if the stored config is unchanged (compare the
+ // serialized configs, not rev), else retry.
+ validate(&cfg)?;
+ crate::agent::workspace::prepare(&mut cfg)?;
+ crate::agent::own_memory::settle(&mut cfg, &row.config, patch);
self.store.save_bot(&cfg)?;
- }
+ (row.config, cfg)
+ };
crate::network::publish(self);
if !cfg.is_group() {
- if crate::chat::memory::shared(&cfg) != crate::chat::memory::shared(&row.config) {
+ if crate::chat::memory::shared(&cfg) != crate::chat::memory::shared(&before) {
crate::chat::memory::changed(self, Some(&id));
}
self.send_cmd(&id, Cmd::Reconfigure(Box::new(cfg)))?;
@@ -326,19 +301,7 @@ impl Hub {
}
}
});
- // A deleted bot leaves its groups; what it said there stays.
- for row in self.store.bots()? {
- let mut group = row.config;
- if !row.deleted && group.is_group() && group.members.iter().any(|m| m == id) {
- group.members.retain(|m| m != id);
- {
- let _g = self.emit_lock.locked();
- self.store.save_bot(&group)?;
- }
- self.emit_bot(&group.id);
- }
- }
- Ok(())
+ self.leave_groups(id)
}
/// Marks what the user has seen as read. Nothing unread there is a no-op, so clients
diff --git a/host/src/hub/groups.rs b/host/src/hub/groups.rs
new file mode 100644
index 00000000..7f7a7ec0
--- /dev/null
+++ b/host/src/hub/groups.rs
@@ -0,0 +1,76 @@
+//! Group chats as the hub keeps them: what a busy one shows, and the groups a deleted bot leaves.
+
+use super::{BotStatus, Hub, Runtime};
+use crate::LockExt;
+use crate::store::BotConfig;
+use anyhow::Result;
+
+impl Hub {
+ /// A group is busy while one of its members works in it: that member's status and activity.
+ pub fn group_runtime(&self, group: &BotConfig) -> Runtime {
+ let busy = {
+ let runtime = self.runtime.locked();
+ group.members.iter().find_map(|m| {
+ let r = runtime.get(m)?;
+ (r.status != BotStatus::Idle && r.lane.as_ref().is_some_and(|l| l.chat == group.id))
+ .then(|| (m.clone(), r.clone()))
+ })
+ };
+ let Some((member, mut r)) = busy else { return Runtime::default() };
+ let name = self.bot_name(&member);
+ r.activity = if r.activity.is_empty() { name } else { format!("{name}: {}", r.activity) };
+ r
+ }
+
+ /// Takes bot `id` out of every group it was in; what it said there stays. Each group is read again
+ /// under the lock, so an edit or a section rename since this scan isn't written back.
+ pub(super) fn leave_groups(&self, id: &str) -> Result<()> {
+ let groups: Vec<String> =
+ self.store.bots()?.into_iter().filter(|r| !r.deleted && r.config.is_group()).map(|r| r.config.id).collect();
+ for group in groups {
+ let left = {
+ let _g = self.emit_lock.locked();
+ match self.store.bot(&group)?.filter(|r| !r.deleted) {
+ Some(mut row) if row.config.members.iter().any(|m| m == id) => {
+ row.config.members.retain(|m| m != id);
+ self.store.save_bot(&row.config)?;
+ true
+ }
+ _ => false,
+ }
+ };
+ if left {
+ self.emit_bot(&group);
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::hub::Hub;
+ use crate::remote::identity::Identity;
+ use crate::store::{BotConfig, Store};
+ use serde_json::json;
+
+ #[tokio::test]
+ async fn a_deleted_bot_leaves_its_groups_and_they_keep_their_latest_section() {
+ let dir = std::env::temp_dir().join(format!("codync-groups-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let hub = Hub::new(store, "groups-test".into(), Identity::load_or_create(&dir).unwrap(), "test".into(), 0);
+ for v in [
+ json!({"id": "a", "name": "a", "backend": "claude", "cwd": "/tmp"}),
+ json!({"id": "b", "name": "b", "backend": "claude", "cwd": "/tmp"}),
+ json!({"id": "g", "name": "g", "kind": "group", "members": ["a", "b"], "section": "Work"}),
+ ] {
+ hub.store.save_bot(&serde_json::from_value::<BotConfig>(v).unwrap()).unwrap();
+ }
+ hub.rename_section("Work", Some("Play")).unwrap();
+ hub.delete_bot("a").unwrap();
+ let group = hub.store.bot("g").unwrap().unwrap().config;
+ assert_eq!((group.members, group.section.as_deref()), (vec!["b".to_owned()], Some("Play")));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/host/src/hub/order.rs b/host/src/hub/order.rs
index fcee329f..b91b5943 100644
--- a/host/src/hub/order.rs
+++ b/host/src/hub/order.rs
@@ -9,13 +9,14 @@ impl Hub {
/// skipped; bots left out (hidden ones) keep their place.
pub fn reorder_bots(&self, ids: &[String]) -> Result<()> {
for (position, id) in (0_i64..).zip(ids) {
- let Some(mut row) = self.store.bot(id)?.filter(|r| !r.deleted) else { continue };
- if row.config.position == position {
- continue;
- }
- row.config.position = position;
{
+ // Read and save under one lock: an edit in between would otherwise be written back.
let _g = self.emit_lock.locked();
+ let Some(mut row) = self.store.bot(id)?.filter(|r| !r.deleted) else { continue };
+ if row.config.position == position {
+ continue;
+ }
+ row.config.position = position;
self.store.save_bot(&row.config)?;
}
self.emit_bot(id);
diff --git a/host/src/hub/patch.rs b/host/src/hub/patch.rs
new file mode 100644
index 00000000..07b27362
--- /dev/null
+++ b/host/src/hub/patch.rs
@@ -0,0 +1,51 @@
+//! An edit to a bot's settings: the fields a client sends, laid over what is saved.
+
+use crate::store::BotConfig;
+use anyhow::{Result, bail};
+use serde_json::Value;
+
+/// `stored` with `patch` laid over it: a field the patch leaves out keeps its saved value, a `null`
+/// clears it. The id, creation and lead fields never change here.
+pub(super) fn patched(stored: &BotConfig, patch: &Value) -> Result<BotConfig> {
+ let mut merged = serde_json::to_value(stored)?;
+ for (k, v) in patch.as_object().into_iter().flatten() {
+ if !matches!(k.as_str(), "id" | "createdAt" | "createdBy" | "lead") {
+ merged[k] = v.clone();
+ }
+ }
+ let mut cfg: BotConfig = serde_json::from_value(merged)?;
+ if cfg.name.trim().is_empty() {
+ cfg.name.clone_from(&stored.name);
+ }
+ // A name the user picked ends automatic naming; the namer passes `autoName` itself.
+ if cfg.name != stored.name && patch.get("autoName").is_none() {
+ cfg.auto_name = false;
+ }
+ // Options belong to one model; an app that doesn't know them can't clear them itself.
+ if (cfg.model != stored.model || cfg.backend != stored.backend) && patch.get("modelOptions").is_none() {
+ cfg.model_options.clear();
+ }
+ if cfg.kind != stored.kind {
+ bail!("a bot can't become a group, or a group a bot");
+ }
+ Ok(cfg)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::patched;
+ use crate::store::BotConfig;
+ use serde_json::json;
+
+ #[test]
+ fn a_patch_keeps_the_saved_section_unless_it_names_one() {
+ let stored: BotConfig = serde_json::from_value(
+ json!({"id": "a", "name": "a", "backend": "claude", "cwd": "/tmp", "section": "Play"}),
+ )
+ .expect("a bot config");
+ let section = |patch| patched(&stored, &patch).expect("a valid patch").section;
+ assert_eq!(section(json!({"id": "a", "name": "b"})).as_deref(), Some("Play"), "left out: kept");
+ assert_eq!(section(json!({"id": "a", "section": null})), None, "null: out of its section");
+ assert_eq!(section(json!({"id": "a", "section": "Work"})).as_deref(), Some("Work"));
+ }
+}
diff --git a/host/src/hub/sections.rs b/host/src/hub/sections.rs
new file mode 100644
index 00000000..1e23248d
--- /dev/null
+++ b/host/src/hub/sections.rs
@@ -0,0 +1,98 @@
+//! Roster sections: a name the user files bots and group chats under (`BotConfig::section`), at
+//! most one per row. A section exists while a bot is in it.
+
+use super::Hub;
+use crate::LockExt;
+use anyhow::{Result, bail};
+
+/// The longest section name, in characters.
+const MAX_SECTION_CHARS: usize = 40;
+
+/// A section name as bots keep it: trimmed, `None` when nothing is left. Refused when too long or
+/// with a control character.
+pub(super) fn normalize_section(raw: Option<&str>) -> Result<Option<String>> {
+ let Some(name) = raw.map(str::trim).filter(|n| !n.is_empty()) else { return Ok(None) };
+ if name.chars().count() > MAX_SECTION_CHARS {
+ bail!("A section name can be at most {MAX_SECTION_CHARS} characters.");
+ }
+ if name.chars().any(char::is_control) {
+ bail!("A section name can't contain control characters.");
+ }
+ Ok(Some(name.to_owned()))
+}
+
+impl Hub {
+ /// Moves every bot in section `from` (trimmed) to `to`: `None` or an empty name takes them out of
+ /// it, an existing name merges the two. Saved under one `emit_lock`, then each moved bot is emitted.
+ pub fn rename_section(&self, from: &str, to: Option<&str>) -> Result<()> {
+ let to = normalize_section(to)?;
+ let from = from.trim();
+ if to.as_deref() == Some(from) {
+ return Ok(());
+ }
+ let mut moved = vec![];
+ let saved = self.save_section(from, to.as_deref(), &mut moved);
+ // Emitted even when a save failed: a saved row has its rev already, and a client past it must not miss it.
+ for id in &moved {
+ self.emit_bot(id);
+ }
+ saved
+ }
+
+ /// Saves the new section of each live bot in `from` under one `emit_lock`, noting every id in `moved`.
+ fn save_section(&self, from: &str, to: Option<&str>, moved: &mut Vec<String>) -> Result<()> {
+ let _g = self.emit_lock.locked();
+ for mut row in self.store.bots()? {
+ if row.deleted || row.config.section.as_deref() != Some(from) {
+ continue;
+ }
+ row.config.section = to.map(str::to_owned);
+ self.store.save_bot(&row.config)?;
+ moved.push(row.config.id);
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::hub::Hub;
+ use crate::remote::identity::Identity;
+ use crate::store::{BotConfig, Store};
+ use serde_json::json;
+
+ #[tokio::test]
+ async fn renaming_moves_merges_and_removes_a_section() {
+ let dir = std::env::temp_dir().join(format!("codync-sections-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let hub = Hub::new(store, "sections-test".into(), Identity::load_or_create(&dir).unwrap(), "test".into(), 0);
+ for (id, section) in
+ [("a", Some("Work")), ("b", Some("Work")), ("c", Some("Home")), ("d", None), ("e", Some("Work"))]
+ {
+ let cfg: BotConfig = serde_json::from_value(
+ json!({"id": id, "name": id, "backend": "claude", "cwd": "/tmp", "section": section}),
+ )
+ .unwrap();
+ hub.store.save_bot(&cfg).unwrap();
+ }
+ hub.store.delete_bot("e").unwrap();
+ let section = |id: &str| hub.store.bot(id).unwrap().unwrap().config.section;
+ let mut events = hub.events.subscribe();
+
+ hub.rename_section(" Work ", Some("Home")).unwrap();
+ assert!(["a", "b", "c"].into_iter().all(|id| section(id).as_deref() == Some("Home")), "merged");
+ let emitted = std::iter::from_fn(|| events.try_recv().ok()).filter(|e| e["type"] == "bot").count();
+ assert_eq!(emitted, 2, "each moved bot is emitted once, a deleted one is skipped");
+
+ let long = hub.rename_section("Home", Some("x".repeat(41).as_str())).unwrap_err();
+ assert_eq!(long.to_string(), "A section name can be at most 40 characters.");
+ assert_eq!(section("a").as_deref(), Some("Home"), "a refused name moves nothing");
+
+ hub.rename_section("Home", Some(" Play ")).unwrap();
+ assert_eq!(section("c").as_deref(), Some("Play"), "trimmed");
+ hub.rename_section("Play", None).unwrap();
+ assert!(["a", "b", "c", "d"].into_iter().all(|id| section(id).is_none()), "removed; its bots stay");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/host/src/store/bots.rs b/host/src/store/bots.rs
index f4b9b6e9..9fd9bab8 100644
--- a/host/src/store/bots.rs
+++ b/host/src/store/bots.rs
@@ -172,6 +172,7 @@ mod tests {
lead: false,
position: 0,
hidden: false,
+ section: None,
notify: None,
connectors: vec![],
skills: vec![],
diff --git a/host/src/store/model.rs b/host/src/store/model.rs
index 2611f51d..e669588d 100644
--- a/host/src/store/model.rs
+++ b/host/src/store/model.rs
@@ -104,6 +104,9 @@ pub struct BotConfig {
pub position: i64,
#[serde(default)]
pub hidden: bool,
+ /// The roster section it shows in; none when unset. Trimmed and checked (`hub::sections`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub section: Option<String>,
#[serde(default)]
pub notify: Option<bool>,
/// Connector ids (MCP servers) handed to the agent; see `market`.
diff --git a/host/src/tui/app/bot.rs b/host/src/tui/app/bot.rs
index 9370615f..f1d644a4 100644
--- a/host/src/tui/app/bot.rs
+++ b/host/src/tui/app/bot.rs
@@ -44,6 +44,8 @@ pub struct Bot {
/// Where the user dragged it (see `App::roster`).
pub position: i64,
pub hidden: bool,
+ /// Its roster section; `None` for none (the host trims and checks the name).
+ pub section: Option<String>,
pub notify: bool,
pub computer: bool,
/// It creates bots and changes any bot's setup (`chat::manage`); `None` from a host without it.
@@ -185,6 +187,7 @@ impl Bot {
lead: v["lead"] == true,
position: v["position"].as_i64().unwrap_or(0),
hidden: v["hidden"].as_bool().unwrap_or(false),
+ section: v["section"].as_str().map(str::to_owned),
notify: v["notify"].as_bool().unwrap_or(true),
computer: v["computer"].as_bool().unwrap_or(false),
manage_team: v["manageTeam"].as_bool(),
diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rs
index 5ec295bd..69fea964 100644
--- a/host/src/tui/app/events.rs
+++ b/host/src/tui/app/events.rs
@@ -221,6 +221,7 @@ impl App {
After::Hello => {
self.mismatch = crate::compat::check(env!("CARGO_PKG_VERSION"), crate::compat::MIN_HOST, &v);
v["name"].as_str().unwrap_or("computer").clone_into(&mut self.host);
+ v["version"].as_str().unwrap_or_default().clone_into(&mut self.host_version);
v["home"].as_str().unwrap_or_default().clone_into(&mut self.home);
self.backends = v["backends"].as_array().cloned().unwrap_or_default();
self.analytics_hello(&v);
diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rs
index 96e26b29..09167d7c 100644
--- a/host/src/tui/app/input.rs
+++ b/host/src/tui/app/input.rs
@@ -212,7 +212,7 @@ impl App {
}
}
_ => {
- if let Some(id) = self.roster().get(i).map(|b| b.id.clone()) {
+ if let Some(id) = self.stop_at(i) {
self.select(&id);
}
}
@@ -373,6 +373,9 @@ impl App {
self.call("updateBot", json!({"id": id, "pinned": pinned}), After::Nothing);
}
}
+ KeyCode::Char('w') => self.ask_section(),
+ KeyCode::Char('W') => self.ask_rename_section(),
+ KeyCode::Char('z') => self.toggle_section(),
KeyCode::Char('c') => self.copy_last(),
_ => {}
}
@@ -418,6 +421,10 @@ impl App {
Some(Click::Composer) => self.start_typing(),
Some(Click::Steps) => self.toggle_steps(),
Some(Click::BotChat(entry)) => self.open_bot_chat(&entry),
+ Some(Click::Section(name)) => {
+ self.click_section(&name);
+ self.focus = Focus::Roster;
+ }
None => {
if self.overlays.is_empty() {
if self.hits.trace.contains(at) {
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index 983fb3a7..27e1806a 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -12,6 +12,7 @@ mod model;
mod navigate;
mod new_bot;
mod overlay_keys;
+mod roster;
mod slash;
mod steps;
mod ui;
@@ -20,6 +21,7 @@ pub use bot::{AgentModel, Bot, ModelOption, OwnMemory};
pub use editor::Editor;
pub use exchange::{ConversationRow, Exchange, Item, Outcome, conversation, group, rows};
pub use model::{After, Entry, Kind, Mark, Msg, Status};
+pub use roster::{RosterLine, cursor_line, rename_fold, roster_lines, stops};
pub use slash::SlashAction;
pub(super) use steps::{running_turn, working_steps};
pub use ui::{
@@ -53,6 +55,8 @@ pub struct App {
pub url: String,
pub host: String,
pub home: String,
+ /// The host's version (`hello`): features newer than `MIN_HOST` check it.
+ pub host_version: String,
pub online: bool,
pub error: Option<String>,
/// This client and the host can't work together until one of them updates.
@@ -106,6 +110,8 @@ pub struct App {
pub pick: Option<String>,
/// Chat lines showing their full text: a handoff (`o` on the picked line).
pub unfolded: HashSet<String>,
+ /// Roster sections showing their label alone (`z`); this run only.
+ pub folded: HashSet<String>,
/// Voice calls' own messages, by call id (`callEntries`): the chat loaded here may not reach back to them.
pub call_entries: HashMap<String, Vec<Entry>>,
pub market: (Vec<Toggle>, Vec<Toggle>),
@@ -145,6 +151,7 @@ impl App {
url,
host: String::new(),
home: String::new(),
+ host_version: String::new(),
online: false,
error: None,
mismatch: None,
@@ -181,6 +188,7 @@ impl App {
reply: None,
pick: None,
unfolded: HashSet::new(),
+ folded: HashSet::new(),
call_entries: HashMap::new(),
market: (vec![], vec![]),
plugins: (vec![], vec![]),
@@ -205,19 +213,6 @@ impl App {
// ---------- derived ----------
- /// Roster order: the lead, pinned bots, then where the user put them, then most recent (same as the phone).
- pub fn roster(&self) -> Vec<&Bot> {
- let mut v: Vec<&Bot> = self.bots.values().filter(|b| !b.hidden).collect();
- v.sort_by(|a, b| {
- a.band()
- .cmp(&b.band())
- .then(a.position.cmp(&b.position))
- .then(b.last_at.cmp(&a.last_at))
- .then(a.name.cmp(&b.name))
- });
- v
- }
-
pub fn bot(&self) -> Option<&Bot> {
self.selected.as_ref().and_then(|id| self.bots.get(id))
}
@@ -314,21 +309,6 @@ impl App {
}
}
- fn move_bot(&mut self, delta: isize) {
- let ids: Vec<String> = self.roster().iter().map(|b| b.id.clone()).collect();
- if ids.is_empty() {
- return;
- }
- let i = self.selected.as_ref().and_then(|s| ids.iter().position(|x| x == s));
- let n = isize::try_from(ids.len()).unwrap_or(isize::MAX);
- let next = match i {
- Some(i) => (isize::try_from(i).unwrap_or(0) + delta).clamp(0, n - 1),
- None => 0,
- };
- let id = ids[usize::try_from(next).unwrap_or(0)].clone();
- self.select(&id);
- }
-
/// Next bot (after the selected one, wrapping) whose mark matches.
fn jump(&mut self, want: Mark) {
// A bot busy in a group needs you there, and the group is marked too: skip the bot.
diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rs
index 6d8f9e9c..87401373 100644
--- a/host/src/tui/app/navigate.rs
+++ b/host/src/tui/app/navigate.rs
@@ -251,15 +251,23 @@ impl App {
true
}
- /// Moves the selected bot one place up (-1) or down (+1), staying in its band (`Bot::band`),
- /// and saves the order. Shown at once; the host's bot events confirm it.
+ /// Moves the selected bot one place up (-1) or down (+1) and saves the order, staying in its band
+ /// (`Bot::band`: the lead, pinned bots, the rest). Pinned bots move among all pinned bots (they
+ /// show no sections), the rest only inside their section. Shown at once; the host's bot events
+ /// confirm it.
pub(super) fn reorder_bot(&mut self, d: isize) {
- let roster: Vec<(String, u8)> = self.roster().iter().map(|b| (b.id.clone(), b.band())).collect();
- let Some(i) = self.selected.as_ref().and_then(|s| roster.iter().position(|(id, _)| id == s)) else { return };
- let Some(j) = i.checked_add_signed(d).filter(|&j| j < roster.len() && roster[j].1 == roster[i].1) else {
+ let roster = self.roster();
+ let Some(i) = self.selected.as_ref().and_then(|s| roster.iter().position(|b| &b.id == s)) else { return };
+ let group = roster[i].roster_group();
+ // A folded section shows no order to change.
+ if group.1.is_some_and(|s| self.folded.contains(s)) {
+ return;
+ }
+ let Some(j) = i.checked_add_signed(d).filter(|&j| roster.get(j).is_some_and(|b| b.roster_group() == group))
+ else {
return;
};
- let mut ids: Vec<String> = roster.into_iter().map(|(id, _)| id).collect();
+ let mut ids: Vec<String> = roster.iter().map(|b| b.id.clone()).collect();
ids.swap(i, j);
for (position, id) in (0_i64..).zip(&ids) {
if let Some(b) = self.bots.get_mut(id) {
@@ -306,4 +314,34 @@ mod tests {
app.reorder_bot(-1);
assert_eq!(order(&app), ["l", "p", "a", "c", "b"], "nor a pinned one above the lead");
}
+
+ #[tokio::test]
+ async fn unpinned_bots_reorder_inside_their_section_pinned_ones_among_all_pinned() {
+ let mut app = test_app();
+ let bots = [
+ ("p1", true, Some("Home"), 5),
+ ("p2", true, None, 4),
+ ("a", false, Some("Work"), 3),
+ ("b", false, Some("Work"), 2),
+ ("c", false, None, 1),
+ ];
+ for (id, pinned, section, last_at) in bots {
+ let bot = Bot::parse(&json!({"id": id, "pinned": pinned, "section": section, "lastAt": last_at}))
+ .expect("a bot with an id parses");
+ app.bots.insert(id.into(), bot);
+ }
+ let order = |app: &super::App| app.roster().iter().map(|b| b.id.clone()).collect::<Vec<_>>();
+ app.selected = Some("p2".into());
+ app.reorder_bot(-1);
+ assert_eq!(order(&app), ["p2", "p1", "a", "b", "c"], "pinned rows show no sections: any two swap");
+ app.selected = Some("c".into());
+ app.reorder_bot(-1);
+ assert_eq!(order(&app), ["p2", "p1", "a", "b", "c"], "a bot in no section can't move into one");
+ app.selected = Some("b".into());
+ app.reorder_bot(-1);
+ assert_eq!(order(&app), ["p2", "p1", "b", "a", "c"]);
+ app.folded.insert("Work".into());
+ app.reorder_bot(1);
+ assert_eq!(order(&app), ["p2", "p1", "b", "a", "c"], "a folded section shows no order to change");
+ }
}
diff --git a/host/src/tui/app/roster.rs b/host/src/tui/app/roster.rs
new file mode 100644
index 00000000..ac3c5c90
--- /dev/null
+++ b/host/src/tui/app/roster.rs
@@ -0,0 +1,469 @@
+//! The roster as shown: its order and its lines (the lead, pinned bots, then each section under its
+//! label, sorted by name, then bots in none), and moving through it.
+
+use std::cmp::Reverse;
+use std::collections::HashSet;
+
+use icu_normalizer::DecomposingNormalizerBorrowed;
+
+use super::super::l10n::tr;
+use super::super::manage::{Submit, section_fields};
+use super::{App, Bot, Click, Overlay};
+
+/// The first host with roster sections (`section`, `renameSection`).
+const SECTIONS_SINCE: &str = "2.32.0";
+
+/// One line of the roster.
+pub enum RosterLine<'a> {
+ /// `PINNED` above the pinned bots, `BOTS` above the bots in no section.
+ Label(&'static str),
+ /// A section's label: how many bots it holds, their unread messages (shown while folded) and the
+ /// first of them, which the cursor lands on while it is folded.
+ Section {
+ name: &'a str,
+ bots: usize,
+ unread: i64,
+ folded: bool,
+ first: &'a Bot,
+ },
+ Bot(&'a Bot),
+}
+
+impl Bot {
+ /// The section the roster shows it in: none for the lead or while pinned (they stay on top,
+ /// outside sections).
+ pub fn shown_section(&self) -> Option<&str> {
+ if self.lead || self.pinned { None } else { self.section.as_deref() }
+ }
+
+ /// The bots it shows among and reorders with: its band (`Bot::band`), and for the rest its section
+ /// (or none).
+ pub fn roster_group(&self) -> (u8, Option<&str>) {
+ (self.band(), self.shown_section())
+ }
+}
+
+/// How sections sort: by name with case and accents set aside ("Çalışma" beside "Cherry", "home"
+/// before "Work"); then unaccented first ("Cafe", "Café"), then lowercase first ("work", "Work",
+/// whose capitals have the lower code points), as the apps' collators order them.
+// ponytail: accents folded, no locale rules (Swedish "å" sorts as "a", Turkish "ı" by code point,
+// unlike the apps' system collators); icu_collator if the terminal must match them exactly.
+fn section_key(name: &str) -> (String, String, Reverse<&str>) {
+ let base = DecomposingNormalizerBorrowed::new_nfd()
+ .normalize(name)
+ .chars()
+ .filter(|c| !('\u{300}'..='\u{36f}').contains(c))
+ .flat_map(char::to_lowercase)
+ .collect();
+ (base, name.to_lowercase(), Reverse(name))
+}
+
+/// `roster` (in `App::roster` order) as lines; a folded section is its label alone. Without pinned
+/// bots or sections there is nothing to tell apart, so no labels; the lead, on top, has none.
+pub fn roster_lines<'a>(roster: &[&'a Bot], folded: &HashSet<String>) -> Vec<RosterLine<'a>> {
+ let labeled = roster.iter().any(|b| b.pinned || b.shown_section().is_some());
+ let mut lines = vec![];
+ let mut group = None;
+ for &b in roster {
+ let here = b.roster_group();
+ if labeled && !b.lead && group != Some(here) {
+ lines.push(match here {
+ (_, None) if b.pinned => RosterLine::Label("PINNED"),
+ (_, None) => RosterLine::Label("BOTS"),
+ (_, Some(name)) => {
+ let members: Vec<&Bot> =
+ roster.iter().copied().filter(|m| m.shown_section() == Some(name)).collect();
+ RosterLine::Section {
+ name,
+ bots: members.len(),
+ unread: members.iter().map(|m| m.unread).sum(),
+ folded: folded.contains(name),
+ first: b,
+ }
+ }
+ });
+ }
+ group = Some(here);
+ if !here.1.is_some_and(|name| folded.contains(name)) {
+ lines.push(RosterLine::Bot(b));
+ }
+ }
+ lines
+}
+
+/// The line the cursor is on: the selected bot's, or its folded section's label.
+pub fn cursor_line(lines: &[RosterLine<'_>], selected: Option<&Bot>) -> Option<usize> {
+ let selected = selected?;
+ lines.iter().position(|line| match line {
+ RosterLine::Bot(b) => b.id == selected.id,
+ RosterLine::Section { name, folded: true, .. } => selected.shown_section() == Some(*name),
+ _ => false,
+ })
+}
+
+impl RosterLine<'_> {
+ /// The bot the cursor selects on this line: a bot's own, a folded section's first.
+ fn stop(&self) -> Option<&str> {
+ match self {
+ Self::Bot(b) | Self::Section { first: b, folded: true, .. } => Some(b.id.as_str()),
+ _ => None,
+ }
+ }
+
+ /// What a click on this line does: a section's label folds or unfolds it, a bot's row selects it.
+ pub fn click(&self) -> Option<Click> {
+ match self {
+ Self::Section { name, .. } => Some(Click::Section((*name).to_owned())),
+ Self::Bot(b) => Some(Click::Bot(b.id.clone())),
+ Self::Label(_) => None,
+ }
+ }
+}
+
+/// Keeps a section's fold through a rename on this device: a folded `from` stays folded as `to` (a
+/// merge folds the section it joins) and is forgotten when removed (`to` is `None`); an unfolded
+/// `from` changes nothing, so `to` is never unfolded.
+pub fn rename_fold(folded: &mut HashSet<String>, from: &str, to: Option<&str>) {
+ if folded.remove(from)
+ && let Some(to) = to
+ {
+ folded.insert(to.to_owned());
+ }
+}
+
+/// What the cursor can stop on, in order, as (line, bot id): the bots shown and each folded section
+/// (at its first bot). The number keys, j/k and the compact strip all count these.
+pub fn stops<'l>(lines: &'l [RosterLine<'_>]) -> Vec<(usize, &'l str)> {
+ lines.iter().enumerate().filter_map(|(i, l)| Some((i, l.stop()?))).collect()
+}
+
+/// The bot `delta` stops from the cursor (no cursor: the first). A folded section is one stop.
+fn step(lines: &[RosterLine<'_>], selected: Option<&Bot>, delta: isize) -> Option<String> {
+ let stops = stops(lines);
+ let last = stops.len().checked_sub(1)?;
+ let at = cursor_line(lines, selected).and_then(|c| stops.iter().position(|&(i, _)| i == c));
+ let next = at.map_or(0, |i| i.saturating_add_signed(delta).min(last));
+ Some(stops[next].1.to_owned())
+}
+
+const NOT_IN_A_SECTION: &str = "This bot isn't in a section";
+
+impl App {
+ /// Roster order: the lead, pinned bots, then sections by name, then bots in none; inside each,
+ /// where the user put them, then most recent (same as the phone).
+ pub fn roster(&self) -> Vec<&Bot> {
+ let mut v: Vec<&Bot> = self.bots.values().filter(|b| !b.hidden).collect();
+ v.sort_by_cached_key(|&b| {
+ let section = b.shown_section().map(section_key);
+ (b.band(), section.is_none(), section, b.position, Reverse(b.last_at), b.name.clone())
+ });
+ v
+ }
+
+ /// Every section on this computer once (hidden and pinned bots' too), in the roster's order.
+ fn section_names(&self) -> Vec<&str> {
+ let mut names: Vec<&str> = self.bots.values().filter_map(|b| b.section.as_deref()).collect();
+ names.sort_by_cached_key(|&name| section_key(name));
+ names.dedup();
+ names
+ }
+
+ /// j/k in the roster: the next shown bot, a folded section counting as one.
+ pub(super) fn move_bot(&mut self, delta: isize) {
+ let Some(id) = step(&roster_lines(&self.roster(), &self.folded), self.bot(), delta) else { return };
+ self.select(&id);
+ }
+
+ /// The bot key `n` (from 0 for `1`) selects: the n-th stop, a folded section being one (its first bot).
+ pub(super) fn stop_at(&self, n: usize) -> Option<String> {
+ let lines = roster_lines(&self.roster(), &self.folded);
+ stops(&lines).get(n).map(|&(_, id)| id.to_owned())
+ }
+
+ /// `z`: folds the section under the cursor, or unfolds it.
+ pub(super) fn toggle_section(&mut self) {
+ let Some(bot) = self.bot() else { return };
+ let Some(name) = bot.shown_section().map(str::to_owned) else {
+ self.flash(NOT_IN_A_SECTION);
+ return;
+ };
+ self.toggle_fold(&name);
+ }
+
+ /// Folds section `name`, or unfolds it (`z`, a click on its label).
+ pub(super) fn toggle_fold(&mut self, name: &str) {
+ if !self.folded.remove(name) {
+ self.folded.insert(name.to_owned());
+ }
+ }
+
+ /// A click on section `name`'s label: folds or unfolds it. Opened, its first bot takes the cursor
+ /// (where j/k land), so the list doesn't scroll back to a bot elsewhere and leave it off screen.
+ pub(super) fn click_section(&mut self, name: &str) {
+ self.toggle_fold(name);
+ if self.folded.contains(name) {
+ return;
+ }
+ if let Some(id) = self.roster().iter().find(|b| b.shown_section() == Some(name)).map(|b| b.id.clone()) {
+ self.select(&id);
+ }
+ }
+
+ /// `w`: "Move to section" for the selected bot: one of the sections, a new name, or empty for none.
+ /// The lead stays on top, outside sections.
+ pub(super) fn ask_section(&mut self) {
+ if self.bot().is_some_and(|b| b.lead) {
+ self.flash("The lead bot always stays on top");
+ return;
+ }
+ if self.bot().is_none() || !self.sections_supported() {
+ return;
+ }
+ let Some(bot) = self.bot() else { return };
+ let names = self.section_names();
+ // Translated before the names go in: the sheet's own translation can't match a filled-in note.
+ let mut note = tr("Empty takes it out of its section; a new name makes one.").into_owned();
+ if !names.is_empty() {
+ note.push_str(&tr(" Sections: {list}").replace("{list}", &names.join(", ")));
+ }
+ let fields = section_fields("Move to section", note, bot.section.as_deref(), Submit::Section(bot.id.clone()));
+ self.overlays.push(Overlay::Fields(Box::new(fields)));
+ }
+
+ /// `W`: "Rename section" for the section under the cursor: an existing name merges the two, empty
+ /// removes the section (its bots stay).
+ pub(super) fn ask_rename_section(&mut self) {
+ if self.bot().is_none() || !self.sections_supported() {
+ return;
+ }
+ let Some(name) = self.bot().and_then(Bot::shown_section).map(str::to_owned) else {
+ self.flash(NOT_IN_A_SECTION);
+ return;
+ };
+ let note = "Empty removes the section; its bots stay. A name in use merges them.".to_owned();
+ let fields = section_fields("Rename section", note, Some(name.as_str()), Submit::RenameSection(name.clone()));
+ self.overlays.push(Overlay::Fields(Box::new(fields)));
+ }
+
+ /// Whether the host has sections; says what to update when it doesn't.
+ fn sections_supported(&mut self) -> bool {
+ if self.host_version.is_empty() {
+ self.flash("Still connecting: try again in a moment.");
+ return false;
+ }
+ let supported = crate::compat::at_least(&self.host_version, SECTIONS_SINCE);
+ if !supported {
+ let why = tr("Update Codync on {host}: sections need {version} or newer.")
+ .replace("{host}", &self.host)
+ .replace("{version}", SECTIONS_SINCE);
+ self.flash(&why);
+ }
+ supported
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::{Bot, Click, Overlay, test_app};
+ use super::{App, NOT_IN_A_SECTION, RosterLine, cursor_line, rename_fold, roster_lines, section_key};
+ use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
+ use ratatui::layout::Rect;
+ use serde_json::json;
+ use std::collections::HashSet;
+
+ fn add(app: &mut App, id: &str, pinned: bool, section: Option<&str>, last_at: i64, unread: i64) {
+ let v = json!({"id": id, "pinned": pinned, "section": section, "lastAt": last_at, "unread": unread});
+ app.bots.insert(id.into(), Bot::parse(&v).expect("a bot with an id parses"));
+ }
+
+ /// The roster as text: labels, `▾ name (bots)` or `▸ name (bots) unread`, bot ids.
+ fn shown(app: &App) -> Vec<String> {
+ roster_lines(&app.roster(), &app.folded)
+ .iter()
+ .map(|line| match line {
+ RosterLine::Label(l) => (*l).to_owned(),
+ RosterLine::Section { name, bots, folded: false, .. } => format!("▾ {name} ({bots})"),
+ RosterLine::Section { name, bots, unread, .. } => format!("▸ {name} ({bots}) {unread}"),
+ RosterLine::Bot(b) => b.id.clone(),
+ })
+ .collect()
+ }
+
+ #[tokio::test]
+ async fn pinned_bots_then_sections_by_name_then_the_rest() {
+ let mut app = test_app();
+ for (id, pinned, section, last_at, unread) in [
+ ("p", true, Some("Work"), 9, 0),
+ ("w1", false, Some("Work"), 3, 2),
+ ("w2", false, Some("Work"), 2, 1),
+ ("h", false, Some("home"), 1, 0),
+ ("x", false, None, 5, 0),
+ ] {
+ add(&mut app, id, pinned, section, last_at, unread);
+ }
+ // "home" before "Work": case doesn't count; the pinned bot stays on top and out of Work.
+ assert_eq!(shown(&app), ["PINNED", "p", "▾ home (1)", "h", "▾ Work (2)", "w1", "w2", "BOTS", "x"]);
+ app.folded.insert("Work".into());
+ assert_eq!(shown(&app), ["PINNED", "p", "▾ home (1)", "h", "▸ Work (2) 3", "BOTS", "x"]);
+ }
+
+ #[tokio::test]
+ async fn the_lead_stays_on_top_without_a_label_or_a_section() {
+ let mut app = test_app();
+ let lead = json!({"id": "l", "lead": true, "section": "Work", "lastAt": 0});
+ app.bots.insert("l".into(), Bot::parse(&lead).expect("a bot with an id parses"));
+ add(&mut app, "w", false, Some("Work"), 2, 0);
+ add(&mut app, "x", false, None, 1, 0);
+ assert_eq!(shown(&app), ["l", "▾ Work (1)", "w", "BOTS", "x"]);
+ add(&mut app, "p", true, None, 3, 0);
+ assert_eq!(shown(&app), ["l", "PINNED", "p", "▾ Work (1)", "w", "BOTS", "x"]);
+ app.host_version = "2.32.0".into();
+ app.selected = Some("l".into());
+ app.ask_section();
+ assert!(app.overlays.is_empty(), "the lead goes in no section");
+ assert_eq!(app.hint.as_ref().map(|(s, _)| s.as_str()), Some("The lead bot always stays on top"));
+ }
+
+ #[tokio::test]
+ async fn sections_sort_with_case_and_accents_set_aside_in_the_roster_and_the_prompt() {
+ let mut app = test_app();
+ for (id, section) in [("d", "Dersler"), ("c", "Çalışma"), ("e", "Éclair"), ("f", "fig"), ("h", "home")] {
+ add(&mut app, id, false, Some(section), 0, 0);
+ }
+ let order = ["Çalışma", "Dersler", "Éclair", "fig", "home"];
+ let headers: Vec<String> =
+ shown(&app).into_iter().filter_map(|l| l.strip_prefix("▾ ").map(str::to_owned)).collect();
+ assert_eq!(headers, order.map(|s| format!("{s} (1)")));
+ assert_eq!(app.section_names(), order);
+ }
+
+ #[tokio::test]
+ async fn j_and_k_pass_a_folded_section_as_one_row() {
+ let mut app = test_app();
+ for (id, section, last_at) in [("a", Some("Work"), 3), ("b", Some("Work"), 2), ("c", None, 1)] {
+ add(&mut app, id, false, section, last_at, 0);
+ }
+ app.selected = Some("b".into());
+ app.toggle_section();
+ assert!(app.folded.contains("Work"));
+ let lines = roster_lines(&app.roster(), &app.folded);
+ assert_eq!(cursor_line(&lines, app.bot()), Some(0), "the cursor is on the folded label");
+ app.move_bot(1);
+ assert_eq!(app.selected.as_deref(), Some("c"));
+ app.move_bot(-1);
+ assert_eq!(app.selected.as_deref(), Some("a"), "back onto the label: its first bot");
+ app.toggle_section();
+ assert!(app.folded.is_empty());
+ app.move_bot(1);
+ assert_eq!(app.selected.as_deref(), Some("b"));
+ }
+
+ #[tokio::test]
+ async fn number_keys_count_a_folded_section_as_one_row() {
+ let mut app = test_app();
+ for (id, section, last_at) in [("a", Some("Work"), 3), ("b", Some("Work"), 2), ("c", None, 1)] {
+ add(&mut app, id, false, section, last_at, 0);
+ }
+ assert_eq!([0, 1, 2, 3].map(|n| app.stop_at(n)), [Some("a".into()), Some("b".into()), Some("c".into()), None]);
+ app.folded.insert("Work".into());
+ let at = [0, 1, 2].map(|n| app.stop_at(n));
+ assert_eq!(at, [Some("a".into()), Some("c".into()), None], "1 is the section's first bot, 2 the next row");
+ }
+
+ #[tokio::test]
+ async fn a_click_folds_a_section_or_opens_it_on_its_first_bot() {
+ let mut app = test_app();
+ for (id, section, last_at) in [("a", Some("Work"), 3), ("b", Some("Work"), 2), ("c", None, 1)] {
+ add(&mut app, id, false, section, last_at, 0);
+ }
+ app.selected = Some("c".into());
+ let click = MouseEvent {
+ kind: MouseEventKind::Down(MouseButton::Left),
+ column: 4,
+ row: 0,
+ modifiers: KeyModifiers::NONE,
+ };
+ for (folded, selected) in [(true, "c"), (false, "a")] {
+ // The label's click, as the full roster and the compact strip (folded: its one cell) register it.
+ let section = roster_lines(&app.roster(), &app.folded).iter().find_map(|l| match l {
+ RosterLine::Section { .. } => l.click(),
+ _ => None,
+ });
+ assert!(matches!(&section, Some(Click::Section(name)) if name == "Work"));
+ app.hits.clicks = section.into_iter().map(|c| (Rect::new(0, 0, 20, 1), c)).collect();
+ app.on_mouse(click);
+ assert_eq!(app.folded.contains("Work"), folded);
+ assert_eq!(app.selected.as_deref(), Some(selected), "folding keeps the selection, opening moves it in");
+ }
+ }
+
+ #[test]
+ fn names_alike_but_for_case_or_accents_sort_as_the_apps_do() {
+ for names in [["Work", "work", "Café", "Cafe"], ["Cafe", "work", "Café", "Work"]] {
+ let mut v = names.to_vec();
+ v.sort_by_cached_key(|&name| section_key(name));
+ assert_eq!(v, ["Cafe", "Café", "work", "Work"]);
+ }
+ }
+
+ #[test]
+ fn a_rename_keeps_a_folded_section_folded_under_its_new_name() {
+ let fold = |folded: &[&str], from: &str, to: Option<&str>| {
+ let mut set: HashSet<String> = folded.iter().map(|&s| s.to_owned()).collect();
+ rename_fold(&mut set, from, to);
+ let mut v: Vec<String> = set.into_iter().collect();
+ v.sort();
+ v
+ };
+ assert_eq!(fold(&["Work", "Home"], "Work", Some("Play")), ["Home", "Play"], "folded: the fold moves");
+ assert_eq!(fold(&["Home"], "Work", Some("Play")), ["Home"], "unfolded: nothing changes");
+ assert_eq!(fold(&["Work"], "Work", None), Vec::<String>::new(), "removed: forgotten");
+ assert_eq!(fold(&["Work"], "Work", Some("Home")), ["Home"], "merged: the joined section folds");
+ assert_eq!(fold(&["Home"], "Work", Some("Home")), ["Home"], "an unfolded merge never unfolds it");
+ }
+
+ #[tokio::test]
+ async fn z_outside_a_section_only_says_so() {
+ let mut app = test_app();
+ add(&mut app, "p", true, Some("Work"), 1, 0);
+ app.selected = Some("p".into());
+ app.toggle_section();
+ assert!(app.folded.is_empty(), "a pinned bot shows in no section");
+ assert_eq!(app.hint.as_ref().map(|(s, _)| s.as_str()), Some(NOT_IN_A_SECTION));
+ app.hint = None;
+ app.selected = None;
+ app.toggle_section();
+ assert!(app.hint.is_none(), "nothing selected: nothing to say");
+ }
+
+ #[tokio::test]
+ async fn sections_wait_for_a_host_that_has_them() {
+ let mut app = test_app();
+ add(&mut app, "a", false, Some("Work"), 0, 0);
+ app.ask_section();
+ app.ask_rename_section();
+ assert!(app.overlays.is_empty() && app.hint.is_none(), "nothing selected: silent, like z");
+ app.selected = Some("a".into());
+ app.ask_section();
+ assert!(app.overlays.is_empty(), "no hello yet: the host's version is unknown");
+ assert_eq!(app.hint.as_ref().map(|(s, _)| s.as_str()), Some("Still connecting: try again in a moment."));
+ app.host = "test".into();
+ app.host_version = "2.31.2".into();
+ app.ask_section();
+ assert!(app.overlays.is_empty(), "an older host would drop the name");
+ let why = app.hint.as_ref().map(|(s, _)| s.as_str());
+ assert_eq!(why, Some("Update Codync on test: sections need 2.32.0 or newer."));
+ app.host_version = "2.32.1-dev".into();
+ app.ask_section();
+ assert!(matches!(app.overlays.pop(), Some(Overlay::Fields(_))), "a dev build after it has them");
+ app.host_version = "2.32.0".into();
+ app.ask_section();
+ let Some(Overlay::Fields(f)) = app.overlays.last() else { panic!("the section prompt") };
+ assert_eq!((f.title.as_str(), f.inputs[0].ed.text.as_str()), ("Move to section", "Work"));
+ assert_eq!(f.note, "Empty takes it out of its section; a new name makes one. Sections: Work");
+ app.overlays.clear();
+ app.ask_rename_section();
+ let Some(Overlay::Fields(f)) = app.overlays.last() else { panic!("the rename prompt") };
+ assert_eq!((f.title.as_str(), f.inputs[0].placeholder.as_str()), ("Rename section", "Section name"));
+ }
+}
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index e632b13c..6f979da9 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -349,6 +349,8 @@ pub enum Click {
Steps,
/// A bot-message row (entry id): opens the conversation.
BotChat(String),
+ /// A section's label (its name): folds or unfolds it, like `z`.
+ Section(String),
}
#[derive(Default)]
diff --git a/host/src/tui/manage/fields.rs b/host/src/tui/manage/fields.rs
index ed597b90..c3bad606 100644
--- a/host/src/tui/manage/fields.rs
+++ b/host/src/tui/manage/fields.rs
@@ -78,6 +78,14 @@ impl App {
Submit::Handoff(entry) => {
self.sheet("editHandoff", json!({"entryId": entry, "text": values["text"]}), Reply::FieldsSaved);
}
+ Submit::Section(bot) => {
+ self.sheet("updateBot", json!({"id": bot, "section": values.get("name")}), Reply::FieldsSaved);
+ }
+ Submit::RenameSection(from) => {
+ let to = values.get("name").and_then(Value::as_str).map(str::to_owned);
+ let r = Reply::SectionRenamed { from: from.clone(), to: to.clone() };
+ self.sheet("renameSection", json!({"from": from, "to": to}), r);
+ }
Submit::RenameArtifact { bot, artifact } => {
let body = json!({"botId": bot, "artifactId": artifact, "title": values["title"]});
self.sheet("renameArtifact", body, Reply::FieldsSaved);
@@ -108,3 +116,26 @@ pub fn handoff_fields(entry: &Entry) -> Fields {
submit: Submit::Handoff(entry.id.clone()),
}
}
+
+/// Asks for a section name: where a bot goes, or a section's new name. Empty is allowed.
+pub fn section_fields(title: &str, note: String, current: Option<&str>, submit: Submit) -> Fields {
+ Fields {
+ title: title.into(),
+ note,
+ choices: vec![],
+ choice: 0,
+ inputs: vec![Input {
+ name: "name".into(),
+ label: "Section".into(),
+ secret: false,
+ required: false,
+ multiline: false,
+ placeholder: "Section name".into(),
+ ed: Editor::with(current.unwrap_or_default()),
+ }],
+ cursor: 0,
+ error: None,
+ saving: false,
+ submit,
+ }
+}
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index 1511f89a..64274820 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -23,7 +23,7 @@ mod skill;
mod when;
pub use analytics::AnalyticsSheet;
-pub use fields::handoff_fields;
+pub use fields::{handoff_fields, section_fields};
pub use gear::{Gear, GearRow};
pub use library::{ArtifactTitles, LibraryItem};
pub use memory::{MemoryMode, MemorySheet, Scroll, Section};
@@ -77,6 +77,11 @@ pub enum Reply {
Auth(String),
Setup,
FieldsSaved,
+ /// `renameSection` from a Fields sheet: saved like `FieldsSaved`, and the fold follows the name.
+ SectionRenamed {
+ from: String,
+ to: Option<String>,
+ },
SignIn,
Models(String),
Downloaded,
@@ -202,6 +207,10 @@ pub enum Submit {
Import,
/// A handoff card's text (the card's entry id).
Handoff(String),
+ /// A bot's section (its id): a name, or empty for none.
+ Section(String),
+ /// A section's new name (its current one), or empty to remove it.
+ RenameSection(String),
RenameArtifact {
bot: String,
artifact: String,
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index 2a76e981..20063be9 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -2,7 +2,7 @@
use serde_json::{Value, json};
-use super::super::app::{After, AgentModel, App, Entry, Overlay, Toggle};
+use super::super::app::{After, AgentModel, App, Entry, Overlay, Toggle, rename_fold};
use super::{Market, MemoryMode, Reply, Shell, open_browser, s};
impl App {
@@ -181,6 +181,10 @@ impl App {
self.flash("Saved");
self.refresh_sheets();
}
+ Reply::SectionRenamed { from, to } => {
+ rename_fold(&mut self.folded, &from, to.as_deref());
+ self.on_sheet_reply(Reply::FieldsSaved, Ok(v));
+ }
Reply::SignIn => {
let url = s(&v, "url");
super::super::app::copy(&url);
@@ -241,7 +245,7 @@ impl App {
f.error = Some(e);
}
}
- Reply::FieldsSaved => match self.overlays.last_mut() {
+ Reply::FieldsSaved | Reply::SectionRenamed { .. } => match self.overlays.last_mut() {
Some(Overlay::Fields(f)) => {
f.saving = false;
f.error = Some(e);
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index 2da3c1ef..ac0bd9c4 100644
--- a/host/src/tui/view/help.rs
+++ b/host/src/tui/view/help.rs
@@ -10,7 +10,7 @@ use super::buffer::{centered, frame_box, put, u};
use super::overlay::field_line;
use super::style::theme;
-const HELP: [(&str, &str, &str); 69] = [
+const HELP: [(&str, &str, &str); 72] = [
("MOVE", "j k ↑ ↓", "next / previous bot"),
("MOVE", "[ ]", "previous / next bot"),
("MOVE", "1…9", "jump to bot 1–9"),
@@ -58,6 +58,9 @@ const HELP: [(&str, &str, &str); 69] = [
("BOTS", "I", "About the lead agent"),
("BOTS", "p", "pin / unpin"),
("BOTS", "J K", "move bot down / up"),
+ ("BOTS", "w", "move to section"),
+ ("BOTS", "W", "rename / remove section"),
+ ("BOTS", "z", "fold / unfold section"),
("BOTS", "S", "new session"),
("BOTS", "M", "memory"),
("BOTS", "R", "details: routines, computer"),
diff --git a/host/src/tui/view/roster.rs b/host/src/tui/view/roster.rs
index d8e29378..d799a8e1 100644
--- a/host/src/tui/view/roster.rs
+++ b/host/src/tui/view/roster.rs
@@ -5,7 +5,7 @@ use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::Span;
-use super::super::app::{App, Bot, Click, Focus, Mark, Status};
+use super::super::app::{App, Bot, Click, Focus, Mark, RosterLine, Status, cursor_line, roster_lines, stops};
use super::super::l10n::tr;
use super::super::md::{self, truncate, width as w};
use super::buffer::{fill, hline, put, put_line, restyle, rput, u};
@@ -50,61 +50,36 @@ pub(super) fn roster(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
y += 1;
}
}
- // Rows: an optional section label, then 2 lines per bot and a gap. The lead, on top, has no label.
- let any_pinned = bots.iter().any(|b| b.pinned);
- let mut rows: Vec<(u16, Option<&'static str>, Option<usize>)> = vec![];
+ // Lines: a label takes one row, a bot two and a gap.
+ let shown: Vec<&Bot> = bots.iter().collect();
+ let lines = roster_lines(&shown, &app.folded);
+ let mut rows: Vec<u16> = vec![];
let mut y = 0u16;
- for (i, b) in bots.iter().enumerate() {
- if any_pinned && !b.lead && (i == 0 || bots[i - 1].band() != b.band()) {
- rows.push((y, Some(if b.pinned { "PINNED" } else { "BOTS" }), None));
- y += 1;
- }
- rows.push((y, None, Some(i)));
- y += 3;
+ for line in &lines {
+ rows.push(y);
+ y += extent(line).0;
}
- let sel_idx = app.selected.as_ref().and_then(|s| bots.iter().position(|b| &b.id == s));
+ let cursor = cursor_line(&lines, app.selected.as_ref().and_then(|s| bots.iter().find(|b| &b.id == s)));
let view_h = bottom.saturating_sub(top);
- let sel_y = sel_idx.and_then(|i| rows.iter().find(|r| r.2 == Some(i)).map(|r| r.0)).unwrap_or(0);
- let offset = (sel_y + 3).saturating_sub(view_h);
- for (ry, label, idx) in rows {
+ let offset = cursor.map_or(0, |i| rows[i] + extent(&lines[i]).0).saturating_sub(view_h);
+ let bar = if focused { t.bold } else { t.secondary };
+ for (i, (line, &ry)) in lines.iter().zip(&rows).enumerate() {
let Some(yy) = (top + ry).checked_sub(offset) else { continue };
- if ry < offset || yy + 1 >= bottom {
+ if ry < offset || yy + extent(line).1 > bottom {
continue;
}
- if let Some(l) = label {
- put(buf, x0 + 1, yy, wd, l, t.dim.add_modifier(Modifier::BOLD));
- continue;
- }
- let Some(i) = idx else { continue };
- let b = &bots[i];
- let selected = Some(i) == sel_idx;
- let row = Rect::new(x0, yy, wd, 2);
- app.hits.clicks.push((row, Click::Bot(b.id.clone())));
- if selected {
- restyle(buf, row, t.sel);
- let bar = if focused { t.bold } else { t.secondary };
- put(buf, x0, yy, 1, "▌", bar);
- put(buf, x0, yy + 1, 1, "▌", bar);
- }
- put_line(buf, x0 + 2, yy, 2, &avatar(app, b));
- let (g, gs) = glyph(app, b.mark());
- let time = if b.status == Status::Working { elapsed(b.started_at) } else { when(b.last_at) };
- let tx = rput(buf, r.right() - 1, yy, &time, if b.unread > 0 { t.bold } else { t.dim });
- let gx = tx.saturating_sub(2);
- put(buf, gx, yy, 1, g, gs);
- // The badge sits below the avatar, leaving activity and unread indicators visible.
- if b.lead {
- put(buf, x0 + 3, yy + 1, 1, "★", t.amber);
- app.hits.clicks.push((Rect::new(x0 + 3, yy + 1, 1, 1), Click::LeadAgent));
+ if let Some(click) = line.click() {
+ app.hits.clicks.push((Rect::new(x0, yy, wd, extent(line).1), click));
}
- let name_x = x0 + 5;
- put(buf, name_x, yy, gx.saturating_sub(name_x + 1), &b.name, t.bold);
- let (pv, ps) = preview(b);
- let badge = if b.unread > 0 { format!(" {} ", b.unread) } else { String::new() };
- let room = usize::from(wd.saturating_sub(7)).saturating_sub(w(&badge) + usize::from(!badge.is_empty()));
- put(buf, x0 + 5, yy + 1, u(room), &truncate(&pv, room), ps);
- if !badge.is_empty() {
- rput(buf, r.right() - 1, yy + 1, &badge, t.btn_primary);
+ let cursor_bar = (cursor == Some(i)).then_some(bar);
+ match line {
+ RosterLine::Label(l) => {
+ put(buf, x0 + 1, yy, wd, l, t.dim.add_modifier(Modifier::BOLD));
+ }
+ RosterLine::Section { name, bots: count, unread, folded, .. } => {
+ section_row(buf, Rect::new(x0, yy, wd, 1), cursor_bar, name, *count, *unread, *folded);
+ }
+ RosterLine::Bot(b) => bot_row(buf, Rect::new(x0, yy, wd, 2), app, b, cursor_bar),
}
}
if !narrow {
@@ -118,6 +93,59 @@ pub(super) fn roster(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
}
}
+/// (rows a line takes in the list, rows it draws): a bot has a gap row below it.
+fn extent(line: &RosterLine<'_>) -> (u16, u16) {
+ if matches!(line, RosterLine::Bot(_)) { (3, 2) } else { (1, 1) }
+}
+
+/// A section's label row, `▾ name (bots)`: the name is cut so `(bots)` and a gap before the unread
+/// badge (shown while folded) always fit.
+fn section_row(buf: &mut Buffer, row: Rect, bar: Option<Style>, name: &str, bots: usize, unread: i64, folded: bool) {
+ let t = theme();
+ if let Some(bar) = bar {
+ mark_cursor(buf, row, bar);
+ }
+ let badge = if folded && unread > 0 { format!(" {unread} ") } else { String::new() };
+ let room = usize::from(row.width.saturating_sub(2)).saturating_sub(w(&badge) + usize::from(!badge.is_empty()));
+ let tail = format!(" ({bots})");
+ let name = truncate(name, room.saturating_sub(2 + w(&tail)));
+ let label = format!("{} {name}{tail}", if folded { "▸" } else { "▾" });
+ put(buf, row.x + 1, row.y, u(room), &label, t.dim.add_modifier(Modifier::BOLD));
+ if !badge.is_empty() {
+ rput(buf, row.right() - 1, row.y, &badge, t.btn_primary);
+ }
+}
+
+/// A bot's two rows: avatar, name, status glyph and time, then its preview and unread badge; the
+/// lead's star below its avatar.
+fn bot_row(buf: &mut Buffer, row: Rect, app: &mut App, b: &Bot, bar: Option<Style>) {
+ let t = theme();
+ let (x0, y) = (row.x, row.y);
+ if let Some(bar) = bar {
+ mark_cursor(buf, row, bar);
+ }
+ put_line(buf, x0 + 2, y, 2, &avatar(app, b));
+ let (g, gs) = glyph(app, b.mark());
+ let time = if b.status == Status::Working { elapsed(b.started_at) } else { when(b.last_at) };
+ let tx = rput(buf, row.right() - 1, y, &time, if b.unread > 0 { t.bold } else { t.dim });
+ let gx = tx.saturating_sub(2);
+ put(buf, gx, y, 1, g, gs);
+ // The badge sits below the avatar, leaving activity and unread indicators visible.
+ if b.lead {
+ put(buf, x0 + 3, y + 1, 1, "★", t.amber);
+ app.hits.clicks.push((Rect::new(x0 + 3, y + 1, 1, 1), Click::LeadAgent));
+ }
+ let name_x = x0 + 5;
+ put(buf, name_x, y, gx.saturating_sub(name_x + 1), &b.name, t.bold);
+ let (pv, ps) = preview(b);
+ let badge = if b.unread > 0 { format!(" {} ", b.unread) } else { String::new() };
+ let room = usize::from(row.width.saturating_sub(7)).saturating_sub(w(&badge) + usize::from(!badge.is_empty()));
+ put(buf, x0 + 5, y + 1, u(room), &truncate(&pv, room), ps);
+ if !badge.is_empty() {
+ rput(buf, row.right() - 1, y + 1, &badge, t.btn_primary);
+ }
+}
+
/// A one-line preview without Markdown punctuation: its first line (also how a reply's quote shows).
pub(super) fn plain(s: &str) -> String {
let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default();
@@ -154,28 +182,84 @@ pub(super) fn compact_roster(buf: &mut Buffer, r: Rect, app: &mut App) {
let t = theme();
app.hits.roster = r;
let bots: Vec<Bot> = app.roster().into_iter().cloned().collect();
- let sel = app.selected.clone();
- let sel_idx = sel.as_ref().and_then(|s| bots.iter().position(|b| &b.id == s)).unwrap_or(0);
+ let shown: Vec<&Bot> = bots.iter().collect();
+ let lines = roster_lines(&shown, &app.folded);
+ let cursor = cursor_line(&lines, app.bot());
+ let cells = stops(&lines);
+ let at = cells.iter().position(|&(i, _)| Some(i) == cursor).unwrap_or(0);
let per = 2u16;
let view = r.height.saturating_sub(1) / per;
- let offset = (u(sel_idx) + 1).saturating_sub(view);
- for (i, b) in bots.iter().enumerate().skip(usize::from(offset)) {
- let y = r.y + 1 + (u(i) - offset) * per;
+ let offset = (u(at) + 1).saturating_sub(view);
+ for (n, &(i, _)) in cells.iter().enumerate().skip(usize::from(offset)) {
+ let y = r.y + 1 + (u(n) - offset) * per;
if y >= r.bottom() {
break;
}
let row = Rect::new(r.x, y, r.width, 1);
- app.hits.clicks.push((row, Click::Bot(b.id.clone())));
- if sel.as_deref() == Some(b.id.as_str()) {
- restyle(buf, row, t.sel);
- put(buf, r.x, y, 1, "▌", if app.focus == Focus::Roster { t.bold } else { t.secondary });
+ // A folded section's cell unfolds it, like its label in the full roster.
+ if let Some(click) = lines[i].click() {
+ app.hits.clicks.push((row, click));
+ }
+ if cursor == Some(i) {
+ mark_cursor(buf, row, if app.focus == Focus::Roster { t.bold } else { t.secondary });
+ }
+ match &lines[i] {
+ RosterLine::Section { bots: count, unread, .. } => {
+ compact_section(buf, row, *count, (*unread > 0).then(|| glyph(app, Mark::Unread)));
+ }
+ RosterLine::Bot(b) => {
+ put_line(buf, r.x + 1, y, 2, &avatar(app, b));
+ let (g, gs) = glyph(app, b.mark());
+ put(buf, r.x + 3, y, 1, g, gs);
+ if b.lead && y + 1 < r.bottom() {
+ put(buf, r.x + 2, y + 1, 1, "★", t.amber);
+ app.hits.clicks.push((Rect::new(r.x + 2, y + 1, 1, 1), Click::LeadAgent));
+ }
+ }
+ RosterLine::Label(_) => {}
}
- put_line(buf, r.x + 1, y, 2, &avatar(app, b));
- let (g, gs) = glyph(app, b.mark());
- put(buf, r.x + 3, y, 1, g, gs);
- if b.lead && y + 1 < r.bottom() {
- put(buf, r.x + 2, y + 1, 1, "★", t.amber);
- app.hits.clicks.push((Rect::new(r.x + 2, y + 1, 1, 1), Click::LeadAgent));
+ }
+}
+
+/// A folded section in the compact strip: `▸`, its bot count and the unread glyph if it has unread.
+fn compact_section(buf: &mut Buffer, row: Rect, bots: usize, unread: Option<(&str, Style)>) {
+ let t = theme();
+ let x = put(buf, row.x + 1, row.y, 1, "▸", t.dim);
+ let x = put(buf, x, row.y, 2, &bots.to_string(), t.dim.add_modifier(Modifier::BOLD));
+ if let Some((g, style)) = unread {
+ put(buf, x, row.y, 1, g, style);
+ }
+}
+
+/// The cursor's rows: a selection tint and a bar in the first cell of each.
+fn mark_cursor(buf: &mut Buffer, row: Rect, bar: Style) {
+ restyle(buf, row, theme().sel);
+ for y in row.top()..row.bottom() {
+ put(buf, row.x, y, 1, "▌", bar);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_long_section_name_gives_way_to_the_count_and_leaves_a_gap_before_the_badge() {
+ let row = Rect::new(0, 0, 24, 1);
+ let mut buf = Buffer::empty(row);
+ section_row(&mut buf, row, None, &"n".repeat(40), 12, 7, true);
+ let text = (0..row.width).map(|x| buf[(x, 0)].symbol()).collect::<String>();
+ assert_eq!(text, " ▸ nnnnnnnnnn… (12) 7 ");
+ }
+
+ #[test]
+ fn a_folded_section_is_one_cell_row_in_the_compact_strip() {
+ let row = Rect::new(0, 0, 5, 1);
+ for (bots, unread, text) in [(3, None, " ▸3 "), (12, Some(("●", Style::new())), " ▸12●")] {
+ let mut buf = Buffer::empty(row);
+ compact_section(&mut buf, row, bots, unread);
+ let cells = (0..row.width).map(|x| buf[(x, 0)].symbol()).collect::<String>();
+ assert_eq!(cells, text);
}
}
}
diff --git a/host/tests/e2e/wire_shape.rs b/host/tests/e2e/wire_shape.rs
index 04b8af0c..a9dd88b3 100644
--- a/host/tests/e2e/wire_shape.rs
+++ b/host/tests/e2e/wire_shape.rs
@@ -155,6 +155,8 @@ async fn wire_shape_matches_the_snapshot() {
.await;
let made = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;
assert!(made["data"]["text"].as_str().unwrap().starts_with("Done: "), "{made}");
+ // A bot in a roster section: its `section`.
+ host.call("updateBot", json!({"id": bot, "section": "Work"})).await;
let hello = host.call("hello", json!({})).await;
let min_app = hello["minApp"].as_str().unwrap().to_owned();
diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.json
index ec81fc91..1fc2d405 100644
--- a/host/tests/fixtures/wire-shape.json
+++ b/host/tests/fixtures/wire-shape.json
@@ -44,6 +44,7 @@
"event:bot.bot.reachableByAssistants": "bool",
"event:bot.bot.resting": "array",
"event:bot.bot.rev": "number",
+ "event:bot.bot.section": "string",
"event:bot.bot.selfFallbacks": "bool",
"event:bot.bot.sharedMemory": "bool",
"event:bot.bot.skills": "array",
diff --git a/host/tests/sections_e2e.rs b/host/tests/sections_e2e.rs
new file mode 100644
index 00000000..e621fac8
--- /dev/null
+++ b/host/tests/sections_e2e.rs
@@ -0,0 +1,71 @@
+//! Roster sections through a real host: `section` on bots and groups, and `renameSection`.
+
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+mod common;
+
+use common::host::Host;
+use serde_json::{Value, json};
+
+/// Each bot's `section` as a client holds it after catching up (`null`: none).
+async fn sections(host: &Host, ids: &[&str]) -> Vec<Value> {
+ let snapshot = host.snapshot().await;
+ let bots = snapshot["bots"].as_array().unwrap();
+ ids.iter().map(|id| bots.iter().find(|b| b["id"] == *id).unwrap()["section"].clone()).collect()
+}
+
+#[tokio::test]
+async fn bots_and_groups_take_a_trimmed_checked_section() {
+ let host = Host::start().await;
+ let (a, b) = (host.bot("A", "auto").await, host.bot("B", "auto").await);
+ let group = host.call("createBot", json!({"name": "G", "kind": "group", "members": [a, b]})).await["bot"]["id"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ let made = host
+ .call(
+ "createBot",
+ json!({"name": "C", "backend": "custom", "command": "unused", "connectors": [], "section": " Side "}),
+ )
+ .await;
+ assert_eq!(made["bot"]["section"], "Side", "createBot takes one too");
+
+ let set = host.call("updateBot", json!({"id": a, "section": " Work "})).await;
+ assert_eq!(set["bot"]["section"], "Work", "trimmed");
+ host.call("updateBot", json!({"id": a, "name": "A2"})).await;
+ host.call("updateBot", json!({"id": group, "section": "Home"})).await;
+ assert_eq!(
+ sections(&host, &[a.as_str(), group.as_str()]).await,
+ [json!("Work"), json!("Home")],
+ "a patch without `section` leaves it"
+ );
+ let cleared = host.call("updateBot", json!({"id": a, "section": null})).await;
+ assert!(cleared["bot"]["section"].is_null(), "null clears it");
+ let blank = host.call("updateBot", json!({"id": group, "section": " \t "})).await;
+ assert!(blank["bot"]["section"].is_null(), "nothing left after trimming: no section");
+
+ // Characters count, not bytes: 40 two-byte ones fit.
+ let longest = "İ".repeat(40);
+ let fits = host.call("updateBot", json!({"id": b, "section": longest})).await;
+ assert_eq!(fits["bot"]["section"], longest.as_str());
+ let long = host.refused("updateBot", json!({"id": b, "section": "x".repeat(41)})).await;
+ assert_eq!(long, "A section name can be at most 40 characters.");
+ let control = host.refused("updateBot", json!({"id": group, "section": "Wo\u{7}rk"})).await;
+ assert_eq!(control, "A section name can't contain control characters.", "groups are checked too");
+}
+
+#[tokio::test]
+async fn rename_section_answers_like_reorder_bots() {
+ let host = Host::start().await;
+ let a = host.bot("A", "auto").await;
+ host.call("updateBot", json!({"id": a, "section": "Work"})).await;
+ assert_eq!(host.call("renameSection", json!({"from": "Work", "to": "Play"})).await, json!({}));
+ assert_eq!(sections(&host, &[a.as_str()]).await, [json!("Play")]);
+ let typo = host.refused("renameSection", json!({"from": "Play", "to": 5})).await;
+ assert!(typo.starts_with("`to` must be a section name or null"), "{typo}");
+ let missing = host.refused("renameSection", json!({"from": "Play"})).await;
+ assert!(missing.starts_with("`to` must be a section name or null"), "{missing}");
+ assert_eq!(sections(&host, &[a.as_str()]).await, [json!("Play")], "a missing `to` moves nothing");
+ host.call("renameSection", json!({"from": "Play", "to": null})).await;
+ assert_eq!(sections(&host, &[a.as_str()]).await, [Value::Null]);
+}
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index 56e483a3..9b5eb8a1 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -10,7 +10,7 @@ Every computer comes with one bot of its own, named **Codync** until you rename
- **It checks in.** Its routine **Check in** runs at 9:00 and 18:00 on your computer's clock. If something deserves your attention, or there's a step it can take for you, it messages you; otherwise it stays quiet. What it reads in your email, documents or web pages is information to it, never instructions, and it doesn't send, forward, reply to, delete, pay for or post anything you didn't ask for in the chat. It skips a check-in while your agent plan is above 75% of a limit. Change the times, pause it or delete it like any routine. See [Routines](/docs/routines).
- **It speaks first on a call.** Call it and it opens with what's worth your attention, or a greeting. Other bots wait for you to speak. See [Voice](/docs/voice).
-You set it up like any bot: name, avatar, agent, folder, connectors. It can't be deleted or hidden, and it stays on top, so it has no Pin.
+You set it up like any bot: name, avatar, agent, folder, connectors. It can't be deleted or hidden, and it stays on top, outside [sections](#sections), so it has no Pin or Move to section.
## How a bot runs
@@ -95,6 +95,15 @@ Each bot keeps a long-term memory across sessions, which you can read on its **M
- **Terminal UI:** press Ctrl+K, type `unhide`, and pick **Unhide** followed by the bot's name.
- **Mark as read:** clears a bot's unread badge, from the same menus.
+### Sections
+
+Sections group a computer's bots under headings you name, such as Work and Personal. They need Codync 2.32.0 or newer on the computer.
+
+- **Move a bot into a section:** open the bot's menu (iPhone: touch and hold it; Desktop: right-click it) and choose **Move to section**, then a section, **New section…** or **Remove from section**. Terminal UI: `w`, then type the section's name, or leave it empty to take the bot out.
+- **Fold a section:** tap or click its heading to fold its bots away. A folded heading shows their unread count. Each device keeps its own folds. Terminal UI: `z`, or click the section's label; its folds last until you quit.
+- **Rename or remove a section:** touch and hold its heading (Desktop: right-click it) and choose **Rename section…** or **Remove section**. Its bots stay, without a section. Renaming it to another section's name merges the two. Terminal UI: `W`; an empty name removes the section.
+- Your lead bot and pinned bots stay on top, outside sections, and the lead bot has no **Move to section**. A pinned bot goes back to its section when you unpin it. Bots in no section sit under a **Bots** label, and dragging moves a bot only within its section.
+
## New session
A bot's chat and its agent's session are two different things. The chat is the permanent record you scroll through. The session is the agent's working context: what the model currently remembers of the conversation.