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.

fix: allow sections to move above and below Bots

leepokai036b12d9ff01
diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxproj
index a8d17c3e..18a98258 100644
--- a/apps/Codync.xcodeproj/project.pbxproj
+++ b/apps/Codync.xcodeproj/project.pbxproj
@@ -30,6 +30,7 @@
4C9ADD8046382132129B1302 /* CodyncBot-squircle-Ink.ttf in Resources */ = {isa = PBXBuildFile; fileRef = CEF1A5792B9675FDA7E07740 /* CodyncBot-squircle-Ink.ttf */; };
4DDC38E58D673047B332FDD5 /* AccessRequestView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B97102DEC6029268332DF901 /* AccessRequestView.swift */; };
501377099B6CF42761B230CB /* WelcomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D57A7C09154869DD84BACE19 /* WelcomeView.swift */; };
+ 518BD325D0FE6D7AAE973588 /* BotRosterLine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70093609851E57B883D23DB9 /* BotRosterLine.swift */; };
52CF04B855C6AAEC47B75B8F /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };
54CEEA0734C2940E2D9FAC7D /* AXTree.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4D13418ABB5FD7CFC087677 /* AXTree.swift */; };
5A56EF5D36D12ACCEA100642 /* LanguageSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73D324231A9BCE79C84C0403 /* LanguageSettings.swift */; };
@@ -85,6 +86,7 @@
F6A380E8A026CA849620F2F7 /* Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D16AD9979C77D976BC832D1 /* Driver.swift */; };
F842AE1C5ED96AF9A7F5D16C /* Widgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 6D734BEE7CD3F84677B0218B /* Widgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
F97C489DDB806224CEFCEB57 /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28B2CB561A43ED9F2F1A4391 /* ScreenHelper.swift */; };
+ FABB0D19F485A2B9DC16A446 /* EmptyRoster.swift in Sources */ = {isa = PBXBuildFile; fileRef = 531BFEBACA116F08530E289F /* EmptyRoster.swift */; };
FCE6E509AEFC88C3D05D8E3D /* CodyncBot-tablet-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = F7CAD5C4F330637102B40288 /* CodyncBot-tablet-Tint.ttf */; };
FFCAB62428CD3D4FB479B4AB /* SessionCandidates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46538A6E6E6B7C5E212F5CDF /* SessionCandidates.swift */; };
/* End PBXBuildFile section */
@@ -149,6 +151,7 @@
4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSwitcherView.swift; sourceTree = "<group>"; };
4FA78A055791BBBA79DF8C8B /* Permissions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Permissions.swift; sourceTree = "<group>"; };
52A96030D47F1B9678095909 /* iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = iOS.entitlements; sourceTree = "<group>"; };
+ 531BFEBACA116F08530E289F /* EmptyRoster.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmptyRoster.swift; sourceTree = "<group>"; };
5A21538E748C62E82DF7B139 /* CodyncBot-cloud-Ink.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-cloud-Ink.ttf"; sourceTree = "<group>"; };
5B22589689593E0089118FDB /* WidgetGalleryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetGalleryView.swift; sourceTree = "<group>"; };
5C4EB0DBA2F08CD7C0E25E30 /* OpenBotIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenBotIntent.swift; sourceTree = "<group>"; };
@@ -158,6 +161,7 @@
6BC00039A6C2C0D3F39A5F67 /* ComputerStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerStatus.swift; sourceTree = "<group>"; };
6D734BEE7CD3F84677B0218B /* Widgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = Widgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };
6FC76D28AB02DF1427D530ED /* LaunchSplash.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LaunchSplash.swift; sourceTree = "<group>"; };
+ 70093609851E57B883D23DB9 /* BotRosterLine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotRosterLine.swift; sourceTree = "<group>"; };
73D324231A9BCE79C84C0403 /* LanguageSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanguageSettings.swift; sourceTree = "<group>"; };
741B706007BA1B91CB853699 /* Screen.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Screen.app; sourceTree = BUILT_PRODUCTS_DIR; };
7B7E845BA1B8696B266CF578 /* NotificationService.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -324,9 +328,11 @@
DD3DE9A4EEB369C4F75C9448 /* ActivityGalleryView.swift */,
0814BD0C30F01A163FBDF896 /* AppearanceSettings.swift */,
0582B6169BFC36E4BCD51C0D /* BotListView.swift */,
+ 70093609851E57B883D23DB9 /* BotRosterLine.swift */,
1FB8080D4CB79347C36A7E75 /* ComputerSection.swift */,
6BC00039A6C2C0D3F39A5F67 /* ComputerStatus.swift */,
E3E35BCE6E7037B78D22F927 /* ComputersView.swift */,
+ 531BFEBACA116F08530E289F /* EmptyRoster.swift */,
73D324231A9BCE79C84C0403 /* LanguageSettings.swift */,
6FC76D28AB02DF1427D530ED /* LaunchSplash.swift */,
ECD0B4EA4BBA2BB2826C4362 /* PairingView.swift */,
@@ -720,12 +726,14 @@
107232310A15C4D9A3BCF466 /* AppStore+Shortcuts.swift in Sources */,
16C24A622E33414C24B0C148 /* AppearanceSettings.swift in Sources */,
01A1F820EFEE49A8FCCFC3F3 /* BotListView.swift in Sources */,
+ 518BD325D0FE6D7AAE973588 /* BotRosterLine.swift in Sources */,
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 */,
+ FABB0D19F485A2B9DC16A446 /* EmptyRoster.swift in Sources */,
5A56EF5D36D12ACCEA100642 /* LanguageSettings.swift in Sources */,
35CFB641A4F10C0EBD21CB14 /* LaunchSplash.swift in Sources */,
E695251CFD06AC6F4E3396B7 /* OpenBotIntent.swift in Sources */,
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 4c143be8..af9866c9 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
@@ -19,6 +19,7 @@ import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
@@ -62,18 +63,33 @@ import kotlinx.serialization.json.putJsonArray
var naming by remember { mutableStateOf<SectionNaming?>(null) }
val context = LocalContext.current
var folded by remember { mutableStateOf(FoldedSections.load(context)) }
+ val sectionKey = SectionOrders.key(state.contextId, state.computers.firstOrNull()?.id.orEmpty())
+ val listState = rememberLazyListState()
+ var sectionOrder by remember(sectionKey) { mutableStateOf(SectionOrders.load(context, sectionKey)) }
+ val sectionReorder = remember(sectionKey) { SectionReorder() }
+ sectionReorder.save = { sectionOrder = it; sectionReorder.names = it; SectionOrders.save(context, sectionKey, it) }
+ sectionReorder.position = { name ->
+ val key = if (name.isEmpty()) "label:bots" else "section:$name"
+ listState.layoutInfo.visibleItemsInfo.firstOrNull { it.key == key }?.offset?.toFloat() ?: 0f
+ }
// 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 orderBefore = sectionOrder
+ val orderAfter = renamedSectionOrder(sectionReorder.names, from, to)
+ sectionReorder.save(orderAfter)
val before = folded
val renamed = foldsAfterRename(before, from, to)
folded = renamed
FoldedSections.save(context, renamed)
store.renameSection(from, to) {
+ if (SectionOrders.load(context, sectionKey) == orderAfter) sectionReorder.save(orderBefore)
folded = foldsAfterRefusal(FoldedSections.load(context), renamed, before).also { FoldedSections.save(context, it) }
}
}
val roster = roster(state.bots)
+ val sectionNames = sectionNames(roster.filterNot { it.pinned })
+ sectionReorder.names = orderedSections(sectionNames + if (roster.any { !it.pinned && it.section == null }) listOf("") else emptyList(), sectionOrder)
val sections = menuSections(state.bots)
val reorder = remember { RosterReorder() }
reorder.roster = roster
@@ -92,13 +108,13 @@ import kotlinx.serialization.json.putJsonArray
}) {
// Pull to refresh reconnects and asks the account for its computers again (iOS `refreshable`).
PullToRefresh({ store.reconnect(); store.refreshComputers() }, Modifier.fillMaxSize(), indicatorTop = top + 50.dp) {
- LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = top + 56.dp, bottom = bottomInset)) {
+ LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = top + 56.dp, bottom = bottomInset)) {
// A computer waiting for an update has its card instead; its bots may not be readable yet.
state.mismatch?.let { mismatch -> item("update") { UpdateNeededCard(state, mismatch, store::requestHostUpdate, Modifier.padding(vertical = 8.dp)) } }
if (roster.isEmpty() && state.mismatch == null) item {
EmptyRoster(canCreate = usable, hasComputer = usable, create = newBot, showComputers = manage)
}
- items(rosterLines(reorder.shown(roster), folded), key = RosterLine::key) { line ->
+ items(rosterLines(reorder.shown(roster), folded, sectionReorder.shown, sectionReorder.dragged != null), 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 = {
@@ -107,8 +123,12 @@ import kotlinx.serialization.json.putJsonArray
}, 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())
+ modifier = Modifier.onSizeChanged { sectionReorder.heights[line.name] = it.height }
+ .then(if (sectionReorder.dragged == line.name) Modifier.zIndex(1f).graphicsLayer { translationY = sectionReorder.translation(line.name) } else Modifier.animateItem()),
+ drag = sectionReorder.handle(line.name),
+ move = { sectionReorder.move(line.name, it) })
+ RosterLine.Label -> SectionLabel(Modifier.onSizeChanged { sectionReorder.heights[""] = it.height }
+ .then(if (sectionReorder.dragged == "") Modifier.zIndex(1f).graphicsLayer { translationY = sectionReorder.translation("") } else Modifier.animateItem()), sectionReorder.handle("")) { sectionReorder.move("", it) }
is RosterLine.Row -> {
val bot = line.bot
val lifted = reorder.dragged == bot.id
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt
new file mode 100644
index 00000000..895c8d93
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt
@@ -0,0 +1,76 @@
+package com.codync.android
+
+import android.content.Context
+import androidx.core.content.edit
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import com.codync.android.design.ContextDrag
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonPrimitive
+
+/** The empty name is the unsectioned Bots group; stale names stay out and new groups follow. */
+internal fun orderedSections(names: List<String>, saved: List<String>): List<String> =
+ (saved.filter { it in names } + names).distinct()
+
+internal fun renamedSectionOrder(order: List<String>, from: String, to: String?): List<String> =
+ if (from == to) order else order.mapNotNull { if (it != from) it else to?.takeUnless(order::contains) }
+
+internal object SectionOrders {
+ fun key(account: String, computer: String): String = "sectionOrder:$account:$computer"
+ private fun prefs(context: Context) = context.getSharedPreferences("codync-roster", Context.MODE_PRIVATE)
+ fun load(context: Context, key: String): List<String> = try {
+ Json.parseToJsonElement(prefs(context).getString(key, "[]") ?: "[]").jsonArray.map { it.jsonPrimitive.content }
+ } catch (_: IllegalArgumentException) { emptyList() } // A malformed local preference starts with the default order.
+ fun save(context: Context, key: String, names: List<String>) {
+ prefs(context).edit { putString(key, JsonArray(names.map(::JsonPrimitive)).toString()) }
+ }
+}
+
+/** Touch and hold a heading, then drag it past neighbors. Only a completed drop is saved. */
+internal class SectionReorder {
+ var names: List<String> = emptyList()
+ private var order by mutableStateOf<List<String>?>(null)
+ val shown: List<String> get() = order ?: names
+ var dragged by mutableStateOf<String?>(null)
+ private set
+ private var offset by mutableFloatStateOf(0f)
+ private var origin = 0f
+ val heights = mutableMapOf<String, Int>()
+ /** LazyColumn item offsets, before graphics transforms, so folding and scrolling don't move the held header. */
+ var position: (String) -> Float = { 0f }
+ var save: (List<String>) -> Unit = {}
+ private val handles = mutableMapOf<String, ContextDrag>()
+
+ fun translation(name: String): Float = if (dragged == name) origin + offset - position(name) else 0f
+
+ fun move(name: String, direction: Int) {
+ val ids = shown
+ val at = ids.indexOf(name)
+ if (at < 0 || at + direction !in ids.indices) return
+ val next = ids.toMutableList().apply { add(at + direction, removeAt(at)) }
+ if (dragged == null) save(next) else order = next
+ }
+
+ private fun finish(commit: Boolean) {
+ if (commit) order?.takeIf { it != names }?.let(save)
+ dragged = null
+ order = null
+ offset = 0f
+ }
+
+ fun handle(name: String): ContextDrag = handles.getOrPut(name) {
+ ContextDrag(start = { origin = position(name); order = names; dragged = name; offset = 0f }, move = { step ->
+ offset += step
+ val distance = translation(name)
+ val direction = if (distance > 0) 1 else -1
+ val next = shown.getOrNull(shown.indexOf(name) + direction)
+ val height = next?.let(heights::get)
+ if (height != null && kotlin.math.abs(distance) > height / 2f) move(name, direction)
+ }, end = { finish(true) }, cancel = { finish(false) })
+ }
+}
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
index e0371488..4e434db9 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt
@@ -25,6 +25,8 @@ 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.CustomAccessibilityAction
+import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
@@ -45,7 +47,8 @@ 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) {
+@Composable internal fun SectionHeader(header: RosterLine.Header, toggle: () -> Unit, actions: List<MenuItem>, modifier: Modifier = Modifier, drag: ContextDrag? = null, move: (Int) -> Unit = {}) {
+ val translate = translator()
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.
@@ -56,12 +59,13 @@ import com.codync.android.design.*
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 }
+ val tap = if (actions.isEmpty() && drag == null) Modifier.clickable(role = Role.Button, onClick = toggle)
+ else Modifier.contextActions(onClick = toggle, reorder = drag) { 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()
+ customActions = listOf(CustomAccessibilityAction(translate("Move up")) { move(-1); true }, CustomAccessibilityAction(translate("Move down")) { move(1); true })
stateDescription = state
contentDescription = spoken
}
@@ -81,8 +85,12 @@ import com.codync.android.design.*
}
/** 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),
+@Composable internal fun SectionLabel(modifier: Modifier = Modifier, drag: ContextDrag? = null, move: (Int) -> Unit = {}) {
+ val translate = translator()
+ Text(tr("Bots"), modifier.fillMaxWidth().padding(top = 14.dp, bottom = 2.dp).contextActions(reorder = drag) { emptyList() }.semantics {
+ heading()
+ customActions = listOf(CustomAccessibilityAction(translate("Move up")) { move(-1); true }, CustomAccessibilityAction(translate("Move down")) { move(1); true })
+ }.padding(vertical = 6.dp),
style = Type.footnote.semibold, color = Palette.secondary)
}
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
index ed2c5399..2059270d 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
@@ -33,20 +33,23 @@ internal sealed interface RosterLine {
* bots in roster order unless it's [folded]), then bots without a section, under [RosterLine.Label]
* when there are sections. A pinned bot shows only on top.
*/
-internal fun rosterLines(roster: List<Bot>, folded: Set<String>): List<RosterLine> = buildList {
+internal fun rosterLines(roster: List<Bot>, folded: Set<String>, order: List<String> = emptyList(), moving: Boolean = false): List<RosterLine> = buildList {
val (pinned, unpinned) = roster.partition { it.pinned }
val sections = unpinned.groupBy(Bot::section)
pinned.forEach { add(RosterLine.Row(it)) }
- val names = sectionNames(unpinned)
+ val custom = sectionNames(unpinned)
+ val names = orderedSections(custom + if (sections[null].isNullOrEmpty()) emptyList() else listOf(""), order)
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)) }
+ if (name.isEmpty()) {
+ if (custom.isNotEmpty()) add(RosterLine.Label)
+ if (!moving) sections[null].orEmpty().forEach { add(RosterLine.Row(it)) }
+ } else {
+ val bots = sections.getValue(name)
+ val header = RosterLine.Header(name, bots.size, bots.sumOf { it.unread }, moving || 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). */
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionOrderTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionOrderTest.kt
new file mode 100644
index 00000000..3d90de6d
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionOrderTest.kt
@@ -0,0 +1,69 @@
+package com.codync.android
+
+import com.codync.android.core.Bot
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class RosterSectionOrderTest {
+ @Test fun sectionsMoveAcrossBotsWithTheirRowsAndPinnedBotsStayFirst() {
+ val bots = listOf(Bot("pin", pinned = true), Bot("a", section = "Work"), Bot("b", section = "Work"), Bot("loose"))
+ fun shown(order: List<String>) = rosterLines(bots, emptySet(), order).filterIsInstance<RosterLine.Row>().map { it.bot.id }
+ assertEquals(listOf("pin", "loose", "a", "b"), shown(listOf("", "Work")))
+ assertEquals(listOf("pin", "a", "b", "loose"), shown(listOf("Work", "")))
+ assertEquals(listOf(RosterLine.Row(bots[0]), RosterLine.Label, RosterLine.Header("Work", 2, 0, true)),
+ rosterLines(bots, emptySet(), listOf("", "Work"), moving = true))
+ }
+ @Test fun aHeadingDragMovesBothWaysAcrossBots() {
+ val drag = SectionReorder()
+ drag.names = listOf("Work", "")
+ drag.heights[""] = 40
+ drag.heights["Work"] = 40
+ drag.position = { drag.shown.indexOf(it) * 40f }
+ drag.save = { drag.names = it }
+ val handle = drag.handle("Work")
+ handle.start()
+ handle.move(30f)
+ assertEquals(listOf("", "Work"), drag.shown)
+ handle.move(-40f)
+ assertEquals(listOf("Work", ""), drag.shown)
+ handle.end()
+ assertEquals(null, drag.dragged)
+ }
+ @Test fun foldingKeepsTheHeadingUnderTheFingerAndCancellationDiscardsMoves() {
+ val drag = SectionReorder()
+ drag.names = listOf("Home", "Work", "")
+ var top = 200f
+ drag.position = { top }
+ drag.heights[""] = 40
+ var saved = false
+ drag.save = { saved = true }
+ val handle = drag.handle("Work")
+ handle.start()
+ top = 80f
+ assertEquals(120f, drag.translation("Work"))
+ handle.move(30f)
+ assertEquals(listOf("Home", "", "Work"), drag.shown)
+ handle.cancel?.invoke()
+ assertEquals(false, saved)
+ assertEquals(drag.names, drag.shown)
+ }
+ @Test fun independentComputersHaveSeparatePreferenceKeys() {
+ val first = SectionOrders.key("account", "first")
+ val second = SectionOrders.key("account", "second")
+ val orders = mapOf(first to listOf("Work", ""), second to listOf("", "Work"))
+ assertEquals(listOf("Work", ""), orders[first])
+ assertEquals(listOf("", "Work"), orders[second])
+ }
+ @Test fun mergingIntoANewGroupKeepsItsCurrentPlace() {
+ val displayed = orderedSections(listOf("Home", "Work", ""), listOf("Work", ""))
+ assertEquals(listOf("", "Home"), renamedSectionOrder(displayed, "Work", "Home"))
+ }
+ @Test fun savedOrderIgnoresAbsentNamesAndAppendsNewGroupsOnce() {
+ assertEquals(listOf("Work", "", "Home"), orderedSections(listOf("Home", "Work", ""), listOf("Work", "missing", "", "Work")))
+ }
+ @Test fun renameKeepsItsPlaceAndMergeKeepsDestinationPlace() {
+ assertEquals(listOf("Work", ""), renamedSectionOrder(listOf("Work", ""), "Work", "Work"))
+ assertEquals(listOf("Play", "", "Home"), renamedSectionOrder(listOf("Work", "", "Home"), "Work", "Play"))
+ assertEquals(listOf("", "Home"), renamedSectionOrder(listOf("Work", "", "Home"), "Work", "Home"))
+ }
+}
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 a38a20c0..3f7c6e1d 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
@@ -104,7 +104,7 @@ class ReactionPick(val emoji: List<String>, val chosen: List<String>, val toggle
}
/** Long-press then move: the row leaves its menu and follows the finger, as iOS list rows reorder. */
-class ContextDrag(val start: () -> Unit, val move: (Float) -> Unit, val end: () -> Unit)
+class ContextDrag(val start: () -> Unit, val move: (Float) -> Unit, val end: () -> Unit, val cancel: (() -> Unit)? = null)
/**
* Long-press opens the menu under a lifted copy of the content; `reactions` adds the emoji row.
@@ -141,15 +141,16 @@ class ContextDrag(val start: () -> Unit, val move: (Float) -> Unit, val end: ()
var moved = 0f
var started = false
// finally: a cancelled gesture (the row left the list, the handler restarted) still ends the drag.
+ var completed = false
try {
- drag(held.id) { change ->
+ completed = 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) { if (completed) reorder.end() else (reorder.cancel ?: reorder.end)() }
}
}
}
diff --git a/apps/desktop/src/renderer/lib/prefs.ts b/apps/desktop/src/renderer/lib/prefs.ts
index 4d222f59..9a32661e 100644
--- a/apps/desktop/src/renderer/lib/prefs.ts
+++ b/apps/desktop/src/renderer/lib/prefs.ts
@@ -62,6 +62,7 @@ export const prefs = {
computerOrder: pref<string[]>('computerOrder', []),
collapsedComputers: pref<string[]>('collapsedComputerSections', []),
/** Folded roster sections, by name: on this device only. */
+ rosterSectionOrder: pref<Record<string, string[]>>('rosterSectionOrder', {}),
collapsedRosterSections: pref<string[]>('collapsedRosterSections', []),
usageIconStyle: pref<'character' | 'original'>('usageIconStyle', 'character'),
onboardingDone: pref('macAccountOnboardingCompleted', false),
diff --git a/apps/desktop/src/renderer/lib/roster-section-order.test.ts b/apps/desktop/src/renderer/lib/roster-section-order.test.ts
new file mode 100644
index 00000000..f2cac4c3
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/roster-section-order.test.ts
@@ -0,0 +1,31 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { moveInOrder } from './computer-roster.ts'
+import { orderedSections, renamedSectionOrder } from './roster-section-order.ts'
+import { rosterGroups, rosterLines, shownRows } from './roster-sections.ts'
+
+test('whole sections move both ways across Bots while pinned rows stay first and navigation follows', () => {
+ const item = (id: string, section?: string, pinned = false) => ({ bot: { id, section, pinned, unread: 0 } })
+ const items = [item('pin', 'Work', true), item('a', 'Work'), item('b', 'Work'), item('loose')]
+ const order = moveInOrder(['Work', ''], 'Work', '')
+ assert.deepEqual(shownRows(rosterLines(items, [], order)).map((i) => i.bot.id), ['pin', 'loose', 'a', 'b'])
+ assert.deepEqual(shownRows(rosterLines(items, [], moveInOrder(order, 'Work', ''))).map((i) => i.bot.id), ['pin', 'a', 'b', 'loose'])
+ assert.deepEqual(shownRows(rosterLines(items, ['Work'], order)).map((i) => i.bot.id), ['pin', 'loose'])
+})
+
+test('saved order ignores absent groups and appends new groups once', () => {
+ assert.deepEqual(orderedSections(['Home', 'Work', ''], ['Work', 'missing', '', 'Work']), ['Work', '', 'Home'])
+})
+
+test('renaming keeps position and merging keeps the destination position', () => {
+ assert.deepEqual(renamedSectionOrder(['Work', '', 'Home'], 'Work', 'Play'), ['Play', '', 'Home'])
+ assert.deepEqual(renamedSectionOrder(['Work', '', 'Home'], 'Work', 'Home'), ['', 'Home'])
+ assert.deepEqual(renamedSectionOrder(['Work', ''], 'Work', null), [''])
+ assert.deepEqual(renamedSectionOrder(['Work', ''], 'Work', 'Work'), ['Work', ''])
+})
+
+test('merge into a newly created group keeps the destination in its displayed position', () => {
+ const bots = [{ section: 'Work' }, {}, { section: 'Home' }].map((bot) => ({ bot: { ...bot, pinned: false, unread: 0 } }))
+ const displayed = rosterGroups(bots, [], ['Work', '']).map((group) => group.name)
+ assert.deepEqual(renamedSectionOrder(displayed, 'Work', 'Home'), ['', 'Home'])
+})
diff --git a/apps/desktop/src/renderer/lib/roster-section-order.ts b/apps/desktop/src/renderer/lib/roster-section-order.ts
new file mode 100644
index 00000000..3587f02d
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/roster-section-order.ts
@@ -0,0 +1,10 @@
+/** Device-local section order. The empty name stands for the unsectioned Bots group. */
+export function orderedSections(names: readonly string[], saved: readonly string[] = []): string[] {
+ return [...new Set([...saved.filter((name) => names.includes(name)), ...names])]
+}
+
+/** Keep a renamed section in its place; a merge keeps the destination's existing place. */
+export function renamedSectionOrder(order: readonly string[], from: string, to: string | null): string[] {
+ if (from === to) return [...order]
+ return order.flatMap((name) => name !== from ? [name] : to === null || order.includes(to) ? [] : [to])
+}
diff --git a/apps/desktop/src/renderer/lib/roster-sections.ts b/apps/desktop/src/renderer/lib/roster-sections.ts
index c8c8bc23..c38b6910 100644
--- a/apps/desktop/src/renderer/lib/roster-sections.ts
+++ b/apps/desktop/src/renderer/lib/roster-sections.ts
@@ -1,4 +1,5 @@
import { isBelow } from '../../shared/compat.ts'
+import { orderedSections } from './roster-section-order.ts'
import { rosterBand } from './computer-roster.ts'
/** The first host with roster sections. */
@@ -28,17 +29,22 @@ export type RosterLine<T> =
* sections. A pinned bot shows 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>[] {
+export function rosterLines<T extends { bot: Placed }>(items: T[], folded: readonly string[], order: readonly string[] = []): RosterLine<T>[] {
const row = (item: T): RosterLine<T> => ({ kind: 'row', item })
+ const groups = rosterGroups(items, folded, order)
+ const labeled = groups.some((group) => group.name !== '')
+ return [...items.filter((item) => item.bot.pinned).map(row), ...groups.flatMap((group): RosterLine<T>[] =>
+ group.name !== '' ? [group] : [...(labeled ? [{ kind: 'label' } as const] : []), ...group.items.map(row)])]
+}
+
+/** The same whole groups for rendering, keyboard navigation, dragging, and renaming. */
+export function rosterGroups<T extends { bot: Placed }>(items: T[], folded: readonly string[], order: readonly string[] = []): Extract<RosterLine<T>, { kind: 'section' }>[] {
const unpinned = items.filter((item) => !item.bot.pinned)
- 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 names = [...sectionNames(unpinned.map((item) => item.bot)), ...(unpinned.some((item) => !item.bot.section) ? [''] : [])]
+ return orderedSections(names, order).map((name) => {
+ const rows = unpinned.filter((item) => (item.bot.section ?? '') === name)
+ return { kind: 'section', name, count: rows.length, unread: rows.reduce((sum, item) => sum + item.bot.unread, 0), folded: name !== '' && 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) => item.bot.pinned).map(row), ...sections, ...label, ...loose]
}
/** The rows on screen, top to bottom: a folded section's rows are left out. */
diff --git a/apps/desktop/src/renderer/store/computer-roster.ts b/apps/desktop/src/renderer/store/computer-roster.ts
index be8eedef..ef9f770d 100644
--- a/apps/desktop/src/renderer/store/computer-roster.ts
+++ b/apps/desktop/src/renderer/store/computer-roster.ts
@@ -1,7 +1,8 @@
import { computerSections, moveInOrder, orderedComputers } from '../lib/computer-roster'
+import { renamedSectionOrder } from '../lib/roster-section-order'
import { prefs, usePref } from '../lib/prefs'
import { useModel } from '../lib/observable'
-import { foldsAfterRename, rosterLines, sameRosterGroup, sectionRename, shownRows, shownSection } from '../lib/roster-sections'
+import { foldsAfterRename, rosterGroups, rosterLines, sameRosterGroup, sectionRename, shownRows, shownSection } from '../lib/roster-sections'
import type { BotStore } from './bot-store'
import type { AppModel, BotRef } from './app-model'
@@ -9,6 +10,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 [sectionOrders, setSectionOrders] = usePref(prefs.rosterSectionOrder)
const [folded, setFolded] = usePref(prefs.collapsedRosterSections)
const computers = orderedComputers(app.computers, order)
const sections = computerSections(computers.filter((c) => shown.has(c.id)), app.roster)
@@ -20,9 +22,13 @@ export function useComputerRoster(app: AppModel, shown: Set<string>) {
grouped,
collapsed,
folded,
+ sectionOrders,
+ orderSections(computerId: string, names: string[]) {
+ setSectionOrders({ ...prefs.rosterSectionOrder.get(), [computerId]: names })
+ },
items: sections.flatMap((section) => 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))),
+ navigable: sections.flatMap((section) => grouped && collapsed.includes(section.computer.id) ? [] : shownRows(rosterLines(section.items, folded, sectionOrders[section.computer.id]))),
toggle(id: string) {
setCollapsed(toggled(collapsed, id))
},
@@ -32,12 +38,19 @@ export function useComputerRoster(app: AppModel, shown: Set<string>) {
},
/** 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) {
+ const orders = prefs.rosterSectionOrder.get()
+ const oldOrder = orders[store.computer.id] ?? []
+ const displayed = rosterGroups(store.roster.map((bot) => ({ bot })), [], oldOrder).map((group) => group.name)
+ const newOrder = renamedSectionOrder(displayed, from, sectionRename(from, to).to)
+ setSectionOrders({ ...orders, [store.computer.id]: newOrder })
// 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, () => {
+ const current = prefs.rosterSectionOrder.get()
+ if (current[store.computer.id] === newOrder) setSectionOrders({ ...current, [store.computer.id]: oldOrder })
if (prefs.collapsedRosterSections.get() === after) setFolded(before)
})
},
diff --git a/apps/desktop/src/renderer/views/BotRoster.tsx b/apps/desktop/src/renderer/views/BotRoster.tsx
index af922ae5..f22321a9 100644
--- a/apps/desktop/src/renderer/views/BotRoster.tsx
+++ b/apps/desktop/src/renderer/views/BotRoster.tsx
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
import { isGroup, type Bot } from '@shared/models'
import { moveInOrder } from '../lib/computer-roster'
import { pointerDrag, type Point } from '../lib/pointer-drag'
-import { rosterLines, sameRosterGroup } from '../lib/roster-sections'
+import { sameRosterGroup } from '../lib/roster-sections'
import { reduceMotion } from '../lib/theme'
import { useSlide } from '../lib/slide'
import { sameRef, refKey, type RosterItem } from '../store/app-model'
@@ -12,7 +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 { SectionRoster } from './SectionRoster'
import { UpdateNeededCard } from './UpdateNeededCard'
/** A bot being dragged among its computer's bots, and the order it has made so far. */
@@ -213,12 +213,10 @@ export function BotRoster({ roster, compact, onContext, onSectionContext, openEx
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 = 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>
- ))
+ const rows = <SectionRoster computerId={computer.id} items={ordered(computer.id, items)} compact={compact}
+ folded={roster.folded} order={roster.sectionOrders[computer.id] ?? []}
+ save={(names) => roster.orderSections(computer.id, names)} toggle={roster.toggleFold}
+ onContext={(name, x, y) => onSectionContext(name, store, x, y)} row={(item) => row(item, items)} />
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/RosterSection.tsx b/apps/desktop/src/renderer/views/RosterSection.tsx
index a68d53aa..464a653a 100644
--- a/apps/desktop/src/renderer/views/RosterSection.tsx
+++ b/apps/desktop/src/renderer/views/RosterSection.tsx
@@ -3,6 +3,7 @@ import { Icon } from '../components/Icon'
import { HStack } from '../components/Stack'
import { Text } from '../components/Text'
import { useSlide } from '../lib/slide'
+import type { pointerDrag } from '../lib/pointer-drag'
import { useTr } from '../lib/use-language'
import './computer-roster.css'
@@ -15,16 +16,20 @@ interface Props {
compact: boolean
toggle: () => void
onContext: (x: number, y: number) => void
+ drag?: ReturnType<typeof pointerDrag>
+ move?: (offset: 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) {
+export function RosterSection({ name, count, unread, folded, compact, toggle, onContext, drag, move, 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}
+ <button data-section-heading className="roster-section-toggle" {...drag} onKeyDown={(e) => {
+ if (e.altKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) { e.preventDefault(); e.stopPropagation(); move?.(e.key === 'ArrowUp' ? -1 : 1) }
+ }} aria-expanded={!folded} aria-label={name} title={name} onClick={toggle}
onContextMenu={(e) => {
e.preventDefault()
onContext(e.clientX, e.clientY)
@@ -45,10 +50,14 @@ export function RosterSection({ name, count, unread, folded, compact, toggle, on
/** 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 }) {
+export function RosterLabel({ compact, drag, move }: { compact: boolean; drag?: ReturnType<typeof pointerDrag>; move?: (offset: number) => void }) {
const tr = useTr()
- const label = useRef<HTMLDivElement>(null)
+ const label = useRef<HTMLButtonElement>(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>
+ return <button ref={label} data-section-heading className="roster-label" {...drag} aria-label={tr('Bots')}
+ onKeyDown={(e) => {
+ if (e.altKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) { e.preventDefault(); e.stopPropagation(); move?.(e.key === 'ArrowUp' ? -1 : 1) }
+ }}>
+ {!compact ? <Text as="span" size="caption" weight="semibold" tone="secondary">{tr('Bots')}</Text> : null}
+ </button>
}
diff --git a/apps/desktop/src/renderer/views/SectionRoster.tsx b/apps/desktop/src/renderer/views/SectionRoster.tsx
new file mode 100644
index 00000000..13df1658
--- /dev/null
+++ b/apps/desktop/src/renderer/views/SectionRoster.tsx
@@ -0,0 +1,87 @@
+import { useRef, useState, type ReactNode } from 'react'
+import { createPortal } from 'react-dom'
+import { moveInOrder } from '../lib/computer-roster'
+import { pointerDrag, type Point } from '../lib/pointer-drag'
+import { rosterGroups } from '../lib/roster-sections'
+import { useSlide } from '../lib/slide'
+import type { RosterItem } from '../store/app-model'
+import { RosterLabel, RosterSection } from './RosterSection'
+
+interface Drag { name: string; order: string[]; at: Point; grab: Point; width: number }
+
+/** Sections move as blocks within one computer, including the unsectioned Bots group. */
+export function SectionRoster({ computerId, items, compact, folded, order, save, toggle, onContext, row }: {
+ computerId: string
+ items: RosterItem[]
+ compact: boolean
+ folded: string[]
+ order: string[]
+ save: (names: string[]) => void
+ toggle: (name: string) => void
+ onContext: (name: string, x: number, y: number) => void
+ row: (item: RosterItem) => ReactNode
+}) {
+ const [drag, setDrag] = useState<Drag | null>(null)
+ const current = useRef<Drag | null>(null)
+ const container = useRef<HTMLDivElement>(null)
+ const ghost = useRef<HTMLDivElement>(null)
+ const groups = rosterGroups(items, folded, order)
+ const byName = new Map(groups.map((group) => [group.name, group]))
+ const custom = groups.some((group) => group.name !== '')
+ const names = groups.map((group) => group.name)
+ const shown = drag?.order ?? names
+ const update = (next: Drag | null) => { current.current = next; setDrag(next) }
+ const heading = (name: string) => [...container.current?.querySelectorAll<HTMLElement>('[data-roster-group]') ?? []]
+ .find((element) => element.dataset.rosterGroup === name)?.querySelector<HTMLElement>('[data-section-heading]')
+ const move = (name: string, offset: number) => {
+ const target = names[names.indexOf(name) + offset]
+ if (target !== undefined) save(moveInOrder(names, name, target))
+ }
+ const handlers = (name: string) => pointerDrag({
+ start(at) {
+ const box = heading(name)?.getBoundingClientRect()
+ if (box) update({ name, order: names, at, grab: { x: at.x - box.left, y: at.y - box.top }, width: box.width })
+ },
+ over(at, under) {
+ const held = current.current
+ if (!held) return
+ if (ghost.current) ghost.current.style.translate = `${at.x - held.grab.x}px ${at.y - held.grab.y}px`
+ const target = under?.closest<HTMLElement>('[data-roster-group]')
+ if (!target || !container.current?.contains(target) || target.getAnimations().length) return
+ const name = target.dataset.rosterGroup!
+ if (name !== held.name) update({ ...held, at, order: moveInOrder(held.order, held.name, name) })
+ },
+ drop() { if (current.current) save(current.current.order); update(null) },
+ cancel() { update(null) },
+ })
+ const label = (name: string, preview = false) => {
+ const group = byName.get(name)
+ if (!group) return null
+ const props = preview ? {} : { drag: handlers(name), move: (offset: number) => move(name, offset) }
+ return name === '' ? <RosterLabel compact={compact} {...props} /> : <RosterSection name={name} count={group.count}
+ unread={group.unread} compact={compact}
+ folded={drag !== null || folded.includes(name)} toggle={() => toggle(name)}
+ onContext={(x, y) => onContext(name, x, y)} {...props}>
+ {preview ? null : group.items.map(row)}
+ </RosterSection>
+ }
+ return <div ref={container} data-section-computer={computerId}>
+ {items.filter((item) => item.bot.pinned).map(row)}
+ {shown.map((name) => <SectionBlock key={name} name={name} lifted={drag?.name === name}>
+ {name === '' && !custom ? null : label(name)}
+ {name === '' ? <div className={`computer-roster-content ${drag ? 'collapsed' : ''}`} inert={drag !== null} aria-hidden={drag !== null}>
+ <div>{byName.get('')?.items.map(row)}</div>
+ </div> : null}
+ </SectionBlock>)}
+ {drag ? createPortal(<div ref={ghost} className="roster-ghost" style={{ width: drag.width,
+ translate: `${drag.at.x - drag.grab.x}px ${drag.at.y - drag.grab.y}px` }}>
+ <div className="roster-ghost-card">{label(drag.name, true)}</div>
+ </div>, document.body) : null}
+ </div>
+}
+
+function SectionBlock({ name, lifted, children }: { name: string; lifted: boolean; children: ReactNode }) {
+ const ref = useRef<HTMLDivElement>(null)
+ useSlide(ref)
+ return <div ref={ref} data-roster-group={name} className={`computer-roster-section ${lifted ? 'lifted' : ''}`}>{children}</div>
+}
diff --git a/apps/desktop/src/renderer/views/computer-roster.css b/apps/desktop/src/renderer/views/computer-roster.css
index 736dc69b..de6a5561 100644
--- a/apps/desktop/src/renderer/views/computer-roster.css
+++ b/apps/desktop/src/renderer/views/computer-roster.css
@@ -126,3 +126,7 @@
padding: 4px 0;
gap: 2px;
}
+
+.roster-section-toggle,
+button.roster-label { cursor: grab; }
+.pointer-dragging .roster-section-toggle:hover { background: none; }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift
index 883363dc..a715aaad 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/RosterSection.swift
@@ -75,7 +75,7 @@ public struct RosterSection: Sendable {
/// each section by name with its bots (none while folded), then the bots in no section, under the
/// "Bots" label when there are sections. A pinned bot shows only on top, whatever its section;
/// every part keeps the roster's order.
- public static func lines<Item>(_ roster: [Item], folded: Set<String>, bot: (Item) -> Bot) -> [RosterSectionLine<Item>] {
+ public static func lines<Item>(_ roster: [Item], folded: Set<String>, order: [String] = [], bot: (Item) -> Bot) -> [RosterSectionLine<Item>] {
var pinned: [Item] = [], loose: [Item] = [], bySection: [String: [Item]] = [:]
for item in roster {
let placed = bot(item)
@@ -88,15 +88,21 @@ public struct RosterSection: Sendable {
}
}
var lines = pinned.map { RosterSectionLine.bot($0) }
- for name in sorted(bySection.keys) {
+ let available = sorted(bySection.keys) + (loose.isEmpty ? [] : [""])
+ let names = ComputerOrder(ids: order).orderedIDs(available)
+ for name in names {
+ if name.isEmpty {
+ if !bySection.isEmpty { lines.append(.label) }
+ lines += loose.map { RosterSectionLine.bot($0) }
+ continue
+ }
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) }
+ return lines
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/RosterSectionOrder.swift b/apps/ios/Kit/Sources/CodyncUI/Store/RosterSectionOrder.swift
new file mode 100644
index 00000000..658352af
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/RosterSectionOrder.swift
@@ -0,0 +1,30 @@
+import CodyncKit
+import Foundation
+
+/// This device's section order per computer. The empty name stands for the unsectioned Bots group.
+public struct RosterSectionOrder: Codable, Sendable {
+ private var computers: [ComputerID: [String]] = [:]
+
+ public init(data: Data) {
+ self = (try? JSONDecoder().decode(Self.self, from: data)) ?? Self()
+ }
+
+ private init() {}
+
+ public var data: Data { (try? JSONEncoder().encode(self)) ?? Data() }
+
+ public func saved(on computer: ComputerID) -> [String] { computers[computer] ?? [] }
+
+ public mutating func set(_ names: [String], on computer: ComputerID) {
+ computers[computer] = names
+ }
+
+ public mutating func rename(_ from: String, to: String?, on computer: ComputerID) {
+ guard from != to else { return }
+ let order = computers[computer] ?? []
+ computers[computer] = order.compactMap { name in
+ guard name == from else { return name }
+ return to.flatMap { order.contains($0) ? nil : $0 }
+ }
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/RosterSectionOrderTests.swift b/apps/ios/Kit/Tests/CodyncUITests/RosterSectionOrderTests.swift
new file mode 100644
index 00000000..3a380c52
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/RosterSectionOrderTests.swift
@@ -0,0 +1,40 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+@testable import CodyncUI
+
+@Test func sectionOrderPersistsPerComputerAndKeepsRenamesInPlace() {
+ var order = RosterSectionOrder(data: Data())
+ order.set(["", "Work", "Home"], on: "mac")
+ order.set(["Home", "Work", ""], on: "other")
+ order.rename("Work", to: "Work", on: "mac")
+ order = RosterSectionOrder(data: order.data)
+ #expect(order.saved(on: "mac") == ["", "Work", "Home"])
+ #expect(order.saved(on: "other") == ["Home", "Work", ""])
+ order.rename("Work", to: "Play", on: "mac")
+ #expect(order.saved(on: "mac") == ["", "Play", "Home"])
+ order.rename("Play", to: "Home", on: "mac")
+ #expect(order.saved(on: "mac") == ["", "Home"])
+}
+
+@Test func sectionsMoveAcrossBotsWithoutMovingPinnedBots() throws {
+ let bots = try [#"{"id":"pin","pinned":true}"#, #"{"id":"a","section":"Work"}"#, #"{"id":"b","section":"Work"}"#, #"{"id":"loose"}"#]
+ .map { try JSONDecoder().decode(Bot.self, from: Data($0.utf8)) }
+ func shown(_ names: [String], folded: Set<String> = []) -> [String] {
+ RosterSection.lines(bots, folded: folded, order: names) { $0 }.compactMap {
+ if case let .bot(bot) = $0 { bot.id } else { nil }
+ }
+ }
+ #expect(shown(["", "Work"]) == ["pin", "loose", "a", "b"])
+ #expect(shown(["Work", ""]) == ["pin", "a", "b", "loose"])
+ #expect(shown(["", "Work"], folded: ["Work"]) == ["pin", "loose"])
+}
+
+@Test func mergingIntoANewGroupKeepsItsDisplayedPosition() {
+ var order = RosterSectionOrder(data: Data())
+ order.set(["Work", ""], on: "mac")
+ let displayed = ComputerOrder(ids: order.saved(on: "mac")).orderedIDs(["Home", "Work", ""])
+ order.set(displayed, on: "mac")
+ order.rename("Work", to: "Home", on: "mac")
+ #expect(order.saved(on: "mac") == ["", "Home"])
+}
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index 4c50b238..442bf5f1 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -27,6 +27,12 @@ struct BotListView: View {
// ponytail: one name folds that section on every computer; key it by computer if they must fold apart.
@AppStorage("collapsedRosterSections") private var collapsedRosterSections = ""
+ @AppStorage("rosterSectionOrder") private var sectionOrderData = Data()
+ private var sectionOrder: RosterSectionOrder {
+ get { RosterSectionOrder(data: sectionOrderData) }
+ nonmutating set { sectionOrderData = newValue.data }
+ }
+
private var collapsedIDs: Set<ComputerID> { Set(collapsedComputers.split(separator: ",").map(String.init)) }
private func toggleCollapsed(_ id: ComputerID) {
@@ -52,10 +58,17 @@ struct BotListView: View {
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 orderBefore = sectionOrderData
+ var renamedOrder = sectionOrder
+ renamedOrder.set(sectionLines(store).compactMap { $0.sectionName(on: store.computer.id) }, on: store.computer.id)
+ renamedOrder.rename(name, to: newName, on: store.computer.id)
+ sectionOrder = renamedOrder
+ let orderAfter = sectionOrderData
let before = foldedSections
let moved = RosterSection.folds(before, renaming: name, to: newName)
foldedSections = moved
if await store.renameSection(from: name, to: newName) { return }
+ if sectionOrderData == orderAfter { sectionOrderData = orderBefore }
foldedSections = RosterSection.folds(foldedSections, refused: moved, before: before)
}
}
@@ -104,7 +117,7 @@ struct BotListView: View {
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
+ return RosterSection.lines(items, folded: foldedSections, order: sectionOrder.saved(on: id)) { $0.bot }.map { line -> RosterLine in
switch line {
case let .header(section): .section(section, id, store)
case .label: .label(id)
@@ -117,6 +130,7 @@ struct BotListView: View {
let roster = accounts.roster.filter { shownIDs.contains($0.ref.computerId) }
let lines = self.lines
let movingComputer = lines.contains { $0.id == lifted && $0.computerId != nil }
+ let movingSection = lines.first { $0.id == lifted }?.sectionComputer
List {
Group {
// A newer app release (dismissible; everything still works). Computers update
@@ -138,12 +152,18 @@ struct BotListView: View {
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) }
+ if movingComputer { Color.clear.frame(height: 0) } else {
+ RosterBotsLabel().itemProvider { lift(line) }
+ .accessibilityActions {
+ Button(L10n.tr("Move up")) { moveSection(line, by: -1) }
+ Button(L10n.tr("Move down")) { moveSection(line, by: 1) }
+ }
+ }
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
// the list, and the system then drops the drag.
- if movingComputer { Color.clear.frame(height: 0) } else { row(item, store: store) }
+ if movingComputer || movingSection == item.ref.computerId { Color.clear.frame(height: 0) } else { row(item, store: store) }
}
}
.onMove(perform: moveLines)
@@ -236,7 +256,7 @@ 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 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.
+ /// another computer), it goes first or last of its own. Section headings and the Bots label move as groups on this device.
private func moveLines(from source: IndexSet, to destination: Int) {
let before = lines
guard let from = source.first, before.indices.contains(from) else { return }
@@ -250,7 +270,9 @@ struct BotListView: View {
case let .bot(item, store):
store.drop(item.bot.id, in: after.compactMap { $0.botId(on: item.ref.computerId) })
case .section, .label:
- break
+ guard let computer = before[from].sectionComputer else { return }
+ let names = after.compactMap { $0.sectionName(on: computer) }
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { sectionOrder.set(names, on: computer) }
}
}
@@ -281,8 +303,13 @@ struct BotListView: View {
/// 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)
+ let header = RosterSectionHeader(section: section, hasMenu: store.supportsSections, toggle: { toggleSection(section.name) },
+ moving: lines.first { $0.id == lifted }?.sectionComputer == store.computer.id)
+ .itemProvider { lift(.section(section, store.computer.id, store)) }
+ .accessibilityActions {
+ Button(L10n.tr("Move up")) { moveSection(.section(section, store.computer.id, store), by: -1) }
+ Button(L10n.tr("Move down")) { moveSection(.section(section, store.computer.id, store), by: 1) }
+ }
if store.supportsSections {
header.contextActions {
[
@@ -299,6 +326,14 @@ struct BotListView: View {
}
}
+ private func moveSection(_ line: RosterLine, by offset: Int) {
+ guard let computer = line.sectionComputer, let name = line.sectionName(on: computer) else { return }
+ var names = lines.compactMap { $0.sectionName(on: computer) }
+ guard let from = names.firstIndex(of: name), names.indices.contains(from + offset) else { return }
+ names.swapAt(from, from + offset)
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { sectionOrder.set(names, on: computer) }
+ }
+
private func row(_ item: RosterItem, store: BotStore) -> some View {
let bot = item.bot
let line = RosterLine.bot(item, store)
@@ -364,7 +399,7 @@ struct BotListView: View {
/// A heading folds the bots away and back with an animation.
private func lift(_ line: RosterLine) -> NSItemProvider {
let id = line.id
- let animation = line.computerId != nil ? Motion.reduced(Motion.layout, reduceMotion) : nil
+ let animation = (line.computerId != nil || line.sectionComputer != nil) ? Motion.reduced(Motion.layout, reduceMotion) : nil
withAnimation(animation) { lifted = id }
return LiftItem { Task { @MainActor in if lifted == id { withAnimation(animation) { lifted = nil } } } }
}
diff --git a/apps/ios/Views/BotRosterLine.swift b/apps/ios/Views/BotRosterLine.swift
index ff0512ea..0a0d88f6 100644
--- a/apps/ios/Views/BotRosterLine.swift
+++ b/apps/ios/Views/BotRosterLine.swift
@@ -37,6 +37,22 @@ enum RosterLine: Identifiable {
if case let .computer(id, _) = self { id } else { nil }
}
+ var sectionComputer: ComputerID? {
+ switch self {
+ case let .section(_, id, _), let .label(id): id
+ default: nil
+ }
+ }
+
+ func sectionName(on computer: ComputerID) -> String? {
+ guard sectionComputer == computer else { return nil }
+ return switch self {
+ case let .section(section, _, _): section.name
+ case .label: ""
+ default: nil
+ }
+ }
+
func botId(on computerId: ComputerID) -> String? {
if case let .bot(item, _) = self, item.ref.computerId == computerId { item.bot.id } else { nil }
}
diff --git a/apps/ios/Views/RosterSectionHeader.swift b/apps/ios/Views/RosterSectionHeader.swift
index 68bcfe84..081815f6 100644
--- a/apps/ios/Views/RosterSectionHeader.swift
+++ b/apps/ios/Views/RosterSectionHeader.swift
@@ -10,9 +10,10 @@ struct RosterSectionHeader: View {
/// Whether touch and hold opens its menu (rename, remove): not on a computer without sections.
let hasMenu: Bool
let toggle: () -> Void
+ var moving = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- private var showsUnread: Bool { section.folded && section.unread > 0 }
+ private var showsUnread: Bool { (section.folded || moving) && section.unread > 0 }
var body: some View {
HStack(spacing: 6) {
@@ -35,7 +36,7 @@ struct RosterSectionHeader: View {
Image(systemName: "chevron.down")
.font(.caption.weight(.semibold))
.foregroundStyle(Palette.tertiary)
- .rotationEffect(.degrees(section.folded ? -90 : 0))
+ .rotationEffect(.degrees((section.folded || moving) ? -90 : 0))
.accessibilityHidden(true)
}
// `ComputerSection`'s 14 + 6 points above and 2 + 6 below: about 46 points to tap.
@@ -46,10 +47,10 @@ struct RosterSectionHeader: View {
.accessibilityElement(children: .ignore)
.accessibilityAddTraits([.isHeader, .isButton])
.accessibilityLabel(spoken)
- .accessibilityValue(section.folded ? L10n.tr("Collapsed") : L10n.tr("Expanded"))
+ .accessibilityValue((section.folded || moving) ? 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(named: (section.folded || moving) ? L10n.tr("Expand") : L10n.tr("Collapse"), toggle)
.accessibilityAction(.default) { toggle() }
}
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 5300ae0c..b5813cb9 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -46,7 +46,7 @@ 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 gets no heading. Inside each computer,
-the lead bot comes first, then pinned rows, then foldable section headers sorted by name (name,
+the lead bot comes first, then pinned rows, then foldable section headers in device-local order, initially 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
@@ -184,3 +184,5 @@ disabling security checks. Distributed builds still require Developer ID signing
Composer keyboard behavior, animation and durable draft storage, with a host-free
regression fixture: [composer checks](../guides/composer.md).
+
+Section headings and the unsectioned Bots group also drag up or down within their computer. Alt+Up/Down on a focused heading moves it one place. Dragging folds the groups temporarily; cancelling restores the order, and dropping saves it per computer on this device.
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 8c5d1112..1d10daee 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)). 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.
+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 and the plain "Bots" group in device-local order after pinned bots (initially sections sorted by name, then Bots). 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`.
@@ -278,3 +278,5 @@ The terminal's `Ctrl+K` actions offer the same three choices, saved in the local
`tui-appearance` file. System retains the terminal's foreground/background and
uses `COLORFGBG` for accent contrast. `CODYNC_THEME` supplies the initial choice
when none is saved; `NO_COLOR` continues to disable color output.
+
+Roster section headings and the Bots label move whole groups within a computer: drag on desktop, touch and hold then drag on phones. Section order is per computer and per device. Pinned bots remain above all groups. Terminal Alt+Up/Down moves the selected bot's group for that run.
diff --git a/docs/features/computer-order.md b/docs/features/computer-order.md
index a2842e97..55371000 100644
--- a/docs/features/computer-order.md
+++ b/docs/features/computer-order.md
@@ -53,7 +53,7 @@ A bot or group chat can be in one section, a name the user picks (`section`, set
`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
+in device-local order, initially 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
@@ -71,10 +71,10 @@ nothing), while a rename made on another device arrives unfolded.
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 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.
+ drop saves the order (`BotListView.moveLines`, `BotStore.drop`). Dragging a section heading or the Bots label moves that whole group within its computer; each device keeps this order.
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).
+- **Desktop:** drag a row, or Alt+Up/Down on the selected bot (macOS, Linux, Windows). Drag section headings or the Bots label to move whole groups; Alt+Up/Down on a focused heading does the same.
- **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).
+ unfolds it (in the compact strip a click on a folded section unfolds it). Alt+Up/Down moves the selected bot's whole section, including Bots; section order lasts until quitting.
diff --git a/docs/plans/roster-sections.md b/docs/plans/roster-sections.md
index 5b5580bf..c29366aa 100644
--- a/docs/plans/roster-sections.md
+++ b/docs/plans/roster-sections.md
@@ -19,9 +19,9 @@ Bots a plain label (no fold, count or menu), only when th
```
- 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
+- **Order:** the lead bot, then pinned rows, then sections in device-local drag order (initially 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
+ rows without a section initially come last, under a "Bots" label that can also move. 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
@@ -36,7 +36,7 @@ Bots a plain label (no fold, count or menu), only when th
- 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
+Not in this change: dropping a bot onto a section by drag, nested
sections.
## Host
@@ -93,3 +93,5 @@ This change bumps every version file to 2.32.0, the first host with sections, an
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`.
+
+Section headings and the unsectioned Bots group can be reordered on each device, independently per computer. A rename keeps its place; a merge keeps the destination's place. Pinned bots stay on top. Terminal Alt+↑/↓ moves the selected bot's group for that terminal session.
diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rs
index 9e5fe274..a2b97004 100644
--- a/host/src/tui/app/input.rs
+++ b/host/src/tui/app/input.rs
@@ -200,6 +200,8 @@ impl App {
KeyCode::Char('u') => self.jump(Mark::Unread),
KeyCode::Char('[') => self.move_bot(-1),
KeyCode::Char(']') => self.move_bot(1),
+ KeyCode::Up if k.modifiers.contains(KeyModifiers::ALT) => self.move_section(-1),
+ KeyCode::Down if k.modifiers.contains(KeyModifiers::ALT) => self.move_section(1),
KeyCode::Char('K') => self.reorder_bot(-1),
KeyCode::Char('J') => self.reorder_bot(1),
KeyCode::Char(c @ '1'..='9') => {
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index 36e2eac4..ebd8834b 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -13,6 +13,7 @@ mod navigate;
mod new_bot;
mod overlay_keys;
mod roster;
+mod section_order;
mod slash;
mod steps;
mod ui;
@@ -113,6 +114,8 @@ pub struct App {
pub unfolded: HashSet<String>,
/// Roster sections showing their label alone (`z`); this run only.
pub folded: HashSet<String>,
+ /// Section order for this terminal session; the empty name is the unsectioned Bots group.
+ pub section_order: Vec<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>),
@@ -191,6 +194,7 @@ impl App {
pick: None,
unfolded: HashSet::new(),
folded: HashSet::new(),
+ section_order: Vec::new(),
call_entries: HashMap::new(),
market: (vec![], vec![]),
plugins: (vec![], vec![]),
diff --git a/host/src/tui/app/roster.rs b/host/src/tui/app/roster.rs
index e7c9d88c..5db6c3d2 100644
--- a/host/src/tui/app/roster.rs
+++ b/host/src/tui/app/roster.rs
@@ -157,7 +157,9 @@ impl App {
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())
+ let name = b.shown_section().unwrap_or("");
+ let order = self.section_order.iter().position(|s| s == name).unwrap_or(self.section_order.len());
+ (b.band(), order, section.is_none(), section, b.position, Reverse(b.last_at), b.name.clone())
});
v
}
diff --git a/host/src/tui/app/section_order.rs b/host/src/tui/app/section_order.rs
new file mode 100644
index 00000000..721c1f9e
--- /dev/null
+++ b/host/src/tui/app/section_order.rs
@@ -0,0 +1,88 @@
+//! Device-local ordering of whole roster groups, including unsectioned bots.
+
+use super::App;
+
+impl App {
+ pub(crate) fn rename_section_order(&mut self, from: &str, to: Option<&str>) {
+ if to == Some(from) {
+ return;
+ }
+ let destination_exists = to.is_some_and(|name| self.section_order.iter().any(|n| n == name));
+ self.section_order = self
+ .section_order
+ .iter()
+ .filter_map(|name| {
+ if name != from {
+ Some(name.clone())
+ } else if destination_exists {
+ None
+ } else {
+ to.map(str::to_owned)
+ }
+ })
+ .collect();
+ }
+
+ /// Capture the effective displayed order before a rename's bot events arrive.
+ pub(crate) fn shown_section_names(&self) -> Vec<String> {
+ let mut names = Vec::new();
+ for bot in self.roster().into_iter().filter(|b| !b.pinned) {
+ let section = bot.shown_section().unwrap_or("").to_owned();
+ if !names.contains(&section) {
+ names.push(section);
+ }
+ }
+ names
+ }
+
+ /// Alt+↑/↓ moves the selected bot's entire section one place, keeping pinned bots on top.
+ pub(super) fn move_section(&mut self, direction: isize) {
+ let Some(bot) = self.bot().filter(|b| !b.pinned) else { return };
+ let name = bot.shown_section().unwrap_or("").to_owned();
+ let mut names = self.shown_section_names();
+ let Some(from) = names.iter().position(|n| n == &name) else { return };
+ let Some(to) = from.checked_add_signed(direction).filter(|&i| i < names.len()) else { return };
+ names.swap(from, to);
+ self.section_order = names;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::{Bot, test_app};
+ use serde_json::json;
+
+ #[tokio::test]
+ async fn merging_into_a_new_group_keeps_its_displayed_place() {
+ let mut app = test_app();
+ for (id, section) in [("a", Some("Work")), ("b", Some("Home")), ("loose", None)] {
+ app.bots.insert(id.into(), Bot::parse(&json!({"id": id, "section": section})).expect("bot"));
+ }
+ app.section_order = vec!["Work".into(), String::new()];
+ app.section_order = app.shown_section_names();
+ app.rename_section_order("Work", Some("Home"));
+ assert_eq!(app.section_order, ["", "Home"]);
+ }
+
+ #[tokio::test]
+ async fn whole_sections_move_both_ways_past_bots_without_moving_pinned_bots() {
+ let mut app = test_app();
+ for (id, pinned, section) in
+ [("pin", true, None), ("a", false, Some("Work")), ("b", false, Some("Work")), ("loose", false, None)]
+ {
+ app.bots.insert(
+ id.into(),
+ Bot::parse(&json!({"id": id, "name": id, "pinned": pinned, "section": section})).expect("bot"),
+ );
+ }
+ app.selected = Some("a".into());
+ app.move_section(1);
+ let ids = |app: &super::App| app.roster().iter().map(|b| b.id.clone()).collect::<Vec<_>>();
+ assert_eq!(ids(&app), ["pin", "loose", "a", "b"]);
+ app.folded.insert("Work".into());
+ app.move_section(-1);
+ assert_eq!(ids(&app), ["pin", "a", "b", "loose"]);
+ app.move_section(-1);
+ assert_eq!(ids(&app), ["pin", "a", "b", "loose"]);
+ }
+}
diff --git a/host/src/tui/manage/fields.rs b/host/src/tui/manage/fields.rs
index e3320493..8e230019 100644
--- a/host/src/tui/manage/fields.rs
+++ b/host/src/tui/manage/fields.rs
@@ -92,6 +92,7 @@ impl App {
self.sheet("updateBot", json!({"id": bot, "section": values.get("name")}), Reply::FieldsSaved);
}
Submit::RenameSection(from) => {
+ self.section_order = self.shown_section_names();
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);
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index 20063be9..cd0d2c42 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -183,6 +183,7 @@ impl App {
}
Reply::SectionRenamed { from, to } => {
rename_fold(&mut self.folded, &from, to.as_deref());
+ self.rename_section_order(&from, to.as_deref());
self.on_sheet_reply(Reply::FieldsSaved, Ok(v));
}
Reply::SignIn => {
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index fc6c75bc..4294a60b 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); 72] = [
+const HELP: [(&str, &str, &str); 73] = [
("MOVE", "j k ↑ ↓", "next / previous bot"),
("MOVE", "[ ]", "previous / next bot"),
("MOVE", "1…9", "jump to bot 1–9"),
@@ -58,6 +58,7 @@ const HELP: [(&str, &str, &str); 72] = [
("BOTS", "I", "About the lead agent"),
("BOTS", "*", "Make lead agent"),
("BOTS", "p", "pin / unpin"),
+ ("BOTS", "alt ↑ ↓", "move section up / down"),
("BOTS", "J K", "move bot down / up"),
("BOTS", "w", "move to section"),
("BOTS", "W", "rename / remove section"),
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index fc5a6e36..cc1e55a7 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -106,6 +106,7 @@ Each bot keeps a long-term memory across sessions, which you can read on its **M
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.
+- **Reorder sections:** drag a heading up or down (iPhone: touch and hold, then drag). Move custom sections above or below **Bots**; pinned bots stay on top. Each device remembers its own order. On Desktop, focus a heading and press `Alt+↑` or `Alt+↓`. Terminal UI: select a bot in the section and press `Alt+↑` or `Alt+↓`; its order lasts until you quit.
- **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.
- Pinned bots stay on top, outside sections. 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.