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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: arrange the agents in Usage, on a cleaner page
leepokaif7e296bcadcf
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2a7c69ec..86f3bcca 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -25,7 +25,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- **Host owns the logic**: bot management, sessions, agent processes, MCP servers/connectors, routing, routines, memory, validation and anything heavy or needed by more than one client run in the Rust host. iOS, desktop and TUI render host state and send intents through the host API; they keep only UI state and device-only work (mic/speech, Keychain, push decryption; desktop main process: host service, SSH, updates). A client that needs something the host lacks gets a new host method, never its own copy: [ownership rules](docs/architecture/overview.md#host-owns-the-logic).- iPhone Swift package (`apps/ios/Kit/`, iOS only): `CodyncKit` (models, client, theme, avatars; also used by the widgets and the notification extension) + `CodyncUI` (`BotStore` + screens).- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).-- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation, and the iPhone root uses the system `TabView`, for system Liquid Glass; BotListView is a `List` with its styling removed, for system drag-to-reorder; as specified in `docs/design/ui-conventions.md`. **iOS menus are always the system ones**: tap menus through `DropdownMenu`/`ChoicePicker` (native `Menu`), long-press through `.contextActions` (native `contextMenu`). Never hand-build a dropdown on iOS: a custom overlay lands in the wrong place (sheets, scroll views, the composer's + menu). The desktop app's menu bar/tray menu is the system menu. Keep system authentication and widget containers native. On iOS `.codyncSheet` presents the system sheet (grabber, swipe down). Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `ContentUnavailableView`. Use `apps/ios/Kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `.codyncDialog`, `ToggleStyle.codync`); on the desktop, `apps/desktop/src/renderer/components/` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`, `Controls.tsx`, `Icon` for SF Symbols). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation, and the iPhone root uses the system `TabView`, for system Liquid Glass; BotListView is a `List` with its styling removed and UsageView a grouped `List`, for system drag-to-reorder; as specified in `docs/design/ui-conventions.md`. **iOS menus are always the system ones**: tap menus through `DropdownMenu`/`ChoicePicker` (native `Menu`), long-press through `.contextActions` (native `contextMenu`). Never hand-build a dropdown on iOS: a custom overlay lands in the wrong place (sheets, scroll views, the composer's + menu). The desktop app's menu bar/tray menu is the system menu. Keep system authentication and widget containers native. On iOS `.codyncSheet` presents the system sheet (grabber, swipe down). Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `ContentUnavailableView`. Use `apps/ios/Kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `.codyncDialog`, `ToggleStyle.codync`); on the desktop, `apps/desktop/src/renderer/components/` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`, `Controls.tsx`, `Icon` for SF Symbols). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.- `host/` — **codync-host** (Rust, macOS + Linux + Windows; platform differences in `service/` and `shell.rs`). Detects installed harnesses (`agent/backends.rs`: login-shell PATH + known dirs) and the ACP registry (`agent/registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `agent/acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`agent/bot/`) owns the agent process + session and maps `session/update` onto transcript entries. Every patch around an adapter's bug has a row in [ACP adapter workarounds](docs/reference/acp-adapter-workarounds.md), added or removed in the same change.- Chat/session ownership, groups, collaboration, memory and visible-message rules: [conversation runtime](docs/architecture/conversation-runtime.md).- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.ktindex 9373c51b..d0438861 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt@@ -2,10 +2,14 @@ package com.codync.androidimport androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.semantics.SemanticsActionsimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.unit.dpimport com.codync.android.core.*import com.codync.android.design.LocalDismissModal+import kotlinx.coroutines.CompletableDeferredimport kotlinx.serialization.json.jsonObjectimport org.junit.Assert.*import org.junit.Rule@@ -14,26 +18,25 @@ import org.junit.Testclass UsageScreenTest {@get:Rule val compose = createComposeRule()+ private val computer = Computer("fixture", "Acceptance computer", "fixture")++ private fun usage(json: String) = WireJson.parseToJsonElement(json).jsonObject++ private fun offline(json: String) = AppState(computer, loading = false, usage = usage(json), actualConnection = LinkState.ComputerOffline(null))+@Test fun unavailableWindowsAndOldReportsNeverBecomeZeroUsage() {- val raw = WireJson.parseToJsonElement("""{"providers":[{"id":"future","name":"Future provider","source":"future-source","updatedAt":1,"windows":[{"id":"month","label":"Monthly"}]}]}""")- val state = mutableStateOf(AppState(Computer("fixture", "Acceptance computer", "fixture"), loading = false, usage = raw.jsonObject,- actualConnection = LinkState.ComputerOffline(null)))+ val state = mutableStateOf(offline("""{"providers":[{"id":"future","name":"Future provider","source":"future-source","updatedAt":1,"windows":[{"id":"month","label":"Monthly"}]}]}"""))val refreshes = mutableListOf<Boolean>()var closed = falsecompose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides { closed = true }) {- UsageScreen(state.value, { refreshes.add(it) }, { refreshes.add(true) }, { _, _ -> })+ UsageScreen(state.value, { refreshes.add(it) }, { refreshes.add(true) }, { _, _ -> }, {})} } }+ compose.onNodeWithText("Acceptance computer").assertIsDisplayed()compose.onNodeWithText("Future provider").assertIsDisplayed()compose.onNodeWithText("Monthly").assertIsDisplayed()compose.onNodeWithText("—").assertIsDisplayed()compose.onNodeWithText("0%").assertDoesNotExist()- compose.onNodeWithText("future-source").assertIsDisplayed()- compose.onNodeWithText("Not reported").assertDoesNotExist()assertEquals(emptyList<Boolean>(), refreshes)- compose.onNodeWithContentDescription("Collapse").performClick()- compose.onNodeWithText("Monthly").assertDoesNotExist()- compose.onNodeWithContentDescription("Expand").performClick()- compose.onNodeWithText("Monthly").assertIsDisplayed()// Coming online asks for a current report, from cache when the computer has one.compose.runOnUiThread { state.value = state.value.copy(actualConnection = LinkState.Ready(HostRoute.Direct)) }compose.waitForIdle()@@ -44,39 +47,81 @@ class UsageScreenTest {@Test fun usageExplainsWhenThereIsNoComputerOrNoReportYet() {val state = mutableStateOf<AppState?>(null)- compose.setContent { Hosted { UsageScreen(state.value, {}, {}, { _, _ -> }) } }+ compose.setContent { Hosted { UsageScreen(state.value, {}, {}, { _, _ -> }, {}) } }compose.onNodeWithText("No computer yet").assertIsDisplayed()compose.onNodeWithText("Usage shows up once a computer is connected.").assertIsDisplayed()- compose.runOnUiThread { state.value = AppState(Computer("fixture", "Acceptance computer", "fixture"), loading = false) }- compose.onNodeWithText("No usage yet").assertIsDisplayed()- compose.onNodeWithText("Your computer reads plan limits from the agents your bots run and the ones you turn on.").assertIsDisplayed()+ compose.runOnUiThread { state.value = AppState(computer, loading = false) }+ compose.onNodeWithText("No usage information yet.").assertIsDisplayed()}- @Test fun theChooserListsTheAgentsAndATapReachesTheHostThenTheCardFoldsAway() {- val usage = { providers: String, shown: Boolean ->- WireJson.parseToJsonElement("""{"providers":[$providers],"services":[{"id":"claude","name":"Claude","shown":$shown},{"id":"cursor","name":"Cursor","shown":false},{"id":"amp","name":"Amp","shown":true}]}""").jsonObject- }- val card = """{"id":"claude","name":"Claude","source":"claude","updatedAt":1,"windows":[{"id":"week","label":"Weekly","percent":10}]}"""- val computer = Computer("fixture", "Acceptance computer", "fixture")- val state = mutableStateOf(AppState(computer, loading = false, usage = usage(card, true), actualConnection = LinkState.ComputerOffline(null)))+ @Test fun aLimitShowsItsPercentReadOutAsUsedAndANoteHasNoBar() {+ val state = offline("""{"providers":[{"id":"claude","name":"Claude","windows":[{"id":"week","label":"Weekly","percent":33},{"id":"cost","label":"Cost today","text":"$1.50"}]}]}""")+ compose.setContent { Hosted { UsageScreen(state, {}, {}, { _, _ -> }, {}) } }+ compose.onNodeWithText("33%").assertIsDisplayed()+ compose.onNodeWithContentDescription("33% used").assertIsDisplayed()+ compose.onNodeWithText("$1.50").assertIsDisplayed()+ compose.onNodeWithText("Cost today").assertIsDisplayed()+ }++ private val services = """"services":[{"id":"claude","name":"Claude","shown":true},{"id":"cursor","name":"Cursor","shown":false},{"id":"amp","name":"Amp","shown":true}]"""+ private val reading = """{"id":"claude","name":"Claude","windows":[{"id":"week","label":"Weekly","percent":10}]}"""++ @Test fun theButtonSwapsTheReadingsForTheAgentsAndATapReachesTheHost() {val changes = mutableListOf<Pair<String, Boolean>>()- compose.setContent { Hosted { UsageScreen(state.value, {}, {}, { id, shown -> changes.add(id to shown) }) } }- compose.onNodeWithText("Show usage for").performScrollTo().assertIsDisplayed()- compose.onNodeWithText("No reading yet").assertExists()- compose.onNodeWithText("Cursor").performScrollTo().performClick()- assertEquals(listOf("cursor" to true), changes)- // The card names its tightest limit and lists it too.- compose.onAllNodesWithText("Weekly").onFirst().assertExists()- compose.runOnUiThread { state.value = state.value.copy(usage = usage("", false)) }+ val state = offline("""{"providers":[$reading],$services}""")+ compose.setContent { Hosted { UsageScreen(state, {}, {}, { id, shown -> changes.add(id to shown) }, {}) } }+ compose.onNodeWithText("Weekly").assertIsDisplayed()+ compose.onNodeWithText("No reading yet").assertDoesNotExist()+ compose.onNodeWithContentDescription("Choose and arrange").performClick()compose.waitForIdle()compose.onNodeWithText("Weekly").assertDoesNotExist()+ compose.onNodeWithText("No reading yet").assertIsDisplayed()+ compose.onNodeWithText("On by default for the agents your bots run.").assertIsDisplayed()+ compose.onNodeWithText("Cursor").performClick()+ assertEquals(listOf("cursor" to true), changes)+ compose.onNodeWithContentDescription("Done").performClick()+ compose.waitForIdle()+ compose.onNodeWithText("Weekly").assertIsDisplayed()+ }++ @Test fun aDraggedRowHoldsItsPlaceUntilTheAnswerThenShowsTheHostsOrder() {+ val sent = mutableListOf<List<String>>()+ val answer = CompletableDeferred<Unit>()+ val state = offline("""{"providers":[$reading],$services}""")+ compose.setContent { Hosted { UsageScreen(state, {}, {}, { _, _ -> }, { sent.add(it); answer.await() }) } }+ compose.onNodeWithContentDescription("Choose and arrange").performClick()+ compose.waitForIdle()+ compose.onNodeWithContentDescription("Move Claude").performTouchInput {+ down(center)+ moveBy(Offset(0f, 60.dp.toPx()))+ up()+ }+ compose.waitForIdle()+ assertEquals(listOf(listOf("cursor", "claude", "amp")), sent)+ fun top(name: String) = compose.onNodeWithText(name).getBoundsInRoot().top+ assertTrue(top("Cursor") < top("Claude"))+ // This host keeps its order, as an older one refusing the call would.+ answer.complete(Unit)+ compose.waitForIdle()+ assertTrue(top("Claude") < top("Cursor"))+ }++ @Test fun anAccessibilityActionMovesTheRowAPlace() {+ val sent = mutableListOf<List<String>>()+ val state = offline("""{"providers":[$reading],$services}""")+ compose.setContent { Hosted { UsageScreen(state, {}, {}, { _, _ -> }, { sent.add(it) }) } }+ compose.onNodeWithContentDescription("Choose and arrange").performClick()+ compose.waitForIdle()+ val actions = compose.onNodeWithContentDescription("Move Cursor").fetchSemanticsNode().config[SemanticsActions.CustomActions]+ compose.runOnUiThread { actions.first { it.label == "Move up" }.action() }+ compose.waitForIdle()+ assertEquals(listOf(listOf("cursor", "claude", "amp")), sent)}- @Test fun aHostWithNoListShowsNoSwitches() {- val usage = WireJson.parseToJsonElement("""{"providers":[]}""").jsonObject- val state = AppState(Computer("fixture", "Acceptance computer", "fixture"), loading = false, usage = usage)- compose.setContent { Hosted { UsageScreen(state, {}, {}, { _, _ -> }) } }- compose.onNodeWithText("No usage yet").assertIsDisplayed()- compose.onNodeWithText("Show usage for").assertDoesNotExist()+ @Test fun aHostWithNoListHasNoButton() {+ val state = AppState(computer, loading = false, usage = usage("""{"providers":[]}"""))+ compose.setContent { Hosted { UsageScreen(state, {}, {}, { _, _ -> }, {}) } }+ compose.onNodeWithText("No usage information yet.").assertIsDisplayed()+ compose.onNodeWithContentDescription("Choose and arrange").assertDoesNotExist()}}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.ktindex b0d4e734..1e1577f5 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@@ -6,6 +6,7 @@ import java.io.IOExceptionimport java.util.concurrent.ConcurrentHashMapimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.*+import kotlinx.coroutines.channels.Channelimport kotlinx.coroutines.flow.*import kotlinx.serialization.json.*@@ -64,6 +65,8 @@ class AppStore internal constructor(/** The message sent from here last: its row in the queue scrolls into view ([QueuedMessages]). */internal var lastSentNonce: String? = nullinternal val actions = mutableMapOf<String, Job>()+ /** The agents' order waiting to go to the host (`setUsageOrder`). */+ internal val usageOrders = Channel<List<String>>(Channel.CONFLATED)/** 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. */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.ktindex e1fb8285..645db28b 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@@ -2,6 +2,7 @@ package com.codync.androidimport com.codync.android.core.*import kotlinx.coroutines.*+import kotlinx.coroutines.channels.Channelimport kotlinx.coroutines.flow.*import kotlinx.serialization.json.*@@ -177,6 +178,21 @@ fun AppStore.refreshUsage(force: Boolean = true) = action("usage") {fun AppStore.setUsageShown(id: String, shown: Boolean) = action("usageShown.$id") {landUsage(ready().call("setUsageShown", buildJsonObject { put("id", id); put("shown", shown) }).jsonObject)}+/**+ * The order this computer lists its agents in, back once the host has answered. A host older than this refuses the call:+ * the error shows and the order stays. Drops while one is on its way replace each other, so only the last goes out next.+ */+suspend fun AppStore.setUsageOrder(ids: List<String>) {+ usageOrders.trySend(ids)+ action("usageOrder") {+ usageOrders.sendEach { order -> landUsage(ready().call("setUsageOrder", buildJsonObject { putJsonArray("ids") { order.forEach(::add) } }).jsonObject) }+ }+ actions["usageOrder"]?.join()+}+/** Hands over what waits in this conflated channel, one at a time, until nothing does. */+internal suspend fun <T : Any> Channel<T>.sendEach(deliver: suspend (T) -> Unit) {+ while (true) deliver(tryReceive().getOrNull() ?: return)+}private suspend fun AppStore.landUsage(response: JsonObject) {UsageReport.decode(response)withContext(Dispatchers.IO) { requireNotNull(database).apply(MirrorEvent.Usage(response)) }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.ktindex 3d9b2d32..92015316 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@@ -67,7 +67,7 @@ import kotlinx.serialization.json.put/** One computer's roster while the list shows it: its rows' and sections' drags and its section order (kept on this device). */private class ComputerRoster(private val context: Context, val key: String) {val reorder = RosterReorder()- val sections = SectionReorder()+ val sections = ListReorder()var order by mutableStateOf(SectionOrders.load(context, key))/** Points the drags at [state]'s bots and sections as [list] shows them. */@@ -104,7 +104,7 @@ private class ComputerRoster(private val context: Context, val key: String) {// Computers that can take a new bot once they're connected, and the ones that can right now (iOS `availableStores`, `onlineStores`).val available = availableComputers(app, states)val online = available.filter { it.actualConnection is LinkState.Ready }- val computerReorder = remember { SectionReorder() }+ val computerReorder = remember { ListReorder() }computerReorder.names = shown.map { it.computer.id }computerReorder.save = { ids -> accounts.orderComputers(ids) }computerReorder.position = { id -> listState.layoutInfo.visibleItemsInfo.firstOrNull { it.key == "computer:$id" }?.offset?.toFloat() ?: 0f }@@ -190,7 +190,7 @@ private class ComputerRoster(private val context: Context, val key: String) {}/** A computer's heading (and, while it needs one, its update notice) that drags to reorder the computers. */-@Composable private fun LazyItemScope.ComputerHeading(state: AppState, store: AppStore, reorder: SectionReorder, folded: Boolean, stale: Boolean,+@Composable private fun LazyItemScope.ComputerHeading(state: AppState, store: AppStore, reorder: ListReorder, folded: Boolean, stale: Boolean,toggle: () -> Unit, extensions: () -> Unit) {val id = state.computer.idColumn(reorderable(reorder, id)) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.ktindex 139cc9b2..0e80e6a9 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt@@ -238,8 +238,8 @@ private fun computerChoice(state: AppState): String =states.map { other -> MenuItem(other.computer.name, selected = other.computer.id == state.computer.id, verbatim = true) { accounts.noteActive(other.computer.id) } }}, label = "Computer: ${state.computer.name}") { ComputerBadge(state.hello?.text("device"), 28.dp, state.computer.color) }}- if (state == null || store == null) UsageScreen(null, {}, {}, { _, _ -> }, picker)- else key(state.computer.id) { UsageScreen(state, store::refreshUsage, store::reloadUsage, { id, shown -> store.setUsageShown(id, shown) }, picker) }+ if (state == null || store == null) UsageScreen(null, {}, {}, { _, _ -> }, {}, picker)+ else key(state.computer.id) { UsageScreen(state, store::refreshUsage, store::reloadUsage, { id, shown -> store.setUsageShown(id, shown) }, store::setUsageOrder, picker) }}/** The remote screen as a full-window layer that fades in and out (iOS `.codyncOverlay`); it keeps its computer while fading. */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt b/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.ktindex cac2a5cc..30554d6d 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt@@ -53,12 +53,9 @@ import com.codync.android.design.*heading()contentDescription = "${state.hostName}, ${translate(status)}"stateDescription = translate(if (folded) "Collapsed" else "Expanded")- customActions = listOfNotNull(- CustomAccessibilityAction(translate(if (folded) "Expand" else "Collapse")) { toggle(); true },- CustomAccessibilityAction(translate("Move up")) { move(-1); true },- CustomAccessibilityAction(translate("Move down")) { move(1); true },- extensions?.let { open -> CustomAccessibilityAction(translate("Extensions")) { open(); true } },- )+ customActions = listOf(CustomAccessibilityAction(translate(if (folded) "Expand" else "Collapse")) { toggle(); true }) ++ moveActions(translate, move) ++ listOfNotNull(extensions?.let { open -> CustomAccessibilityAction(translate("Extensions")) { open(); true } })}.padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {ComputerBadge(state.hello?.text("device"), 20.dp, state.computer.color)// The name and the connection share the row; the connection sits at the trailing edge, before the heading's buttons.diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ListReorder.kt b/apps/android/app/src/main/kotlin/com/codync/android/ListReorder.ktnew file mode 100644index 00000000..ed045f55--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/ListReorder.kt@@ -0,0 +1,63 @@+package com.codync.android++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.semantics.CustomAccessibilityAction+import com.codync.android.design.ContextDrag++/** Drags a row past its neighbors, or steps it a place with [move]. Only a completed drop is saved. */+internal class ListReorder {+ 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 row. */+ var position: (String) -> Float = { 0f }+ var save: (List<String>) -> Unit = {}+ /** Just before a drag swaps two rows, while the old order is still laid out. */+ var beforeSwap: () -> 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 { beforeSwap(); order = next }+ }++ private fun finish(commit: Boolean) {+ if (commit) order?.takeIf { it != names }?.let(save)+ dragged = null+ order = null+ offset = 0f+ }++ /** [name]'s row left the list: if it was the one held, its gesture will never end, so the drag ends here. */+ fun released(name: String) { if (dragged == name) finish(false) }++ 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) })+ }+}++/** What TalkBack offers in place of a drag. */+internal fun moveActions(translate: (String) -> String, move: (Int) -> Unit): List<CustomAccessibilityAction> = listOf(+ CustomAccessibilityAction(translate("Move up")) { move(-1); true },+ CustomAccessibilityAction(translate("Move down")) { move(1); true },+)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.ktindex 4e6e9617..f8586825 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt@@ -7,11 +7,6 @@ import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.layout.onSizeChangedimport androidx.compose.ui.zIndeximport 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.ContextDragimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonPrimitive@@ -35,50 +30,6 @@ internal object SectionOrders {}}-/** 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) })- }-}-/** A heading [reorder] drags by [name]: its height for the swaps, lifted above the rest while held, otherwise sliding into place. */-internal fun LazyItemScope.reorderable(reorder: SectionReorder, name: String): Modifier = Modifier.onSizeChanged { reorder.heights[name] = it.height }+internal fun LazyItemScope.reorderable(reorder: ListReorder, name: String): Modifier = Modifier.onSizeChanged { reorder.heights[name] = it.height }.then(if (reorder.dragged == name) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.translation(name) } else Modifier.animateItem())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.ktindex 99d0da91..cd8560e2 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,7 +25,6 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.draw.rotateimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequester-import androidx.compose.ui.semantics.CustomAccessibilityActionimport androidx.compose.ui.semantics.customActionsimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.clearAndSetSemantics@@ -65,7 +64,7 @@ import com.codync.android.design.*// 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 })+ customActions = moveActions(translate, move)stateDescription = statecontentDescription = spoken}@@ -89,7 +88,7 @@ import com.codync.android.design.*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 })+ customActions = moveActions(translate, move)}.padding(vertical = 6.dp),style = Type.footnote.semibold, color = Palette.secondary)}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UsageChooser.kt b/apps/android/app/src/main/kotlin/com/codync/android/UsageChooser.ktnew file mode 100644index 00000000..c0289712--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/UsageChooser.kt@@ -0,0 +1,120 @@+package com.codync.android++import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectVerticalDragGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyItemScope+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.customActions+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex+import com.codync.android.core.UsageReport+import com.codync.android.core.UsageService+import com.codync.android.design.*+import com.kyant.shapes.RoundedRectangle+import com.kyant.shapes.UnevenRoundedRectangle+import kotlinx.coroutines.launch++private val CardCorner = 20.dp++/** Readings and rows trade places with a short fade (iOS: the `List`'s, under `Motion.layout`). */+internal fun LazyItemScope.trading(): Modifier = Modifier.animateItem(Motion.fade(), Motion.layoutOffset, Motion.fade())++/** The agents' drags. What shows is the order just dropped until the host answers, so the row doesn't jump back. */+@Composable internal fun rememberUsageReorder(report: UsageReport, list: LazyListState, setOrder: suspend (ids: List<String>) -> Unit): ListReorder {+ val scope = rememberCoroutineScope()+ val reorder = remember { ListReorder() }+ var sent by remember { mutableStateOf<List<String>?>(null) }+ reorder.names = report.servicesIn(sent).map { it.id }+ reorder.position = { id -> list.layoutInfo.visibleItemsInfo.firstOrNull { it.key == id }?.offset?.toFloat() ?: 0f }+ // The list keeps its first visible item in place by key: left to that, a held row there never gets further from its slot and swaps on and on.+ reorder.beforeSwap = { list.requestScrollToItem(list.firstVisibleItemIndex, list.firstVisibleItemScrollOffset) }+ reorder.save = { ids ->+ sent = ids+ scope.launch {+ setOrder(ids)+ // A later drop keeps its own order on screen until its own answer.+ if (sent === ids) sent = null+ }+ }+ return reorder+}++/** One card of every agent, then the line under it. */+internal fun LazyListScope.chooserRows(report: UsageReport, services: List<UsageService>, reorder: ListReorder, setShown: (id: String, shown: Boolean) -> Unit) {+ itemsIndexed(services, key = { _, service -> service.id }) { index, service ->+ ChooserSlot(service, report.hasNoReading(service), reorder, setShown, first = index == 0, last = index == services.lastIndex)+ }+ item(key = "note") {+ Text(tr("On by default for the agents your bots run."), trading().padding(start = 16.dp, top = 8.dp), style = Type.caption, color = Palette.secondary)+ }+}++/** The row's place in the card, which stays filled while the row is lifted out of it and follows the finger. */+@Composable private fun LazyItemScope.ChooserSlot(service: UsageService, hasNoReading: Boolean, reorder: ListReorder, setShown: (id: String, shown: Boolean) -> Unit, first: Boolean, last: Boolean) {+ val lifted = reorder.dragged == service.id+ val top = if (first) CardCorner else 0.dp+ val bottom = if (last) CardCorner else 0.dp+ DisposableEffect(service.id) { onDispose { reorder.released(service.id) } }+ Box(Modifier.onSizeChanged { reorder.heights[service.id] = it.height }.then(if (lifted) Modifier.zIndex(1f) else trading())+ .background(Palette.surface, UnevenRoundedRectangle(topStart = top, topEnd = top, bottomStart = bottom, bottomEnd = bottom))) {+ Row(Modifier.fillMaxWidth().heightIn(min = 52.dp).graphicsLayer { translationY = reorder.translation(service.id) }+ .then(if (lifted) Modifier.clip(RoundedRectangle(14.dp)).background(Palette.bubbleUser) else Modifier),+ verticalAlignment = Alignment.CenterVertically) {+ DragHandle(service.name, reorder.handle(service.id)) { reorder.move(service.id, it) }+ ChooserSwitch(service, hasNoReading) { setShown(service.id, it) }+ }+ }+}++@Composable private fun RowScope.ChooserSwitch(service: UsageService, hasNoReading: Boolean, change: (Boolean) -> Unit) {+ CodyncSwitch(service.shown, change, Modifier.weight(1f).heightIn(min = 52.dp).padding(end = 16.dp)) {+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ ProviderMascot(service.provider, 20.dp)+ Text(service.name, Modifier.weight(1f, fill = false), style = Type.subheadline, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (hasNoReading) Text(tr("No reading yet"), style = Type.subheadline, color = Palette.secondary, maxLines = 1)+ }+ }+}++/** Where a row is dragged from: at once, with no hold first, since a touch here means nothing else. TalkBack moves it a place at a time. */+@Composable private fun DragHandle(name: String, drag: ContextDrag, move: (Int) -> Unit) {+ val translate = translator()+ Box(Modifier.size(44.dp).pointerInput(drag) {+ detectVerticalDragGestures(onDragStart = { drag.start() }, onDragEnd = drag.end, onDragCancel = drag.cancel ?: drag.end) { change, step ->+ change.consume()+ drag.move(step)+ }+ }.semantics {+ contentDescription = translate("Move {name}").replace("{name}", name)+ customActions = moveActions(translate, move)+ }, contentAlignment = Alignment.Center) {+ Symbol("line.3.horizontal", size = 18.dp, tint = Palette.secondary)+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.ktindex 561438f1..9999f03c 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt@@ -1,23 +1,18 @@package com.codync.android-import androidx.compose.animation.AnimatedVisibility-import androidx.compose.animation.core.MutableTransitionState-import androidx.compose.animation.core.animateFloatAsState-import androidx.compose.animation.expandVertically-import androidx.compose.animation.fadeIn-import androidx.compose.animation.fadeOut-import androidx.compose.animation.shrinkVertically+import androidx.compose.animation.animateContentSizeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.size-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffect@@ -30,8 +25,11 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip-import androidx.compose.ui.draw.rotate+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.codync.android.core.LinkStateimport com.codync.android.core.UsageProvider@@ -39,18 +37,14 @@ import com.codync.android.core.UsageReportimport com.codync.android.core.UsageWindowimport com.codync.android.design.*import com.kyant.shapes.RoundedRectangle-import java.time.Instant-import java.time.ZoneId-import java.time.format.DateTimeFormatter-import java.time.format.FormatStyleimport kotlin.math.roundToInt/**- * Usage limits, opened from the State tab (iOS `UsageSheet` + `UsageView`): one card per- * provider, the tightest limit as a big bar, every limit listed below. Pull down to refresh.+ * One computer's usage, opened from the State tab (iOS `UsageSheet` + `UsageView`): its name, what its agents+ * have used, and behind a button which agents show and in what order. Pull down to refresh.*/@Composable fun UsageScreen(state: AppState?, refresh: (force: Boolean) -> Unit, reload: suspend () -> Unit,- setShown: (id: String, shown: Boolean) -> Unit, trailing: @Composable () -> Unit = {}) {+ setShown: (id: String, shown: Boolean) -> Unit, setOrder: suspend (ids: List<String>) -> Unit, trailing: @Composable () -> Unit = {}) {val dismiss = LocalDismissModal.currentval report = remember(state?.usage) { state?.let { runCatching { UsageReport.decode(it.usage) }.getOrNull() } ?: UsageReport() }val online = state?.actualConnection is LinkState.Ready@@ -60,117 +54,85 @@ import kotlin.math.roundToIntScreenHeader(leading = { IconButton("Close", "xmark", action = dismiss) },title = { Text("Usage", style = Type.body.semibold, color = Palette.text) }, trailing = { trailing() })if (state == null) {- EmptyUsage("No computer yet", "Usage shows up once a computer is connected.")+ EmptyState("chart.bar", "No computer yet", Modifier.fillMaxWidth().padding(top = 60.dp), "Usage shows up once a computer is connected.")return@Column}- PullToRefresh({ if (online) reload() }, Modifier.weight(1f)) {- Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {- ProviderCards(report.providers)- if (report.providers.isEmpty()) EmptyUsage("No usage yet", "Your computer reads plan limits from the agents your bots run and the ones you turn on.")- if (report.services.isNotEmpty()) UsageChooser(report, setShown)- }- }+ PullToRefresh({ if (online) reload() }, Modifier.weight(1f)) { UsageSection(state, report, setShown, setOrder) }}}-@Composable private fun EmptyUsage(title: String, message: String) =- EmptyState("chart.bar", title, Modifier.fillMaxWidth().padding(top = 60.dp), message)--/** The cards, each folding in or out as its agent turns on or off. */-@Composable private fun ProviderCards(providers: List<UsageProvider>) {- val atFirst = remember { providers.map { it.id }.toSet() }- // Every card seen, so that one turned off can still fold away.- val seen = remember { java.util.TreeMap<String, UsageProvider>() }- providers.forEach { seen[it.id] = it }- for ((id, provider) in seen) key(id) {- val showing = remember { MutableTransitionState(id in atFirst) }- showing.targetState = providers.any { it.id == id }- AnimatedVisibility(showing, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),- exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) { ProviderCard(provider) }+@Composable private fun UsageSection(state: AppState, report: UsageReport, setShown: (id: String, shown: Boolean) -> Unit, setOrder: suspend (ids: List<String>) -> Unit) {+ var arranging by rememberSaveable { mutableStateOf(false) }+ val canArrange = report.services.isNotEmpty()+ val editing = arranging && canArrange+ val list = rememberLazyListState()+ val reorder = rememberUsageReorder(report, list, setOrder)+ val services = report.servicesIn(reorder.shown)+ LazyColumn(Modifier.fillMaxSize(), list, PaddingValues(16.dp)) {+ item(key = "heading") { UsageHeading(state, canArrange, editing) { arranging = !editing } }+ when {+ editing -> chooserRows(report, services, reorder, setShown)+ report.providers.isEmpty() -> item(key = "none") {+ Text(tr("No usage information yet."), trading().padding(start = 16.dp, top = 8.dp), style = Type.subheadline, color = Palette.secondary)+ }+ else -> item(key = "limits") { UsageLimits(report.providers, trading()) }+ }}}-/** Which agents' limits this computer lists. */-@Composable private fun UsageChooser(report: UsageReport, setShown: (id: String, shown: Boolean) -> Unit) {- Column(Modifier.fillMaxWidth().clip(RoundedRectangle(20.dp)).background(Palette.surface).padding(14.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)) {- Text(tr("Show usage for"), style = Type.subheadline.semibold, color = Palette.text)- for (service in report.services) key(service.id) {- CodyncSwitch(service.shown, { setShown(service.id, it) }, Modifier.fillMaxWidth()) {- ProviderTile(service.provider)- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(service.name, style = Type.subheadline, color = Palette.text)- if (service.shown && report.providers.none { it.id == service.id }) {- Text(tr("No reading yet"), style = Type.caption, color = Palette.tertiary)- }- }- }- }- Text(tr("On by default for the agents your bots run."), style = Type.caption, color = Palette.tertiary)+/** The computer's name, and the one button that swaps the readings for the list of agents. */+@Composable private fun UsageHeading(state: AppState, canArrange: Boolean, editing: Boolean, toggle: () -> Unit) {+ // The start lines up with the mascots below, and the 44 dp target's glyph with the switches' edge.+ Row(Modifier.fillMaxWidth().heightIn(min = 44.dp).padding(start = 16.dp, end = 4.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ ComputerBadge(state.hello?.text("device"), 20.dp, state.computer.color)+ Text(state.hostName, Modifier.weight(1f), style = Type.subheadline.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (canArrange) IconButton(if (editing) "Done" else "Choose and arrange", if (editing) "checkmark" else "slider.horizontal.3", Modifier.size(44.dp), action = toggle)}}-/** An agent's mascot or logo on its tinted tile. */-@Composable private fun ProviderTile(provider: UsageProvider) {- Box(Modifier.size(34.dp).clip(RoundedRectangle(10.dp)).background(provider.tint().copy(alpha = 0.12f)), contentAlignment = Alignment.Center) {- ProviderMascot(provider, 22.dp)+@Composable private fun UsageLimits(providers: List<UsageProvider>, modifier: Modifier) {+ Column(modifier.fillMaxWidth().clip(RoundedRectangle(20.dp)).background(Palette.surface).animateContentSize(Motion.layoutSize)) {+ for (provider in providers) key(provider.id) { ProviderLimits(provider) }}}-@Composable private fun ProviderCard(provider: UsageProvider) {- var collapsed by rememberSaveable(provider.id) { mutableStateOf(false) }- val turn by animateFloatAsState(if (collapsed) 180f else 0f, Motion.layout(), label = "Collapse")+@Composable private fun ProviderLimits(provider: UsageProvider) {val tint = provider.widgetTint()- Column(Modifier.fillMaxWidth().clip(RoundedRectangle(20.dp)).background(Palette.surface).padding(14.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {- ProviderTile(provider)- Text(provider.name, Modifier.weight(1f), style = Type.subheadline.semibold, color = Palette.text)- IconButton(if (collapsed) "Expand" else "Collapse", "chevron.up", Modifier.rotate(turn)) { collapsed = !collapsed }- }- provider.tightest?.let { top ->- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- Row {- Text(tr(top.title), Modifier.weight(1f), style = Type.subheadline, color = Palette.text)- Text(usedText(top.percent), style = Type.subheadline.monospacedDigit, color = Palette.text)- }- UsageTicks(top.percent ?: 0.0, tint, 15.dp)- val reset = top.resetsShort()- if (reset != null) Text(resetLine(reset), Modifier.fillMaxWidth(), style = Type.caption.monospacedDigit, color = Palette.tertiary, textAlign = TextAlign.End)- }+ Column(Modifier.padding(horizontal = 16.dp, vertical = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ ProviderMascot(provider, 20.dp)+ Text(provider.name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)}- AnimatedVisibility(!collapsed, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),- exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- for (window in provider.windows) {- DetailRow(tr(window.title), reading(window))- val reset = window.resetsShort()- if (reset != null) DetailRow(tr("Resets"), resetLine(reset))+ for (window in provider.windows) key(window.id) { WindowLimit(window, tint) }+ }+}++/** A limit's name and when it resets, how much is used, and under them the bar; or the note an agent gives instead. */+@Composable private fun WindowLimit(window: UsageWindow, tint: Color) {+ val note = window.text?.takeIf { it.isNotBlank() }+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (note != null) {+ Text(tr(window.title), style = Type.subheadline, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(note, Modifier.weight(1f), style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.End)+ } else {+ Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(tr(window.title), Modifier.weight(1f, fill = false), style = Type.subheadline, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(window.resetsShort()?.let { resetLine(it) }.orEmpty(), style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)}- DetailRow("Source", provider.sourceLabel)- DetailRow("Updated", provider.updatedAt?.takeIf { it > 0 }?.let(::updatedAt) ?: "Not reported")+ PercentUsed(window.reportedPercent)}}+ if (note == null) window.reportedPercent?.let { UsageTicks(it, tint, 5.dp) }}}-@Composable private fun reading(window: UsageWindow) = window.text?.takeIf { it.isNotBlank() } ?: usedText(window.percent)+/** "33%", read out as "33% used"; a dash when the agent didn't say, never a zero. */+@Composable private fun PercentUsed(percent: Double?) {+ val spoken = usedText(percent)+ Text(percent?.let { "${it.roundToInt()}%" } ?: "—", Modifier.semantics { contentDescription = spoken }, style = Type.subheadline.medium.monospacedDigit, color = Palette.text)+}/** "62% used": the share of the cap already spent, said so (a bare percent reads as what's left). */@Composable private fun usedText(value: Double?) =- value?.takeIf { it.isFinite() }?.let { tr("{percent}% used").replace("{percent}", "${it.roundToInt()}") } ?: "—"--/** "Oct 17, 2026 at 10:20 PM", as iOS formats an abbreviated date with a short time. */-private fun updatedAt(milliseconds: Long): String {- val at = Instant.ofEpochMilli(milliseconds).atZone(ZoneId.systemDefault())- val date = at.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))- val time = at.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))- return if (java.util.Locale.getDefault().language == "en") "$date at $time" else "$date $time"-}--@Composable private fun DetailRow(label: String, value: String) {- Row {- Text(tr(label), Modifier.weight(1f), style = Type.footnote, color = Palette.secondary)- Text(value, style = Type.footnote.monospacedDigit, color = Palette.text)- }-}+ value?.let { tr("{percent}% used").replace("{percent}", "${it.roundToInt()}") } ?: "—"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.ktindex 3d90de6d..75aae2dd 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionOrderTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionOrderTest.kt@@ -14,7 +14,7 @@ class RosterSectionOrderTest {rosterLines(bots, emptySet(), listOf("", "Work"), moving = true))}@Test fun aHeadingDragMovesBothWaysAcrossBots() {- val drag = SectionReorder()+ val drag = ListReorder()drag.names = listOf("Work", "")drag.heights[""] = 40drag.heights["Work"] = 40@@ -30,7 +30,7 @@ class RosterSectionOrderTest {assertEquals(null, drag.dragged)}@Test fun foldingKeepsTheHeadingUnderTheFingerAndCancellationDiscardsMoves() {- val drag = SectionReorder()+ val drag = ListReorder()drag.names = listOf("Home", "Work", "")var top = 200fdrag.position = { top }diff --git a/apps/android/app/src/test/kotlin/com/codync/android/UsageReorderTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/UsageReorderTest.ktnew file mode 100644index 00000000..900227d4--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/UsageReorderTest.kt@@ -0,0 +1,74 @@+package com.codync.android++import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test++class UsageReorderTest {+ private val row = 40+ private val saved = mutableListOf<List<String>>()++ private fun reorder(vararg ids: String) = ListReorder().apply {+ names = ids.toList()+ ids.forEach { heights[it] = row }+ position = { shown.indexOf(it) * row.toFloat() }+ save = { saved.add(it) }+ }++ @Test fun aDroppedRowLandsWhereItWasLetGo() {+ val drag = reorder("claude", "codex", "cursor")+ drag.handle("claude").apply { start(); move(30f); end() }+ assertEquals(listOf(listOf("codex", "claude", "cursor")), saved)+ saved.clear()+ val back = reorder("claude", "codex", "cursor")+ back.handle("cursor").apply { start(); move(-30f); move(-40f); end() }+ assertEquals(listOf(listOf("cursor", "claude", "codex")), saved)+ }++ @Test fun aRowDroppedInItsOwnPlaceSendsNothing() {+ val drag = reorder("claude", "codex")+ drag.handle("claude").apply { start(); move(10f); end() }+ assertEquals(emptyList<List<String>>(), saved)+ }++ @Test fun anAccessibilityStepMovesOnePlaceAndStopsAtTheEnds() {+ val drag = reorder("claude", "codex", "cursor")+ drag.move("codex", -1)+ drag.move("codex", 1)+ drag.move("claude", -1)+ drag.move("cursor", 1)+ assertEquals(listOf(listOf("codex", "claude", "cursor"), listOf("claude", "cursor", "codex")), saved)+ }++ @Test fun aDragThatSwapsAsksForTheListToHoldItsPlaceFirst() {+ var pinned = 0+ val drag = reorder("claude", "codex", "cursor").apply { beforeSwap = { pinned++ } }+ drag.move("claude", 1)+ assertEquals("an accessibility step isn't a drag", 0, pinned)+ drag.handle("cursor").apply { start(); move(-10f); assertEquals(0, pinned); move(-20f); assertEquals(1, pinned) }+ }++ @Test fun aHeldRowLeavingTheListEndsTheDragAndAnotherLeavingDoesNot() {+ val drag = reorder("claude", "codex", "cursor")+ drag.handle("claude").apply { start(); move(30f) }+ drag.released("cursor")+ assertEquals("claude", drag.dragged)+ drag.released("claude")+ assertNull(drag.dragged)+ assertEquals(listOf("claude", "codex", "cursor"), drag.shown)+ assertEquals(emptyList<List<String>>(), saved)+ }++ @Test fun dropsWhileOneIsOnItsWayLeaveOnlyTheLastToSend() = runBlocking {+ val waiting = Channel<String>(Channel.CONFLATED)+ val sent = mutableListOf<String>()+ waiting.trySend("first")+ waiting.sendEach { order ->+ sent += order+ if (order == "first") { waiting.trySend("second"); waiting.trySend("third") }+ }+ assertEquals(listOf("first", "third"), sent)+ }+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.ktindex 7fbf5d32..5a13c5b3 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt@@ -17,6 +17,15 @@ import java.util.Locale/** `services` is absent from a host older than the chooser. */@Serializable data class UsageReport(val providers: List<UsageProvider> = emptyList(), val services: List<UsageService> = emptyList()) {+ /** The agents in [order], a move still on its way to the host; any it doesn't name follow in the host's order. */+ fun servicesIn(order: List<String>?): List<UsageService> {+ if (order == null) return services+ return order.mapNotNull { id -> services.firstOrNull { it.id == id } } + services.filter { it.id !in order }+ }++ /** On, with nothing to show: signed out, or nothing to report. */+ fun hasNoReading(service: UsageService): Boolean = service.shown && providers.none { it.id == service.id }+companion object { fun decode(value: JsonElement): UsageReport = WireJson.decodeFromJsonElement(value) }}@@ -26,10 +35,6 @@ import java.util.Localeval registry: String? = null) {val limits: List<UsageWindow> get() = windows.filter { it.text.isNullOrBlank() }val tightest: UsageWindow? get() = limits.filter { it.percent?.isFinite() == true }.maxByOrNull { requireNotNull(it.percent) }- val sourceLabel: String get() = when (source) {- "claude" -> "Claude Code"; "statusline" -> "Claude Code status line"- "agent" -> "A running bot"; "sessions" -> "Codex sessions"; "" -> "Unknown source"; else -> source- }}@Serializable data class UsageWindow(val id: String, val label: String, val percent: Double? = null,diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.ktindex 7d94590f..21e4ab7d 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt@@ -12,10 +12,22 @@ class UsageTest {assertEquals("github-copilot-cli", named.services.single().provider.registry)assertTrue(UsageReport.decode(WireJson.parseToJsonElement("""{"providers":[]}""")).services.isEmpty())}+ @Test fun `a move on its way holds the order and agents it does not name follow`() {+ val report = UsageReport(services = listOf("claude", "codex", "cursor").map { UsageService(it, it, true) })+ assertEquals(listOf("claude", "codex", "cursor"), report.servicesIn(null).map { it.id })+ assertEquals(listOf("cursor", "claude", "codex"), report.servicesIn(listOf("cursor", "gone", "claude")).map { it.id })+ assertTrue(UsageReport().servicesIn(listOf("claude")).isEmpty())+ }+ @Test fun `only an agent that is on can lack a reading`() {+ val report = UsageReport(providers = listOf(UsageProvider("claude", "Claude")))+ assertFalse(report.hasNoReading(UsageService("claude", "Claude", true)))+ assertTrue(report.hasNoReading(UsageService("cursor", "Cursor", true)))+ assertFalse(report.hasNoReading(UsageService("cursor", "Cursor", false)))+ }@Test fun `unknown providers and missing windows remain distinct from zero consumption`() {val report = UsageReport.decode(WireJson.parseToJsonElement("""{"providers":[{"id":"future","name":"Future agent","source":"future-source","windows":[{"id":"unknown","label":"Monthly"},{"id":"zero","label":"Daily","percent":0}]}]}"""))val provider = report.providers.single()- assertEquals("future-source", provider.sourceLabel)+ assertEquals("future-source", provider.source)assertNull(provider.updatedAt)assertNull(provider.windows.first().reportedPercent)assertNull(provider.windows.first().barFraction)@@ -37,6 +49,5 @@ class UsageTest {val provider = UsageProvider("codex", "Codex", listOf(window, window.copy(id = "week", percent = 15.0)), "sessions", 1)assertEquals(1L, provider.updatedAt)assertEquals("session", provider.tightest?.id)- assertEquals("Codex sessions", provider.sourceLabel)}}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.ktindex 55073b60..ccd2a6f8 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@@ -29,7 +29,6 @@ import androidx.compose.foundation.layout.ColumnScopeimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.RowScope-import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height@@ -144,8 +143,8 @@ import com.kyant.shapes.RoundedRectangleRow(modifier.toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange).graphicsLayer { alpha = if (enabled) 1f else 0.4f },verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {- label()- Spacer(Modifier.weight(1f))+ // Its own row, so that a label's weight has all the room left of the track.+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), content = label)Box(Modifier.size(34.dp, 20.dp).clip(Capsule()).background(track).padding(2.dp)) {Box(Modifier.offset(x = knob).size(16.dp).clip(Capsule()).background(knobInk))}diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.ktindex 38258725..29f206cb 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt@@ -103,6 +103,7 @@ import androidx.annotation.DrawableRes"keyboard" -> R.drawable.sf_keyboard"keyboard.chevron.compact.down" -> R.drawable.sf_keyboard_chevron_compact_down"laptopcomputer" -> R.drawable.sf_laptopcomputer+ "line.3.horizontal" -> R.drawable.sf_line_3_horizontal"list.bullet" -> R.drawable.sf_list_bullet"list.bullet.rectangle" -> R.drawable.sf_list_bullet_rectangle"lock.display" -> R.drawable.sf_lock_display@@ -159,6 +160,7 @@ import androidx.annotation.DrawableRes"safari" -> R.drawable.sf_safari"shift" -> R.drawable.sf_shift"shippingbox" -> R.drawable.sf_shippingbox+ "slider.horizontal.3" -> R.drawable.sf_slider_horizontal_3"square.and.arrow.down" -> R.drawable.sf_square_and_arrow_down"square.and.arrow.up" -> R.drawable.sf_square_and_arrow_up"square.and.pencil" -> R.drawable.sf_square_and_pencildiff --git a/apps/android/design/src/main/res/drawable/sf_line_3_horizontal.xml b/apps/android/design/src/main/res/drawable/sf_line_3_horizontal.xmlnew file mode 100644index 00000000..8dfa216a--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_line_3_horizontal.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `menu`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M157.37-228.28q-19.15 0-32.33-13.18-13.17-13.17-13.17-32.32t13.17-32.33q13.18-13.17 32.33-13.17h645.26q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.32q-13.18 13.18-32.33 13.18H157.37Zm0-206.22q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17h645.26q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H157.37Zm0-206.22q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.32q13.18-13.18 32.33-13.18h645.26q19.15 0 32.33 13.18 13.17 13.17 13.17 32.32t-13.17 32.33q-13.18 13.17-32.33 13.17H157.37Z"/>+ </group>+</vector>diff --git a/apps/android/design/src/main/res/drawable/sf_slider_horizontal_3.xml b/apps/android/design/src/main/res/drawable/sf_slider_horizontal_3.xmlnew file mode 100644index 00000000..cb45633e--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_slider_horizontal_3.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `tune`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M481.91-112.59q-18.43 0-31.13-12.53-12.69-12.53-12.69-31.05v-160.24q0-18.53 12.69-31.06Q463.48-360 481.91-360q18.44 0 31.01 12.53 12.58 12.53 12.58 31.06V-280h276.41q18.53 0 31.06 12.53 12.53 12.53 12.53 31.06 0 18.43-12.53 31.13-12.53 12.69-31.06 12.69H525.5v36.42q0 18.52-12.53 31.05-12.53 12.53-31.06 12.53Zm-323.82-80q-18.53 0-31.06-12.69-12.53-12.7-12.53-31.13 0-18.44 12.53-31.01Q139.56-280 158.09-280h160.24q18.52 0 31.05 12.53 12.53 12.53 12.53 31.06 0 18.43-12.53 31.13-12.53 12.69-31.05 12.69H158.09Zm160.24-163.82q-18.44 0-31.13-12.7-12.7-12.69-12.7-31.13v-36.17H158.09q-18.53 0-31.06-12.53Q114.5-461.48 114.5-480t12.53-31.06q12.53-12.53 31.06-12.53H274.5V-560q0-18.52 12.7-31.06 12.69-12.53 31.13-12.53 18.43 0 31.01 12.53 12.57 12.54 12.57 31.06v160q0 18.52-12.53 31.06-12.53 12.53-31.05 12.53Zm163.34-80q-18.52 0-31.05-12.53-12.53-12.54-12.53-31.06t12.53-31.06q12.53-12.53 31.05-12.53h320.24q18.53 0 31.06 12.53Q845.5-498.52 845.5-480t-12.53 31.06q-12.53 12.53-31.06 12.53H481.67ZM641.91-600q-18.43 0-31.13-12.53-12.69-12.53-12.69-31.06v-160.24q0-18.52 12.69-31.05 12.7-12.53 31.13-12.53 18.44 0 31.01 12.53 12.58 12.53 12.58 31.05v36.42h116.41q18.53 0 31.06 12.53 12.53 12.53 12.53 31.05 0 18.44-12.53 31.13-12.53 12.7-31.06 12.7H685.5v36.41q0 18.53-12.53 31.06Q660.44-600 641.91-600Zm-483.82-80q-18.53 0-31.06-12.7-12.53-12.69-12.53-31.13 0-18.43 12.53-31.01 12.53-12.57 31.06-12.57h320.24q18.52 0 31.05 12.53 12.53 12.53 12.53 31.05 0 18.44-12.53 31.13-12.53 12.7-31.05 12.7H158.09Z"/>+ </group>+</vector>diff --git a/apps/android/tools/symbols.py b/apps/android/tools/symbols.pyindex 538a5215..c693554d 100644--- a/apps/android/tools/symbols.py+++ b/apps/android/tools/symbols.py@@ -114,6 +114,7 @@ MAP = {"keyboard": "keyboard","keyboard.chevron.compact.down": "keyboard_hide","laptopcomputer": "laptop_mac",+ "line.3.horizontal": "menu","list.bullet": "format_list_bulleted","list.bullet.rectangle": "list_alt","lock.display": "screen_lock_landscape",@@ -171,6 +172,7 @@ MAP = {"safari": "explore","shift": "shift","shippingbox": "package_2",+ "slider.horizontal.3": "tune","square.and.arrow.down": "download","square.and.arrow.up": "ios_share","square.and.pencil": "edit_square",diff --git a/apps/desktop/e2e/usage-chooser.spec.ts b/apps/desktop/e2e/usage-chooser.spec.tsindex 998d5468..60294ec9 100644--- a/apps/desktop/e2e/usage-chooser.spec.ts+++ b/apps/desktop/e2e/usage-chooser.spec.ts@@ -12,8 +12,10 @@ test('Settings > Usage chooses which agents show, and the host keeps the choice'const shownAtStart = service.showntry {await api(page, 'setUsageShown', { id: service.id, shown: false })+ await page.reload() // A settings window left open would cover the account button.await page.locator('.sidebar-account').click()await page.locator('.account-panel').getByText('Usage', { exact: true }).click()+ await page.getByRole('button', { name: 'Choose and arrange' }).first().click()const row = page.locator('.settings-usage-chooser').getByRole('switch', { name: service.name })await expect(row).toHaveAttribute('aria-checked', 'false')@@ -31,3 +33,37 @@ test('Settings > Usage chooses which agents show, and the host keeps the choice'await browser.close()}})++test('dragging an agent in Settings > Usage changes its order, and the host keeps it', async () => {+ const { browser, page } = await attach()+ const order = async () => (await api<Usage>(page, 'usage', {})).services.map((s) => s.id)+ const before = await order()+ test.skip(before.length < 2, 'needs two agents that can report their usage')+ try {+ await page.reload() // A settings window left open would cover the account button.+ await page.locator('.sidebar-account').click()+ await page.locator('.account-panel').getByText('Usage', { exact: true }).click()+ await page.getByRole('button', { name: 'Choose and arrange' }).first().click()+ const rows = page.locator('.settings-usage-choice')+ await expect(rows).toHaveCount(before.length)++ const grip = await rows.nth(0).locator('.settings-usage-grip').boundingBox()+ const target = await rows.nth(1).boundingBox()+ if (!grip || !target) throw new Error('the rows have no box')+ await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2)+ await page.mouse.down()+ await page.mouse.move(grip.x + grip.width / 2, target.y + target.height / 2, { steps: 8 })+ await page.mouse.up()++ const swapped = [before[1], before[0], ...before.slice(2)]+ await expect.poll(order).toEqual(swapped)+ await expect(rows.nth(0)).toHaveAttribute('data-usage-service', before[1])++ await rows.nth(0).locator('.settings-usage-grip').focus()+ await page.keyboard.press('ArrowDown')+ await expect.poll(order).toEqual(before)+ } finally {+ await api(page, 'setUsageOrder', { ids: before }).catch(() => {})+ await browser.close()+ }+})diff --git a/apps/desktop/src/renderer/components/icon-fallbacks.ts b/apps/desktop/src/renderer/components/icon-fallbacks.tsindex 673d2fd8..17580d09 100644--- a/apps/desktop/src/renderer/components/icon-fallbacks.ts+++ b/apps/desktop/src/renderer/components/icon-fallbacks.ts@@ -161,6 +161,7 @@ const map: Record<string, IconNode> = {'server.rack': L.Server,shippingbox: L.Package,'sidebar.left': L.PanelLeft,+ 'line.3.horizontal': L.Menu,'slider.horizontal.3': L.SlidersHorizontal,sparkles: L.Sparkles,'speaker.slash.fill': L.VolumeX,diff --git a/apps/desktop/src/renderer/components/symbols.json b/apps/desktop/src/renderer/components/symbols.jsonindex 0b6aa42d..71ba4068 100644--- a/apps/desktop/src/renderer/components/symbols.json+++ b/apps/desktop/src/renderer/components/symbols.json@@ -163,5 +163,6 @@"xmark.circle","xmark.circle.fill","house.fill",-"bubble.left.fill"+"bubble.left.fill",+"line.3.horizontal"]diff --git a/apps/desktop/src/renderer/demo/fake-host.ts b/apps/desktop/src/renderer/demo/fake-host.tsindex f4eb89a6..1e22c5d6 100644--- a/apps/desktop/src/renderer/demo/fake-host.ts+++ b/apps/desktop/src/renderer/demo/fake-host.ts@@ -270,6 +270,7 @@ export class FakeHost {case 'credentialStatus':return { provider: '', onePasswordConnected: false }case 'setUsageShown':+ case 'setUsageOrder':return story.usage(Date.now())case 'setAnalytics':this.analytics = b.enabled === truediff --git a/apps/desktop/src/renderer/lib/usage-order.test.ts b/apps/desktop/src/renderer/lib/usage-order.test.tsnew file mode 100644index 00000000..a9a7049e--- /dev/null+++ b/apps/desktop/src/renderer/lib/usage-order.test.ts@@ -0,0 +1,28 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { hasNoReading, pastMiddle, servicesIn } from './usage-order.ts'++const service = (id: string, shown = true) => ({ id, name: id, shown })++test('a move on its way holds the order and agents it does not name follow', () => {+ const usage = { services: ['claude', 'codex', 'cursor'].map((id) => service(id)) }+ const ids = (order: string[] | null) => servicesIn(usage, order).map((s) => s.id)+ assert.deepEqual(ids(null), ['claude', 'codex', 'cursor'])+ assert.deepEqual(ids(['cursor', 'gone', 'claude']), ['cursor', 'claude', 'codex'])+ assert.deepEqual(servicesIn({}, ['claude']), [])+})++test('only an agent that is on can lack a reading', () => {+ const usage = { providers: [{ id: 'claude', name: 'Claude', windows: [], source: 'claude', updatedAt: 1 }] }+ assert.equal(hasNoReading(usage, service('claude')), false)+ assert.equal(hasNoReading(usage, service('cursor')), true)+ assert.equal(hasNoReading(usage, service('cursor', false)), false)+})++test('a dragged row takes a place only past its middle', () => {+ const box = { top: 100, height: 40 }+ assert.equal(pastMiddle(true, 119, box), false)+ assert.equal(pastMiddle(true, 120, box), true)+ assert.equal(pastMiddle(false, 121, box), false)+ assert.equal(pastMiddle(false, 120, box), true)+})diff --git a/apps/desktop/src/renderer/lib/usage-order.ts b/apps/desktop/src/renderer/lib/usage-order.tsnew file mode 100644index 00000000..cc1047a9--- /dev/null+++ b/apps/desktop/src/renderer/lib/usage-order.ts@@ -0,0 +1,17 @@+import type { Usage, UsageService } from '@shared/models'++/** The agents in `order`, a move still on its way to the host; any it doesn't name follow in the host's order. */+export function servicesIn({ services = [] }: Pick<Usage, 'services'>, order: string[] | null): UsageService[] {+ if (!order) return services+ return [...order.flatMap((id) => services.find((s) => s.id === id) ?? []), ...services.filter((s) => !order.includes(s.id))]+}++/** On, with nothing to show: signed out, or nothing to report. */+export const hasNoReading = ({ providers }: Pick<Usage, 'providers'>, service: UsageService) =>+ service.shown && !providers.some((p) => p.id === service.id)++/** Whether a row dragged over `box` takes its place: past the middle, not the edge, because rows slide as they swap and an edge would swap them straight back. */+export function pastMiddle(down: boolean, y: number, box: { top: number; height: number }) {+ const middle = box.top + box.height / 2+ return down ? y >= middle : y <= middle+}diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex ff2cdeff..039a9bf9 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -459,6 +459,11 @@ export class BotStore extends BotSync {this.changed()}+ async setUsageOrder(ids: string[]) {+ this.usage = await (await this.ready()).call<Usage>('setUsageOrder', { ids })+ this.changed()+ }+async refreshUsage() {if (this.retired || !this.client) returntry {diff --git a/apps/desktop/src/renderer/views/settings/SettingsView.tsx b/apps/desktop/src/renderer/views/settings/SettingsView.tsxindex baa17f4e..e1138ddf 100644--- a/apps/desktop/src/renderer/views/settings/SettingsView.tsx+++ b/apps/desktop/src/renderer/views/settings/SettingsView.tsx@@ -21,7 +21,7 @@ import { UpdateButton, useUpdates } from '../UpdateButton'import { ComputersView } from './ComputersView'import { NetworkView } from './NetworkView'import { errorText, isMac, thisMac } from './parts'-import { UsageChooser, UsageLimits } from './UsageLimits'+import { UsageSection } from './UsageLimits'import { VoiceChatSettingsView } from './VoiceChatSettingsView'import { ComputerAccessView } from '../computer-access/ComputerAccessView'import { FormSheet } from '../marketplace/pieces'@@ -271,22 +271,18 @@ function UsageLimitsList() {if (withUsage.length === 0) return <Text tone="secondary">{tr(`No usage information yet.`)}</Text>return (<>- {withUsage.flatMap((store) => [- stores.length > 1 ? (- <HStack key={`${store.computer.id}-label`} gap={6} className="settings-usage-computer">+ {withUsage.map((store) => (+ <UsageSection+ key={store.computer.id}+ title={<><ComputerBadge computer={store.computer} size={16} />{store.hostName}- </HStack>- ) : null,- <UsageLimits key={store.computer.id} usage={store.usage} />,- store.usage.services?.length ? (- <UsageChooser- key={`${store.computer.id}-chooser`}- usage={store.usage}- onChange={(id, shown) => void store.setUsageShown(id, shown).catch((e: unknown) => app.setError(errorText(e)))}- />- ) : null,- ])}+ </>}+ usage={store.usage}+ onShown={(id, shown) => void store.setUsageShown(id, shown).catch((e: unknown) => app.setError(errorText(e)))}+ onOrder={(ids) => store.setUsageOrder(ids).catch((e: unknown) => app.setError(errorText(e)))}+ />+ ))}</>)}diff --git a/apps/desktop/src/renderer/views/settings/UsageChooser.tsx b/apps/desktop/src/renderer/views/settings/UsageChooser.tsxnew file mode 100644index 00000000..7171a84b--- /dev/null+++ b/apps/desktop/src/renderer/views/settings/UsageChooser.tsx@@ -0,0 +1,123 @@+import { useRef, useState, type KeyboardEvent } from 'react'+import type { Usage, UsageProvider, UsageService } from '@shared/models'+import { Switch } from '../../components/Controls'+import { Icon } from '../../components/Icon'+import { HStack, VStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { moveInOrder } from '../../lib/computer-roster'+import { fill } from '../../lib/fill.ts'+import { pointerDrag } from '../../lib/pointer-drag'+import { prefs, usePref } from '../../lib/prefs'+import { useSlide } from '../../lib/slide'+import { useTr } from '../../lib/use-language'+import { hasNoReading, pastMiddle, servicesIn } from '../../lib/usage-order.ts'+import { ProviderMascot } from '../usage/ProviderMascot'+import './settings.css'++/** What a mascot needs of an agent that has no reading. */+const unreadProvider = ({ id, name, registry }: UsageService): UsageProvider => ({ id, name, registry, windows: [], source: '', updatedAt: 0 })++/** The agents in the host's order, or the one here while a row is held or its new place is on its way to the host. */+function useUsageOrder(usage: Usage, onOrder: (ids: string[]) => Promise<void>) {+ const [order, setOrder] = useState<string[] | null>(null)+ const [held, setHeld] = useState<string | null>(null)+ // A drag's handlers are the ones from when it was pressed: they read the order here, not from that render.+ const moving = useRef<string[]>([])+ const shown = servicesIn(usage, order)+ const ids = shown.map((s) => s.id)+ const commit = (next: string[]) => {+ setOrder(next)+ // A later move keeps its own order on screen until its own answer.+ void onOrder(next).finally(() => setOrder((current) => (current === next ? null : current)))+ }+ const handlers = (id: string) => ({+ lift: () => { moving.current = ids; setHeld(id); setOrder(ids) },+ over: (target: string, y: number, box: DOMRect) => {+ const down = moving.current.indexOf(target) > moving.current.indexOf(id)+ if (!pastMiddle(down, y, box)) return+ moving.current = moveInOrder(moving.current, id, target)+ setOrder(moving.current)+ },+ drop: () => {+ setHeld(null)+ if (moving.current.join() === ids.join()) setOrder(null)+ else commit(moving.current)+ },+ cancel: () => { setHeld(null); setOrder(null) },+ step: (by: number) => {+ const target = ids[ids.indexOf(id) + by]+ if (target) commit(moveInOrder(ids, id, target))+ },+ })+ return { shown, held, handlers }+}++/** Which agents' limits this computer lists, and in what order. */+export function UsageChooser({ usage, onShown, onOrder }: {+ usage: Usage+ onShown: (id: string, shown: boolean) => void+ onOrder: (ids: string[]) => Promise<void>+}) {+ const tr = useTr()+ const { shown, held, handlers } = useUsageOrder(usage, onOrder)+ return (+ <VStack gap={10} align="stretch" className="fade-in">+ <div className="settings-usage-card settings-usage-chooser">+ {shown.map((service) => (+ <ChooserRow+ key={service.id}+ service={service}+ unread={hasNoReading(usage, service)}+ held={held === service.id}+ onShown={(on) => onShown(service.id, on)}+ drag={handlers(service.id)}+ />+ ))}+ </div>+ <Text tone="secondary" size="caption">{tr('On by default for the agents your bots run.')}</Text>+ </VStack>+ )+}++function ChooserRow({ service, unread, held, onShown, drag }: {+ service: UsageService+ unread: boolean+ held: boolean+ onShown: (on: boolean) => void+ drag: ReturnType<ReturnType<typeof useUsageOrder>['handlers']>+}) {+ const [style] = usePref(prefs.usageIconStyle)+ const tr = useTr()+ const row = useRef<HTMLDivElement>(null)+ useSlide(row)+ const grip = pointerDrag({+ start: drag.lift,+ over: (at, under) => {+ const target = under?.closest<HTMLElement>('[data-usage-service]')+ const id = target?.dataset.usageService+ if (target && id && id !== service.id) drag.over(id, at.y, target.getBoundingClientRect())+ },+ drop: drag.drop,+ cancel: drag.cancel,+ })+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return+ event.preventDefault()+ drag.step(event.key === 'ArrowUp' ? -1 : 1)+ }+ const moveLabel = fill(tr('Move {name}'), { name: service.name })+ return (+ <div ref={row} data-usage-service={service.id} className={`settings-usage-choice${held ? ' held' : ''}`}>+ <button className="settings-usage-grip" title={moveLabel} aria-label={moveLabel} onKeyDown={onKeyDown} {...grip}>+ <Icon name="line.3.horizontal" size={12} color="var(--secondary)" />+ </button>+ <Switch on={service.shown} onChange={onShown} className="settings-usage-switch">+ <HStack gap={8}>+ <ProviderMascot provider={unreadProvider(service)} size={18} style={style} />+ <Text tone="text" truncate>{service.name}</Text>+ {unread ? <Text tone="secondary" truncate>{tr('No reading yet')}</Text> : null}+ </HStack>+ </Switch>+ </div>+ )+}diff --git a/apps/desktop/src/renderer/views/settings/UsageLimits.tsx b/apps/desktop/src/renderer/views/settings/UsageLimits.tsxindex 72730b3b..fc3015f0 100644--- a/apps/desktop/src/renderer/views/settings/UsageLimits.tsx+++ b/apps/desktop/src/renderer/views/settings/UsageLimits.tsx@@ -1,89 +1,103 @@-import { useRef } from 'react'-import type { Usage, UsageProvider, UsageService } from '@shared/models'-import { Reveal, Switch } from '../../components/Controls'-import { HStack, VStack } from '../../components/Stack'+import { useRef, useState, type ReactNode } from 'react'+import type { Usage, UsageProvider, UsageWindow } from '@shared/models'+import { IconButton, Reveal } from '../../components/Controls'+import { HStack, Spacer, VStack } from '../../components/Stack'import { Text } from '../../components/Text'import { prefs, usePref } from '../../lib/prefs'import { useResetLine, useTr } from '../../lib/use-language'import { ProviderMascot } from '../usage/ProviderMascot'import { UsageBar } from '../usage/UsageBar'-import { providerTintCSS, resetDescription, windowReading, windowTitle } from '../usage/usage-model'+import { providerTintCSS, resetDescription, windowTitle } from '../usage/usage-model'+import { UsageChooser } from './UsageChooser'import './settings.css'-/** What a mascot needs of an agent that has no reading. */-const unreadProvider = ({ id, name, registry }: UsageService): UsageProvider => ({ id, name, registry, windows: [], source: '', updatedAt: 0 })--/** Every provider seen, so that one turned off can still fold away, and the ones the page opened with. */-function useProvidersSeen(providers: UsageProvider[]) {+/** Every provider seen, in the order the host gives, so that one turned off can still fold away; and the ones the page opened with. */+function useProvidersSeen({ providers, services }: Usage) {const seen = useRef(new Map<string, UsageProvider>())const atFirst = useRef(new Set(providers.map((p) => p.id)))for (const provider of providers) seen.current.set(provider.id, provider)- return { seen: [...seen.current.values()].sort((a, b) => a.id.localeCompare(b.id)), atFirst: atFirst.current }+ const rank = (id: string) => {+ const at = services?.findIndex((s) => s.id === id) ?? -1+ return at < 0 ? Number.MAX_SAFE_INTEGER : at+ }+ return { seen: [...seen.current.values()].sort((a, b) => rank(a.id) - rank(b.id)), atFirst: atFirst.current }+}++/** One computer's usage: its name, what its agents have used, and behind a button which agents show and in what order. */+export function UsageSection({ title, usage, onShown, onOrder }: {+ title: ReactNode+ usage: Usage+ onShown: (id: string, shown: boolean) => void+ onOrder: (ids: string[]) => Promise<void>+}) {+ const tr = useTr()+ const [editing, setEditing] = useState(false)+ const canEdit = !!usage.services?.length+ return (+ <VStack gap={10}>+ <HStack gap={6} className="settings-usage-computer">+ {title}+ <Spacer />+ {canEdit ? (+ <IconButton+ title={tr(editing ? 'Done' : 'Choose and arrange')}+ icon={editing ? 'checkmark' : 'slider.horizontal.3'}+ onClick={() => setEditing(!editing)}+ />+ ) : null}+ </HStack>+ {editing ? <UsageChooser usage={usage} onShown={onShown} onOrder={onOrder} /> : <UsageLimits usage={usage} />}+ </VStack>+ )}/** Every limit as a bar under its provider, the way the menu bar lists them. */-export function UsageLimits({ usage }: { usage: Usage }) {+function UsageLimits({ usage }: { usage: Usage }) {const tr = useTr()- const { seen, atFirst } = useProvidersSeen(usage.providers)+ const { seen, atFirst } = useProvidersSeen(usage)+ if (usage.providers.length === 0) return <Text tone="secondary">{tr('No usage information yet.')}</Text>return (- <VStack gap={18}>- {usage.providers.length === 0 ? <Text tone="secondary">{tr('No usage information yet.')}</Text> : null}+ <div className="settings-usage-card fade-in">{seen.map((provider) => (<Reveal key={provider.id} show={usage.providers.some((p) => p.id === provider.id)} animateOnMount={!atFirst.has(provider.id)}><ProviderLimits provider={provider} /></Reveal>))}- </VStack>+ </div>)}function ProviderLimits({ provider }: { provider: UsageProvider }) {const [style] = usePref(prefs.usageIconStyle)- const resetLine = useResetLine()- const tr = useTr()return (- <VStack gap={10} className="settings-usage-provider">+ <VStack gap={12} className="settings-usage-provider"><HStack gap={8}><ProviderMascot provider={provider} size={18} style={style} /><Text size="body" weight="semibold" tone="text">{provider.name}</Text></HStack>- {provider.windows.map((w) => (- <HStack key={w.id} gap={10} className="settings-usage-row">- <Text tone="text" truncate className="settings-usage-title">{tr(windowTitle(w))}</Text>- {w.text ? (- <Text tone="text" truncate className="settings-usage-note">{w.text}</Text>- ) : (- <>- <UsageBar percent={w.percent} tint={providerTintCSS(provider.id)} />- <Text tone="text" tabular className="settings-usage-percent">{windowReading(w, tr)}</Text>- <Text tone="secondary" truncate className="settings-usage-reset">{resetLine(resetDescription(w) ?? '')}</Text>- </>- )}- </HStack>- ))}+ {provider.windows.map((w) => <WindowLimit key={w.id} window={w} providerId={provider.id} />)}</VStack>)}-/** Which agents' limits this computer lists. */-export function UsageChooser({ usage, onChange }: { usage: Usage; onChange: (id: string, shown: boolean) => void }) {- const [style] = usePref(prefs.usageIconStyle)+/** A limit's name and when it resets, how much is used, and under them the bar; or the note an agent gives instead. */+function WindowLimit({ window: w, providerId }: { window: UsageWindow; providerId: string }) {+ const resetLine = useResetLine()const tr = useTr()return (- <VStack gap={10} className="settings-usage-chooser">- <Text tone="secondary">{tr('Show usage for')}</Text>- {usage.services?.map((service) => (- <Switch key={service.id} on={service.shown} onChange={(shown) => onChange(service.id, shown)}>- <HStack gap={8}>- <ProviderMascot provider={unreadProvider(service)} size={18} style={style} />- <Text tone="text" truncate>{service.name}</Text>- {service.shown && !usage.providers.some((p) => p.id === service.id) ? (- <Text tone="secondary" truncate>{tr('No reading yet')}</Text>- ) : null}- </HStack>- </Switch>- ))}- <Text tone="secondary">{tr('On by default for the agents your bots run.')}</Text>+ <VStack gap={6} align="stretch">+ <HStack gap={8}>+ <Text tone="text" truncate>{tr(windowTitle(w))}</Text>+ {w.text ? (+ <Text tone="secondary" truncate grow className="settings-usage-note">{w.text}</Text>+ ) : (+ <>+ <Text tone="secondary" truncate grow>{resetLine(resetDescription(w) ?? '')}</Text>+ <Text tone="text" weight="medium" tabular>{Math.round(w.percent)}%</Text>+ </>+ )}+ </HStack>+ {w.text ? null : <UsageBar percent={w.percent} tint={providerTintCSS(providerId)} />}</VStack>)}diff --git a/apps/desktop/src/renderer/views/settings/settings.css b/apps/desktop/src/renderer/views/settings/settings.cssindex dc8f2418..212180c0 100644--- a/apps/desktop/src/renderer/views/settings/settings.css+++ b/apps/desktop/src/renderer/views/settings/settings.css@@ -134,43 +134,61 @@justify-content: flex-end;}-/* Usage: a computer's label over its limits, then one row per limit. */+/* Usage: a computer's name and button over its card. */.settings-usage-computer {font-size: var(--text-body);- font-weight: 700;+ font-weight: 600;+ min-height: 28px;}-.settings-usage-row {+/* One card a computer: its agents' limits, or which agents show and in what order. */+.settings-usage-card {+ background: var(--surface);+ border-radius: var(--radius-l);font-size: var(--text-callout);- font-weight: 400;- white-space: nowrap;}-.settings-usage-title {- width: 64px;- flex: none;-}-.settings-usage-percent {- /* Grows past this for longer translations (de, fr); the bar gives way. */- min-width: 76px;- flex: none;- text-align: right;+/* Padding, not a gap: it folds away with an agent turned off, and leaves room for a mascot's alert. */+.settings-usage-provider {+ padding: 14px 16px;}.settings-usage-note {- flex: 1;- min-width: 0;text-align: right;}-.settings-usage-reset {- width: 130px;+.settings-usage-card .progress-track.usage-bar {flex: none;- text-align: right;-}-/* Room for a mascot's alert, which sits just above it, inside the fold's clip. */-.settings-usage-provider {- padding-top: 3px;+ height: 5px;+ background: rgba(var(--text-rgb), 0.08);}.settings-usage-chooser {- margin-top: 18px;- font-size: var(--text-callout);+ padding: 4px;+}+.settings-usage-choice {+ display: flex;+ align-items: center;+ gap: 4px;+ min-height: 40px;+ padding-right: 10px;+ border-radius: var(--radius-m);+ transition: background-color var(--hover);+}+.settings-usage-choice.held {+ position: relative;+ z-index: 1;+ background: var(--sheet);+ box-shadow: var(--shadow-m);+}+.settings-usage-switch {+ flex: 1;+ min-width: 0;+}+.settings-usage-grip {+ display: grid;+ place-items: center;+ width: 28px;+ height: 32px;+ flex: none;+ border-radius: var(--radius-xs);+ cursor: grab;+ touch-action: none;}/* Computers & devices. */diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Usage.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Usage.swiftnew file mode 100644index 00000000..8bc11f20--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Usage.swift@@ -0,0 +1,17 @@+import Foundation++public extension HostClient {+ func usage(refresh: Bool = false) async throws -> Usage {+ try await call("usage", ["refresh": refresh])+ }++ /// Whether this computer lists one agent's limits.+ func setUsageShown(_ id: String, shown: Bool) async throws -> Usage {+ struct Body: Encodable { var id: String; var shown: Bool }+ return try await call("setUsageShown", Body(id: id, shown: shown))+ }++ func setUsageOrder(_ ids: [String]) async throws -> Usage {+ try await call("setUsageOrder", ["ids": ids])+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 707c52a7..096db499 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -393,16 +393,6 @@ public extension HostClient {let _: Empty = try await call("registerActivity", ["botId": botId, "ticket": ticket])}- func usage(refresh: Bool = false) async throws -> Usage {- try await call("usage", ["refresh": refresh])- }-- /// Whether this computer lists one agent's limits.- func setUsageShown(_ id: String, shown: Bool) async throws -> Usage {- struct Body: Encodable { var id: String; var shown: Bool }- return try await call("setUsageShown", Body(id: id, shown: shown))- }-func selectWorkspace(_ path: String) async throws -> String {struct Reply: Decodable { var path: String }let reply: Reply = try await call("selectWorkspace", ["path": path])diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Usage+Services.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Usage+Services.swiftnew file mode 100644index 00000000..831dfaeb--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Usage+Services.swift@@ -0,0 +1,13 @@+public extension Usage {+ /// The agents in `order`, a move still on its way to the host; any it doesn't name follow in the host's order.+ func services(in order: [String]?) -> [UsageService] {+ let all = services ?? []+ guard let order else { return all }+ return order.compactMap { id in all.first { $0.id == id } } + all.filter { !order.contains($0.id) }+ }++ /// On, with nothing to show: signed out, or nothing to report.+ func hasNoReading(_ service: UsageService) -> Bool {+ service.shown && !providers.contains { $0.id == service.id }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex 27bae656..cefe63ea 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1841,5 +1841,8 @@"Credits": "Guthaben","Prepaid": "Prepaid","Monthly": "Monatlich",- "Completions": "Vervollständigungen"+ "Completions": "Vervollständigungen",+ "Choose and arrange": "Auswählen und anordnen",+ "Move {name}": "{name} verschieben",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ wählen · J K ordnen · space schalten · esc schließen"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex ef3cc814..b3161c55 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1841,5 +1841,8 @@"Credits": "Créditos","Prepaid": "Prepago","Monthly": "Mensual",- "Completions": "Autocompletados"+ "Completions": "Autocompletados",+ "Choose and arrange": "Elegir y ordenar",+ "Move {name}": "Mover {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ elegir · J K ordenar · space alternar · esc cerrar"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex e08dae63..22c7386d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1841,5 +1841,8 @@"Credits": "Crédits","Prepaid": "Prépayé","Monthly": "Mensuel",- "Completions": "Complétions"+ "Completions": "Complétions",+ "Choose and arrange": "Choisir et organiser",+ "Move {name}": "Déplacer {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ choisir · J K organiser · space basculer · esc fermer"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.jsonindex 89288ee2..44bf9cea 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json@@ -1841,5 +1841,8 @@"Credits": "Crediti","Prepaid": "Prepagato","Monthly": "Mensile",- "Completions": "Completamenti"+ "Completions": "Completamenti",+ "Choose and arrange": "Scegli e ordina",+ "Move {name}": "Sposta {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ scegli · J K ordina · space attiva · esc chiudi"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 55f34e46..cac2fab8 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1841,5 +1841,8 @@"Credits": "クレジット","Prepaid": "プリペイド","Monthly": "月間",- "Completions": "補完"+ "Completions": "補完",+ "Choose and arrange": "選択と並べ替え",+ "Move {name}": "{name} を移動",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 選択 · J K 並べ替え · space 切替 · esc 閉じる"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex f9f44d4a..aeabcd3e 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1841,5 +1841,8 @@"Credits": "크레딧","Prepaid": "선불","Monthly": "월간",- "Completions": "자동 완성"+ "Completions": "자동 완성",+ "Choose and arrange": "선택 및 정렬",+ "Move {name}": "{name} 이동",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 선택 · J K 정렬 · space 전환 · esc 닫기"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.jsonindex e7b54db4..c6e1346c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json@@ -1841,5 +1841,8 @@"Credits": "Créditos","Prepaid": "Pré-pago","Monthly": "Mensal",- "Completions": "Preenchimentos"+ "Completions": "Preenchimentos",+ "Choose and arrange": "Escolher e organizar",+ "Move {name}": "Mover {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ escolher · J K ordenar · space alternar · esc fechar"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.jsonindex 920de313..c26526de 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json@@ -1841,5 +1841,8 @@"Credits": "Кредиты","Prepaid": "Предоплата","Monthly": "Ежемесячно",- "Completions": "Автодополнения"+ "Completions": "Автодополнения",+ "Choose and arrange": "Выбрать и упорядочить",+ "Move {name}": "Переместить {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ выбор · J K порядок · space переключить · esc закрыть"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex cf897776..54cdda8a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1841,5 +1841,8 @@"Credits": "额度","Prepaid": "预付","Monthly": "每月",- "Completions": "补全"+ "Completions": "补全",+ "Choose and arrange": "选择与排序",+ "Move {name}": "移动 {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 选择 · J K 排序 · space 切换 · esc 关闭"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 087d7ee4..f0807412 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1841,5 +1841,8 @@"Credits": "額度","Prepaid": "預付","Monthly": "每月",- "Completions": "自動完成"+ "Completions": "自動完成",+ "Choose and arrange": "選擇與排序",+ "Move {name}": "移動 {name}",+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 選擇 · J K 排序 · space 切換 · esc 關閉"}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swiftindex eefe1bdc..f0bdac77 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift@@ -403,6 +403,15 @@ extension BotStore {}}+ /// The order this computer lists its agents in. A host older than this refuses the call: the error shows and the order stays.+ public func setUsageOrder(_ ids: [String]) async {+ do {+ setUsage(try await ready().setUsageOrder(ids))+ } catch {+ lastError = error.localizedDescription+ }+ }+public func refreshUsage() async {guard !retired, let client else { return }if let u = try? await client.usage(refresh: true), !Task.isCancelled { setUsage(u) }diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/UsageOrder.swift b/apps/ios/Kit/Sources/CodyncUI/Store/UsageOrder.swiftnew file mode 100644index 00000000..b489a3a8--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/UsageOrder.swift@@ -0,0 +1,11 @@+import SwiftUI++/// What a move does to the agents' order. The host keeps the order; this says what to send it.+public enum UsageOrder {+ /// `ids` after a drop, as `onMove` reports it; nil when the row landed where it was.+ public static func moved(_ ids: [String], from source: IndexSet, to destination: Int) -> [String]? {+ var moved = ids+ moved.move(fromOffsets: source, toOffset: destination)+ return moved == ids ? nil : moved+ }+}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/UsageServiceTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/UsageServiceTests.swiftindex d4532d86..391cc2fe 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/UsageServiceTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/UsageServiceTests.swift@@ -15,6 +15,22 @@ import Testing#expect(usage.services == nil)}+ @Test func aMoveOnItsWayHoldsTheOrderAndAgentsItDoesNotNameFollow() {+ let service = { (id: String) in UsageService(id: id, name: id, shown: true) }+ let usage = Usage(services: ["claude", "codex", "cursor"].map(service))+ #expect(usage.services(in: nil).map(\.id) == ["claude", "codex", "cursor"])+ #expect(usage.services(in: ["cursor", "gone", "claude"]).map(\.id) == ["cursor", "claude", "codex"])+ #expect(Usage().services(in: ["claude"]).isEmpty)+ }++ @Test func onlyAnAgentThatIsOnCanLackAReading() {+ let read = UsageProvider(id: "claude", name: "Claude", windows: [], source: "claude", updatedAt: 1)+ let usage = Usage(providers: [read])+ #expect(!usage.hasNoReading(UsageService(id: "claude", name: "Claude", shown: true)))+ #expect(usage.hasNoReading(UsageService(id: "cursor", name: "Cursor", shown: true)))+ #expect(!usage.hasNoReading(UsageService(id: "cursor", name: "Cursor", shown: false)))+ }+@Test func everyReadersLogoLoadsFromTheKit() {let named = ["claude-acp", "codex-acp", "antigravity-acp", "cursor", "github-copilot-cli", "grok-build", "amp-acp", "auggie", "junie", "kilo", "kimi", "mistral-vibe"]for registry in named {diff --git a/apps/ios/Kit/Tests/CodyncUITests/UsageOrderTests.swift b/apps/ios/Kit/Tests/CodyncUITests/UsageOrderTests.swiftnew file mode 100644index 00000000..82f64071--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/UsageOrderTests.swift@@ -0,0 +1,16 @@+import Foundation+import Testing+@testable import CodyncUI++@Suite struct UsageOrderTests {+ @Test func aDroppedRowLandsWhereItWasLetGo() {+ let ids = ["claude", "codex", "cursor"]+ #expect(UsageOrder.moved(ids, from: [0], to: 2) == ["codex", "claude", "cursor"])+ #expect(UsageOrder.moved(ids, from: [2], to: 0) == ["cursor", "claude", "codex"])+ }++ @Test func aRowDroppedInItsOwnPlaceSendsNothing() {+ #expect(UsageOrder.moved(["claude", "codex"], from: [0], to: 0) == nil)+ #expect(UsageOrder.moved(["claude", "codex"], from: [0], to: 1) == nil)+ }+}diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swiftindex 8ebcb665..b6f5f2c1 100644--- a/apps/ios/Views/RootView.swift+++ b/apps/ios/Views/RootView.swift@@ -298,6 +298,11 @@ private struct UsageSheet: View {}}.background(Palette.background)+ // What failed here (a switch, a drag) shows over this sheet, not under it at the root,+ // where the same error clears with this one.+ .codyncDialog("Something went wrong", isPresented: Binding(+ get: { store?.lastError != nil }, set: { if !$0 { store?.lastError = nil } }+ ), message: store?.lastError, cancel: "OK", inPlace: true) { [] }.tracked(.screenViewed(.usage))}}diff --git a/apps/ios/Views/UsageView.swift b/apps/ios/Views/UsageView.swiftindex aa4ff980..829e2e87 100644--- a/apps/ios/Views/UsageView.swift+++ b/apps/ios/Views/UsageView.swift@@ -2,159 +2,173 @@ import CodyncKitimport CodyncUIimport SwiftUI-/// Usage limits (opened from the State tab): one card per provider, the tightest limit as a big bar, every limit listed below.+/// One computer's usage (opened from the State tab): its name, what its agents have used, and behind a button+/// which agents show and in what order. A `List` for the system's reordering, in edit mode only while arranging,+/// which is what limits a drag to the handle.struct UsageView: View {@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var collapsed: Set<String> = []+ @State private var arranging = false+ /// The order just dropped: on screen until the host answers, so the row doesn't jump back.+ @State private var sentOrder: [String]?var body: some View {- ScrollView {- VStack(spacing: 16) {- ForEach(model.usage.providers) { provider in- ProviderCard(provider: provider, collapsed: Binding(- get: { collapsed.contains(provider.id) },- set: { if $0 { collapsed.insert(provider.id) } else { collapsed.remove(provider.id) } }- ))- }- if model.usage.providers.isEmpty {- VStack(spacing: 8) {- Image(systemName: "chart.bar").font(.system(size: 40)).foregroundStyle(Palette.tertiary)- Text(L10n.tr("No usage yet")).font(.title3.weight(.semibold)).foregroundStyle(Palette.text)- Text(L10n.tr("Your computer reads plan limits from the agents your bots run and the ones you turn on."))- .font(.subheadline).foregroundStyle(Palette.secondary)+ let usage = model.usage+ let services = usage.services(in: sentOrder)+ let editing = arranging && !services.isEmpty+ List {+ Section {+ if editing {+ ForEach(services) { service in+ ChooserRow(service: service, hasNoReading: usage.hasNoReading(service))+ }+ .onMove { source, destination in+ UsageOrder.moved(services.map(\.id), from: source, to: destination).map(send)+ }+ } else if usage.providers.isEmpty {+ Text(L10n.tr("No usage information yet."))+ .font(.subheadline)+ .foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .listRowBackground(Color.clear)+ } else {+ // One row, not one each: a row that was on screen before edit mode keeps its place in the+ // list under the same id, and the system then gives it no handle.+ VStack(alignment: .leading, spacing: 28) {+ ForEach(usage.providers) { ProviderLimits(provider: $0) }}- .multilineTextAlignment(.center)- .frame(maxWidth: .infinity)- .padding(.top, 60)+ .listRowInsets(EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16))}- if let services = model.usage.services, !services.isEmpty {- UsageChooser(services: services)+ } header: {+ heading(canArrange: !services.isEmpty, editing: editing)+ } footer: {+ if editing {+ Text(L10n.tr("On by default for the agents your bots run."))+ .font(.caption)+ .foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)}}- .padding(16)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: model.usage.providers.map(\.id))+ .listRowBackground(Palette.surface)+ .listRowSeparator(.hidden)+ .environment(\.layoutDirection, .leftToRight)}+ .listStyle(.insetGrouped)+ // The system keeps its reorder handle at the row's trailing edge: this makes that the left.+ .environment(\.layoutDirection, .rightToLeft)+ .scrollContentBackground(.hidden)+ .scrollIndicators(.hidden)+ .environment(\.editMode, .constant(editing ? .active : .inactive))+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: usage.providers.map(\.id)).background(Palette.background).refreshable { await model.refreshUsage() }}++ private func heading(canArrange: Bool, editing: Bool) -> some View {+ HStack(spacing: 6) {+ ComputerBadge(model.computer, size: 20)+ Text(model.hostName)+ .font(.subheadline.weight(.semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ Spacer(minLength: 0)+ if canArrange {+ IconButton(editing ? "Done" : "Choose and arrange", systemImage: editing ? "checkmark" : "slider.horizontal.3") {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { arranging = !editing }+ }+ // Its glyph over the switches' edge.+ .padding(.trailing, -8)+ }+ }+ .textCase(nil)+ }++ /// Holds `ids` on screen until the answer lands, or until a refusal puts the host's order back.+ private func send(_ ids: [String]) {+ sentOrder = ids+ Task {+ await model.setUsageOrder(ids)+ // A later drop keeps its own order on screen until its own answer.+ if sentOrder == ids { sentOrder = nil }+ }+ }}-/// Which agents' limits this computer lists.-private struct UsageChooser: View {- let services: [UsageService]+/// An agent's name, its switch, and the system's handle beside it.+private struct ChooserRow: View {+ let service: UsageService+ let hasNoReading: Bool@Environment(BotStore.self) private var modelvar body: some View {- VStack(alignment: .leading, spacing: 12) {- Text(L10n.tr("Show usage for")).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)- ForEach(services) { service in- Toggle(isOn: binding(service)) {- HStack(spacing: 10) {- ProviderTile(provider: service.provider)- VStack(alignment: .leading, spacing: 2) {- Text(service.name).font(.subheadline).foregroundStyle(Palette.text)- if service.shown, !model.usage.providers.contains(where: { $0.id == service.id }) {- Text(L10n.tr("No reading yet")).font(.caption).foregroundStyle(Palette.tertiary)- }- }- }+ Toggle(isOn: Binding(get: { service.shown }, set: { shown in+ Task { await model.setUsageShown(service.id, shown: shown) }+ })) {+ HStack(spacing: 8) {+ Mascot(provider: service.provider)+ Text(service.name).font(.subheadline).foregroundStyle(Palette.text).lineLimit(1)+ if hasNoReading {+ Text(L10n.tr("No reading yet")).font(.subheadline).foregroundStyle(Palette.secondary).lineLimit(1)}- .toggleStyle(.codync)}- Text(L10n.tr("On by default for the agents your bots run.")).font(.caption).foregroundStyle(Palette.tertiary)}- .padding(14)- .frame(maxWidth: .infinity, alignment: .leading)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 20, style: .continuous))- }-- private func binding(_ service: UsageService) -> Binding<Bool> {- Binding(get: { service.shown }, set: { shown in- Task { await model.setUsageShown(service.id, shown: shown) }- })+ .toggleStyle(.codync)}}-/// An agent's mascot or logo on its tinted tile.-private struct ProviderTile: View {+/// An agent's mascot or logo, whichever the widgets' setting chose.+private struct Mascot: View {let provider: UsageProvider@AppStorage(SharedStore.usageIconStyleKey, store: UserDefaults(suiteName: SharedStore.appGroup))private var usageIconStyle = UsageIconStyle.character.rawValuevar body: some View {- ProviderMascot(provider, size: 22, style: UsageIconStyle(rawValue: usageIconStyle) ?? .character)- .frame(width: 34, height: 34)- .background(provider.tint.opacity(0.12), in: RoundedRectangle(cornerRadius: 10, style: .continuous))+ ProviderMascot(provider, size: 20, style: UsageIconStyle(rawValue: usageIconStyle) ?? .character)}}-private struct ProviderCard: View {+private struct ProviderLimits: View {let provider: UsageProvider- @Binding var collapsed: Bool- @Environment(\.accessibilityReduceMotion) private var reduceMotionvar body: some View {VStack(alignment: .leading, spacing: 12) {- HStack(spacing: 10) {- ProviderTile(provider: provider)- Text(provider.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)- Spacer()- IconButton(collapsed ? "Expand" : "Collapse", systemImage: "chevron.up") {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { collapsed.toggle() }- }- .rotationEffect(.degrees(collapsed ? 180 : 0))- }-- if let top = provider.tightest {- VStack(alignment: .leading, spacing: 6) {- HStack {- Text(L10n.tr(top.title))- Spacer()- Text(top.usedText).monospacedDigit()- }- .font(.subheadline)- .foregroundStyle(Palette.text)- UsageTicks(percent: top.percent, tint: provider.widgetTint, height: 15)- if let reset = top.resetsShort() {- Text(L10n.resetLine(reset)).font(.caption.monospacedDigit()).foregroundStyle(Palette.tertiary)- .frame(maxWidth: .infinity, alignment: .trailing)- }- }- }-- if !collapsed {- VStack(spacing: 8) {- ForEach(provider.windows) { w in- row(L10n.tr(w.title), w.reading)- if let reset = w.resetsShort() { row(L10n.tr("Resets"), L10n.resetLine(reset)) }- }- row("Source", source)- row("Updated", Date(milliseconds: provider.updatedAt).formatted(date: .abbreviated, time: .shortened))- }- .transition(.opacity)+ HStack(spacing: 8) {+ Mascot(provider: provider)+ Text(provider.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)}+ ForEach(provider.windows) { WindowLimit(window: $0, tint: provider.widgetTint) }}- .padding(14)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 20, style: .continuous))}+}- private var source: String {- switch provider.source {- case "claude": "Claude Code"- case "statusline": "Claude Code status line"- case "agent": "A running bot"- case "sessions": "Codex sessions"- default: provider.source- }- }+/// A limit's name and when it resets, how much is used, and under them the bar; or the note an agent gives instead.+private struct WindowLimit: View {+ let window: UsageWindow+ let tint: Color- private func row(_ label: String, _ value: String) -> some View {- HStack {- Text(L10n.tr(label)).foregroundStyle(Palette.secondary)- Spacer()- Text(value).foregroundStyle(Palette.text).monospacedDigit()+ var body: some View {+ VStack(alignment: .leading, spacing: 6) {+ HStack(spacing: 8) {+ Text(L10n.tr(window.title)).foregroundStyle(Palette.text).lineLimit(1).layoutPriority(window.text == nil ? 0 : 1)+ if let note = window.text {+ Text(note).foregroundStyle(Palette.secondary).lineLimit(1).frame(maxWidth: .infinity, alignment: .trailing)+ } else {+ Text(window.resetsShort().map(L10n.resetLine) ?? "")+ .foregroundStyle(Palette.secondary)+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: .leading)+ Text("\(Int(window.percent.rounded()))%")+ .fontWeight(.medium)+ .monospacedDigit()+ .foregroundStyle(Palette.text)+ .layoutPriority(1)+ .accessibilityLabel(window.usedText)+ }+ }+ .font(.subheadline)+ if window.text == nil {+ UsageTicks(percent: window.percent, tint: tint, height: 5)+ }}- .font(.footnote)}}diff --git a/apps/maestro/usage-chooser.js b/apps/maestro/usage-chooser.jsindex 09f034ea..407ea592 100644--- a/apps/maestro/usage-chooser.js+++ b/apps/maestro/usage-chooser.js@@ -1,6 +1,7 @@-// Starts `usage-chooser.yaml` with one agent off on the host the phone is paired with (HOST_PORT and HOST_TOKEN, passed-// with `-e`), and checks what the switch did there: `EXPECT` is the state the host must hold. Phones in one run share-// that host, so each takes an agent of its own, from the end of the list: the ones a computer rarely has a login for.+// Helps `usage-chooser.yaml`, on the host the phone is paired with (HOST_PORT and HOST_TOKEN, passed with `-e`). Phones in+// one run share that host, so each takes agents of its own, by id, and asks only what its own actions did.+// Without `STEP` it picks them: one to switch, from the middle of the list (the ends are for dragging), starting off; and+// one to drag: the iPhone's goes from the top downward, Android's from the bottom upward, past the agent next to it.const api = (method, body) => {const res = http.post(`http://127.0.0.1:${HOST_PORT}/api/${method}`, {headers: { Authorization: `Bearer ${HOST_TOKEN}`, 'Content-Type': 'application/json' },@@ -10,11 +11,22 @@ const api = (method, body) => {return json(res.body)}const services = api('usage', {}).services-const service = services[services.length - (maestro.platform === 'ios' ? 1 : 2)]+const ids = services.map((service) => service.id)+const onIphone = maestro.platform === 'ios'-if (typeof EXPECT !== 'undefined') {- if (String(service.shown) !== EXPECT) throw new Error(`${service.id} shown is ${service.shown}, expected ${EXPECT}`)-} else {- api('setUsageShown', { id: service.id, shown: false })- output.agent = service.name+if (typeof STEP === 'undefined') {+ const switched = services[Math.floor(services.length / 2) - (onIphone ? 1 : 0)]+ const dragged = onIphone ? 0 : services.length - 1+ api('setUsageShown', { id: switched.id, shown: false })+ output.agent = switched.name+ output.switched = switched.id+ output.dragged = services[dragged].name+ output.draggedId = ids[dragged]+ output.passed = ids[dragged + (onIphone ? 1 : -1)]+} else if (STEP === 'shown') {+ const shown = String(services.find((service) => service.id === output.switched).shown)+ if (shown !== EXPECT) throw new Error(`${output.switched} shown is ${shown}, expected ${EXPECT}`)+} else if (STEP === 'dragged') {+ const below = ids.indexOf(output.draggedId) > ids.indexOf(output.passed)+ if (below !== onIphone) throw new Error(`${output.draggedId} didn't pass ${output.passed}: ${ids}`)}diff --git a/apps/maestro/usage-chooser.yaml b/apps/maestro/usage-chooser.yamlindex 1a3e4282..d9fceea5 100644--- a/apps/maestro/usage-chooser.yaml+++ b/apps/maestro/usage-chooser.yaml@@ -1,6 +1,6 @@-# State > Usage limits lists the computer's agents, each with a switch: turning one on and off reaches the host, which-# keeps the choice. The phone must already be signed in and paired with the host (a worktree's sandbox,-# docs/guides/dev-app.md#worktree-sandboxes), and the computer must list two agents:+# State > Usage limits keeps the agents behind one button, each with a switch and a handle: turning one on and off and+# dragging one past another reach the host, which keeps both. The phone must already be signed in and paired with the host+# (a worktree's sandbox, docs/guides/dev-app.md#worktree-sandboxes), and the computer must list four agents:# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags usage \# -e HOST_PORT=<sandbox port> -e HOST_TOKEN="$(cat ~/.codync-dev-<sandbox name>/token)" apps/maestroappId: com.pokai.Codync.ios.dev@@ -22,26 +22,43 @@ tags:appId: com.pokai.Codync.android.dev- tapOn: "State"- tapOn: "Usage limits"-- scrollUntilVisible:- element: "On by default for the agents your bots run."- direction: DOWN-- assertVisible: "Show usage for"+- tapOn: "Choose and arrange"+- assertVisible: "On by default for the agents your bots run."- takeScreenshot: usage-chooser-# Below the heading: an agent with a reading has a card above, under the same name.-- tapOn:- text: "${output.agent}.*"- below: "Show usage for"+- tapOn: "${output.agent}.*"- runScript:file: usage-chooser.jsenv:+ STEP: shownEXPECT: "true"-- scrollUntilVisible:- element: "On by default for the agents your bots run."- direction: DOWN-- tapOn:- text: "${output.agent}.*"- below: "Show usage for"+- tapOn: "${output.agent}.*"- runScript:file: usage-chooser.jsenv:+ STEP: shownEXPECT: "false"+# The handle's label: the system's on iOS, ours on Android.+- runFlow:+ when:+ platform: iOS+ commands:+ - swipe:+ from:+ text: "Reorder ${output.dragged}"+ direction: DOWN+ duration: 1500+- runFlow:+ when:+ platform: Android+ commands:+ - swipe:+ from:+ text: "Move ${output.dragged}"+ direction: UP+ duration: 1500+- runScript:+ file: usage-chooser.js+ env:+ STEP: dragged+- tapOn: "Done"+- assertNotVisible: "On by default for the agents your bots run."diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 75711f30..d760d65c 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -46,7 +46,7 @@ The tray menu is Electron's native `Menu` (`apps/desktop/src/main/tray.ts`), theThe menu retains host installation/restart, bot conversation/stop actions, approval review, usage limits, remote-screen permissions, open-at-login and quit. Pairing opens a separate titled window because its QR needs a persistent scanning surface. The chat window retains its own UI conventions.Usage limits appear directly in the top-level menu, grouped by provider with native section headers. Show each window's used percentage (`{percent}% used`), reset time when available, and the provider's last update; do not hide them in submenus. The account menu's-Usage row shows no number; it opens Settings' Usage page with the same per-provider bars. Below the bars, that page and the phones' Usage screen list the computer's agents with a switch each ([which agents show](../features/usage-limits.md#which-agents-show)).+Usage row shows no number; it opens Settings' Usage page with the same per-provider bars. That page and the phones' Usage screen show one card a computer, and a button beside its name swaps the bars for the computer's agents with a drag handle and a switch each ([which agents show](../features/usage-limits.md#which-agents-show)).## Account menu and Settings (desktop)@@ -75,7 +75,7 @@ Other custom iPhone screens use `Chrome.swift` and `Controls.swift`. The desktop| Toggle | `ToggleStyle.codync` || Form-like content | `CardForm`, `CardSection` (a small bold heading over a filled, rounded group; rows split by inset hairlines; a row is `ValueRow` with an optional one-line `detail`, and its picker is an outlined `ChoicePicker`) |-Avoid adding stock `Menu`, `Picker`, `Form`/`List` styling, switch toggles, alerts, `ProgressView` or system sheets to these flows. The iPhone bot list is a `List` with its styling removed (plain, no separators or row backgrounds), only for the system's drag-to-reorder alongside each row's context menu ([bot order](../features/computer-order.md#bot-order)). System presentation APIs inside the shared chrome implementation are implementation details, not permission to bypass the components in feature screens. Native WidgetKit/ActivityKit containers and OS authentication/permission flows remain system integrations.+Avoid adding stock `Menu`, `Picker`, `Form`/`List` styling, switch toggles, alerts, `ProgressView` or system sheets to these flows. The iPhone bot list is a `List` with its styling removed (plain, no separators or row backgrounds), only for the system's drag-to-reorder alongside each row's context menu ([bot order](../features/computer-order.md#bot-order)). The iPhone Usage screen is a grouped `List` for the same reason, in edit mode only while arranging its agents. System presentation APIs inside the shared chrome implementation are implementation details, not permission to bypass the components in feature screens. Native WidgetKit/ActivityKit containers and OS authentication/permission flows remain system integrations.No scroll bars: scroll indicators never show (`.scrollIndicators(.never)` on the iPhone app's root, so every scroll view inherits it; hidden scrollbars in `apps/desktop/src/renderer/styles/theme.css`).diff --git a/docs/features/usage-limits.md b/docs/features/usage-limits.mdindex 978a45a1..de8736a1 100644--- a/docs/features/usage-limits.md+++ b/docs/features/usage-limits.md@@ -4,10 +4,11 @@ What the apps show about plan limits, read on the host (`host/src/usage/`) from## Which agents show-Every Usage screen lists the agents that can report on this computer, each with a switch: desktop **Settings > Usage**, the phones' **State > Usage limits**, and the terminal UI's `U` then `s`. The choice is per computer and lives on its host, so every app, widget, the menu bar and the notch island follow it.+Every Usage screen can list the agents that can report on this computer, each with a switch, behind the button beside the computer's name: desktop **Settings > Usage**, the phones' **State > Usage limits**, and the terminal UI's `U` then `s`. The choice is per computer and lives on its host, so every app, widget, the menu bar and the notch island follow it.- **Default:** an agent shows when a bot on this computer runs it, as its own agent or a fallback. Being installed or signed in isn't enough: a Cursor app that's signed in stays off until a bot uses Cursor or the user turns it on.- **A choice wins over the default:** `setUsageShown {id, shown}` saves `usage.shown.<id>` in the host's kv and answers with the new `usage`.+- **One order per computer:** `setUsageOrder {ids}` saves `usage.order`, and the host sorts `services` and `providers` by it, so every Usage screen, the menu bar and the terminal UI follow. The notch island's list and the widgets' headline stay tightest first, and the widgets' other rows follow the order. An agent the order doesn't name follows the others in `READERS` order. The switches and the order live behind one button on each Usage screen; in the terminal, `J` and `K` move a row in the chooser.- **Reading follows the list:** an agent nobody runs or asked for is never started, and its saved login is never read. One that becomes wanted (a new bot's, one just turned on) is read right away instead of at the next five-minute poll, through `Hub::usage_wake`.- **Hidden isn't unread:** an agent a bot still runs keeps being read while hidden, because background work (`near_limit`) and fallbacks (`rest::reset_time`) go by its limits. `hub.usage` holds every reading; the apps get `Usage::visible()`.- **Listed:** wanted, holding a reading, its CLI installed (`backends::installed`), or something to read without the CLI (`Reader::found_without_cli`: Cursor's saved login, a JetBrains IDE's quota file).diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.mdindex 5c90fc2d..f7abab0e 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -109,7 +109,7 @@ host answers and sends it once the host is up.| `agent_setup_started` | host | `agentSetup` (an agent's install or sign-in terminal) | `agent` || `agent_signed_in` | host | `agentAuthenticate` | `agent` || `reach_account_answered` | host `track` (desktop) | The ask before *Reach from anywhere* turns on for a computer in no account ended | `outcome` (`added`/`own_relay`/`cancelled`/`failed`), `error` on `failed` (`unreachable`: the cloud couldn't be reached; `refused`: it refused; `host`: the host failed) |-| `setting_changed` | host, iOS, Android | A setting is switched | `setting` (host: `remote_access`/`remote_access_url` (`on`: a relay address is saved, never the address)/`approval` (`on`: approved without the code)/`automatic_updates`/`remote_screen`/`cloud_assistants`/`usage_shown` (with `agent`: which agent's limits the Usage screen lists); phones: `push`/`live_activities`), `on` |+| `setting_changed` | host, iOS, Android | A setting is switched | `setting` (host: `remote_access`/`remote_access_url` (`on`: a relay address is saved, never the address)/`approval` (`on`: approved without the code)/`automatic_updates`/`remote_screen`/`cloud_assistants`/`usage_shown` (with `agent`: which agent's limits the Usage screen lists)/`usage_order` (the agents were arranged); phones: `push`/`live_activities`), `on` || `host_update_installed` | host | `installHostUpdate` | — || `network_joined` | host | `networkCreate` / `networkJoin`: the computer is in a network of the user's computers | `via` (`create`/`invite`), never a name, invite or connector address || `network_changed` | host | `networkInvite` / `networkPromote` / `networkRemove` / `networkRecover` / `setNetworkRules` / `networkLeave` | `action` (`invite`/`promote`/`remove`/`recover`/`rules`/`leave`), never a computer's name, the invite, the recovery code or a rule |diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex 4d33ce60..89b3cc43 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -88,6 +88,11 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Evep.insert("on".into(), (b["shown"] == true).into());Event::SettingChanged}+ "setUsageOrder" => {+ p.insert("setting".into(), "usage_order".into());+ p.insert("on".into(), true.into());+ Event::SettingChanged+ }"updateBot" => Event::BotUpdated,"reorderBots" => Event::BotsReordered,"renameSection" => {diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rsindex 7cb297fa..ae988a9f 100644--- a/host/src/analytics/observe/tests.rs+++ b/host/src/analytics/observe/tests.rs@@ -84,6 +84,10 @@ fn settings_routines_screen_and_devices() {);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!(+ setting("setUsageOrder", json!({"ids": ["codex", "claude"]})),+ Some((Event::SettingChanged, json!("usage_order"), json!(true)))+ );assert_eq!(props("setRoutineEnabled", &json!({"botId": "b", "id": "r", "enabled": false})),diff --git a/host/src/api/host.rs b/host/src/api/host.rsindex 702cea12..b4bf44e1 100644--- a/host/src/api/host.rs+++ b/host/src/api/host.rs@@ -113,6 +113,17 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value.await??;serde_json::to_value(usage)?}+ // The order the Usage screens list the agents in.+ "setUsageOrder" => {+ let ids: Vec<String> = serde_json::from_value(b["ids"].clone()).context("ids is required")?;+ let hub = hub.clone();+ let usage = tokio::task::spawn_blocking(move || {+ usage::set_order(&hub, &ids)?;+ anyhow::Ok(hub.usage.locked().visible())+ })+ .await??;+ serde_json::to_value(usage)?+ }"listDirs" => {let path = b["path"].as_str().map(std::path::PathBuf::from);let hub = hub.clone();diff --git a/host/src/tui/app/analytics.rs b/host/src/tui/app/analytics.rsindex 57d2e845..878824c2 100644--- a/host/src/tui/app/analytics.rs+++ b/host/src/tui/app/analytics.rs@@ -53,7 +53,7 @@ impl App {/// one, else the full trace.fn screen_on_top(&self) -> Option<Screen> {let overlay = self.overlays.iter().rev().find_map(|o| match o {- Overlay::Usage(_) | Overlay::UsageChooser(_) => Some(Screen::Usage),+ Overlay::Usage(_) | Overlay::UsageChooser { .. } => Some(Screen::Usage),Overlay::Pair(_) => Some(Screen::Pairing),Overlay::Network(_) => Some(Screen::Network),Overlay::Memory(_) => Some(Screen::Memory),diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex a58e671d..aaabefcd 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -167,6 +167,10 @@ impl App {self.network_reply(n, r);return;}+ if let After::UsageOrder(to) = after {+ self.usage_order_answered(to, r);+ return;+ }if matches!(after, After::Pairing | After::Cloud | After::PairingRequests | After::PairingDecided) {self.pair_reply(&after, r);return;@@ -214,6 +218,7 @@ impl App {| After::Answered(_)| After::Sheet(_)| After::Network(_)+ | After::UsageOrder(_)| After::Sent(_)| After::Connection(_, _)| After::Pairingdiff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex 96a63713..88eff603 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -55,6 +55,8 @@ pub enum After {Sheet(Reply),/// The network sheet's calls.Network(super::super::manage::NetReply),+ /// A move in the Usage chooser, to this row.+ UsageOrder(usize),}#[derive(Clone, Copy, PartialEq, Eq, Debug)]diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rsindex b56aa9ca..35c86c8f 100644--- a/host/src/tui/app/overlay_keys.rs+++ b/host/src/tui/app/overlay_keys.rs@@ -1,7 +1,7 @@//! Keys in the pickers: go-to, actions and folders.use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};-use serde_json::json;+use serde_json::{Value, json};use super::super::manage::{AnalyticsSheet, Reply};use super::super::view::usage_services;@@ -162,27 +162,43 @@ impl App {KeyCode::PageDown | KeyCode::Char(' ') => Some(Overlay::Usage((scroll + 10).min(max))),KeyCode::PageUp => Some(Overlay::Usage(scroll.saturating_sub(10))),KeyCode::Char('s') if !usage_services(self).is_empty() => {- self.overlays.push(Overlay::UsageChooser(0));+ self.overlays.push(Overlay::UsageChooser { row: 0, moving: false });Some(Overlay::Usage(scroll))}_ => Some(Overlay::Usage(scroll)),}}- Overlay::UsageChooser(row) => {+ Overlay::UsageChooser { row, moving } => {let services = usage_services(self);let last = services.len().saturating_sub(1);+ // The list can shrink under the cursor: an agent turned off, a bot deleted on another device.+ let row = row.min(last);match k.code {KeyCode::Esc | KeyCode::Char('q' | 's') => None,- KeyCode::Down | KeyCode::Char('j') => Some(Overlay::UsageChooser((row + 1).min(last))),- KeyCode::Up | KeyCode::Char('k') => Some(Overlay::UsageChooser(row.saturating_sub(1))),+ KeyCode::Down | KeyCode::Char('j') => {+ Some(Overlay::UsageChooser { row: (row + 1).min(last), moving })+ }+ KeyCode::Up | KeyCode::Char('k') => {+ Some(Overlay::UsageChooser { row: row.saturating_sub(1), moving })+ }+ KeyCode::Char(key @ ('J' | 'K')) => {+ let to = if key == 'J' { (row + 1).min(last) } else { row.saturating_sub(1) };+ let starts = !moving && to != row;+ if starts {+ let mut ids: Vec<_> = services.iter().map(|service| &service["id"]).collect();+ ids.swap(row, to);+ self.call("setUsageOrder", json!({"ids": ids}), After::UsageOrder(to));+ }+ Some(Overlay::UsageChooser { row, moving: moving || starts })+ }KeyCode::Char(' ') | KeyCode::Enter => {if let Some(service) = services.get(row) {let shown = service["shown"].as_bool() != Some(true);self.call("setUsageShown", json!({"id": service["id"], "shown": shown}), After::Nothing);}- Some(Overlay::UsageChooser(row))+ Some(Overlay::UsageChooser { row, moving })}- _ => Some(Overlay::UsageChooser(row.min(last))),+ _ => Some(Overlay::UsageChooser { row, moving }),}}o @ Overlay::Pair(_) => {@@ -199,6 +215,27 @@ impl App {}}+ /// The host's answer to a move. Only now do the list change and the cursor follow, so the next move starts from+ /// the order this one left, and a refused one leaves both where they were.+ pub(super) fn usage_order_answered(&mut self, to: usize, answer: Result<Value, String>) {+ let moved = match answer {+ Ok(usage) => {+ self.usage = usage;+ true+ }+ Err(error) => {+ self.flash(&error);+ false+ }+ };+ if let Some(Overlay::UsageChooser { row, moving }) = self.overlays.last_mut() {+ *moving = false;+ if moved {+ *row = to;+ }+ }+ }+fn goto_key(&mut self, mut g: Goto, k: KeyEvent) -> Option<Overlay> {let items_len = self.goto_items(&g).len();match k.code {@@ -371,7 +408,7 @@ impl App {#[cfg(test)]mod tests {use super::super::super::net::Client;- use super::super::{App, Bot, Editor, Goto, GotoItem, Overlay, test_app};+ use super::super::{After, App, Bot, Editor, Goto, GotoItem, Msg, Overlay, test_app};use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};use serde_json::json;@@ -412,21 +449,69 @@ mod tests {let key = |code| KeyEvent::new(code, KeyModifiers::NONE);app.overlays.push(Overlay::Usage(0));app.overlay_key(key(KeyCode::Char('s')));- assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser(0))));+ assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser { row: 0, .. })));app.overlay_key(key(KeyCode::Down));- assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser(1))));+ assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser { row: 1, .. })));app.overlay_key(key(KeyCode::Char(' ')));- let request = tokio::time::timeout(std::time::Duration::from_secs(10), requests.recv())- .await- .expect("the host hears of it in time")- .expect("the host is up");+ let request = next_request(&mut requests).await;assert!(request.starts_with("POST /api/setUsageShown"), "{request}");assert!(request.contains(r#""id":"cursor""#) && request.contains(r#""shown":true"#), "{request}");- assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser(1))), "the chooser stays open");+ assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser { row: 1, .. })), "the chooser stays open");app.overlay_key(key(KeyCode::Esc));assert!(matches!(app.overlays.last(), Some(Overlay::Usage(0))), "back to the limits");}+ #[tokio::test]+ async fn j_and_k_move_the_selected_agent_as_the_host_answers() {+ let (base, mut requests) = host().await;+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(Client::new(&base, Some("token")), tx, String::new());+ let usage = |ids: &[&str]| {+ let services: Vec<_> = ids.iter().map(|id| json!({"id": id, "name": id, "shown": true})).collect();+ json!({"providers": [], "services": services})+ };+ let press = |app: &mut App, c| app.overlay_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE));+ let row = |app: &App| match app.overlays.last() {+ Some(Overlay::UsageChooser { row, .. }) => *row,+ other => panic!("the chooser is closed: {:?}", other.is_some()),+ };+ app.usage = usage(&["a", "b", "c"]);+ app.overlays.push(Overlay::UsageChooser { row: 0, moving: false });++ press(&mut app, 'K');+ press(&mut app, 'J');+ press(&mut app, 'J');+ assert_eq!(row(&app), 0, "the cursor waits for the host");+ let sent = next_request(&mut requests).await;+ assert!(sent.starts_with("POST /api/setUsageOrder"), "{sent}");+ assert!(sent.contains(r#""ids":["b","a","c"]"#), "the top's K and the waiting J sent nothing: {sent}");+ app.on_msg(Msg::Reply(After::UsageOrder(1), Ok(usage(&["b", "a", "c"]))));+ assert_eq!(row(&app), 1, "the cursor follows the agent");++ press(&mut app, 'J');+ assert!(next_request(&mut requests).await.contains(r#""ids":["b","c","a"]"#));+ app.on_msg(Msg::Reply(After::UsageOrder(2), Ok(usage(&["b", "c", "a"]))));+ press(&mut app, 'J');+ assert_eq!(row(&app), 2, "the end of the list does nothing");++ press(&mut app, 'K');+ assert!(next_request(&mut requests).await.contains(r#""ids":["b","a","c"]"#), "the last J sent nothing");+ app.on_msg(Msg::Reply(After::UsageOrder(1), Err("unknown method".into())));+ assert_eq!(row(&app), 2, "a refused move keeps the cursor on its agent");++ // An agent turned off leaves the cursor past the end.+ app.usage = usage(&["b", "c"]);+ press(&mut app, 'K');+ assert!(next_request(&mut requests).await.contains(r#""ids":["c","b"]"#));+ }++ async fn next_request(requests: &mut tokio::sync::mpsc::UnboundedReceiver<String>) -> String {+ tokio::time::timeout(std::time::Duration::from_secs(10), requests.recv())+ .await+ .expect("the host hears of it in time")+ .expect("the host is up")+ }+#[tokio::test]async fn a_host_with_no_list_offers_no_chooser() {let mut app = test_app();diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rsindex 610526c6..611797ad 100644--- a/host/src/tui/app/ui.rs+++ b/host/src/tui/app/ui.rs@@ -327,8 +327,12 @@ pub enum Overlay {Group(GroupForm),/// How far its list is scrolled.Usage(usize),- /// Which agents' limits show: the row under the cursor.- UsageChooser(usize),+ /// Which agents' limits show: the row under the cursor, and whether a move is on its way to the host (the next waits+ /// for its answer).+ UsageChooser {+ row: usize,+ moving: bool,+ },Pair(PairCode),Memory(MemorySheet),/// A read-only conversation between two bots.diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rsindex fad3c12d..e552d2bd 100644--- a/host/src/tui/view/overlay.rs+++ b/host/src/tui/view/overlay.rs@@ -139,7 +139,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &OverlayOverlay::Form(form) => form_view(buf, area, app, form),Overlay::Group(g) => group_view(buf, area, app, g),Overlay::Usage(scroll) => usage(buf, area, app, *scroll),- Overlay::UsageChooser(row) => usage_chooser(buf, area, app, *row),+ Overlay::UsageChooser { row, .. } => usage_chooser(buf, area, app, *row),Overlay::Pair(code) => pair(buf, area, app, code),Overlay::Memory(m) => super::super::sheets::memory(buf, area, app, m),Overlay::BotChat(c) => super::bot_chat::bot_chat(buf, area, app, c),diff --git a/host/src/tui/view/usage.rs b/host/src/tui/view/usage.rsindex b57a6c8d..6e15c59e 100644--- a/host/src/tui/view/usage.rs+++ b/host/src/tui/view/usage.rs@@ -76,7 +76,7 @@ pub(super) fn usage(buf: &mut Buffer, area: Rect, app: &App, scroll: usize) {put(buf, inner.x, inner.bottom() - 1, inner.width, &footer, t.dim.patch(t.panel));}-/// Which agents' limits show on this computer.+/// Which agents' limits show on this computer, and in what order.pub(super) fn usage_chooser(buf: &mut Buffer, area: Rect, app: &App, row: usize) {let t = theme();let services = usage_services(app);@@ -106,7 +106,8 @@ pub(super) fn usage_chooser(buf: &mut Buffer, area: Rect, app: &App, row: usize)}let note = tr("On by default for the agents your bots run.");put(buf, inner.x, inner.bottom() - 2, inner.width, note.as_ref(), t.dim.patch(t.panel));- put(buf, inner.x, inner.bottom() - 1, inner.width, "↑↓ move · space toggle · esc close", t.dim.patch(t.panel));+ let keys = tr("↑↓ select · J K arrange · space toggle · esc close");+ put(buf, inner.x, inner.bottom() - 1, inner.width, keys.as_ref(), t.dim.patch(t.panel));}/// One limit: its label, a bar with the percent and when it resets; or its note.diff --git a/host/src/usage/mod.rs b/host/src/usage/mod.rsindex d9195793..94b972b6 100644--- a/host/src/usage/mod.rs+++ b/host/src/usage/mod.rs@@ -36,7 +36,7 @@ mod vibe;pub use claude::{ingest_claude_rate_limit, ingest_statusline};pub(crate) use command::strip_ansi;-pub use services::{bots_changed, set_shown};+pub use services::{bots_changed, set_order, set_shown};use crate::LockExt;use crate::hub::Hub;@@ -118,7 +118,10 @@ impl Usage {/// What the apps get: without the readings of the agents the user doesn't show.pub fn visible(&self) -> Self {let hidden = |id: &str| self.services.iter().any(|service| service.id == id && !service.shown);- let providers = self.providers.iter().filter(|provider| !hidden(provider.id)).cloned().collect();+ let rank = |id: &str| self.services.iter().position(|service| service.id == id).unwrap_or(usize::MAX);+ let mut providers: Vec<Provider> =+ self.providers.iter().filter(|provider| !hidden(provider.id)).cloned().collect();+ providers.sort_by_key(|provider| rank(provider.id));Self { providers, services: self.services.clone() }}diff --git a/host/src/usage/services.rs b/host/src/usage/services.rsindex b98764b8..359fdb69 100644--- a/host/src/usage/services.rs+++ b/host/src/usage/services.rs@@ -152,6 +152,21 @@ pub(super) const READERS: &[Reader] = &[},];+/// The order the user arranged the agents in, as ids.+const ORDER_KEY: &str = "usage.order";++fn arranged(store: &Store) -> Vec<String> {+ let Some(saved) = store.kv_get(ORDER_KEY) else { return Vec::new() };+ serde_json::from_str(&saved).unwrap_or_else(|error| {+ tracing::warn!(error = format!("{error:#}"), "couldn't read the usage order");+ Vec::new()+ })+}++fn reader(id: &str) -> Result<&'static Reader> {+ READERS.iter().find(|reader| reader.id == id).context("unknown usage service")+}+fn choice_key(id: &str) -> String {format!("usage.shown.{id}")}@@ -222,7 +237,7 @@ pub(super) fn sync(hub: &Hub) {let used = used_agents(store);// The database and the disk stay outside the usage lock: a reading landing meanwhile is kept.let held = held_readings(hub);- let services: Vec<Service> = READERS+ let mut services: Vec<Service> = READERS.iter().filter(|reader| listed(reader, &used, store, &held)).map(|reader| Service {@@ -232,6 +247,9 @@ pub(super) fn sync(hub: &Hub) {shown: chosen(store, reader.id).unwrap_or_else(|| used.contains(reader.id)),}).collect();+ // Stable: an agent the order doesn't name follows the others, in the readers' order.+ let order = arranged(store);+ services.sort_by_key(|service| order.iter().position(|id| id == service.id).unwrap_or(usize::MAX));let keep: HashSet<&str> = READERS.iter().map(|reader| reader.id).filter(|id| wanted(id, &used, store)).collect();hub.update_usage(|usage| {usage.services = services;@@ -253,12 +271,21 @@ pub fn bots_changed(hub: &Hub) {/// The user's choice for one agent.pub fn set_shown(hub: &Hub, id: &str, shown: bool) -> Result<()> {- let reader = READERS.iter().find(|reader| reader.id == id).context("unknown usage service")?;- hub.store.kv_set(&choice_key(reader.id), if shown { "1" } else { "0" })?;+ hub.store.kv_set(&choice_key(reader(id)?.id), if shown { "1" } else { "0" })?;changed(hub);Ok(())}+/// The user's order for the agents, which every Usage screen follows.+pub fn set_order(hub: &Hub, ids: &[String]) -> Result<()> {+ for id in ids {+ reader(id)?;+ }+ hub.store.kv_set(ORDER_KEY, &serde_json::to_string(ids)?)?;+ sync(hub);+ Ok(())+}+#[cfg(test)]mod tests {use super::super::{Provider, near_limit};@@ -292,6 +319,25 @@ mod tests {hub.usage.locked().services.iter().find(|service| service.id == id).map(|service| service.shown)}+ #[test]+ fn the_users_order_leads_the_list_and_the_readings() {+ let hub = hub();+ hub.store.save_bot(&bot("a", "claude", Some("codex"))).unwrap();+ hub.update_usage(|usage| usage.providers = vec![reading("claude", 1.0), reading("codex", 2.0)]);+ sync(&hub);+ let ids = |usage: &super::super::Usage| usage.services.iter().map(|s| s.id).take(2).collect::<Vec<_>>();+ let providers = |usage: &super::super::Usage| usage.providers.iter().map(|p| p.id).collect::<Vec<_>>();+ assert_eq!(ids(&hub.usage.locked().visible()), ["claude", "codex"]);++ set_order(&hub, &["codex".to_owned()]).unwrap();+ let visible = hub.usage.locked().visible();+ assert_eq!(ids(&visible), ["codex", "claude"], "one it doesn't name follows");+ assert_eq!(providers(&visible), ["codex", "claude"]);++ assert!(set_order(&hub, &["not-an-agent".to_owned()]).is_err());+ assert_eq!(ids(&hub.usage.locked().visible()), ["codex", "claude"], "a refused order changes nothing");+ }+#[test]fn only_the_agents_bots_run_are_shown_and_read_by_default() {let hub = hub();diff --git a/host/tests/usage_chooser_e2e.rs b/host/tests/usage_chooser_e2e.rsindex d5b59b3e..5587b649 100644--- a/host/tests/usage_chooser_e2e.rs+++ b/host/tests/usage_chooser_e2e.rs@@ -1,5 +1,5 @@-//! The Usage chooser on the wire: a choice reaches every client, and what they get leaves out the-//! agents the user hides, also when one reconnects.+//! The Usage chooser on the wire: a choice or an order reaches every client, and what they get leaves+//! out the agents the user hides, also when one reconnects.#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]@@ -27,6 +27,13 @@ fn shown(usage: &Value, id: &str) -> Option<bool> {usage["services"].as_array()?.iter().find(|service| service["id"] == id)?["shown"].as_bool()}+/// The first `count` agents listed: a host may also list what the computer it runs on has installed.+fn first_agents(usage: &Value, count: usize) -> Vec<&str> {+ usage["services"].as_array().map_or_else(Vec::new, |services| {+ services.iter().filter_map(|service| service["id"].as_str()).take(count).collect()+ })+}+fn has_reading(usage: &Value, id: &str) -> bool {usage["providers"].as_array().is_some_and(|providers| providers.iter().any(|provider| provider["id"] == id))}@@ -85,3 +92,34 @@ async fn an_agent_it_does_not_know_can_not_be_chosen() {let error = host.refused("setUsageShown", json!({"id": "not-an-agent", "shown": true})).await;assert!(error.contains("unknown usage service"), "{error}");}++#[tokio::test]+async fn an_order_reaches_the_other_clients_and_stays_when_one_is_refused() {+ let host = Host::start().await;+ let mut other_client = host.events().await;+ let bot = json!({+ "name": "Two agents", "backend": "claude", "fallbacks": [{"backend": "codex"}],+ "connectors": [], "permission": "ask",+ });+ host.call("createBot", bot).await;+ let listed = usage_until(&mut other_client, "both agents are listed", |usage| {+ shown(usage, "claude") == Some(true) && shown(usage, "codex") == Some(true)+ })+ .await;+ assert_eq!(first_agents(&listed["usage"], 2), ["claude", "codex"]);++ let answer = host.call("setUsageOrder", json!({"ids": ["codex", "claude"]})).await;+ assert_eq!(first_agents(&answer, 2), ["codex", "claude"]);+ usage_until(&mut other_client, "the order arrived", |usage| first_agents(usage, 2) == ["codex", "claude"]).await;++ let mut reconnected = host.events().await;+ let hello = reconnected.recv().await.unwrap();+ assert_eq!(hello["type"], "hello", "{hello}");+ assert_eq!(first_agents(&hello["usage"], 2), ["codex", "claude"]);++ let error = host.refused("setUsageOrder", json!({"ids": ["not-an-agent"]})).await;+ assert!(error.contains("unknown usage service"), "{error}");+ let error = host.refused("setUsageOrder", json!({})).await;+ assert!(error.contains("ids is required"), "{error}");+ assert_eq!(first_agents(&host.call("usage", json!({})).await, 2), ["codex", "claude"]);+}diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdxindex c3600e88..e4efdbc1 100644--- a/web/content/docs/agents.mdx+++ b/web/content/docs/agents.mdx@@ -8,7 +8,7 @@ If an agent's login stops working (for example, signing in somewhere else revokeOn desktop, open **Settings > Usage** to see the limits reported by your connected computers. On the phones it's **State > Usage limits**, and in the terminal UI press `U`. The host refreshes usage every five minutes, and GitHub Copilot's every 30.-Usage shows the agents your bots run. Below the limits there's a switch for every agent that can report on that computer, so you can turn on one no bot uses yet, or hide one you don't want to see. In the terminal UI, press `s` on the usage sheet to open that list. The choice belongs to the computer: your other devices follow it. An agent that's on but has nothing to read says **No reading yet**, which usually means it's signed out.+Usage shows the agents your bots run. The button beside the computer's name opens a list of every agent that can report on that computer: use its switches to turn on one no bot uses yet or hide one you don't want to see, and drag an agent by its handle to change the order Usage lists them in. In the terminal UI, press `s` on the usage sheet to open that list, and `J` or `K` to move an agent. The choices belong to the computer: your other devices follow them. An agent that's on but has nothing to read says **No reading yet**, which usually means it's signed out.These agents can report their limits: Claude Code, Codex, Google Antigravity, Cursor, GitHub Copilot, Grok Build, Hermes Agent, Amp, Auggie, Junie, Kilo, Kimi Code, Kiro CLI, Mistral Vibe, oh-my-pi and OpenCode. Unified Cursor plans, including Super, show one **Weekly** allowance with its next reset. Older Cursor plans retain their monthly usage readings.diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex e60dcec2..17569c12 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -160,11 +160,11 @@ When you send a message from the iPhone, a Live Activity for that bot appears on## Usage limits-Codync reads plan limits on your computer, without starting a conversation or model turn. It shows the agents your bots run, and every agent that can report has a switch, so you can turn on one no bot uses or hide one: [which agents, and how](/docs/agents#usage-limits). To see them:+Codync reads plan limits on your computer, without starting a conversation or model turn. It shows the agents your bots run. The button beside the computer's name opens every agent that can report, each with a switch and a handle, so you can turn on one no bot uses, hide one, or change their order: [which agents, and how](/docs/agents#usage-limits). To see them:- **iPhone and Android:** the **State** tab, then **Usage limits**. There's also a Usage widget.- **Desktop:** the menu bar or tray menu, or **Usage** in the account menu at the bottom of the sidebar.-- **Terminal UI:** press `U`, then `s` for the switches.+- **Terminal UI:** press `U`, then `s` to choose and arrange.Each limit reads as the share already used, such as **62% used**. Widgets and the small meters in the island and the terminal UI's status bar show just the number, which is also the share used.