Skip to content

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

feat: choose which agents show in Usage and read more of them

leepokaic62c66815a0c
diff --git a/CLAUDE.md b/CLAUDE.md
index b73d6376..2a7c69ec 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -37,7 +37,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it (plus its X25519 push key) to the host; the host seals title/body to that key and a Notification Service Extension opens it, so `relay/` sees only generic text. Alert kinds: *needs you*, *done*, and *failed*, suppressed while the iOS app is connected. Delivery and lifecycle: [notification design](docs/design/push-and-live-activity.md).
- Voice call (iPhone, desktop): on-device speech (macOS desktop: the `codync-speech` helper), or OpenAI / Gemini realtime on the user's own key (kept in the host's vault, which mints per-call credentials; audio goes device ↔ provider); the host sees plain messages. Grok-style call bar: [docs/features/voice-call.md](docs/features/voice-call.md).
- Analytics: PostHog, on by default (off in each device's Settings), feature use only (never content); host events come from `api::dispatch`: [docs/features/analytics.md](docs/features/analytics.md). **Every new feature or module adds its PostHog events in the same change** (use, outcome, failure category), so bugs can be traced later: [adding a feature](docs/features/analytics.md#adding-a-feature).
-- Usage: read from the agents on the computer — Claude's `claude -p /usage --no-session-persistence`, the status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update`, the Codex CLI's `account/rateLimits/read` (`codex app-server`, no turn), and the other agents' local commands, databases and IDE files. Cursor is the one provider call: the token Cursor saved, then its dashboard service (unified plans) or `cursor.com/api/usage-summary`. Never call any other provider API with agent credentials.
+- Usage: read from the agents on the computer, for the agents a bot runs or the user turned on; a choice per computer on the host. Never call a provider API with agent credentials (Cursor's dashboard is the one exception): [usage limits](docs/features/usage-limits.md).
- The desktop app is thin: the Mac build bundles `codync-host` in `Contents/Resources` (Linux uses the installed host) and installs it as a launchd/systemd agent via `codync-host install`; the menu bar/tray shows status/pairing/usage and opens the chat window. Not sandboxed, not Mac App Store (the host must spawn CLIs).
## Cross-platform UI changes
diff --git a/README.md b/README.md
index 8bfb453e..c943bc78 100644
--- a/README.md
+++ b/README.md
@@ -95,7 +95,7 @@ Host notifications → APNs worker (relay/) → iPhone
- **The chat only shows what matters**: your messages, each turn's final reply, approval cards and notices. Every tool call, diff, plan and thought is one tap away in *Full conversation*. While a bot works, its row shows what it's doing right now.
- **Agents are detected automatically**: the host hydrates PATH from your login shell (plus Homebrew, ~/.local/bin, nvm, bun, volta, asdf, mise, pnpm…), finds every harness you have installed, and prefers its native ACP mode. Anything else in the official [ACP registry](https://agentclientprotocol.com/registry) can be picked too — Codync fetches it on first use (npx, uvx or a checksummed binary).
- **codync-host** (Rust, macOS, Windows and Linux) runs on your computer. It speaks the [Agent Client Protocol](https://agentclientprotocol.com) to each agent, keeps transcripts in SQLite, and serves the phone. Every change carries a global `rev`, so the phone reconnects with `since: rev` and never misses anything.
-- **Usage limits** come from the agents installed on your computer. Claude uses `claude -p /usage` (a local command, no model call) plus Claude Code's status line, and the signed-in Codex CLI reports current account limits without a model call. oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie are read from their own command, database or IDE file. Cursor asks cursor.com with the sign-in it saved locally. The phone, widgets and menu bar see the resulting limits.
+- **Usage limits** are read on your computer, without a model call, for the agents your bots run and any others you turn on in the Usage screen. The phone, widgets and menu bar see the resulting limits. See [usage limits](docs/features/usage-limits.md).
- **Push** goes through a tiny relay that holds the APNs key. The phone trades its device token for an encrypted ticket; the host only ever holds tickets.
UI patterns (roster, character avatars, approval cards, trace sheet, "needs you / done" notifications) follow Grok Bot.
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 23692dde..e07ccb44 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -10,9 +10,11 @@ else a generic "Bug fixes and improvements" line. Delete old sections.
## 2.40.0
### zh-Hant
- bot 現在可以讓 dev server 持續在電腦上執行,不會因為 bot 閒置或重新啟動而中斷。port 會顯示在聊天標題下方;點 bot 的名稱,就能看記錄、重新啟動或停止;手機連得到電腦時,也能直接開啟。
+- 用量頁面可以自己選要看哪些服務:預設只顯示 bot 正在用的,也可以打開或隱藏其他服務。另外支援顯示 Google Antigravity 和 GitHub Copilot 的額度。
### en-US
- Bots can now keep a dev server running on your computer, even when the bot goes idle or restarts. Its port shows under the chat title; tap the bot's name to read its logs, restart or stop it, and to open it when your phone can reach it.
+- Choose which agents show in Usage: by default it lists the ones your bots run, and you can turn others on or hide them. Usage now also reads Google Antigravity's and GitHub Copilot's limits.
## 2.39.0
### zh-Hant
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.kt
index 15f56344..e9648ee6 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
@@ -21,7 +21,7 @@ class UsageScreenTest {
val refreshes = mutableListOf<Boolean>()
var closed = false
compose.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("Future provider").assertIsDisplayed()
compose.onNodeWithText("Monthly").assertIsDisplayed()
@@ -44,11 +44,38 @@ 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 installed on it.").assertIsDisplayed()
+ compose.onNodeWithText("Your computer reads plan limits from the agents your bots run and the ones you turn on.").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)))
+ 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)
+ compose.onNodeWithText("Weekly").assertExists()
+ compose.runOnUiThread { state.value = state.value.copy(usage = usage("", false)) }
+ compose.waitForIdle()
+ compose.onNodeWithText("Weekly").assertDoesNotExist()
+ }
+
+ @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()
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
index 6f412cfe..e1fb8285 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
@@ -170,9 +170,14 @@ suspend fun AppStore.agentModels(backend: String): AgentModels {
suspend fun AppStore.reloadUsage() { refreshUsage(true); actions["usage"]?.join() }
fun AppStore.refreshUsage(force: Boolean = true) = action("usage") {
val active = ready()
- // The existing host can spend up to a minute reading an installed provider.
- val result = active.call("usage", buildJsonObject { put("refresh", force) }, timeoutMillis = 75_000)
- val response = result.jsonObject
+ // The host answers within a minute: an agent that reads slower lands through its events.
+ landUsage(active.call("usage", buildJsonObject { put("refresh", force) }, timeoutMillis = 75_000).jsonObject)
+}
+/** Whether this computer lists one agent's limits. */
+fun AppStore.setUsageShown(id: String, shown: Boolean) = action("usageShown.$id") {
+ landUsage(ready().call("setUsageShown", buildJsonObject { put("id", id); put("shown", shown) }).jsonObject)
+}
+private suspend fun AppStore.landUsage(response: JsonObject) {
UsageReport.decode(response)
withContext(Dispatchers.IO) { requireNotNull(database).apply(MirrorEvent.Usage(response)) }
refresh()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
index e63becdb..139cc9b2 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, 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) }, 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/CodyncWidgets.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
index 618dc42c..a6745ea7 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
@@ -164,7 +164,7 @@ private fun dark(context: Context) = context.resources.configuration.uiMode and
val top = provider.tightest
Column(GlanceModifier.fillMaxSize()) {
Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
- val logo = agentIconRes(provider.registry)
+ val logo = agentIconRes(provider.logoRegistry)
if (WidgetStore.originalIcons(context) && logo != null) Image(ImageProvider(logo), provider.name, GlanceModifier.size(22.dp),
colorFilter = ColorFilter.tint(if (provider.id == "claude") ColorProvider(day = Color(0xFFD97757), night = Color(0xFFD97757)) else ink))
else Face(context, if (provider.id == "codex") "hex" else "blob", "gray", 22.dp,
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.kt
index e25e5440..561438f1 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,6 +1,7 @@
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
@@ -49,7 +50,7 @@ import kotlin.math.roundToInt
* provider, the tightest limit as a big bar, every limit listed below. Pull down to refresh.
*/
@Composable fun UsageScreen(state: AppState?, refresh: (force: Boolean) -> Unit, reload: suspend () -> Unit,
- trailing: @Composable () -> Unit = {}) {
+ setShown: (id: String, shown: Boolean) -> Unit, trailing: @Composable () -> Unit = {}) {
val dismiss = LocalDismissModal.current
val report = remember(state?.usage) { state?.let { runCatching { UsageReport.decode(it.usage) }.getOrNull() } ?: UsageReport() }
val online = state?.actualConnection is LinkState.Ready
@@ -64,8 +65,9 @@ import kotlin.math.roundToInt
}
PullToRefresh({ if (online) reload() }, Modifier.weight(1f)) {
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
- for (provider in report.providers) key(provider.id) { ProviderCard(provider) }
- if (report.providers.isEmpty()) EmptyUsage("No usage yet", "Your computer reads plan limits from the agents installed on it.")
+ 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)
}
}
}
@@ -74,6 +76,47 @@ import kotlin.math.roundToInt
@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) }
+ }
+}
+
+/** 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)
+ }
+}
+
+/** 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 ProviderCard(provider: UsageProvider) {
var collapsed by rememberSaveable(provider.id) { mutableStateOf(false) }
val turn by animateFloatAsState(if (collapsed) 180f else 0f, Motion.layout(), label = "Collapse")
@@ -81,9 +124,7 @@ import kotlin.math.roundToInt
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)) {
- Box(Modifier.size(34.dp).clip(RoundedRectangle(10.dp)).background(provider.tint().copy(alpha = 0.12f)), contentAlignment = Alignment.Center) {
- ProviderMascot(provider, 22.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 }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
index 87b12d2b..adf9fb77 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
@@ -49,10 +49,13 @@ import kotlin.math.roundToInt
enum class ProviderLayout { Small, Medium, Large }
-/** Claude keeps its orange; everyone else is ink, like the rest of the app. */
-/** ACP registry id of the provider's agent, for its logo: Claude and Codex run through ACP adapters. */
-internal val UsageProvider.registry: String get() = if (id in listOf("claude", "codex")) "$id-acp" else id
+/**
+ * ACP registry id of the provider's agent, for its logo. A host or a saved widget that doesn't name it:
+ * Claude and Codex run through ACP adapters, others go by their own id.
+ */
+internal val UsageProvider.logoRegistry: String get() = registry ?: if (id in listOf("claude", "codex")) "$id-acp" else id
+/** Claude keeps its orange; everyone else is ink, like the rest of the app. */
@Composable internal fun UsageProvider.tint(): Color = if (id == "claude") Color(0xFFD97757) else Palette.accent
/** Gauges add Codex's blue so two providers' bars tell apart (CodyncKit `widgetTint`). */
@@ -126,7 +129,7 @@ internal fun until(at: Long, now: Long): String {
val context = androidx.compose.ui.platform.LocalContext.current
val revision by WidgetStore.changes.collectAsState()
val original = remember(revision) { WidgetStore.originalIcons(context) }
- val logo = agentIconRes(provider.registry)
+ val logo = agentIconRes(provider.logoRegistry)
Box(Modifier.size(size)) {
if (original && logo != null) androidx.compose.foundation.Image(androidx.compose.ui.res.painterResource(logo), null,
Modifier.fillMaxSize().padding(size * 0.08f), colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(provider.tint()))
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.kt
index a5bdac38..7fbf5d32 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
@@ -9,12 +9,21 @@ import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
-@Serializable data class UsageReport(val providers: List<UsageProvider> = emptyList()) {
+/** An agent the Usage screen can show or hide. The host keeps the choice, so every app follows it. */
+@Serializable data class UsageService(val id: String, val name: String, val shown: Boolean = false, val registry: String? = null) {
+ /** What a mascot needs of an agent that may have no reading. */
+ val provider: UsageProvider get() = UsageProvider(id, name, registry = registry)
+}
+
+/** `services` is absent from a host older than the chooser. */
+@Serializable data class UsageReport(val providers: List<UsageProvider> = emptyList(), val services: List<UsageService> = emptyList()) {
companion object { fun decode(value: JsonElement): UsageReport = WireJson.decodeFromJsonElement(value) }
}
@Serializable data class UsageProvider(val id: String, val name: String, val windows: List<UsageWindow> = emptyList(),
- val source: String = "", val updatedAt: Long? = null) {
+ val source: String = "", val updatedAt: Long? = null,
+ /** The agent's ACP registry id, which its logo goes by. Absent from a host that doesn't name it. */
+ val 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) {
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.kt
index 19d0fde2..7d94590f 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
@@ -4,6 +4,14 @@ import org.junit.Assert.*
import org.junit.Test
class UsageTest {
+ @Test fun `the chooser list decodes and an older host sends none`() {
+ val report = UsageReport.decode(WireJson.parseToJsonElement("""{"providers":[],"services":[{"id":"cursor","name":"Cursor","shown":false}]}"""))
+ assertEquals(listOf(UsageService("cursor", "Cursor", false)), report.services)
+ assertEquals("Cursor", report.services.single().provider.name)
+ val named = UsageReport.decode(WireJson.parseToJsonElement("""{"services":[{"id":"copilot","name":"GitHub Copilot","shown":true,"registry":"github-copilot-cli"}]}"""))
+ assertEquals("github-copilot-cli", named.services.single().provider.registry)
+ assertTrue(UsageReport.decode(WireJson.parseToJsonElement("""{"providers":[]}""")).services.isEmpty())
+ }
@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()
diff --git a/apps/desktop/e2e/usage-chooser.spec.ts b/apps/desktop/e2e/usage-chooser.spec.ts
new file mode 100644
index 00000000..998d5468
--- /dev/null
+++ b/apps/desktop/e2e/usage-chooser.spec.ts
@@ -0,0 +1,33 @@
+import { test, expect } from '@playwright/test'
+import { api, attach } from './sandbox.ts'
+
+type Usage = { providers: { id: string }[]; services: { id: string; name: string; shown: boolean }[] }
+
+test('Settings > Usage chooses which agents show, and the host keeps the choice', async () => {
+ const { browser, page } = await attach()
+ const usage = () => api<Usage>(page, 'usage', {})
+ const { services } = await usage()
+ const service = services.find((s) => s.id === 'cursor') ?? services[0]
+ test.skip(!service, 'no agent on this computer can report its usage')
+ const shownAtStart = service.shown
+ try {
+ await api(page, 'setUsageShown', { id: service.id, shown: false })
+ await page.locator('.sidebar-account').click()
+ await page.locator('.account-panel').getByText('Usage', { exact: true }).click()
+ const row = page.locator('.settings-usage-chooser').getByRole('switch', { name: service.name })
+ await expect(row).toHaveAttribute('aria-checked', 'false')
+
+ await row.click()
+ await expect(row).toHaveAttribute('aria-checked', 'true')
+ expect((await usage()).services.find((s) => s.id === service.id)?.shown).toBe(true)
+
+ await row.click()
+ await expect(row).toHaveAttribute('aria-checked', 'false')
+ const after = await usage()
+ expect(after.services.find((s) => s.id === service.id)?.shown).toBe(false)
+ expect(after.providers.some((p) => p.id === service.id)).toBe(false)
+ } finally {
+ await api(page, 'setUsageShown', { id: service.id, shown: shownAtStart }).catch(() => {})
+ await browser.close()
+ }
+})
diff --git a/apps/desktop/src/renderer/components/Controls.tsx b/apps/desktop/src/renderer/components/Controls.tsx
index dc524ab0..8bb62e00 100644
--- a/apps/desktop/src/renderer/components/Controls.tsx
+++ b/apps/desktop/src/renderer/components/Controls.tsx
@@ -290,8 +290,8 @@ export function Disclosure({ expanded, onToggle, label, children }: { expanded:
}
/** Keeps `children` mounted while it fades and folds away. */
-export function Reveal({ show, children }: { show: boolean; children: ReactNode }) {
- const { mounted, shown } = usePresence(show)
+export function Reveal({ show, animateOnMount, children }: { show: boolean; animateOnMount?: boolean; children: ReactNode }) {
+ const { mounted, shown } = usePresence(show, undefined, animateOnMount)
if (!mounted) return null
return (
<div className={`reveal ${shown ? 'shown' : ''}`}>
diff --git a/apps/desktop/src/renderer/demo/fake-host.ts b/apps/desktop/src/renderer/demo/fake-host.ts
index f1f70837..f4eb89a6 100644
--- a/apps/desktop/src/renderer/demo/fake-host.ts
+++ b/apps/desktop/src/renderer/demo/fake-host.ts
@@ -269,6 +269,8 @@ export class FakeHost {
return { configured: false, keyUrl: '' }
case 'credentialStatus':
return { provider: '', onePasswordConnected: false }
+ case 'setUsageShown':
+ return story.usage(Date.now())
case 'setAnalytics':
this.analytics = b.enabled === true
return { enabled: this.analytics }
diff --git a/apps/desktop/src/renderer/demo/story.ts b/apps/desktop/src/renderer/demo/story.ts
index e5aad1c6..a16f7b1e 100644
--- a/apps/desktop/src/renderer/demo/story.ts
+++ b/apps/desktop/src/renderer/demo/story.ts
@@ -157,5 +157,9 @@ export function usage(now: number): Usage {
{ id: 'secondary', label: 'Weekly', percent: 47, resetsAt: hours(95) },
] },
],
+ services: [
+ { id: 'claude', name: 'Claude', shown: true },
+ { id: 'codex', name: 'Codex', shown: true },
+ ],
}
}
diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.ts
index c86a797b..ff2cdeff 100644
--- a/apps/desktop/src/renderer/store/bot-store.ts
+++ b/apps/desktop/src/renderer/store/bot-store.ts
@@ -453,6 +453,12 @@ export class BotStore extends BotSync {
return (await this.ready()).call<DirListing>('listDirs', { path })
}
+ /** Whether this computer lists one agent's limits. */
+ async setUsageShown(id: string, shown: boolean) {
+ this.usage = await (await this.ready()).call<Usage>('setUsageShown', { id, shown })
+ this.changed()
+ }
+
async refreshUsage() {
if (this.retired || !this.client) return
try {
diff --git a/apps/desktop/src/renderer/views/settings/SettingsView.tsx b/apps/desktop/src/renderer/views/settings/SettingsView.tsx
index 64f889ea..baa17f4e 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 { UsageLimits } from './UsageLimits'
+import { UsageChooser, UsageLimits } from './UsageLimits'
import { VoiceChatSettingsView } from './VoiceChatSettingsView'
import { ComputerAccessView } from '../computer-access/ComputerAccessView'
import { FormSheet } from '../marketplace/pieces'
@@ -267,7 +267,7 @@ function UsageLimitsList() {
const tr = useTr()
const app = useApp()
const stores = app.computers.flatMap((c) => app.store(c.id) ?? [])
- const withUsage = stores.filter((s) => s.usage.providers.length > 0)
+ const withUsage = stores.filter((s) => s.usage.providers.length > 0 || s.usage.services?.length)
if (withUsage.length === 0) return <Text tone="secondary">{tr(`No usage information yet.`)}</Text>
return (
<>
@@ -279,6 +279,13 @@ function UsageLimitsList() {
</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,
])}
</>
)
diff --git a/apps/desktop/src/renderer/views/settings/UsageLimits.tsx b/apps/desktop/src/renderer/views/settings/UsageLimits.tsx
index c1530862..72730b3b 100644
--- a/apps/desktop/src/renderer/views/settings/UsageLimits.tsx
+++ b/apps/desktop/src/renderer/views/settings/UsageLimits.tsx
@@ -1,4 +1,6 @@
-import type { Usage } from '@shared/models'
+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 { Text } from '../../components/Text'
import { prefs, usePref } from '../../lib/prefs'
@@ -8,35 +10,80 @@ import { UsageBar } from '../usage/UsageBar'
import { providerTintCSS, resetDescription, windowReading, windowTitle } from '../usage/usage-model'
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[]) {
+ 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 }
+}
+
/** Every limit as a bar under its provider, the way the menu bar lists them. */
export function UsageLimits({ usage }: { usage: Usage }) {
+ const tr = useTr()
+ const { seen, atFirst } = useProvidersSeen(usage.providers)
+ return (
+ <VStack gap={18}>
+ {usage.providers.length === 0 ? <Text tone="secondary">{tr('No usage information yet.')}</Text> : null}
+ {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>
+ )
+}
+
+function ProviderLimits({ provider }: { provider: UsageProvider }) {
const [style] = usePref(prefs.usageIconStyle)
const resetLine = useResetLine()
const tr = useTr()
return (
- <VStack gap={18}>
- {usage.providers.map((provider) => (
- <VStack key={provider.id} gap={10}>
+ <VStack gap={10} 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>
+ ))}
+ </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)
+ 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={provider} size={18} style={style} />
- <Text size="body" weight="semibold" tone="text">{provider.name}</Text>
+ <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>
- {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>
- ))}
- </VStack>
+ </Switch>
))}
+ <Text tone="secondary">{tr('On by default for the agents your bots run.')}</Text>
</VStack>
)
}
diff --git a/apps/desktop/src/renderer/views/settings/settings.css b/apps/desktop/src/renderer/views/settings/settings.css
index d896a36a..dc8f2418 100644
--- a/apps/desktop/src/renderer/views/settings/settings.css
+++ b/apps/desktop/src/renderer/views/settings/settings.css
@@ -164,6 +164,14 @@
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;
+}
+.settings-usage-chooser {
+ margin-top: 18px;
+ font-size: var(--text-callout);
+}
/* Computers & devices. */
.settings-computers {
diff --git a/apps/desktop/src/renderer/views/usage/ProviderMascot.tsx b/apps/desktop/src/renderer/views/usage/ProviderMascot.tsx
index f5391675..4e1aa4dc 100644
--- a/apps/desktop/src/renderer/views/usage/ProviderMascot.tsx
+++ b/apps/desktop/src/renderer/views/usage/ProviderMascot.tsx
@@ -18,7 +18,7 @@ export function ProviderMascot({ provider, size, style = 'character' }: { provid
if (style === 'original') {
return (
<span className="usage-mascot-logo" style={{ width: size, height: size }}>
- <AgentIcon registry={providerRegistry(provider.id)} size={size * 0.84} color={providerTintCSS(provider.id)} />
+ <AgentIcon registry={providerRegistry(provider)} size={size * 0.84} color={providerTintCSS(provider.id)} />
</span>
)
}
@@ -40,7 +40,7 @@ const loaded = new Map<string, HTMLImageElement>()
export function drawMascot(ctx: CanvasRenderingContext2D, provider: UsageProvider, size: number, style: 'character' | 'original', dark: boolean): boolean {
const tint = provider.id === 'claude' ? '#D97757' : dark ? '#FFFFFF' : '#000000'
if (style === 'original') {
- const url = agentIconURL(providerRegistry(provider.id))
+ const url = agentIconURL(providerRegistry(provider))
if (!url) return false
const image = loaded.get(url)
if (!image) {
diff --git a/apps/desktop/src/renderer/views/usage/usage-model.ts b/apps/desktop/src/renderer/views/usage/usage-model.ts
index bdd3fae2..a0c9a178 100644
--- a/apps/desktop/src/renderer/views/usage/usage-model.ts
+++ b/apps/desktop/src/renderer/views/usage/usage-model.ts
@@ -9,8 +9,12 @@ export function providerTint(id: string) {
/** CSS color for views (follows the scheme by itself). */
export const providerTintCSS = (id: string) => (id === 'claude' ? '#D97757' : 'var(--accent)')
-/** ACP registry id of the provider's agent, for its logo. */
-export const providerRegistry = (id: string) => (['claude', 'codex'].includes(id) ? `${id}-acp` : id)
+/**
+ * ACP registry id of the provider's agent, for its logo. A host that doesn't name it: Claude and
+ * Codex run through ACP adapters, others go by their own id.
+ */
+export const providerRegistry = ({ id, registry }: UsageProvider) =>
+ registry ?? (['claude', 'codex'].includes(id) ? `${id}-acp` : id)
/** The character that stands for this provider. */
export const mascotShape = (id: string) => (id === 'codex' ? 'hex' : 'blob')
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 808f0107..7d7b0d7d 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -425,10 +425,23 @@ export interface UsageProvider {
windows: UsageWindow[]
source: string
updatedAt: number
+ /** The agent's ACP registry id, which its logo goes by. Absent from a host that doesn't name it. */
+ registry?: string
+}
+
+/** An agent the Usage screen can show or hide. The host keeps the choice, so every app follows it. */
+export interface UsageService {
+ id: string
+ name: string
+ shown: boolean
+ /** The agent's ACP registry id, which its logo goes by. */
+ registry?: string
}
export interface Usage {
providers: UsageProvider[]
+ /** Absent from a host older than the chooser. */
+ services?: UsageService[]
}
export interface Backend {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 7a8ba2c9..707c52a7 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -397,6 +397,12 @@ public extension HostClient {
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/Design/ProviderMascot.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swift
index 5bcc2784..fbc546e1 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swift
@@ -27,9 +27,12 @@ public extension UsageProvider {
/// Claude keeps its orange; everyone else is ink, like the rest of the app.
var tint: Color { id == "claude" ? Color(hex: 0xD97757) : Palette.accent }
- /// ACP registry id of the provider's agent, for its logo (`AgentIcon`).
- /// Claude and Codex run through ACP adapters (`claude-acp`, `codex-acp`); others by their own id.
- var registry: String { ["claude", "codex"].contains(id) ? "\(id)-acp" : id }
+ /// The name of this agent's logo in this bundle, when it has one. A host or a saved widget that
+ /// doesn't name the registry id: Claude and Codex run through ACP adapters, others go by their own id.
+ var logoAsset: String? {
+ let name = "agent-\(registry ?? (["claude", "codex"].contains(id) ? "\(id)-acp" : id))"
+ return UIImage(named: name, in: .module, compatibleWith: nil) == nil ? nil : name
+ }
/// The character that stands for this provider.
var mascotShape: String { id == "codex" ? "hex" : "blob" }
@@ -78,8 +81,8 @@ public struct ProviderMascot: View {
public var body: some View {
let full = (provider.tightest?.percent ?? 0) >= 90
Group {
- if style == .original {
- Image("agent-\(provider.registry)", bundle: .module)
+ if style == .original, let logo = provider.logoAsset {
+ Image(logo, bundle: .module)
.resizable().scaledToFit().padding(size * 0.08)
.foregroundStyle(provider.tint)
} else {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
index c0328fb9..196d1b40 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
@@ -94,7 +94,24 @@ public struct PlanItem: Codable, Hashable, Sendable {
public struct Usage: Codable, Hashable, Sendable {
public var providers: [UsageProvider]
- public init(providers: [UsageProvider] = []) { self.providers = providers }
+ /// The agents the Usage screen can show or hide. Absent from a host older than the chooser.
+ public var services: [UsageService]?
+ public init(providers: [UsageProvider] = [], services: [UsageService]? = nil) {
+ self.providers = providers
+ self.services = services
+ }
+}
+
+/// An agent the Usage screen can show or hide. The host keeps the choice, so every app follows it.
+public struct UsageService: Codable, Hashable, Sendable, Identifiable {
+ public var id: String
+ public var name: String
+ public var shown: Bool
+ /// The agent's ACP registry id, which its logo goes by. Without one, its `id`.
+ public var registry: String? = nil
+
+ /// What a mascot needs of an agent that may have no reading.
+ public var provider: UsageProvider { UsageProvider(id: id, name: name, windows: [], source: "", updatedAt: 0, registry: registry) }
}
public struct UsageProvider: Codable, Hashable, Sendable, Identifiable {
@@ -103,6 +120,8 @@ public struct UsageProvider: Codable, Hashable, Sendable, Identifiable {
public var windows: [UsageWindow]
public var source: String
public var updatedAt: Int64
+ /// The agent's ACP registry id, which its logo goes by. Absent from a host that doesn't name it.
+ public var registry: String? = nil
}
public struct UsageWindow: Codable, Hashable, Sendable, Identifiable {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index cc25ba39..27bae656 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "Du kannst erneut Zugriff anfordern. Der Computer zeigt dann einen neuen Bestätigungscode an.",
"Your bots run there. This iPhone is how you talk to them.": "Deine Bots laufen dort. Über dieses iPhone sprichst du mit ihnen.",
"Your computer": "Dein Computer",
- "Your computer reads plan limits from the agents installed on it.": "Dein Computer liest die Planlimits der darauf installierten Agents.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "Dein Computer liest die Planlimits der Agenten deiner Bots und der Agenten, die du einschaltest.",
"or download the Mac app": "oder lade die Mac-App herunter",
"or install with Homebrew": "oder installiere mit Homebrew",
"search bots": "Bots suchen",
@@ -1832,5 +1832,14 @@
"r start": "r Starten",
"s stop": "s stoppen",
"x remove": "x entfernen",
- "esc close": "esc schließen"
+ "esc close": "esc schließen",
+ "Show usage for": "Nutzung anzeigen für",
+ "On by default for the agents your bots run.": "Standardmäßig an für die Agenten deiner Bots.",
+ "No reading yet": "Noch kein Wert",
+ "Premium requests": "Premium-Anfragen",
+ "Balance": "Guthaben",
+ "Credits": "Guthaben",
+ "Prepaid": "Prepaid",
+ "Monthly": "Monatlich",
+ "Completions": "Vervollständigungen"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 3b9c85e7..ef3cc814 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "Puedes volver a solicitar acceso; la computadora mostrará un código nuevo para confirmar.",
"Your bots run there. This iPhone is how you talk to them.": "Tus bots trabajan allí. Este iPhone te permite hablar con ellos.",
"Your computer": "Tu computadora",
- "Your computer reads plan limits from the agents installed on it.": "Tu computadora lee los límites de los planes de los agentes instalados en ella.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "Tu computadora lee los límites de los planes de los agentes que usan tus bots y de los que actives.",
"or download the Mac app": "o descarga la app para Mac",
"or install with Homebrew": "o instala con Homebrew",
"search bots": "buscar bots",
@@ -1832,5 +1832,14 @@
"r start": "r Iniciar",
"s stop": "s detener",
"x remove": "x quitar",
- "esc close": "esc cerrar"
+ "esc close": "esc cerrar",
+ "Show usage for": "Mostrar el uso de",
+ "On by default for the agents your bots run.": "Activado de forma predeterminada para los agentes que usan tus bots.",
+ "No reading yet": "Aún sin lectura",
+ "Premium requests": "Solicitudes premium",
+ "Balance": "Saldo",
+ "Credits": "Créditos",
+ "Prepaid": "Prepago",
+ "Monthly": "Mensual",
+ "Completions": "Autocompletados"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index ac5d94dd..e08dae63 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "Vous pouvez redemander l’accès ; l’ordinateur affichera un nouveau code à confirmer.",
"Your bots run there. This iPhone is how you talk to them.": "Vos bots y travaillent. Cet iPhone vous permet de leur parler.",
"Your computer": "Votre ordinateur",
- "Your computer reads plan limits from the agents installed on it.": "Votre ordinateur lit les limites des forfaits des agents installés dessus.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "Votre ordinateur lit les limites des forfaits des agents que vos bots utilisent et de ceux que vous activez.",
"or download the Mac app": "ou téléchargez l’app Mac",
"or install with Homebrew": "ou installez avec Homebrew",
"search bots": "rechercher des bots",
@@ -1832,5 +1832,14 @@
"r start": "r Démarrer",
"s stop": "s arrêter",
"x remove": "x retirer",
- "esc close": "esc fermer"
+ "esc close": "esc fermer",
+ "Show usage for": "Afficher l'utilisation de",
+ "On by default for the agents your bots run.": "Activé par défaut pour les agents que vos bots utilisent.",
+ "No reading yet": "Pas encore de relevé",
+ "Premium requests": "Requêtes premium",
+ "Balance": "Solde",
+ "Credits": "Crédits",
+ "Prepaid": "Prépayé",
+ "Monthly": "Mensuel",
+ "Completions": "Complétions"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
index a0257753..89288ee2 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
@@ -1402,7 +1402,7 @@
"Your coding agents, as teammates.": "I tuoi agenti di coding, come compagni di squadra.",
"Your computer": "Il tuo computer",
"Your computer is ready": "Il tuo computer è pronto",
- "Your computer reads plan limits from the agents installed on it.": "Il tuo computer legge i limiti del piano dagli agenti installati.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "Il tuo computer legge i limiti del piano dagli agenti usati dai tuoi bot e da quelli che attivi.",
"Your launcher couldn't add it. Add it from the Home Screen instead.": "Il launcher non è riuscito ad aggiungerlo. Aggiungilo dalla schermata Home.",
"Your lead agent is your first point of contact. It follows your goals and unfinished tasks, suggests useful next steps, and coordinates work with your other bots. The lead Codync sets up has a Check in routine that runs twice a day by default; you can change or pause it in Routines.": "Il tuo agente principale è il tuo primo punto di contatto. Segue i tuoi obiettivi e le attività incompiute, suggerisce i prossimi passi utili e coordina il lavoro con gli altri bot. L'agente principale configurato da Codync ha una routine Check in che viene eseguita due volte al giorno per impostazione predefinita; puoi modificarla o metterla in pausa in Routine.",
"Your messages, prompts, code, files, file names or paths, bot names, credentials, or anything your agents produce.": "I tuoi messaggi, prompt, codice, file, nomi e percorsi dei file, nomi dei bot, credenziali o qualsiasi cosa producano i tuoi agenti.",
@@ -1832,5 +1832,14 @@
"r start": "r Avvia",
"s stop": "s arresta",
"x remove": "x rimuovi",
- "esc close": "esc chiudi"
+ "esc close": "esc chiudi",
+ "Show usage for": "Mostra l'utilizzo di",
+ "On by default for the agents your bots run.": "Attivo di default per gli agenti usati dai tuoi bot.",
+ "No reading yet": "Ancora nessun dato",
+ "Premium requests": "Richieste premium",
+ "Balance": "Saldo",
+ "Credits": "Crediti",
+ "Prepaid": "Prepagato",
+ "Monthly": "Mensile",
+ "Completions": "Completamenti"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 29521fe6..55f34e46 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "再度アクセスを要求できます。コンピューターは確認のための新しいコードを表示します。",
"Your bots run there. This iPhone is how you talk to them.": "ボットはそこで実行されます。この iPhone は、彼らと話す方法です。",
"Your computer": "あなたのコンピュータ",
- "Your computer reads plan limits from the agents installed on it.": "このコンピュータに入っているエージェントから、プランの上限を読み取ります。",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "ボットが使うエージェントと、オンにしたエージェントから、プランの上限を読み取ります。",
"or download the Mac app": "またはMacアプリをダウンロードしてください",
"or install with Homebrew": "またはHomebrewでインストールする",
"search bots": "ボットを検索",
@@ -1832,5 +1832,14 @@
"r start": "r 起動",
"s stop": "s 停止",
"x remove": "x 削除",
- "esc close": "esc 閉じる"
+ "esc close": "esc 閉じる",
+ "Show usage for": "用量を表示するサービス",
+ "On by default for the agents your bots run.": "ボットが使うエージェントはデフォルトでオンです。",
+ "No reading yet": "まだ読み取れていません",
+ "Premium requests": "プレミアムリクエスト",
+ "Balance": "残高",
+ "Credits": "クレジット",
+ "Prepaid": "プリペイド",
+ "Monthly": "月間",
+ "Completions": "補完"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 9537d2c5..f9f44d4a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "다시 액세스를 요청할 수 있습니다. 컴퓨터에 확인을 위한 새 코드가 표시됩니다.",
"Your bots run there. This iPhone is how you talk to them.": "당신의 봇이 거기에서 실행됩니다. 이 iPhone는 당신이 그들과 대화하는 방법입니다.",
"Your computer": "귀하의 컴퓨터",
- "Your computer reads plan limits from the agents installed on it.": "이 컴퓨터에 설치된 에이전트의 요금제 한도를 읽습니다.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "봇이 사용하는 에이전트와 직접 켠 에이전트의 요금제 한도를 읽습니다.",
"or download the Mac app": "또는 Mac 앱을 다운로드하세요.",
"or install with Homebrew": "또는 Homebrew로 설치",
"search bots": "검색 봇",
@@ -1832,5 +1832,14 @@
"r start": "r 시작",
"s stop": "s 중지",
"x remove": "x 제거",
- "esc close": "esc 닫기"
+ "esc close": "esc 닫기",
+ "Show usage for": "사용량을 표시할 서비스",
+ "On by default for the agents your bots run.": "봇이 사용하는 에이전트는 기본으로 켜져 있습니다.",
+ "No reading yet": "아직 읽어 오지 못했습니다",
+ "Premium requests": "프리미엄 요청",
+ "Balance": "잔액",
+ "Credits": "크레딧",
+ "Prepaid": "선불",
+ "Monthly": "월간",
+ "Completions": "자동 완성"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
index a32f36aa..e7b54db4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "Você pode pedir acesso novamente; o computador vai mostrar um novo código para confirmar.",
"Your bots run there. This iPhone is how you talk to them.": "Seus bots rodam lá. É por este iPhone que você fala com eles.",
"Your computer": "Seu computador",
- "Your computer reads plan limits from the agents installed on it.": "Seu computador consulta os limites dos planos nos agentes instalados nele.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "Seu computador consulta os limites dos planos nos agentes que seus bots usam e nos que você ativar.",
"or download the Mac app": "ou baixe o app para Mac",
"or install with Homebrew": "ou instale com o Homebrew",
"search bots": "buscar bots",
@@ -1832,5 +1832,14 @@
"r start": "r Iniciar",
"s stop": "s parar",
"x remove": "x remover",
- "esc close": "esc fechar"
+ "esc close": "esc fechar",
+ "Show usage for": "Mostrar uso de",
+ "On by default for the agents your bots run.": "Ativado por padrão para os agentes que seus bots usam.",
+ "No reading yet": "Ainda sem leitura",
+ "Premium requests": "Solicitações premium",
+ "Balance": "Saldo",
+ "Credits": "Créditos",
+ "Prepaid": "Pré-pago",
+ "Monthly": "Mensal",
+ "Completions": "Preenchimentos"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
index 95239248..920de313 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "Можно запросить доступ снова: компьютер покажет новый код для подтверждения.",
"Your bots run there. This iPhone is how you talk to them.": "Ваши боты работают там. Через этот iPhone вы с ними общаетесь.",
"Your computer": "Ваш компьютер",
- "Your computer reads plan limits from the agents installed on it.": "Ваш компьютер читает лимиты тарифов из установленных на нём агентов.",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "Ваш компьютер читает лимиты тарифов агентов, которые используют ваши боты, и тех, что вы включили.",
"or download the Mac app": "или скачайте приложение для Mac",
"or install with Homebrew": "или установите через Homebrew",
"search bots": "поиск ботов",
@@ -1832,5 +1832,14 @@
"r start": "r Запустить",
"s stop": "s стоп",
"x remove": "x убрать",
- "esc close": "esc закрыть"
+ "esc close": "esc закрыть",
+ "Show usage for": "Показывать расход для",
+ "On by default for the agents your bots run.": "По умолчанию включено для агентов, которые используют ваши боты.",
+ "No reading yet": "Пока нет данных",
+ "Premium requests": "Премиум-запросы",
+ "Balance": "Баланс",
+ "Credits": "Кредиты",
+ "Prepaid": "Предоплата",
+ "Monthly": "Ежемесячно",
+ "Completions": "Автодополнения"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index 3a44fc79..cf897776 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "可以再次申请。电脑会显示一个新的配对码供你确认。",
"Your bots run there. This iPhone is how you talk to them.": "Bot 在那台电脑上运行。这台 iPhone 用来和它们对话。",
"Your computer": "你的电脑",
- "Your computer reads plan limits from the agents installed on it.": "电脑会从这台电脑上安装的 agent 读取用量上限。",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "电脑会读取 bot 正在使用的 agent 和你开启的 agent 的用量上限。",
"or download the Mac app": "或下载 Mac 应用",
"or install with Homebrew": "或用 Homebrew 安装",
"search bots": "搜索 Bot",
@@ -1832,5 +1832,14 @@
"r start": "r 启动",
"s stop": "s 停止",
"x remove": "x 移除",
- "esc close": "esc 关闭"
+ "esc close": "esc 关闭",
+ "Show usage for": "显示这些服务的用量",
+ "On by default for the agents your bots run.": "默认只开启 bot 正在使用的 agent。",
+ "No reading yet": "还没有读数",
+ "Premium requests": "高级请求",
+ "Balance": "余额",
+ "Credits": "额度",
+ "Prepaid": "预付",
+ "Monthly": "每月",
+ "Completions": "补全"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index ff638eaa..087d7ee4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -353,7 +353,7 @@
"You can ask for access again; the computer will show a new code to confirm.": "可以再次申請。電腦會顯示一個新的配對碼供你確認。",
"Your bots run there. This iPhone is how you talk to them.": "Bot 在那臺電腦上執行。這臺 iPhone 用來和它們對話。",
"Your computer": "你的電腦",
- "Your computer reads plan limits from the agents installed on it.": "電腦會從這台電腦上安裝的 agent 讀取用量上限。",
+ "Your computer reads plan limits from the agents your bots run and the ones you turn on.": "電腦會讀取 bot 正在使用的 agent 和你開啟的 agent 的用量上限。",
"or download the Mac app": "或下載 Mac 應用",
"or install with Homebrew": "或用 Homebrew 安裝",
"search bots": "搜尋 Bot",
@@ -1832,5 +1832,14 @@
"r start": "r 啟動",
"s stop": "s 停止",
"x remove": "x 移除",
- "esc close": "esc 關閉"
+ "esc close": "esc 關閉",
+ "Show usage for": "顯示這些服務的用量",
+ "On by default for the agents your bots run.": "預設只開啟 bot 正在使用的 agent。",
+ "No reading yet": "還沒有讀數",
+ "Premium requests": "進階請求",
+ "Balance": "餘額",
+ "Credits": "額度",
+ "Prepaid": "預付",
+ "Monthly": "每月",
+ "Completions": "自動完成"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-amp-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-amp-acp.imageset/Contents.json
new file mode 100644
index 00000000..c4b10839
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-amp-acp.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "amp-acp.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-amp-acp.imageset/amp-acp.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-amp-acp.imageset/amp-acp.svg
new file mode 100644
index 00000000..314881af
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-amp-acp.imageset/amp-acp.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M13.9197 13.61L17.3816 26.566L14.242 27.4049L11.2645 16.2643L0.119926 13.2906L0.957817 10.15L13.9197 13.61Z" fill="currentColor"/>
+<path d="M13.7391 16.0892L4.88169 24.9056L2.58872 22.6019L11.4461 13.7865L13.7391 16.0892Z" fill="currentColor"/>
+<path d="M18.9386 8.58315L22.4005 21.5392L19.2609 22.3781L16.2833 11.2374L5.13879 8.26381L5.97668 5.12318L18.9386 8.58315Z" fill="currentColor"/>
+<path d="M23.9803 3.55632L27.4422 16.5124L24.3025 17.3512L21.325 6.21062L10.1805 3.23698L11.0183 0.0963593L23.9803 3.55632Z" fill="currentColor"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-antigravity-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-antigravity-acp.imageset/Contents.json
new file mode 100644
index 00000000..91f07277
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-antigravity-acp.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "antigravity-acp.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svg
new file mode 100644
index 00000000..02f65dab
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M14.1452 14.6818C14.9937 15.3182 16.2664 14.894 15.0997 13.7273C11.5998 10.3333 12.3421 1 7.99366 1C3.64518 1 4.3876 10.3333 0.887603 13.7273C-0.385123 15 0.993664 15.3182 1.84215 14.6818C5.13002 12.4545 4.9179 8.5303 7.99366 8.5303C11.0694 8.5303 10.8573 12.4545 14.1452 14.6818Z" fill="currentColor"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-auggie.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-auggie.imageset/Contents.json
new file mode 100644
index 00000000..2b92198a
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-auggie.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "auggie.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-auggie.imageset/auggie.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-auggie.imageset/auggie.svg
new file mode 100644
index 00000000..21510774
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-auggie.imageset/auggie.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16">
+ <path fill="currentColor" d="M9.972 13.193h2.577q.187 0 .277-.09t.091-.294V10.47q0-.324.133-.59.135-.27.36-.424a1 1 0 0 1 .099-.06 1 1 0 0 1-.1-.058 1.1 1.1 0 0 1-.359-.424 1.3 1.3 0 0 1-.133-.59v-2.33q0-.202-.091-.293t-.277-.089H9.972a.38.38 0 0 1-.294-.124.4.4 0 0 1-.108-.281q.002-.176.131-.293a.46.46 0 0 1 .313-.111h2.775c.36 0 .642.097.836.288q.293.29.294.832V8.24q0 .39.152.562.148.168.555.178a.4.4 0 0 1 .27.128.41.41 0 0 1 .104.287.44.44 0 0 1-.1.282.34.34 0 0 1-.277.132c-.266.006-.452.066-.55.177q-.151.174-.152.573v2.318c0 .235-.043.44-.128.607a.85.85 0 0 1-.389.387 1.3 1.3 0 0 1-.534.124V14h-2.854a.45.45 0 0 1-.315-.118.38.38 0 0 1-.129-.286q0-.164.109-.282a.38.38 0 0 1 .293-.123zM1.103 9.108a.4.4 0 0 1 .276-.128q.4-.008.55-.177.15-.173.151-.562V5.923q.002-.543.294-.832c.195-.191.477-.288.836-.288h2.775q.188 0 .313.111a.37.37 0 0 1 .131.293.4.4 0 0 1-.108.281.38.38 0 0 1-.293.123H3.45q-.186 0-.277.09t-.092.292v2.33c0 .213-.044.413-.133.59a1.1 1.1 0 0 1-.359.424 1 1 0 0 1-.1.059 1 1 0 0 1 .1.059q.225.156.359.423t.133.59v2.34q0 .203.092.293.088.09.277.089h2.577a.38.38 0 0 1 .294.123q.108.12.108.281a.38.38 0 0 1-.13.286.45.45 0 0 1-.314.118l-2.775-.003a1.4 1.4 0 0 1-.613-.126.87.87 0 0 1-.388-.387 1.34 1.34 0 0 1-.129-.608v-2.318q0-.4-.151-.572-.151-.168-.55-.177a.35.35 0 0 1-.278-.132.42.42 0 0 1-.102-.28q0-.173.103-.287"/>
+ <path fill="currentColor" d="M5.437 10.36a.986.986 0 0 1-.994-.975c0-.538.446-.976.994-.976s.994.438.994.976a.986.986 0 0 1-.994.976M10.562 8.41c.548 0 .994.437.994.975a.986.986 0 0 1-.994.976.986.986 0 0 1-.994-.976c0-.538.446-.976.994-.976M8.74 2c.37 0 .446.15.446.275v.034q0 .034-.009.201-.01.162-.017.549-.018.378-.044 1.06c0 .106-.065.233-.375.233-.311 0-.376-.126-.376-.23l-.07-1.835v-.003c0-.13.078-.284.446-.284M7.256 2c.369 0 .446.15.446.275v.034q0 .034-.01.201-.007.162-.017.549-.017.378-.043 1.06c0 .106-.065.233-.376.233-.31 0-.375-.126-.375-.23l-.07-1.835v-.003C6.81 2.154 6.887 2 7.256 2"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-cursor.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-cursor.imageset/Contents.json
new file mode 100644
index 00000000..f71db870
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-cursor.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "cursor.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-cursor.imageset/cursor.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-cursor.imageset/cursor.svg
new file mode 100644
index 00000000..4ca0c250
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-cursor.imageset/cursor.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 466.73 532.09">
+ <path fill="currentColor" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-github-copilot-cli.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-github-copilot-cli.imageset/Contents.json
new file mode 100644
index 00000000..4cf996a8
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-github-copilot-cli.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "github-copilot-cli.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svg
new file mode 100644
index 00000000..626d33ba
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M7.99816 14.2779C12.0678 14.2779 14.9997 11.6274 14.9997 10.9574V9.3189C14.939 8.77306 14.4165 7.82349 13.6074 7.48636C13.5959 7.42498 13.5859 7.36153 13.5756 7.29542C13.5506 7.13548 13.5231 6.95977 13.4649 6.75954C13.6409 6.31508 13.6873 5.81187 13.6873 5.31135C13.6873 4.54947 13.5757 3.76321 13.0811 3.13712C12.5745 2.4959 11.7737 2.15372 10.6972 2.03411C9.64215 1.91688 8.71828 2.06409 8.12157 2.70342C8.07827 2.74981 8.0345 2.79812 7.99655 2.84746C7.95861 2.79812 7.91805 2.74981 7.87475 2.70342C7.27804 2.06409 6.35416 1.91688 5.29908 2.03411C4.22263 2.15372 3.42181 2.4959 2.91521 3.13712C2.42057 3.76321 2.30905 4.54947 2.30905 5.31135C2.30905 5.81187 2.35539 6.31508 2.53142 6.75954C2.47323 6.95977 2.44574 7.13542 2.42072 7.29536C2.41037 7.3615 2.40044 7.42496 2.38893 7.48636C1.57983 7.82349 1.05728 8.77306 0.996582 9.3189V10.9574C0.996582 11.6274 3.92849 14.2779 7.99816 14.2779ZM10.5523 3.33859C9.63863 3.23707 9.25001 3.41798 9.0811 3.59896C8.90273 3.79007 8.76738 4.19254 8.86971 5.0112C8.94909 5.64627 9.13423 6.08757 9.41018 6.36929C9.67188 6.63645 10.0966 6.8426 10.8435 6.8426C11.6506 6.8426 11.9631 6.66867 12.1051 6.51046C12.2619 6.33577 12.3748 6.00462 12.3748 5.31135C12.3748 4.64141 12.2675 4.22455 12.0513 3.95077C11.8469 3.69214 11.4446 3.43773 10.5523 3.33859ZM6.91639 3.59896C6.74748 3.41798 6.35886 3.23707 5.44518 3.33859C4.55289 3.43773 4.15058 3.69214 3.94624 3.95077C3.72994 4.22455 3.62271 4.64141 3.62271 5.31135C3.62271 6.00462 3.73563 6.33577 3.89239 6.51046C4.03436 6.66867 4.34693 6.8426 5.15396 6.8426C5.90092 6.8426 6.32561 6.63645 6.58731 6.36929C6.86326 6.08757 7.0484 5.64627 7.12778 5.0112C7.23011 4.19254 7.09476 3.79007 6.91639 3.59896ZM7.99818 12.9788C9.99307 12.9788 12.0088 12.0076 12.3748 11.7248V8.00133L12.3546 7.90026C11.9257 8.08369 11.4142 8.1551 10.8435 8.1551C9.84049 8.1551 9.04148 7.86851 8.47257 7.28773C8.28092 7.09208 8.12536 6.87308 7.99978 6.6378C7.8742 6.87308 7.71544 7.09208 7.52378 7.28773C6.95488 7.86851 6.15587 8.1551 5.15283 8.1551C4.58212 8.1551 4.07068 8.08369 3.6418 7.90026L3.62158 8.00133V11.7248C3.98755 12.0076 6.00329 12.9788 7.99818 12.9788Z" fill="currentColor"/>
+<path d="M6.46854 9.0301C6.83097 9.0301 7.12479 9.32391 7.12479 9.68635V10.9988C7.12479 11.3613 6.83097 11.6551 6.46854 11.6551C6.1061 11.6551 5.81229 11.3613 5.81229 10.9988V9.68635C5.81229 9.32391 6.1061 9.0301 6.46854 9.0301Z" fill="currentColor"/>
+<path d="M10.1873 9.68635C10.1873 9.32391 9.89347 9.0301 9.53104 9.0301C9.1686 9.0301 8.87479 9.32391 8.87479 9.68635V10.9988C8.87479 11.3613 9.1686 11.6551 9.53104 11.6551C9.89347 11.6551 10.1873 11.3613 10.1873 10.9988V9.68635Z" fill="currentColor"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-grok-build.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-grok-build.imageset/Contents.json
new file mode 100644
index 00000000..0759747e
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-grok-build.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "grok-build.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-grok-build.imageset/grok-build.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-grok-build.imageset/grok-build.svg
new file mode 100644
index 00000000..69f573cb
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-grok-build.imageset/grok-build.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
+ <path fill="currentColor" d="M0.58392448,14.9254204 L0.8326,14.66295 C2.004465,13.42985 3.1678,12.2082 2.45814,10.48105 C1.50813,8.1701 2.061355,5.4619 3.820575,3.70057 C5.6495,1.8709 8.3431,1.40957 10.59295,2.336505 C11.0907,2.52161 11.5245,2.785025 11.86295,3.02993 L9.98425,3.89849 C8.235,3.163775 6.23115,3.66355 5.0081,4.88809 C3.354105,6.5426 3.019895,9.4117 4.95835,11.2656 L-0.335,15.99995 C-0.066496,15.62975 0.2538896,15.275934 0.58392448,14.9254204 Z M14.0391,2.288155 L16.33165,2.57749377e-12 L16.20795,0.172288 C14.4658,2.574355 13.6153,3.749045 14.29795,6.6879 C14.76445,8.68415 14.261,10.90255 12.63545,12.53005 C10.5861,14.58325 7.3066,15.0403 4.6059,13.19215 L6.48885,12.3193 C8.2125,12.99705 10.0983,12.69945 11.4536,11.34255 C12.80895,9.9856 13.1133,8.00925 12.4321,6.3647 C12.30265,6.05285 11.9144,5.97455 11.64275,6.1753 L6.102,10.27035 L14.0391,2.288155 Z"/>
+</svg>
\ No newline at end of file
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-junie.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-junie.imageset/Contents.json
new file mode 100644
index 00000000..73368892
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-junie.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "junie.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-junie.imageset/junie.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-junie.imageset/junie.svg
new file mode 100644
index 00000000..63b60e8f
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-junie.imageset/junie.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 40 40" fill="none">
+ <path d="M25 15H35V16.75C35 29 30.5001 35 16.5001 35H15V25H16.5001C22.6251 25 25 22.875 25 16.75V15Z" fill="currentColor"/>
+ <rect x="5" y="15" width="10" height="10" fill="currentColor"/>
+ <rect x="15" y="5" width="10" height="10" fill="currentColor"/>
+</svg>
\ No newline at end of file
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kilo.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kilo.imageset/Contents.json
new file mode 100644
index 00000000..3eacd61a
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kilo.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "kilo.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kilo.imageset/kilo.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kilo.imageset/kilo.svg
new file mode 100644
index 00000000..8af6e96f
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kilo.imageset/kilo.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 40 40">
+ <path fill="currentColor" d="M27.9998324,34.6666921h6.6666279v5.3333023h-8.3809037l-3.6190266-3.6190266v-8.3809037h5.3333023v6.6666279ZM39.9997627,26.2857884l-3.6190266-3.6190266h-8.3809037v5.3333023h6.6666279v6.6666279h5.3333023v-8.3809037ZM17.3332326,22.6667578h-5.3333023v5.3333023h5.3333023v-5.3333023ZM0,36.3809638l3.6190266,3.6190266h13.714206v-5.3333023H5.3333023v-11.9999302H0v13.714206ZM33.9600959,11.9999247V3.619021L30.3410693-.0000056h-7.6745392v5.3333023h5.9602634v6.6666279h-5.9602634v5.3333023h17.3332326v-5.3333023h-6.0396668ZM5.3333023,0H0v17.3332326h5.3333023v-5.9999651h6.6666279v5.9999651h5.3333023v-5.9999651l-5.3333023-5.3333023h-6.6666279V0ZM17.3332326,0h-5.3333023v5.9999651h5.3333023V0Z"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kimi.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kimi.imageset/Contents.json
new file mode 100644
index 00000000..a37f21cd
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kimi.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "kimi.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kimi.imageset/kimi.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kimi.imageset/kimi.svg
new file mode 100644
index 00000000..4f7547cf
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kimi.imageset/kimi.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
+ <path fill="currentColor" d="M19.514 7.342C19.711 7.862 19.814 8.413 19.816 8.969C19.816 12.494 15.998 14.697 12.946 12.934C11.529 12.116 10.657 10.605 10.657 8.969C10.657 5.646 14.085 3.431 17.115 4.793C15.26 3.373 12.99 2.607 10.655 2.612C4.772 2.614 0.005 7.381 0 13.265C0.002 19.148 4.772 23.918 10.655 23.92C16.538 23.916 21.306 19.147 21.31 13.265C21.312 11.155 20.687 9.095 19.514 7.342ZM14.841 4.666C14.841 8.191 18.657 10.395 21.709 8.632C23.127 7.814 24 6.302 24 4.666C24 1.14 20.184-1.061 17.13 0.699C15.714 1.519 14.841 3.03 14.841 4.666"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kiro.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kiro.imageset/Contents.json
new file mode 100644
index 00000000..21535e78
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kiro.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "kiro.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kiro.imageset/kiro.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kiro.imageset/kiro.svg
new file mode 100644
index 00000000..5fe3cf68
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-kiro.imageset/kiro.svg
@@ -0,0 +1,11 @@
+<svg width="1200" height="1200" viewBox="0 0 1200 1200" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="1200" height="1200" rx="260" fill="#9046FF"/>
+<mask id="mask0_1106_4856" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="272" y="202" width="655" height="796">
+<path d="M926.578 202.793H272.637V997.857H926.578V202.793Z" fill="white"/>
+</mask>
+<g mask="url(#mask0_1106_4856)">
+<path d="M398.554 818.914C316.315 1001.03 491.477 1046.74 620.672 940.156C658.687 1059.66 801.052 970.473 852.234 877.795C964.787 673.567 919.318 465.357 907.64 422.374C827.637 129.443 427.623 128.946 358.8 423.865C342.651 475.544 342.402 534.18 333.458 595.051C328.986 625.86 325.507 645.488 313.83 677.785C306.873 696.424 297.68 712.819 282.773 740.645C259.915 783.881 269.604 867.113 387.87 823.883L399.051 818.914H398.554Z" fill="white"/>
+<path d="M636.123 549.353C603.328 549.353 598.359 510.097 598.359 486.742C598.359 465.623 602.086 448.977 609.293 438.293C615.504 428.852 624.697 424.131 636.123 424.131C647.555 424.131 657.492 428.852 664.447 438.541C672.398 449.474 676.623 466.12 676.623 486.742C676.623 525.998 661.471 549.353 636.375 549.353H636.123Z" fill="black"/>
+<path d="M771.24 549.353C738.445 549.353 733.477 510.097 733.477 486.742C733.477 465.623 737.203 448.977 744.41 438.293C750.621 428.852 759.814 424.131 771.24 424.131C782.672 424.131 792.609 428.852 799.564 438.541C807.516 449.474 811.74 466.12 811.74 486.742C811.74 525.998 796.588 549.353 771.492 549.353H771.24Z" fill="black"/>
+</g>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-mistral-vibe.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-mistral-vibe.imageset/Contents.json
new file mode 100644
index 00000000..adc5914d
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-mistral-vibe.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "mistral-vibe.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svg
new file mode 100644
index 00000000..b13631b9
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svg
@@ -0,0 +1,12 @@
+<svg width="16" height="16" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M8.8147 5.35803H5.35791V8.46914H8.8147V5.35803Z" fill="currentColor"/>
+<path d="M22.6419 5.35803H19.1851V8.46914H22.6419V5.35803Z" fill="currentColor"/>
+<path d="M15.7283 15.7284H12.2715V18.8395H15.7283V15.7284Z" fill="currentColor"/>
+<path d="M8.8147 15.7284H5.35791V18.8395H8.8147V15.7284Z" fill="currentColor"/>
+<path d="M22.6419 15.7284H19.1851V18.8395H22.6419V15.7284Z" fill="currentColor"/>
+<path d="M12.2715 8.81482H5.35791V11.9259H12.2715V8.81482Z" fill="currentColor"/>
+<path d="M12.2718 19.1852H1.90137V22.2963H12.2718V19.1852Z" fill="currentColor"/>
+<path d="M26.0989 19.1852H15.7285V22.2963H26.0989V19.1852Z" fill="currentColor"/>
+<path d="M22.6419 12.2716H5.35791V15.3827H22.6419V12.2716Z" fill="currentColor"/>
+<path d="M22.6421 8.81482H15.7285V11.9259H22.6421V8.81482Z" fill="currentColor"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-omp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-omp.imageset/Contents.json
new file mode 100644
index 00000000..d98fbe5b
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-omp.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "omp.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-omp.imageset/omp.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-omp.imageset/omp.svg
new file mode 100644
index 00000000..a44b5e88
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-omp.imageset/omp.svg
@@ -0,0 +1,3 @@
+<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M2 0H38V8H28V40H20V8H14V30H6V8H2V0Z" fill="currentColor"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-opencode.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-opencode.imageset/Contents.json
new file mode 100644
index 00000000..6e09d35b
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-opencode.imageset/Contents.json
@@ -0,0 +1,5 @@
+{
+ "images" : [ { "filename" : "opencode.svg", "idiom" : "universal" } ],
+ "info" : { "author" : "xcode", "version" : 1 },
+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-opencode.imageset/opencode.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-opencode.imageset/opencode.svg
new file mode 100644
index 00000000..a38d4cf5
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-opencode.imageset/opencode.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M13 14H3V2H13V14ZM10.5 4.4H5.5V11.6H10.5V4.4Z" fill="currentColor"/>
+</svg>
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
index 9274908d..eefe1bdc 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
@@ -394,6 +394,15 @@ extension BotStore {
try await ready().listDirs(path)
}
+ /// Whether this computer lists one agent's limits.
+ public func setUsageShown(_ id: String, shown: Bool) async {
+ do {
+ setUsage(try await ready().setUsageShown(id, shown: shown))
+ } 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/Tests/CodyncKitTests/UsageServiceTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/UsageServiceTests.swift
new file mode 100644
index 00000000..d4532d86
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/UsageServiceTests.swift
@@ -0,0 +1,37 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+@Suite struct UsageServiceTests {
+ @Test func theChooserListDecodes() throws {
+ let json = #"{"providers":[],"services":[{"id":"cursor","name":"Cursor","shown":false}]}"#
+ let usage = try JSONDecoder().decode(Usage.self, from: Data(json.utf8))
+ #expect(usage.services == [UsageService(id: "cursor", name: "Cursor", shown: false)])
+ #expect(usage.services?.first?.provider.windows == [])
+ }
+
+ @Test func aHostOlderThanTheChooserSendsNoList() throws {
+ let usage = try JSONDecoder().decode(Usage.self, from: Data(#"{"providers":[]}"#.utf8))
+ #expect(usage.services == nil)
+ }
+
+ @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 {
+ let service = UsageService(id: "agent", name: "Agent", shown: true, registry: registry)
+ #expect(service.provider.logoAsset == "agent-\(registry)")
+ }
+ for id in ["kiro", "omp", "opencode"] {
+ #expect(UsageService(id: id, name: id, shown: true).provider.logoAsset == "agent-\(id)")
+ }
+ }
+
+ @Test func aHostThatNamesNoRegistryIdStillFindsClaudesLogo() {
+ #expect(UsageService(id: "claude", name: "Claude", shown: true).provider.logoAsset == "agent-claude-acp")
+ #expect(UsageService(id: "codex", name: "Codex", shown: true).provider.logoAsset == "agent-codex-acp")
+ }
+
+ @Test func anAgentWithNoLogoHasNoAsset() {
+ #expect(UsageService(id: "hermes", name: "Hermes Agent", shown: true).provider.logoAsset == nil)
+ }
+}
diff --git a/apps/ios/Views/UsageView.swift b/apps/ios/Views/UsageView.swift
index 6c3975f9..aa4ff980 100644
--- a/apps/ios/Views/UsageView.swift
+++ b/apps/ios/Views/UsageView.swift
@@ -5,6 +5,7 @@ import SwiftUI
/// Usage limits (opened from the State tab): one card per provider, the tightest limit as a big bar, every limit listed below.
struct UsageView: View {
@Environment(BotStore.self) private var model
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var collapsed: Set<String> = []
var body: some View {
@@ -20,34 +21,83 @@ struct UsageView: View {
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 installed on it."))
+ 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)
}
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.padding(.top, 60)
}
+ if let services = model.usage.services, !services.isEmpty {
+ UsageChooser(services: services)
+ }
}
.padding(16)
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: model.usage.providers.map(\.id))
}
.background(Palette.background)
.refreshable { await model.refreshUsage() }
}
}
-private struct ProviderCard: View {
+/// Which agents' limits this computer lists.
+private struct UsageChooser: View {
+ let services: [UsageService]
+ @Environment(BotStore.self) private var model
+
+ var 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)
+ }
+ }
+ }
+ }
+ .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) }
+ })
+ }
+}
+
+/// An agent's mascot or logo on its tinted tile.
+private struct ProviderTile: View {
let provider: UsageProvider
- @Binding var collapsed: Bool
@AppStorage(SharedStore.usageIconStyleKey, store: UserDefaults(suiteName: SharedStore.appGroup))
private var usageIconStyle = UsageIconStyle.character.rawValue
+
+ var 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))
+ }
+}
+
+private struct ProviderCard: View {
+ let provider: UsageProvider
+ @Binding var collapsed: Bool
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
- 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))
+ ProviderTile(provider: provider)
Text(provider.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)
Spacer()
IconButton(collapsed ? "Expand" : "Collapse", systemImage: "chevron.up") {
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index b5227976..06c6cc73 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -9,6 +9,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
## 2.40.0
### zh-Hant
- bot 現在可以讓 dev server 持續在電腦上執行,不會因為 bot 閒置或重新啟動而中斷。port 會顯示在聊天標題下方;點 bot 的名稱,就能看記錄、重新啟動或停止;手機連得到電腦時,也能直接開啟。
+- 用量頁面可以自己選要看哪些服務:預設只顯示 bot 正在用的,也可以打開或隱藏其他服務。另外支援顯示 Google Antigravity 和 GitHub Copilot 的額度。
### en-US
-- Bots can now keep a dev server running on your computer, even when the bot goes idle or restarts. Its port shows under the chat title; tap the bot's name to read its logs, restart or stop it, and to open it when your phone can reach it.
\ No newline at end of file
+- Bots can now keep a dev server running on your computer, even when the bot goes idle or restarts. Its port shows under the chat title; tap the bot's name to read its logs, restart or stop it, and to open it when your phone can reach it.
+- Choose which agents show in Usage: by default it lists the ones your bots run, and you can turn others on or hide them. Usage now also reads Google Antigravity's and GitHub Copilot's limits.
\ No newline at end of file
diff --git a/apps/maestro/usage-chooser.js b/apps/maestro/usage-chooser.js
new file mode 100644
index 00000000..09f034ea
--- /dev/null
+++ b/apps/maestro/usage-chooser.js
@@ -0,0 +1,20 @@
+// 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.
+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' },
+ body: JSON.stringify(body),
+ })
+ if (res.status !== 200) throw new Error(`${method}: ${res.status} ${res.body}`)
+ return json(res.body)
+}
+const services = api('usage', {}).services
+const service = services[services.length - (maestro.platform === 'ios' ? 1 : 2)]
+
+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
+}
diff --git a/apps/maestro/usage-chooser.yaml b/apps/maestro/usage-chooser.yaml
new file mode 100644
index 00000000..1a3e4282
--- /dev/null
+++ b/apps/maestro/usage-chooser.yaml
@@ -0,0 +1,47 @@
+# 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:
+# 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/maestro
+appId: com.pokai.Codync.ios.dev
+tags:
+ - usage
+---
+- runScript: usage-chooser.js
+- runFlow:
+ when:
+ platform: iOS
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.ios.dev
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - launchApp:
+ 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"
+- 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"
+- runScript:
+ file: usage-chooser.js
+ env:
+ EXPECT: "true"
+- scrollUntilVisible:
+ element: "On by default for the agents your bots run."
+ direction: DOWN
+- tapOn:
+ text: "${output.agent}.*"
+ below: "Show usage for"
+- runScript:
+ file: usage-chooser.js
+ env:
+ EXPECT: "false"
diff --git a/docs/README.md b/docs/README.md
index 72cf17da..b204e013 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -38,6 +38,7 @@ Source review, a passing build, local integration tests and production acceptanc
- [Cloud assistants](features/cloud-assistants.md) (ChatGPT, Claude and others message the bots through the Codync connector)
- [codync-network and cloud assistants: design](design/codync-network.md) (why iroh, connectors and relays, trust, addresses, quiet letters, the connector's choices, next steps)
- [Context and memory](features/context-and-memory.md)
+- [Usage limits](features/usage-limits.md) (which agents show, how each one is read, and which can't be)
- [Bot memory and compaction](design/bot-memory.md) (design; storage, gate and dreaming built, compaction to come)
- [Bot memory research](design/bot-memory-research.md) (files vs. database, embeddings, open-source systems, harness instructions)
- [Bot workspaces](features/bot-workspaces.md)
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 4ec9f3e5..83bf8e45 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -44,7 +44,7 @@ The tray menu is Electron's native `Menu` (`apps/desktop/src/main/tray.ts`), the
The 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.
+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)).
## Account menu and Settings (desktop)
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index 5078e479..b375aae0 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -56,7 +56,7 @@ The CLI must be signed in as the user running the host. Missing, rejected or una
## Cursor usage
-Settings > Usage lists Cursor alongside every other provider the host reports. When no desktop login is available in the Cursor app's `state.vscdb`, the host reads the CLI's `accessToken` from its saved `auth.json`: `$XDG_CONFIG_HOME/cursor/auth.json` (normally `~/.config/cursor/auth.json`) on Linux, `%APPDATA%/Cursor/auth.json` on Windows, and `~/.cursor/auth.json` on macOS when the CLI uses file storage. A macOS CLI login stored only in Keychain still needs the desktop-app login for usage reporting.
+Settings > Usage lists Cursor alongside every other provider the host reports, once a bot runs Cursor or the user turns it on ([which agents show](usage-limits.md#which-agents-show)). When no desktop login is available in the Cursor app's `state.vscdb`, the host reads the CLI's `accessToken` from its saved `auth.json`: `$XDG_CONFIG_HOME/cursor/auth.json` (normally `~/.config/cursor/auth.json`) on Linux, `%APPDATA%/Cursor/auth.json` on Windows, and `~/.cursor/auth.json` on macOS when the CLI uses file storage. A macOS CLI login stored only in Keychain still needs the desktop-app login for usage reporting.
Every five minutes, the host calls `https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus` with the saved bearer token. A unified plan (`isUnified: true`, including Super) reports one **Weekly** window from `usagePercent`, resetting at `nextResetTimestampUtc`. Missing usage is not converted to zero. The legacy `https://cursor.com/api/usage-summary` endpoint is read for non-unified plans, retaining their Monthly, Auto and API readings, and also when the dashboard request fails unless the dashboard last named a unified plan; then that poll keeps the previous Weekly window. Its monthly fields can report zero for a unified plan even when the unified allowance is partly used, so they never supply a unified reading. The host sends the existing `usage` event and never logs or changes the credentials. Existing client views render the weekly window without a client or protocol change.
diff --git a/docs/features/usage-limits.md b/docs/features/usage-limits.md
new file mode 100644
index 00000000..978a45a1
--- /dev/null
+++ b/docs/features/usage-limits.md
@@ -0,0 +1,68 @@
+# Usage limits
+
+What the apps show about plan limits, read on the host (`host/src/usage/`) from the agents on the computer. A reading never starts a model turn, and the host calls no provider API with an agent's login (Cursor's dashboard is the one exception, see [Cursor usage](marketplace.md#cursor-usage)).
+
+## 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.
+
+- **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`.
+- **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).
+
+On the wire, `usage` gains `services: [{id, name, shown, registry?}]` next to `providers`, which leaves out the hidden agents. A host older than the chooser sends no `services`, and the apps then show no switches. A shown agent with no reading says **No reading yet**: signed out, or nothing to report. Providers and services carry the agent's ACP `registry` id when it has one, and clients draw its logo by `registry ?? id`.
+
+`usage` with `refresh: true` answers within a minute with what has landed by then; a slower reader (a first download) carries on and lands through `usage` events. Every change goes through `Hub::update_usage`, under the lock, so a reading landing during a sync isn't written over.
+
+Adding an agent is one row in `READERS` (`usage/services.rs`). The reader's `id` is the harness id, so a bot's `backend` finds it (`backends::harness_of`, which also answers to the registry id).
+
+## Readers
+
+| Agent | How it reads | Checked against |
+|---|---|---|
+| Claude | `claude -p /usage`, the status line, ACP rate-limit events | a real login |
+| Codex | the CLI's `account/rateLimits/read` ([Codex usage](marketplace.md#codex-usage)) | a real login |
+| Google Antigravity | its ACP server's `/usage`, or the running app's language server | a real login (ACP) |
+| Cursor | the saved login, then its dashboard service ([Cursor usage](marketplace.md#cursor-usage)) | a real login |
+| GitHub Copilot | `account.getQuota` on `copilot --headless --stdio` | a real login |
+| Hermes Agent | `hermes usage --json` | source only: this provider had no account reading |
+| Grok Build | the `x.ai/billing` ACP extension | the 1.0.75 binary's strings; no login |
+| Auggie | `auggie account status --json` | the 0.36.0 source; no login |
+| Kilo | `kilo profile --json`, the dollar balance as a note | the 7.8.18 source; no login |
+| Amp, Junie, Kimi Code, Kiro CLI, Mistral Vibe, oh-my-pi, OpenCode | their own commands, logs or files (each reader's header) | as each says |
+
+The readers checked only against source fail closed: anything unexpected is no reading, never a wrong number. Check one against a real login when a computer has it.
+
+### An agent's own slash command
+
+`usage/acp_read.rs` runs an ACP slash command that the adapter answers itself. Antigravity's `/usage` is one: its ACP server handles it with no LLM and asks Google with its own login, so the host never touches that login.
+
+- **Only when advertised.** The command is sent only after the session lists it in `available_commands_update`. Sent to an agent that doesn't know it, it would reach the model and spend the plan it was meant to read.
+- **One session per agent,** resumed for every reading (`usage.session.<id>` in the host's kv): each new Antigravity session leaves a conversation database behind, about 400 KB.
+- **Never a browser.** A signed-out Antigravity starts its browser sign-in as soon as a session opens, and it would do so at every poll. The reading runs with `BROWSER=true`, which its Python honors, then gives up after 30 seconds. Windows has no such command, so there it needs a saved login file first.
+- **A bot's build is left alone.** Installing a new registry build removes the one before it, so while a bot here runs that agent and its current version isn't installed, readings wait for that bot's next start to bring it (`backends::update_pending`). Installs run one at a time and check again once they get their turn.
+- **A download isn't cut short.** No timeout wraps a reader's start, or a slow connection would start over at every poll. The handshake has its own.
+
+The report is Markdown meant for people, so an update can change it; `parse` is how that surfaces.
+
+### Failures
+
+`usage_read_failed` reports once per failing run, with the stage, for the readers that start the agent's server (Antigravity, Grok Build, Copilot) or read a CLI's JSON report (Hermes, Auggie, Kilo): a format change shows up as `parse`, which is the only way to learn of one in a reader never run against a login. Nothing printed, or a CLI's words for being signed out, isn't a failure. A document that says there's nothing to read is an empty reading, which removes the row, as Kilo's balance of 0 does: the CLI prints that when its own balance request fails, so it's neither a claim that the account is empty nor a reason to keep an old balance.
+
+### Copilot's log files
+
+Each start of Copilot's headless server leaves an empty file in `~/.copilot/logs`, even with `--log-level none`, so it's read every 30 minutes rather than every five, and 10 minutes after a failure, such as being signed out. Turned off and on within that time, it gets its last reading back without a new start.
+
+## Agents not read
+
+Only what's been looked at, as of 2026-11-06. None of these were run against a login.
+
+| Agent | Why not |
+|---|---|
+| Factory Droid, MiniMax Code, Gemini CLI | Plan limits exist, but only in the TUI. A PTY reader would type into it, where a command it doesn't know goes to the model. Never `gemini -p "/stats"`: that's a real turn. |
+| Qoder | `get_usage_info` is in a newer SDK than the registry's CLI, and starting it outside the SDK's daemon is unverified. |
+| Cline, Devin | Plan numbers only through their HTTP APIs. |
+| CodeBuddy Code, WorkBuddy, Cortex Code | Nothing found outside their websites. Their bundles weren't searched in full. |
+| Qwen Code, Poolside, Pi, DeepSeek Harness, goose | Session tokens only, or bring-your-own-key with no plan. |
diff --git a/docs/reference/acp-adapter-workarounds.md b/docs/reference/acp-adapter-workarounds.md
index a40cf261..5b358120 100644
--- a/docs/reference/acp-adapter-workarounds.md
+++ b/docs/reference/acp-adapter-workarounds.md
@@ -83,6 +83,9 @@ qwen-code 0.26.5.
| Hermes | Starts MCP servers with a filtered environment | `host/src/mcp.rs`: `CODYNC_HOME` in each server's `env` | Keep: within the spec |
| Kilo | `_meta.terminal-auth` names `opencode` | `host/src/agent/auth.rs`: that method is left out | Kilo names its own CLI |
| Qwen Code | Terminal sign-in in `_meta: {type: "terminal", args}` instead of the spec's fields | `host/src/agent/auth.rs` reads it | The spec's fields |
+| Antigravity | Signed out, it starts its browser sign-in as soon as a session opens, so a usage reading would open a browser at every poll | `host/src/usage/acp_read.rs`: started with `BROWSER=true`, which its Python honors. Windows has no such command, so `host/src/usage/antigravity.rs` needs a saved login file first. No issue opened yet: this only surfaced reading usage | `session/new` doesn't start a sign-in |
+| Antigravity | Each new session leaves a conversation database behind, about 400 KB | `host/src/usage/acp_read.rs`: readings share one session, resumed each time (`usage.session.<id>` in the kv). No issue opened yet: keeping sessions may be intended | A session with no turn leaves nothing behind |
+| Grok Build | Not every build answers ACP's extension name `_x.ai/billing`, and the 1.0.75 binary names `x.ai/billing` | `host/src/usage/grok.rs`: asks `x.ai/billing`, then `_x.ai/billing`. No issue opened: seen only in the binary's strings, with no login to run it | The oldest build we support answers one name |
| oh-my-pi | Tool call titles are prose ("Creating probe bot"), not the tool's name, so Codync's own calls aren't recognized as its bookkeeping | **Not patched** (`host/src/agent/bot/tool_entry.rs` matches names only) | Titles or `_meta` carry the tool's name |
## Gaps in ACP itself
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index 49ba0af8..5c90fc2d 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -77,6 +77,7 @@ host answers and sends it once the host is up.
| `turn_stopped` | host | `stop` | — |
| `turn_finished` | host | An agent's turn ends: once per agent it ran on, so a turn that fell back once and then answered sends a `failed` and a `done` | `agent`, `outcome` (`done`/`stopped`/`failed`/`needs_setup`/`incomplete`; `needs_setup` is a failure whose `error` is `sign_in` or `not_installed`: the user has a step to take, nothing broke), `stop_reason`, `source` (`user`/`routine`/`group`/`bot`/`host`: the lead opening a call), `seconds`; when failed or needs_setup, `error` (`not_installed`/`timeout`/`exited`/`no_model`/`sign_in`/`agent_error`/`io`/`other`) and, for `agent_error`, `rpc_code` and `agent_reason` (the adapter's own category, else one the host reads from the message, which is never sent: `session_ended`/`rate_limit`/`quota`/`overloaded`/`context`/`model`/`network`/`provider`/`unknown`) |
| `agent_fell_back` | host | A turn moves on to the bot's next agent ([agent fallbacks](../features/agent-fallback.md)) | `agent` (the one that couldn't answer), `reason` (`usageLimit`/`outOfCredits`/`rateLimited`/`overloaded`/`signedOut`/`notStarting`/`modelMissing`) |
+| `usage_read_failed` | host | Reading an agent's usage stopped, once per failing run, for the readers that start the agent's server or read a CLI's JSON report ([usage limits](../features/usage-limits.md#failures)) | `agent`, `stage` (`start`/`session`/`no_command`/`prompt`/`timeout`/`parse`: the agent's report changed format) |
| `session_reset` | host | `newSession` | — |
| `permission_answered` | host | `respondPermission` | `choice` (`allow_once`/`allow_always`/`reject_once`/`reject_always`/`other`) |
| `reaction_added` | host | `react` | — |
@@ -108,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`; 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); 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/agent/auth.rs b/host/src/agent/auth.rs
index d9b744ee..beed899f 100644
--- a/host/src/agent/auth.rs
+++ b/host/src/agent/auth.rs
@@ -33,6 +33,7 @@ mod agent;
mod models;
pub use agent::authenticate;
use agent::start;
+pub(crate) use agent::{Started, start_with};
pub use models::{InFlight, models, shared_models};
pub(crate) use models::{model_config, model_ids};
@@ -83,7 +84,7 @@ pub struct Status {
static CHECKED: Mutex<BTreeMap<String, Status>> = Mutex::new(BTreeMap::new());
/// Where probe sessions live, away from the user's projects.
-fn probe_dir() -> PathBuf {
+pub(crate) fn probe_dir() -> PathBuf {
crate::service::data_dir().join("probe")
}
@@ -133,7 +134,7 @@ async fn probe(store: &Store, backend: &str) -> Result<Status> {
if backends::agent_checks_off() {
return Ok(Status::default());
}
- let (acp, mut inbox, init, cmd) = start(store, backend).await?;
+ let Started { acp, mut inbox, init, cmd } = start(store, backend).await?;
let methods = methods(backend, &init, &cmd);
if let ControlFlow::Break(signed_in) =
login_without_session(&init, &mut inbox, backend, &env(store, backend)?).await
diff --git a/host/src/agent/auth/agent.rs b/host/src/agent/auth/agent.rs
index c06d2c6a..eaf7084e 100644
--- a/host/src/agent/auth/agent.rs
+++ b/host/src/agent/auth/agent.rs
@@ -12,17 +12,30 @@ use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
-/// Starts `backend` and completes `initialize`, trying each way to launch it.
-/// The agent's inbox must stay open: the reader stops when nobody listens.
-pub(super) type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);
+/// An agent past `initialize`.
+pub(crate) struct Started {
+ pub(crate) acp: Arc<Acp>,
+ /// Must stay open: the reader stops when nobody listens, and the agent then never answers.
+ pub(crate) inbox: mpsc::UnboundedReceiver<Incoming>,
+ /// Its answer to `initialize`.
+ pub(crate) init: Value,
+ pub(crate) cmd: Cmd,
+}
+/// Starts `backend` and completes `initialize`, trying each way to launch it.
pub(super) async fn start(store: &Store, backend: &str) -> Result<Started> {
+ start_with(store, backend, &[]).await
+}
+
+/// [`start`], with `extra` added to the agent's environment.
+pub(crate) async fn start_with(store: &Store, backend: &str, extra: &[(&str, &str)]) -> Result<Started> {
let mut candidates = backends::launch_candidates(backend)?;
// The installed CLI alone when there is one: resolving the registry build can mean a long download.
if matches!(candidates.first(), Some(Candidate::Ready(_))) {
candidates.truncate(1);
}
- let env = launch_env(store, backend)?;
+ let mut env = launch_env(store, backend)?;
+ env.extend(extra.iter().map(|(name, value)| ((*name).to_owned(), (*value).to_owned())));
let dir = probe_dir();
tokio::fs::create_dir_all(&dir).await?;
let mut last = None;
@@ -60,7 +73,7 @@ pub(super) async fn start(store: &Store, backend: &str) -> Result<Started> {
}),
);
match tokio::time::timeout(budget, init).await {
- Ok(Ok(init)) => return Ok((acp, rx, init, cmd)),
+ Ok(Ok(init)) => return Ok(Started { acp, inbox: rx, init, cmd }),
Ok(Err(e)) => {
let why = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|inc| match inc {
Incoming::Closed { stderr_tail } => stderr_reason(&stderr_tail),
@@ -98,7 +111,7 @@ pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result<
.await
.context("couldn't prepare WorkBuddy sign-in")?;
}
- let (acp, mut inbox, _, _) = start(store, backend).await?;
+ let Started { acp, mut inbox, .. } = start(store, backend).await?;
let res = tokio::time::timeout(Duration::from_mins(10), sign_in(&acp, &mut inbox, method)).await;
acp.kill().await;
match res {
diff --git a/host/src/agent/auth/models.rs b/host/src/agent/auth/models.rs
index c0d13146..b8885ef4 100644
--- a/host/src/agent/auth/models.rs
+++ b/host/src/agent/auth/models.rs
@@ -1,6 +1,6 @@
//! The models an agent offers, read from a session it opens for that alone.
-use super::{probe_dir, start, text};
+use super::{Started, probe_dir, start, text};
use crate::LockExt;
use crate::agent::acp::Incoming;
use crate::hub::Hub;
@@ -42,7 +42,7 @@ pub async fn shared_models(hub: &Hub, backend: &str) -> Result<Value> {
/// Discover the agent's advertised models in an isolated, prompt-free session.
/// This uses the same credentials as actual bot sessions and never reads project files.
pub async fn models(store: &Store, backend: &str) -> Result<Value> {
- let (acp, mut inbox, _, _) = start(store, backend).await?;
+ let Started { acp, mut inbox, .. } = start(store, backend).await?;
let result = tokio::time::timeout(Duration::from_mins(1), async {
let request = acp.request("session/new", json!({"cwd": probe_dir(), "mcpServers": []}));
tokio::pin!(request);
diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rs
index ed21fb21..afe32bd1 100644
--- a/host/src/agent/backends.rs
+++ b/host/src/agent/backends.rs
@@ -80,6 +80,16 @@ pub fn harness(id: &str) -> Option<&'static Harness> {
HARNESSES.iter().find(|h| h.id == id)
}
+/// The harness a bot's `backend` is: by its own id or its registry entry's.
+pub fn harness_of(backend: &str) -> Option<&'static Harness> {
+ HARNESSES.iter().find(|h| h.answers_to(backend))
+}
+
+/// `id`'s CLI is on this computer.
+pub fn installed(id: &str) -> bool {
+ harness(id).is_some_and(|h| installed_cli(h).is_some())
+}
+
// MARK: listing + launching
/// Every harness the phone can pick, installed ones first.
@@ -179,6 +189,13 @@ pub fn launch_candidates(id: &str) -> anyhow::Result<Vec<registry::Candidate>> {
Ok(out)
}
+/// Starting `id` would first install a new registry build, which removes the one before it.
+pub fn update_pending(id: &str) -> bool {
+ launch_candidates(id).is_ok_and(|candidates| {
+ matches!(candidates.first(), Some(registry::Candidate::Build(agent)) if registry::update_pending(agent))
+ })
+}
+
/// The registry build that *is* the harness's CLI (same npm package), so it can
/// sign in without the CLI installed. Adapters (claude-acp…) don't count.
fn registry_cli(h: &Harness) -> Option<Value> {
diff --git a/host/src/agent/backends/tests.rs b/host/src/agent/backends/tests.rs
index f819e719..548120ac 100644
--- a/host/src/agent/backends/tests.rs
+++ b/host/src/agent/backends/tests.rs
@@ -52,6 +52,37 @@ fn an_installed_cli_comes_before_the_registry_build() {
}
}
+/// A usage reading holds off for a new build only when starting the agent would really install it.
+#[test]
+fn an_update_is_pending_only_for_a_download_nothing_installed_yet() {
+ let dir = TempDir::new();
+ let _path = TestSearchPath::set(dir.0.clone());
+ let target = json!({"archive": "https://example.com/a.zip", "cmd": "./a"});
+ let binaries: serde_json::Map<String, Value> =
+ ["darwin-aarch64", "darwin-x86_64", "linux-aarch64", "linux-x86_64", "windows-aarch64", "windows-x86_64"]
+ .into_iter()
+ .map(|platform| (platform.to_owned(), target.clone()))
+ .collect();
+ let version = uuid::Uuid::new_v4().to_string();
+ let build = |id: &str| json!({"id": id, "version": version, "distribution": {"binary": binaries}});
+ let npx = json!({"id": "kilo", "distribution": {"npx": {"package": "kilo"}}});
+ registry::set_cache(Some(json!({"agents": [build("antigravity-acp"), build("grok-build"), npx]})));
+ let antigravity = update_pending("antigravity");
+ let installed = crate::service::data_dir().join("agents/antigravity-acp").join(&version);
+ std::fs::create_dir_all(&installed).expect("create the build's folder");
+ std::fs::write(installed.join(".installed"), "").expect("mark it installed");
+ let after_install = update_pending("antigravity");
+ write_cli(&dir.0, "grok");
+ let with_cli = update_pending("grok");
+ let not_a_download = update_pending("kilo");
+ registry::set_cache(None);
+ let _ = std::fs::remove_dir_all(&installed);
+ assert!(antigravity, "its current build isn't here");
+ assert!(!after_install);
+ assert!(!with_cli, "the installed CLI starts: no build gets installed");
+ assert!(!not_a_download, "npx keeps its older packages");
+}
+
#[test]
fn a_harness_the_registry_also_lists_shows_once() {
let dir = TempDir::new();
diff --git a/host/src/agent/registry.rs b/host/src/agent/registry.rs
index 71640c49..66d1c003 100644
--- a/host/src/agent/registry.rs
+++ b/host/src/agent/registry.rs
@@ -302,14 +302,34 @@ pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
})
}
-/// Downloads + extracts a binary distribution into `~/.codync/agents/<id>/<version>`.
-async fn install_binary(agent: &Value, target: &Value, cmd: &Path, progress: &impl Fn(&str)) -> Result<PathBuf> {
+/// `~/.codync/agents/<id>/<version>`, where a binary distribution is unpacked.
+fn binary_dir(agent: &Value) -> Result<PathBuf> {
let id = agent["id"].as_str().and_then(safe_component).ok_or_else(|| anyhow!("registry entry has a bad id"))?;
let version = agent["version"].as_str().and_then(safe_component).unwrap_or("latest");
- let dir = crate::service::data_dir().join("agents").join(id).join(version);
- if tokio::fs::try_exists(dir.join(".installed")).await.unwrap_or(false) {
+ Ok(crate::service::data_dir().join("agents").join(id).join(version))
+}
+
+/// Starting this agent would first install its current build, and with it remove the one before.
+pub fn update_pending(agent: &Value) -> bool {
+ launch_kind(agent) == Some(Launch::Download) && binary_dir(agent).is_ok_and(|dir| !dir.join(".installed").exists())
+}
+
+/// Downloads + extracts a binary distribution into [`binary_dir`].
+async fn install_binary(agent: &Value, target: &Value, cmd: &Path, progress: &impl Fn(&str)) -> Result<PathBuf> {
+ // A sign-in check and a usage reading can start the same agent at once: installing side by side,
+ // each would delete the other's files.
+ // ponytail: one lock for every agent's install, as npx has. Per agent if one big download holding up another hurts.
+ static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+ let dir = binary_dir(agent)?;
+ let installed = async || tokio::fs::try_exists(dir.join(".installed")).await.unwrap_or(false);
+ if installed().await {
+ return Ok(dir);
+ }
+ let _one_at_a_time = INSTALLING.lock().await;
+ if installed().await {
return Ok(dir);
}
+ let id = agent["id"].as_str().unwrap_or("agent");
let url = target["archive"].as_str().ok_or_else(|| anyhow!("registry entry has no archive"))?;
if !url.starts_with("https://") {
bail!("refusing a non-HTTPS download for {id}");
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 7a1ab3d9..d246cad9 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -71,6 +71,7 @@ pub enum Event {
TurnFinished,
/// A turn moved on to the bot's next agent (`agent::fallback`).
AgentFellBack,
+ UsageReadFailed,
SessionReset,
PermissionAnswered,
ReactionAdded,
@@ -154,6 +155,7 @@ impl Event {
Self::TurnStopped => "turn_stopped",
Self::TurnFinished => "turn_finished",
Self::AgentFellBack => "agent_fell_back",
+ Self::UsageReadFailed => "usage_read_failed",
Self::SessionReset => "session_reset",
Self::PermissionAnswered => "permission_answered",
Self::ReactionAdded => "reaction_added",
diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rs
index da62bfed..4d33ce60 100644
--- a/host/src/analytics/observe.rs
+++ b/host/src/analytics/observe.rs
@@ -81,6 +81,13 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Eve
}
Event::BotCreated
}
+ "setUsageShown" => {
+ // A successful call names one of the host's own agents.
+ p.insert("setting".into(), "usage_shown".into());
+ p.insert("agent".into(), b["id"].clone());
+ p.insert("on".into(), (b["shown"] == true).into());
+ Event::SettingChanged
+ }
"updateBot" => Event::BotUpdated,
"reorderBots" => Event::BotsReordered,
"renameSection" => {
diff --git a/host/src/api/events.rs b/host/src/api/events.rs
index f984ad8d..92a6157a 100644
--- a/host/src/api/events.rs
+++ b/host/src/api/events.rs
@@ -77,7 +77,7 @@ pub fn events_stream(
"hostId": hub.host_id,
"computerId": hub.identity.computer_id(),
"rev": hub.store.current_rev(),
- "usage": hub.usage.locked().clone(),
+ "usage": hub.usage.locked().visible(),
"screen": hub.screen.state(),
// Live state like the two above: a `network` event sent before this stream began is in it.
"network": crate::network::status(hub),
diff --git a/host/src/api/host.rs b/host/src/api/host.rs
index 7d14d2c8..702cea12 100644
--- a/host/src/api/host.rs
+++ b/host/src/api/host.rs
@@ -99,7 +99,19 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
if b["refresh"].as_bool().unwrap_or(false) {
usage::refresh(hub).await;
}
- serde_json::to_value(&*hub.usage.locked())?
+ serde_json::to_value(hub.usage.locked().visible())?
+ }
+ // Whether the Usage screens list this agent's limits.
+ "setUsageShown" => {
+ let id = str_arg(&b, "id")?.to_owned();
+ let shown = b["shown"].as_bool().context("shown is required")?;
+ let hub = hub.clone();
+ let usage = tokio::task::spawn_blocking(move || {
+ usage::set_shown(&hub, &id, shown)?;
+ anyhow::Ok(hub.usage.locked().visible())
+ })
+ .await??;
+ serde_json::to_value(usage)?
}
"listDirs" => {
let path = b["path"].as_str().map(std::path::PathBuf::from);
diff --git a/host/src/chat/lead/tests.rs b/host/src/chat/lead/tests.rs
index 3cc59cdc..f90f7d12 100644
--- a/host/src/chat/lead/tests.rs
+++ b/host/src/chat/lead/tests.rs
@@ -126,6 +126,7 @@ async fn check_ins_wait_while_the_plan_is_nearly_used_up() {
providers: vec![Provider {
id: "fixture",
name: "Fixture",
+ registry: None,
windows: vec![Window {
id: "week".into(),
label: "Week".into(),
@@ -137,10 +138,11 @@ async fn check_ins_wait_while_the_plan_is_nearly_used_up() {
source: "agent",
updated_at: 0,
}],
+ services: Vec::new(),
};
- f.hub.set_usage(used(40.0));
+ f.hub.update_usage(|usage| *usage = used(40.0));
assert!(!check_in_waits(&f.hub, &routine, &lead, &scheduled));
- f.hub.set_usage(used(90.0));
+ f.hub.update_usage(|usage| *usage = used(90.0));
assert!(check_in_waits(&f.hub, &routine, &lead, &scheduled));
assert!(!check_in_waits(&f.hub, &routine, &lead, &test), "a test run the user asked for still runs");
assert!(!check_in_waits(&f.hub, "another", &lead, &scheduled), "the user's own routines still run");
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 82ab946c..1a8bcafc 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -1,5 +1,4 @@
//! Shared host state: store, event fan-out, bot actors, push, usage.
-mod bots;
use crate::LockExt;
use crate::agent::bot::{self, BotHandle, Cmd};
@@ -19,6 +18,7 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{broadcast, watch};
+mod bots;
mod groups;
mod lead;
mod order;
@@ -99,6 +99,8 @@ pub struct Hub {
runtime: Mutex<HashMap<String, Runtime>>,
pub phone_clients: AtomicUsize,
pub usage: Mutex<Usage>,
+ /// An agent became wanted: its usage is read now, not at the next poll.
+ pub usage_wake: tokio::sync::Notify,
keep_awake: Mutex<service::KeepAwake>,
/// Generation of the authorized-device table and pairing offers: bumped on every
/// change so open channels re-check their device (and the ACL is republished).
@@ -149,6 +151,7 @@ impl Hub {
runtime: Mutex::default(),
phone_clients: AtomicUsize::new(0),
usage: Mutex::default(),
+ usage_wake: tokio::sync::Notify::new(),
keep_awake: Mutex::default(),
auth: watch::Sender::new(0),
pairing: Mutex::default(),
@@ -378,9 +381,15 @@ impl Hub {
Ok(e)
}
- pub fn set_usage(&self, usage: Usage) {
- let _ = self.events.send(json!({"type": "usage", "usage": usage}));
- *self.usage.locked() = usage;
+ /// Changes the usage under its lock, so a reading that lands meanwhile isn't written over, and
+ /// tells the apps what they may see of it (`hub.usage` also holds the agents the user hides).
+ pub fn update_usage(&self, change: impl FnOnce(&mut Usage)) {
+ let mut usage = self.usage.locked();
+ let before = usage.clone();
+ change(&mut usage);
+ if *usage != before {
+ let _ = self.events.send(json!({"type": "usage", "usage": usage.visible()}));
+ }
}
// MARK: devices
diff --git a/host/src/hub/bots.rs b/host/src/hub/bots.rs
index 0972ef57..0872be18 100644
--- a/host/src/hub/bots.rs
+++ b/host/src/hub/bots.rs
@@ -39,6 +39,7 @@ impl Hub {
crate::market::agent_sign_in::ask_before_first_message(self, &cfg);
}
self.emit_bot(&cfg.id);
+ crate::usage::bots_changed(self);
Ok(self.bot_value(&cfg.id).unwrap_or(Value::Null))
}
@@ -72,6 +73,7 @@ impl Hub {
self.send_cmd(&id, Cmd::Reconfigure(Box::new(cfg)))?;
}
self.emit_bot(&id);
+ crate::usage::bots_changed(self);
Ok(self.bot_value(&id).unwrap_or(Value::Null))
}
@@ -103,6 +105,7 @@ impl Hub {
}
}
});
+ crate::usage::bots_changed(self);
self.leave_groups(id)
}
}
diff --git a/host/src/tui/app/analytics.rs b/host/src/tui/app/analytics.rs
index f7da2b5c..57d2e845 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(_) => 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/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 1185eecb..b56aa9ca 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -4,6 +4,7 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::json;
use super::super::manage::{AnalyticsSheet, Reply};
+use super::super::view::usage_services;
use super::{
ACTIONS, Action, After, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderMode, FolderPicker, Goto, GotoItem,
Overlay, PairCode, contains, fuzzy,
@@ -160,9 +161,30 @@ impl App {
KeyCode::Up | KeyCode::Char('k') => Some(Overlay::Usage(scroll.saturating_sub(1))),
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));
+ Some(Overlay::Usage(scroll))
+ }
_ => Some(Overlay::Usage(scroll)),
}
}
+ Overlay::UsageChooser(row) => {
+ let services = usage_services(self);
+ let last = services.len().saturating_sub(1);
+ 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::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.min(last))),
+ }
+ }
o @ Overlay::Pair(_) => {
if matches!(k.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | 'U' | 'P')) {
None
@@ -348,9 +370,72 @@ impl App {
#[cfg(test)]
mod tests {
- use super::super::{Bot, Editor, Goto, GotoItem, test_app};
+ use super::super::super::net::Client;
+ use super::super::{App, Bot, Editor, Goto, GotoItem, Overlay, test_app};
+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::json;
+ /// A host that hands each request it gets to `requests`, answering them all alike.
+ async fn host() -> (String, tokio::sync::mpsc::UnboundedReceiver<String>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("a free port");
+ let base = format!("http://{}", listener.local_addr().expect("its address"));
+ let (seen, requests) = tokio::sync::mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ while let Ok((mut socket, _)) = listener.accept().await {
+ let mut request = Vec::new();
+ while !request.ends_with(b"}") {
+ let mut chunk = [0; 4096];
+ let read = socket.read(&mut chunk).await.expect("a request");
+ if read == 0 {
+ break;
+ }
+ request.extend_from_slice(&chunk[..read]);
+ }
+ let _ = seen.send(String::from_utf8_lossy(&request).into_owned());
+ let answer = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}";
+ let _ = socket.write_all(answer).await;
+ }
+ });
+ (base, requests)
+ }
+
+ #[tokio::test]
+ async fn the_usage_sheet_opens_the_chooser_and_a_toggle_reaches_the_host() {
+ 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());
+ app.usage = json!({"providers": [], "services": [
+ {"id": "claude", "name": "Claude", "shown": true},
+ {"id": "cursor", "name": "Cursor", "shown": false},
+ ]});
+ 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))));
+ app.overlay_key(key(KeyCode::Down));
+ assert!(matches!(app.overlays.last(), Some(Overlay::UsageChooser(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");
+ 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");
+ app.overlay_key(key(KeyCode::Esc));
+ assert!(matches!(app.overlays.last(), Some(Overlay::Usage(0))), "back to the limits");
+ }
+
+ #[tokio::test]
+ async fn a_host_with_no_list_offers_no_chooser() {
+ let mut app = test_app();
+ app.usage = json!({"providers": []});
+ app.overlays.push(Overlay::Usage(0));
+ app.overlay_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE));
+ assert!(matches!(app.overlays.last(), Some(Overlay::Usage(0))));
+ }
+
#[tokio::test]
async fn the_palette_offers_to_unhide_hidden_bots() {
let mut app = test_app();
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index fb4a07d8..610526c6 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -327,6 +327,8 @@ pub enum Overlay {
Group(GroupForm),
/// How far its list is scrolled.
Usage(usize),
+ /// Which agents' limits show: the row under the cursor.
+ UsageChooser(usize),
Pair(PairCode),
Memory(MemorySheet),
/// A read-only conversation between two bots.
diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rs
index 5b23044d..7e14b5e5 100644
--- a/host/src/tui/view/mod.rs
+++ b/host/src/tui/view/mod.rs
@@ -41,7 +41,7 @@ pub(super) use overlay::{field_line, input_line};
pub(super) use style::theme;
pub(super) use time::when;
pub(super) use transcript::{file_size, unfoldable};
-pub(super) use usage::{usage_scroll_max, when_future};
+pub(super) use usage::{usage_scroll_max, usage_services, when_future};
use ratatui::Frame;
use ratatui::buffer::Buffer;
diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rs
index 82ed893f..fad3c12d 100644
--- a/host/src/tui/view/overlay.rs
+++ b/host/src/tui/view/overlay.rs
@@ -15,7 +15,7 @@ use super::new_bot::new_bot_view;
use super::pair::pair;
use super::set_cursor;
use super::style::{rgb, theme};
-use super::usage::usage;
+use super::usage::{usage, usage_chooser};
pub(super) fn overlays(f: &mut Frame<'_>, app: &mut App) {
if app.overlays.is_empty() {
@@ -139,6 +139,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay
Overlay::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::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.rs
index 4f744146..b57a6c8d 100644
--- a/host/src/tui/view/usage.rs
+++ b/host/src/tui/view/usage.rs
@@ -37,6 +37,11 @@ fn sheet(area: Rect, rows: usize) -> (Rect, usize) {
(r, usize::from(r.height.saturating_sub(4)))
}
+/// The agents this computer's chooser lists. A host older than the chooser sends none.
+pub(in crate::tui) fn usage_services(app: &App) -> &[Value] {
+ app.usage["services"].as_array().map_or(&[], Vec::as_slice)
+}
+
/// How far the list scrolls on a screen `height` rows tall: more providers than fit scroll with ↑↓.
pub(in crate::tui) fn usage_scroll_max(app: &App, height: u16) -> usize {
let providers = app.usage["providers"].as_array().cloned().unwrap_or_default();
@@ -65,12 +70,43 @@ pub(super) fn usage(buf: &mut Buffer, area: Rect, app: &App, scroll: usize) {
Line::Gap => {}
}
}
- let footer = if lines.len() > fits {
- "Read from the agents on this computer. ↑↓ scroll · esc close"
- } else {
- "Read from the agents on this computer. esc close"
- };
- put(buf, inner.x, inner.bottom() - 1, inner.width, footer, t.dim.patch(t.panel));
+ let choose = if usage_services(app).is_empty() { "" } else { "s choose · " };
+ let scrolls = if lines.len() > fits { "↑↓ scroll · " } else { "" };
+ let footer = format!("Read from the agents on this computer. {choose}{scrolls}esc close");
+ put(buf, inner.x, inner.bottom() - 1, inner.width, &footer, t.dim.patch(t.panel));
+}
+
+/// Which agents' limits show on this computer.
+pub(super) fn usage_chooser(buf: &mut Buffer, area: Rect, app: &App, row: usize) {
+ let t = theme();
+ let services = usage_services(app);
+ let providers: &[Value] = app.usage["providers"].as_array().map_or(&[], Vec::as_slice);
+ let r = centered(area, 60, u(services.len() + 5).max(8));
+ let inner = frame_box(buf, r, t.text, t.panel, Some((tr("Show usage for").as_ref(), t.text)));
+ let fits = usize::from(inner.height.saturating_sub(3));
+ let skip = row.saturating_sub(fits.saturating_sub(1));
+ for (i, (y, service)) in (inner.y + 1..).zip(services.iter().skip(skip).take(fits)).enumerate() {
+ let shown = service["shown"].as_bool() == Some(true);
+ let cursor = i + skip == row;
+ let style = if cursor { t.bold } else { t.text }.patch(t.panel);
+ let unread = shown && !providers.iter().any(|p| p["id"] == service["id"]);
+ let name = service["name"].as_str().unwrap_or_default();
+ let line = format!("{} [{}] {name}", if cursor { "›" } else { " " }, if shown { "x" } else { " " });
+ let end = put(buf, inner.x, y, inner.width, &line, style);
+ if unread {
+ put(
+ buf,
+ end + 2,
+ y,
+ inner.right().saturating_sub(end + 2),
+ tr("No reading yet").as_ref(),
+ t.dim.patch(t.panel),
+ );
+ }
+ }
+ 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));
}
/// One limit: its label, a bar with the percent and when it resets; or its note.
@@ -136,6 +172,27 @@ mod tests {
use super::usage_scroll_max;
use serde_json::json;
+ #[tokio::test]
+ async fn the_chooser_marks_what_shows_and_what_has_no_reading() {
+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(Client::new("http://127.0.0.1:1", None), tx, String::new());
+ app.usage = json!({
+ "providers": [{"id": "claude", "name": "Claude", "windows": []}],
+ "services": [
+ {"id": "claude", "name": "Claude", "shown": true},
+ {"id": "antigravity", "name": "Google Antigravity", "shown": true},
+ {"id": "cursor", "name": "Cursor", "shown": false},
+ ],
+ });
+ let area = ratatui::layout::Rect::new(0, 0, 80, 24);
+ let mut buf = ratatui::buffer::Buffer::empty(area);
+ super::usage_chooser(&mut buf, area, &app, 2);
+ let text: String = buf.content().iter().map(ratatui::buffer::Cell::symbol).collect();
+ assert!(text.contains(" [x] Claude"), "{text}");
+ assert!(text.contains("[x] Google Antigravity No reading yet"), "{text}");
+ assert!(text.contains("› [ ] Cursor"), "{text}");
+ }
+
#[tokio::test]
async fn five_providers_scroll_on_a_small_terminal() {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
diff --git a/host/src/usage/acp_read.rs b/host/src/usage/acp_read.rs
new file mode 100644
index 00000000..ba411581
--- /dev/null
+++ b/host/src/usage/acp_read.rs
@@ -0,0 +1,266 @@
+//! Readings through an agent's own ACP server, which asks its provider with the agent's login.
+//!
+//! [`command_reading`] runs a slash command that the adapter answers itself, with no model turn. The
+//! command runs only once the session has advertised it: sent to an agent that doesn't know it, it
+//! would reach the model and spend the plan it was meant to read. One session per agent is resumed
+//! for every reading, as each new session leaves a conversation behind on the computer.
+
+use crate::agent::acp::{Acp, Incoming};
+use crate::agent::auth::{self, Started};
+use crate::agent::backends;
+use crate::hub::Hub;
+use crate::store::Store;
+use anyhow::{Context, Result, bail};
+use serde_json::{Value, json};
+use std::future::Future;
+use std::time::Duration;
+use tokio::sync::mpsc;
+
+use super::reading::{self, UsageReadStage};
+use super::{Window, services};
+
+/// A signed-out agent waits here for a sign-in that never comes.
+const READ_TIMEOUT: Duration = Duration::from_secs(30);
+/// How long a session gets to advertise its commands, which follow its answer.
+const COMMANDS_TIMEOUT: Duration = Duration::from_secs(5);
+/// A check in the background must never open a browser to sign in. Python and most CLIs honor
+/// this; Windows has no command that ignores the address, so its reader checks the login first.
+#[cfg(unix)]
+const NO_BROWSER: &[(&str, &str)] = &[("BROWSER", "true")];
+#[cfg(windows)]
+const NO_BROWSER: &[(&str, &str)] = &[];
+
+/// What `reading` finds through `backend`'s server, one at a time. Nothing while a bot here runs on
+/// an older build: installing the new one would remove it, and that bot's next start brings it.
+pub(super) async fn guarded(
+ hub: &Hub,
+ backend: &str,
+ reading: impl Future<Output = Result<Vec<Window>, UsageReadStage>>,
+) -> Option<Vec<Window>> {
+ if services::runs(&hub.store, backend) && backends::update_pending(backend) {
+ return None;
+ }
+ reading::guarded(hub, backend, reading).await
+}
+
+/// `backend`'s server, past `initialize`. A first start can download its build, which is why no
+/// timeout wraps this: one cut short would start over at every poll. The handshake has its own.
+pub(super) async fn start(store: &Store, backend: &str) -> Result<Started, UsageReadStage> {
+ auth::start_with(store, backend, NO_BROWSER).await.map_err(|error| {
+ tracing::debug!(backend, error = format!("{error:#}"), "couldn't start the agent for its usage");
+ UsageReadStage::Start
+ })
+}
+
+/// What `backend` answers to its `command`, through `parse`. `None`: no reading this time.
+pub(super) async fn command_reading(
+ hub: &Hub,
+ backend: &str,
+ command: &str,
+ parse: fn(&str) -> Option<Vec<Window>>,
+) -> Option<Vec<Window>> {
+ guarded(hub, backend, async {
+ let text = ask(&hub.store, backend, command).await?;
+ parse(&text).ok_or(UsageReadStage::Parse)
+ })
+ .await
+}
+
+async fn ask(store: &Store, backend: &str, command: &str) -> Result<String, UsageReadStage> {
+ let Started { acp, mut inbox, init, .. } = start(store, backend).await?;
+ let mut talk = Talk { acp: &acp, inbox: &mut inbox, commands: None, text: String::new() };
+ let reply = tokio::time::timeout(READ_TIMEOUT, talk.run(store, &init, backend, command)).await;
+ acp.kill().await;
+ reply.unwrap_or(Err(UsageReadStage::Timeout))
+}
+
+/// One conversation with the started agent.
+struct Talk<'a> {
+ acp: &'a Acp,
+ inbox: &'a mut mpsc::UnboundedReceiver<Incoming>,
+ /// What the session advertised, once it has.
+ commands: Option<Vec<String>>,
+ /// The reply so far.
+ text: String,
+}
+
+impl Talk<'_> {
+ async fn run(
+ &mut self,
+ store: &Store,
+ init: &Value,
+ backend: &str,
+ command: &str,
+ ) -> Result<String, UsageReadStage> {
+ let session = self.session(store, init, backend).await.map_err(|error| {
+ tracing::debug!(backend, error = format!("{error:#}"), "couldn't open the usage session");
+ UsageReadStage::Session
+ })?;
+ self.wait_for_commands().await;
+ if !self.commands.iter().flatten().any(|name| name == command) {
+ return Err(UsageReadStage::NoCommand);
+ }
+ self.text.clear();
+ let prompt = json!({"sessionId": session, "prompt": [{"type": "text", "text": format!("/{command}")}]});
+ self.request("session/prompt", prompt).await.map_err(|error| {
+ tracing::debug!(backend, error = format!("{error:#}"), "the usage command failed");
+ UsageReadStage::Prompt
+ })?;
+ Ok(std::mem::take(&mut self.text))
+ }
+
+ /// The session kept for readings, or a new one to keep when it's gone or can't be resumed.
+ async fn session(&mut self, store: &Store, init: &Value, backend: &str) -> Result<String> {
+ let dir = auth::probe_dir();
+ let key = format!("usage.session.{backend}");
+ if let Some(id) = store.kv_get(&key).filter(|_| can_resume(init)) {
+ let resume = json!({"sessionId": id, "cwd": dir, "mcpServers": []});
+ if self.request("session/resume", resume).await.is_ok() {
+ return Ok(id);
+ }
+ }
+ let opened = self.request("session/new", json!({"cwd": dir, "mcpServers": []})).await?;
+ let id = opened["sessionId"].as_str().context("the session has no id")?;
+ store.kv_set(&key, id)?;
+ Ok(id.to_owned())
+ }
+
+ async fn wait_for_commands(&mut self) {
+ let wait = async {
+ while self.commands.is_none() {
+ let Some(incoming) = self.inbox.recv().await else { return };
+ if self.take(incoming).await.is_err() {
+ return;
+ }
+ }
+ };
+ // No list in time reads as no command.
+ let _ = tokio::time::timeout(COMMANDS_TIMEOUT, wait).await;
+ }
+
+ /// `method`'s answer, keeping what the agent says meanwhile.
+ async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
+ let answer = self.acp.send(method, params).await?.response();
+ tokio::pin!(answer);
+ let answered = loop {
+ tokio::select! {
+ answered = &mut answer => break answered,
+ incoming = self.inbox.recv() => match incoming {
+ Some(incoming) => self.take(incoming).await?,
+ None => bail!("the agent closed"),
+ }
+ }
+ };
+ // The answer can overtake the updates sent before it.
+ while let Ok(incoming) = self.inbox.try_recv() {
+ self.take(incoming).await?;
+ }
+ answered
+ }
+
+ async fn take(&mut self, incoming: Incoming) -> Result<()> {
+ match incoming {
+ Incoming::Notification { method, params } if method == "session/update" => self.note(&params["update"]),
+ Incoming::Notification { .. } => {}
+ Incoming::Request { id, .. } => {
+ self.acp.respond_error(id, -32601, "not supported in a usage check").await?;
+ }
+ Incoming::Closed { .. } => bail!("the agent closed"),
+ }
+ Ok(())
+ }
+
+ fn note(&mut self, update: &Value) {
+ match update["sessionUpdate"].as_str() {
+ Some("available_commands_update") => self.commands = Some(command_names(update)),
+ Some("agent_message_chunk") => self.text.push_str(update["content"]["text"].as_str().unwrap_or_default()),
+ _ => {}
+ }
+ }
+}
+
+fn can_resume(init: &Value) -> bool {
+ init["agentCapabilities"]["sessionCapabilities"]["resume"].is_object()
+}
+
+fn command_names(update: &Value) -> Vec<String> {
+ let commands = update["availableCommands"].as_array().into_iter().flatten();
+ commands.filter_map(|command| command["name"].as_str().map(str::to_owned)).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_session_is_resumed_only_when_the_agent_offers_it() {
+ assert!(can_resume(&json!({"agentCapabilities": {"sessionCapabilities": {"resume": {}}}})));
+ assert!(!can_resume(&json!({"agentCapabilities": {"sessionCapabilities": {"list": {}}}})));
+ assert!(!can_resume(&json!({})));
+ }
+
+ #[test]
+ fn the_advertised_commands_are_read_by_name() {
+ let update = json!({"availableCommands": [{"name": "plan"}, {"name": "usage", "description": "x"}, {}]});
+ assert_eq!(command_names(&update), ["plan", "usage"]);
+ }
+
+ /// A fake agent's scratch folder, and the host's memory of its session.
+ struct Fake {
+ dir: std::path::PathBuf,
+ store: Store,
+ }
+
+ impl Fake {
+ fn new() -> Self {
+ let dir = std::env::temp_dir().join(format!("codync-usage-agent-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ Self { dir, store: Store::open(std::path::Path::new(":memory:")).unwrap() }
+ }
+
+ /// One reading from the fake agent, which advertises `advertises`, and the methods it was asked.
+ async fn read(&self, advertises: &str) -> (Result<String, UsageReadStage>, Vec<String>) {
+ let log = self.dir.join("calls.log");
+ let _ = std::fs::remove_file(&log);
+ let fixture =
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/usage_command_agent.py");
+ let env = [
+ ("USAGE_AGENT_LOG".to_owned(), log.to_string_lossy().into_owned()),
+ ("USAGE_AGENT_COMMAND".to_owned(), advertises.to_owned()),
+ ];
+ let (acp, mut inbox) =
+ Acp::spawn(&crate::shell::python(&fixture), env!("CARGO_MANIFEST_DIR"), &env).unwrap();
+ let init = acp.request("initialize", json!({"protocolVersion": 1})).await.unwrap();
+ let mut talk = Talk { acp: &acp, inbox: &mut inbox, commands: None, text: String::new() };
+ let outcome = talk.run(&self.store, &init, "test-agent", "usage").await;
+ acp.kill().await;
+ let calls = std::fs::read_to_string(&log).unwrap();
+ (outcome, calls.lines().map(str::to_owned).collect())
+ }
+ }
+
+ impl Drop for Fake {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.dir);
+ }
+ }
+
+ #[tokio::test]
+ async fn a_command_the_session_does_not_advertise_is_never_sent() {
+ let fake = Fake::new();
+ let (outcome, calls) = fake.read("plan").await;
+ assert_eq!(outcome, Err(UsageReadStage::NoCommand));
+ assert!(!calls.iter().any(|call| call == "session/prompt"), "{calls:?}");
+ }
+
+ #[tokio::test]
+ async fn readings_share_one_resumed_session() {
+ let fake = Fake::new();
+ let (first, calls) = fake.read("usage").await;
+ assert_eq!(first.as_deref(), Ok("the report"));
+ assert_eq!(calls, ["initialize", "session/new", "session/prompt"]);
+ let (second, calls) = fake.read("usage").await;
+ assert_eq!(second.as_deref(), Ok("the report"), "only the command's own reply counts");
+ assert_eq!(calls, ["initialize", "session/resume", "session/prompt"]);
+ }
+}
diff --git a/host/src/usage/amp.rs b/host/src/usage/amp.rs
index f28798a9..03ab2eb6 100644
--- a/host/src/usage/amp.rs
+++ b/host/src/usage/amp.rs
@@ -6,15 +6,7 @@ use std::time::Duration;
use super::Window;
pub(super) async fn collect() -> Option<Vec<Window>> {
- let bin = super::command::program("amp")?;
- let text = super::command::output(&bin, &["usage", "--no-color"], None, Duration::from_secs(8)).await?;
- let windows = parse(&text);
- if windows.is_empty() {
- tracing::debug!("amp usage output had no credit lines");
- None
- } else {
- Some(windows)
- }
+ super::command::windows("amp", &["usage", "--no-color"], None, Duration::from_secs(8), parse).await
}
fn parse(text: &str) -> Vec<Window> {
diff --git a/host/src/usage/antigravity.rs b/host/src/usage/antigravity.rs
index 9aa37a40..d1de85fb 100644
--- a/host/src/usage/antigravity.rs
+++ b/host/src/usage/antigravity.rs
@@ -1,7 +1,7 @@
-//! Antigravity's quota from the language server of the running app or `agy`.
-//! The request stays on 127.0.0.1. When nothing is running, there is no window:
-//! the cloud fallback would send the saved login to Google, and Codync doesn't.
+//! Antigravity's quota: the `/usage` report of its ACP server, which is the login its bots run on,
+//! or the language server of a running Antigravity app. Codync sends no login to Google itself.
+use crate::hub::Hub;
use serde_json::Value;
use std::time::Duration;
@@ -10,7 +10,116 @@ use super::Window;
const BODY: &str =
r#"{"metadata":{"ideName":"antigravity","extensionName":"antigravity","ideVersion":"unknown","locale":"en"}}"#;
-pub(super) async fn collect() -> Option<Vec<Window>> {
+/// The running app answers without a download, until a bot has brought the ACP server here.
+pub(super) async fn collect(hub: &Hub) -> Option<Vec<Window>> {
+ let server_here = crate::service::data_dir().join("agents/antigravity-acp").is_dir();
+ if !server_here && let Some(windows) = from_language_server().await {
+ return Some(windows);
+ }
+ if signed_in_or_unknown()
+ && let Some(windows) = super::acp_read::command_reading(hub, "antigravity", "usage", parse_report).await
+ {
+ return Some(windows);
+ }
+ if server_here { from_language_server().await } else { None }
+}
+
+/// Windows has no command `BROWSER` could name to keep the signed-out adapter from opening a
+/// browser, so its reading needs a saved login (off macOS the adapter keeps it only in these files).
+#[cfg(windows)]
+fn signed_in_or_unknown() -> bool {
+ let home = std::env::var_os("GEMINI_HOME")
+ .filter(|home| !home.is_empty())
+ .map(std::path::PathBuf::from)
+ .or_else(|| dirs::home_dir().map(|home| home.join(".gemini")));
+ home.is_some_and(|home| {
+ ["acp_token.json", "acp_business_token.json"]
+ .iter()
+ .any(|file| home.join("antigravity-acp").join(file).is_file())
+ })
+}
+
+#[cfg(not(windows))]
+const fn signed_in_or_unknown() -> bool {
+ true
+}
+
+/// The `### Quota Limits` part of the ACP server's `/usage` report. `None`: it has no numbers this
+/// time, or its format changed. A plan with no limits at all is an empty reading.
+fn parse_report(text: &str) -> Option<Vec<Window>> {
+ let (_, limits) = text.split_once("### Quota Limits")?;
+ let mut group = "";
+ let mut windows = Vec::new();
+ for line in limits.lines() {
+ if let Some(name) = line.strip_prefix("- **").and_then(|rest| rest.strip_suffix("**")) {
+ group = name;
+ } else if let Some(window) = report_window(group, line) {
+ windows.push(window);
+ }
+ }
+ let none_to_report = ["Not applicable", "No quota limits"].iter().any(|text| limits.contains(text));
+ (!windows.is_empty() || none_to_report).then_some(windows)
+}
+
+/// ` - **Weekly Limit Remaining:** 42% remaining (resets Nov 06, 2026, 05:21 UTC)`.
+fn report_window(group: &str, line: &str) -> Option<Window> {
+ let (bucket, reading) = line.trim_start().strip_prefix("- **")?.split_once(":** ")?;
+ let (left, reset) = reading.split_once("% remaining")?;
+ let used = (100.0 - left.trim().parse::<f64>().ok()?).clamp(0.0, 100.0);
+ let (id, label) = report_names(group, bucket);
+ Some(Window::new(id, label, used, report_reset(reset)))
+}
+
+/// A limit as both sources name it. Its row keeps the id and label named for the model whichever
+/// source reads it.
+struct Limit {
+ /// The language server's `bucketId`.
+ bucket: &'static str,
+ /// Part of the ACP report's group name.
+ group: &'static str,
+ /// The ACP report's bucket, as [`report_names`] shortens it.
+ span: &'static str,
+ id: &'static str,
+ label: &'static str,
+}
+
+const LIMITS: [Limit; 5] = [
+ Limit { bucket: "gemini-5h", group: "Gemini Models", span: "5h", id: "five_hour", label: "Gemini 5h" },
+ Limit { bucket: "gemini-weekly", group: "Gemini Models", span: "7d", id: "seven_day", label: "Gemini 7d" },
+ Limit { bucket: "3p-5h", group: "Claude and GPT models", span: "5h", id: "claude_five_hour", label: "Claude 5h" },
+ Limit {
+ bucket: "3p-weekly",
+ group: "Claude and GPT models",
+ span: "7d",
+ id: "claude_seven_day",
+ label: "Claude 7d",
+ },
+ Limit { bucket: "gemini-argon-wtu-weekly", group: "Argon", span: "7d", id: "argon", label: "Argon Weekly" },
+];
+
+fn report_names(group: &str, bucket: &str) -> (String, String) {
+ let span = if bucket.contains("Five Hour") {
+ "5h"
+ } else if bucket.contains("Weekly") {
+ "7d"
+ } else {
+ bucket.trim_end_matches(" Limit Remaining")
+ };
+ if let Some(limit) = LIMITS.iter().find(|limit| group.contains(limit.group) && span == limit.span) {
+ return (limit.id.to_owned(), limit.label.to_owned());
+ }
+ // A group Google adds later still gets its row.
+ let label = format!("{} {span}", group.trim_end_matches(" Models").trim_end_matches(" models"));
+ (super::slug(&label), label)
+}
+
+fn report_reset(text: &str) -> Option<i64> {
+ let at = text.trim().strip_prefix("(resets ")?.strip_suffix(')')?;
+ let parsed = chrono::NaiveDateTime::parse_from_str(at, "%b %d, %Y, %H:%M UTC").ok()?;
+ Some(parsed.and_utc().timestamp_millis())
+}
+
+async fn from_language_server() -> Option<Vec<Window>> {
let target = tokio::task::spawn_blocking(find_server).await.ok().flatten()?;
let client = reqwest::Client::builder()
.danger_accept_invalid_certs(true)
@@ -191,20 +300,15 @@ fn summary(groups: &[Value]) -> Vec<Window> {
}
}
}
- [
- ("gemini-5h", "five_hour", "Gemini 5h"),
- ("gemini-weekly", "seven_day", "Gemini 7d"),
- ("3p-5h", "claude_five_hour", "Claude 5h"),
- ("3p-weekly", "claude_seven_day", "Claude 7d"),
- ("gemini-argon-wtu-weekly", "argon", "Argon Weekly"),
- ]
- .into_iter()
- .filter_map(|(bucket, id, label)| {
- let item = by_id.get(bucket)?;
- let left = item["remainingFraction"].as_f64()?;
- Some(Window::new(id, label, ((1.0 - left) * 100.0).clamp(0.0, 100.0), epoch_ms(&item["resetTime"])))
- })
- .collect()
+ LIMITS
+ .iter()
+ .filter_map(|limit| {
+ let item = by_id.get(limit.bucket)?;
+ let left = item["remainingFraction"].as_f64()?;
+ let used = ((1.0 - left) * 100.0).clamp(0.0, 100.0);
+ Some(Window::new(limit.id, limit.label, used, epoch_ms(&item["resetTime"])))
+ })
+ .collect()
}
fn models(body: &Value) -> Vec<Window> {
@@ -217,12 +321,8 @@ fn models(body: &Value) -> Vec<Window> {
.filter_map(|item| {
let label = item["label"].as_str().filter(|s| !s.is_empty())?;
let left = item["quotaInfo"]["remainingFraction"].as_f64()?;
- let id = label
- .chars()
- .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' })
- .collect::<String>();
Some(Window::new(
- id,
+ super::slug(label),
label,
((1.0 - left) * 100.0).clamp(0.0, 100.0),
epoch_ms(&item["quotaInfo"]["resetTime"]),
@@ -233,7 +333,7 @@ fn models(body: &Value) -> Vec<Window> {
fn epoch_ms(v: &Value) -> Option<i64> {
if let Some(text) = v.as_str() {
- return chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis());
+ return super::iso_ms(text);
}
let n = v.as_i64().or_else(|| v.as_f64().and_then(super::finite_i64))?;
Some(if n > 100_000_000_000 { n } else { n.saturating_mul(1000) })
@@ -244,6 +344,50 @@ mod tests {
use super::*;
use serde_json::json;
+ const REPORT: &str = "### Session Usage\n- **Session total:** data not available yet\n\n### Quota Limits\n\
+ - **Gemini Models**\n *(Models within this group: Gemini Flash, Gemini Pro)*\n \
+ - **Weekly Limit Remaining:** 91% remaining (resets Nov 07, 2026, 05:50 UTC)\n \
+ - **Five Hour Limit Remaining:** 100% remaining (resets Nov 05, 2026, 21:08 UTC)\n\
+ - **Claude and GPT models**\n *(Models within this group: Claude Opus, Claude Sonnet, GPT-OSS)*\n \
+ - **Weekly Limit Remaining:** 42% remaining (resets Nov 06, 2026, 05:21 UTC)\n\
+ - **Gemini 4 Argon**\n *(For paid Pro plans, Argon quota is separate.)*\n \
+ - **Gemini 4 Argon Weekly Limit:** 100% remaining\n\
+ - **Flash Lite Models**\n - **Weekly Limit Remaining:** 25% remaining\n \
+ - **Daily Limit Remaining:** Disabled: not on this plan\n";
+
+ #[test]
+ fn the_acp_report_is_the_share_used_named_like_the_language_servers_reading() {
+ let w = parse_report(REPORT).unwrap();
+ let names: Vec<_> = w.iter().map(|w| (w.id.as_str(), w.label.as_str())).collect();
+ assert_eq!(
+ names,
+ [
+ ("seven_day", "Gemini 7d"),
+ ("five_hour", "Gemini 5h"),
+ ("claude_seven_day", "Claude 7d"),
+ ("argon", "Argon Weekly"),
+ ("flash_lite_7d", "Flash Lite 7d"),
+ ]
+ );
+ assert!((w[0].percent - 9.0).abs() < 1e-9);
+ assert!((w[2].percent - 58.0).abs() < 1e-9);
+ assert_eq!(w[0].resets_at, super::super::iso_ms("2026-11-07T05:50:00Z"));
+ assert_eq!(w[3].resets_at, None, "no reset was reported");
+ }
+
+ #[test]
+ fn a_report_without_numbers_keeps_the_last_reading() {
+ assert_eq!(parse_report("### Quota Limits\n- Unable to retrieve quota status (offline)"), None);
+ assert_eq!(parse_report("### Quota Limits\n- data not available yet"), None);
+ assert_eq!(parse_report("something else entirely"), None, "the format changed");
+ }
+
+ #[test]
+ fn a_login_with_no_limits_is_an_empty_reading() {
+ assert_eq!(parse_report("### Quota Limits\n- Not applicable for current authentication method."), Some(vec![]));
+ assert_eq!(parse_report("### Quota Limits\n- No quota limits reported."), Some(vec![]));
+ }
+
#[test]
fn a_summary_is_the_share_used() {
let body = json!({"response":{"groups":[{"buckets":[
diff --git a/host/src/usage/auggie.rs b/host/src/usage/auggie.rs
new file mode 100644
index 00000000..d656051d
--- /dev/null
+++ b/host/src/usage/auggie.rs
@@ -0,0 +1,58 @@
+//! `auggie account status --json`: the plan's credits left this cycle, with no session. Signed out
+//! or on a plan without it, the CLI exits non-zero with nothing on stdout.
+//! Read from the 0.36.0 CLI's source; no signed-in computer has run it yet.
+
+use crate::hub::Hub;
+use serde_json::Value;
+use std::time::Duration;
+
+use super::{Window, iso_ms};
+
+pub(super) async fn collect(hub: &Hub) -> Option<Vec<Window>> {
+ let args = ["account", "status", "--json"];
+ super::command::json_windows(hub, "auggie", &args, Duration::from_secs(20), parse).await
+}
+
+/// `None`: a status with no amount left, which the CLI doesn't print for a plan without credits.
+fn parse(status: &Value) -> Option<Vec<Window>> {
+ let left = amount(&status["amountRemaining"])?;
+ let resets = status["billingCycleEndDate"].as_str().and_then(iso_ms);
+ Some(match amount(&status["amountIncludedPerCycle"]).filter(|included| *included > 0.0) {
+ Some(included) => {
+ vec![Window::new("cycle", "Credits", ((included - left) / included * 100.0).clamp(0.0, 100.0), resets)]
+ }
+ None => vec![Window::note("balance", "Balance", format!("{left} left"))],
+ })
+}
+
+/// The CLI passes the server's amount on as it came: a number or a string.
+fn amount(value: &Value) -> Option<f64> {
+ value.as_f64().or_else(|| value.as_str()?.trim().parse().ok()).filter(|amount: &f64| amount.is_finite())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn credits_left_read_as_the_share_used() {
+ let w = parse(&json!({"planName": "Pro", "usageUnit": "credits", "amountRemaining": "25",
+ "amountIncludedPerCycle": 100, "billingCycleEndDate": "2026-12-01T00:00:00Z",
+ "daysRemainingInCycle": 25, "banner": null}))
+ .unwrap();
+ assert!((w[0].percent - 75.0).abs() < 1e-9);
+ assert!(w[0].resets_at.is_some());
+ }
+
+ #[test]
+ fn no_cycle_allowance_is_a_balance() {
+ let w = parse(&json!({"amountRemaining": 12.5, "amountIncludedPerCycle": 0})).unwrap();
+ assert_eq!(w[0].text.as_deref(), Some("12.5 left"));
+ }
+
+ #[test]
+ fn a_status_with_no_amount_is_a_changed_format() {
+ assert_eq!(parse(&json!({"planName": "Pro"})), None);
+ }
+}
diff --git a/host/src/usage/claude.rs b/host/src/usage/claude.rs
index 93db2ab0..467f5431 100644
--- a/host/src/usage/claude.rs
+++ b/host/src/usage/claude.rs
@@ -62,10 +62,7 @@ fn report_window(limit: &Value) -> Option<Window> {
}
_ => return None,
};
- let resets = limit["resets_at"]
- .as_str()
- .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())
- .map(|t| t.timestamp_millis());
+ let resets = limit["resets_at"].as_str().and_then(super::iso_ms);
Some(Window::new(id, label, limit["percent"].as_f64()?, resets))
}
diff --git a/host/src/usage/command.rs b/host/src/usage/command.rs
index a3277d36..e33d55ab 100644
--- a/host/src/usage/command.rs
+++ b/host/src/usage/command.rs
@@ -1,9 +1,14 @@
//! Run an installed CLI for a usage probe. A missing program is silence: the
//! probe is skipped until the agent is installed.
+use crate::hub::Hub;
+use serde_json::Value;
use std::path::{Path, PathBuf};
use std::time::Duration;
+use super::Window;
+use super::reading::{UsageReadStage, report};
+
/// `name` on the login-shell PATH.
pub(super) fn program(name: &str) -> Option<PathBuf> {
crate::agent::backends::which(name)
@@ -40,6 +45,48 @@ pub(super) async fn output(
(!text.trim().is_empty()).then_some(text)
}
+/// What `name` prints, read by `parse`. Printing no limits keeps the last reading.
+pub(super) async fn windows(
+ name: &str,
+ args: &[&str],
+ stdin_text: Option<&str>,
+ timeout: Duration,
+ parse: impl FnOnce(&str) -> Vec<Window>,
+) -> Option<Vec<Window>> {
+ let text = output(&program(name)?, args, stdin_text, timeout).await?;
+ let windows = parse(&text);
+ if windows.is_empty() {
+ tracing::debug!(name, "the usage report had no limits");
+ return None;
+ }
+ Some(windows)
+}
+
+/// The JSON report of the agent `name`'s CLI, read by `parse`: `None` from it means the format changed.
+/// Nothing printed (not installed, signed out, timed out) or the CLI's words for being signed out are
+/// no reading and no failure.
+pub(super) async fn json_windows(
+ hub: &Hub,
+ name: &str,
+ args: &[&str],
+ timeout: Duration,
+ parse: impl FnOnce(&Value) -> Option<Vec<Window>>,
+) -> Option<Vec<Window>> {
+ let text = output(&program(name)?, args, None, timeout).await?;
+ let reading = match serde_json::from_str::<Value>(&text) {
+ Ok(document) => parse(&document).ok_or(UsageReadStage::Parse),
+ Err(_) if says_signed_out(&text) => return None,
+ Err(_) => Err(UsageReadStage::Parse),
+ };
+ report(hub, name, &reading);
+ reading.ok()
+}
+
+fn says_signed_out(text: &str) -> bool {
+ let text = text.to_lowercase();
+ ["not authenticated", "logged in", "log in", "signed in", "sign in"].iter().any(|words| text.contains(words))
+}
+
/// Drop CSI colour sequences (`ESC [ … m`). Other characters stay, including
/// the cursor-position query a Windows console sends.
pub(crate) fn strip_ansi(text: &str) -> String {
@@ -69,4 +116,11 @@ mod tests {
let raw = "Credits \u{1b}[32m(12 of 100\u{1b}[0m covered)";
assert_eq!(strip_ansi(raw), "Credits (12 of 100 covered)");
}
+
+ #[test]
+ fn a_cli_saying_it_is_signed_out_is_told_from_a_changed_format() {
+ assert!(says_signed_out("You are not currently logged in to Augment."));
+ assert!(says_signed_out("Error: Not authenticated with Kilo Gateway"));
+ assert!(!says_signed_out("usage: unknown flag --json"));
+ }
}
diff --git a/host/src/usage/copilot.rs b/host/src/usage/copilot.rs
new file mode 100644
index 00000000..1e044bcd
--- /dev/null
+++ b/host/src/usage/copilot.rs
@@ -0,0 +1,236 @@
+//! GitHub Copilot's plan: `account.getQuota` on the CLI's headless server, with no session and no
+//! prompt. The server asks GitHub itself; signed out, it answers with an error and opens nothing.
+//! Its protocol frames messages with `Content-Length` headers, unlike the agents' ACP.
+
+use crate::LockExt;
+use crate::hub::Hub;
+use anyhow::{Context, Result, bail};
+use serde_json::{Value, json};
+use std::path::Path;
+use std::process::Stdio;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
+use tokio::process::{ChildStdin, ChildStdout};
+
+use super::reading::{self, UsageReadStage};
+use super::{Window, iso_ms};
+
+const READ_TIMEOUT: Duration = Duration::from_secs(30);
+/// ponytail: each start leaves an empty log file in `~/.copilot/logs`, even with `--log-level none`,
+/// so this reads less often than the other agents. Back to every poll if the CLI stops doing that.
+const READ_EVERY: Duration = Duration::from_mins(30);
+/// A failure tries again sooner: a `copilot login` shouldn't wait out [`READ_EVERY`].
+const RETRY_AFTER: Duration = Duration::from_mins(10);
+
+static LAST_READ: Mutex<Option<LastRead>> = Mutex::new(None);
+
+struct LastRead {
+ at: Instant,
+ /// `None`: it failed.
+ windows: Option<Vec<Window>>,
+}
+
+impl LastRead {
+ fn due(&self, now: Instant) -> bool {
+ let wait = if self.windows.is_some() { READ_EVERY } else { RETRY_AFTER };
+ now.duration_since(self.at) >= wait
+ }
+
+ /// What a read between server starts lands. The reading held stands, with its own time; one
+ /// that was dropped (the agent turned off and on again) comes back from here.
+ fn between_starts(&self, held: bool) -> Option<Vec<Window>> {
+ if held { None } else { self.windows.clone() }
+ }
+}
+
+pub(super) async fn collect(hub: &Hub) -> Option<Vec<Window>> {
+ let now = Instant::now();
+ if let Some(last) = LAST_READ.locked().as_ref().filter(|last| !last.due(now)) {
+ return last.between_starts(hub.usage.locked().providers.iter().any(|provider| provider.id == "copilot"));
+ }
+ let bin = super::command::program("copilot")?;
+ let windows = reading::guarded(hub, "copilot", read(&bin)).await;
+ *LAST_READ.locked() = Some(LastRead { at: now, windows: windows.clone() });
+ windows
+}
+
+async fn read(bin: &Path) -> Result<Vec<Window>, UsageReadStage> {
+ let mut command = tokio::process::Command::new(bin);
+ command
+ .args(["--headless", "--no-auto-update", "--log-level", "none", "--stdio"])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .kill_on_drop(true);
+ if let Some(home) = dirs::home_dir() {
+ command.current_dir(home);
+ }
+ let mut child = command.spawn().map_err(|_| UsageReadStage::Start)?;
+ let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
+ return Err(UsageReadStage::Start);
+ };
+ let reply = tokio::time::timeout(READ_TIMEOUT, read_quota(stdin, stdout))
+ .await
+ .map_err(|_| UsageReadStage::Timeout)?
+ .map_err(|error| {
+ tracing::debug!(error = format!("{error:#}"), "couldn't read Copilot's quota");
+ UsageReadStage::Prompt
+ })?;
+ parse(&reply, crate::store::now_ms()).ok_or(UsageReadStage::Parse)
+}
+
+async fn read_quota(mut stdin: ChildStdin, stdout: ChildStdout) -> Result<Value> {
+ let mut reader = BufReader::new(stdout);
+ write_frame(&mut stdin, 1, "connect").await?;
+ write_frame(&mut stdin, 2, "account.getQuota").await?;
+ loop {
+ let message = read_frame(&mut reader).await?;
+ if message["id"] != 2 {
+ continue;
+ }
+ if !message["error"].is_null() {
+ bail!("the server refused: {}", message["error"]["message"]);
+ }
+ return Ok(message["result"].clone());
+ }
+}
+
+async fn write_frame(stdin: &mut (impl AsyncWrite + Unpin), id: i64, method: &str) -> Result<()> {
+ let body = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": {}}).to_string();
+ stdin.write_all(format!("Content-Length: {}\r\n\r\n{body}", body.len()).as_bytes()).await?;
+ Ok(stdin.flush().await?)
+}
+
+async fn read_frame(reader: &mut (impl AsyncBufRead + Unpin)) -> Result<Value> {
+ let mut length = None;
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line).await? == 0 {
+ bail!("the server closed");
+ }
+ let line = line.trim();
+ if line.is_empty() {
+ break;
+ }
+ if let Some((name, value)) = line.split_once(':')
+ && name.eq_ignore_ascii_case("content-length")
+ {
+ length = value.trim().parse::<usize>().ok();
+ }
+ }
+ let mut body = vec![0; length.context("a message without a length")?];
+ reader.read_exact(&mut body).await?;
+ Ok(serde_json::from_slice(&body)?)
+}
+
+/// One bar per capped quota. A plan with none is a note, as Cursor's unlimited plan is.
+/// `None`: not the reply the host knows, so the server's format changed.
+fn parse(reply: &Value, now_ms: i64) -> Option<Vec<Window>> {
+ let snapshots = reply["quotaSnapshots"].as_object()?;
+ let mut windows: Vec<Window> = snapshots.iter().filter_map(|(id, snapshot)| capped(id, snapshot, now_ms)).collect();
+ if windows.is_empty() && snapshots.values().any(|s| s["isUnlimitedEntitlement"] == true) {
+ windows.push(Window::note("unlimited", "Plan", "Unlimited"));
+ }
+ Some(windows)
+}
+
+fn capped(id: &str, snapshot: &Value, now_ms: i64) -> Option<Window> {
+ if snapshot["isUnlimitedEntitlement"] == true {
+ return None;
+ }
+ let left = snapshot["remainingPercentage"].as_f64().filter(|left| left.is_finite())?;
+ let label = match id {
+ "premium_interactions" => "Premium requests",
+ "chat" => "Chat",
+ "completions" => "Completions",
+ other => other,
+ };
+ let resets = snapshot["resetDate"]
+ .as_str()
+ .and_then(iso_ms)
+ // Some plans report the moment of the request here.
+ .filter(|at| *at > now_ms + 3_600_000);
+ Some(Window::new(id, label, (100.0 - left).clamp(0.0, 100.0), resets))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const NOW: i64 = 1_793_900_000_000;
+
+ /// As the 1.0.105 server answered a real login.
+ fn reply() -> Value {
+ json!({"quotaSnapshots": {
+ "chat": {"isUnlimitedEntitlement": true, "entitlementRequests": 0, "remainingPercentage": 100,
+ "resetDate": "2026-12-01T00:00:00.000Z"},
+ "completions": {"isUnlimitedEntitlement": true, "remainingPercentage": 100},
+ "premium_interactions": {"isUnlimitedEntitlement": false, "entitlementRequests": 200, "usedRequests": 50,
+ "remainingPercentage": 75, "resetDate": "2026-12-01T00:00:00.000Z"}
+ }})
+ }
+
+ #[test]
+ fn only_capped_quotas_are_bars() {
+ let w = parse(&reply(), NOW).unwrap();
+ assert_eq!(w.len(), 1);
+ assert_eq!((w[0].id.as_str(), w[0].label.as_str()), ("premium_interactions", "Premium requests"));
+ assert!((w[0].percent - 25.0).abs() < 1e-9);
+ assert!(w[0].resets_at.is_some());
+ }
+
+ #[test]
+ fn a_reset_already_past_is_not_shown() {
+ let long_after_it = 2_000_000_000_000;
+ let w = parse(&reply(), long_after_it).unwrap();
+ assert_eq!(w[0].resets_at, None);
+ }
+
+ #[test]
+ fn a_plan_with_no_caps_is_a_note() {
+ let w = parse(&json!({"quotaSnapshots": {"chat": {"isUnlimitedEntitlement": true}}}), NOW).unwrap();
+ assert_eq!(w[0].text.as_deref(), Some("Unlimited"));
+ }
+
+ #[test]
+ fn a_reply_without_quotas_is_a_changed_format() {
+ assert_eq!(parse(&json!({}), NOW), None);
+ assert_eq!(parse(&json!({"quotaSnapshots": {"chat": {"remainingPercentage": "lots"}}}), NOW), Some(vec![]));
+ }
+
+ #[test]
+ fn the_server_starts_at_most_once_per_interval_and_sooner_after_a_failure() {
+ let at = Instant::now();
+ let read = LastRead { at, windows: Some(Vec::new()) };
+ assert!(!read.due(at + RETRY_AFTER));
+ assert!(read.due(at + READ_EVERY));
+ let failed = LastRead { at, windows: None };
+ assert!(!failed.due(at + Duration::from_mins(5)));
+ assert!(failed.due(at + RETRY_AFTER));
+ }
+
+ #[test]
+ fn a_reading_turned_off_and_on_again_comes_back_without_a_new_start() {
+ let windows = parse(&reply(), NOW);
+ let last = LastRead { at: Instant::now(), windows: windows.clone() };
+ assert_eq!(last.between_starts(false), windows, "the Usage screen has its bars again");
+ assert_eq!(last.between_starts(true), None, "a reading held keeps the time it was made");
+ assert_eq!(LastRead { at: Instant::now(), windows: None }.between_starts(false), None);
+ }
+
+ #[tokio::test]
+ async fn messages_are_framed_with_their_length() {
+ let (mut ours, theirs) = tokio::io::duplex(1024);
+ let (their_read, mut their_write) = tokio::io::split(theirs);
+ write_frame(&mut ours, 7, "account.getQuota").await.unwrap();
+ let sent = read_frame(&mut BufReader::new(their_read)).await.unwrap();
+ assert_eq!((sent["id"].as_i64(), sent["method"].as_str()), (Some(7), Some("account.getQuota")));
+
+ let body = r#"{"id":2,"result":{}}"#;
+ let frame = format!("content-length: {}\r\nContent-Type: application/json\r\n\r\n{body}", body.len());
+ their_write.write_all(frame.as_bytes()).await.unwrap();
+ let answer = read_frame(&mut BufReader::new(ours)).await.unwrap();
+ assert_eq!(answer["id"], 2, "the header's name goes by any case, among others");
+ }
+}
diff --git a/host/src/usage/cursor.rs b/host/src/usage/cursor.rs
index 59931feb..642d3d62 100644
--- a/host/src/usage/cursor.rs
+++ b/host/src/usage/cursor.rs
@@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
-use super::Window;
+use super::{Window, iso_ms};
/// Whether the dashboard last named a unified plan, so a failed poll keeps its weekly reading.
static LAST_UNIFIED: AtomicBool = AtomicBool::new(false);
@@ -83,10 +83,17 @@ fn cli_auth_path() -> Option<PathBuf> {
Some(dirs::config_dir()?.join("cursor/auth.json"))
}
+fn app_db_path() -> Option<PathBuf> {
+ dirs::config_dir().map(|dir| dir.join("Cursor/User/globalStorage/state.vscdb"))
+}
+
fn read_token() -> Option<String> {
- let cli_path = cli_auth_path();
- let app_path = dirs::config_dir().map(|dir| dir.join("Cursor/User/globalStorage/state.vscdb"));
- read_saved_token(cli_path.as_deref(), app_path.as_deref())
+ read_saved_token(cli_auth_path().as_deref(), app_db_path().as_deref())
+}
+
+/// The app or CLI left a login file here. Whether it's still valid only a reading tells.
+pub(super) fn login_saved() -> bool {
+ [cli_auth_path(), app_db_path()].into_iter().flatten().any(|path| path.is_file())
}
fn read_saved_token(cli_path: Option<&Path>, app_path: Option<&Path>) -> Option<String> {
@@ -184,10 +191,6 @@ fn non_negative(value: Option<f64>) -> Option<f64> {
value.filter(|n| n.is_finite() && *n >= 0.0).map(|n| n.clamp(0.0, 100.0))
}
-fn iso_ms(text: &str) -> Option<i64> {
- chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/host/src/usage/grok.rs b/host/src/usage/grok.rs
new file mode 100644
index 00000000..efd8ceb7
--- /dev/null
+++ b/host/src/usage/grok.rs
@@ -0,0 +1,81 @@
+//! Grok's plan: the `x.ai/billing` extension on its ACP server, which asks xAI itself, with no
+//! session and no prompt. Signed out or on an API key, it answers with an error.
+//! Field names are from the 1.0.75 binary; no signed-in computer has run it yet.
+
+use crate::agent::auth::Started;
+use crate::hub::Hub;
+use crate::store::Store;
+use serde_json::{Value, json};
+use std::time::Duration;
+
+use super::reading::UsageReadStage;
+use super::{Window, acp_read, iso_ms};
+
+const READ_TIMEOUT: Duration = Duration::from_secs(20);
+
+pub(super) async fn collect(hub: &Hub) -> Option<Vec<Window>> {
+ acp_read::guarded(hub, "grok", read(&hub.store)).await
+}
+
+async fn read(store: &Store) -> Result<Vec<Window>, UsageReadStage> {
+ let Started { acp, inbox: _inbox, .. } = acp_read::start(store, "grok").await?;
+ // ACP's extension methods take a leading underscore, which not every build expects.
+ let ask = async {
+ match acp.request("x.ai/billing", json!({})).await {
+ Ok(reply) => Ok(reply),
+ Err(_) => acp.request("_x.ai/billing", json!({})).await,
+ }
+ };
+ let reply = tokio::time::timeout(READ_TIMEOUT, ask).await;
+ acp.kill().await;
+ let reply = reply.map_err(|_| UsageReadStage::Timeout)?.map_err(|_| UsageReadStage::Prompt)?;
+ let windows = parse(&reply);
+ if windows.is_empty() { Err(UsageReadStage::Parse) } else { Ok(windows) }
+}
+
+fn parse(reply: &Value) -> Vec<Window> {
+ let config = &reply["config"];
+ let mut windows = Vec::new();
+ if let Some(used) = config["creditUsagePercent"].as_f64().filter(|used| used.is_finite()) {
+ let period = &config["currentPeriod"];
+ let resets = period["end"].as_str().and_then(iso_ms);
+ let kind = period["type"].as_str().unwrap_or_default();
+ let label = if kind.ends_with("WEEKLY") {
+ "Weekly"
+ } else if kind.ends_with("MONTHLY") {
+ "Monthly"
+ } else {
+ "Plan"
+ };
+ windows.push(Window::new("plan", label, used.clamp(0.0, 100.0), resets));
+ }
+ // In cents, as `{"val": N}`.
+ if let Some(cents) = config["prepaidBalance"]["val"].as_f64().filter(|cents| cents.is_finite() && *cents > 0.0) {
+ windows.push(Window::note("prepaid", "Prepaid", format!("${:.2}", cents / 100.0)));
+ }
+ windows
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_plan_reads_as_the_share_used_with_its_prepaid_balance() {
+ let w = parse(&json!({"config": {
+ "creditUsagePercent": 42.5,
+ "currentPeriod": {"type": "USAGE_PERIOD_TYPE_WEEKLY", "start": "2026-11-01T00:00:00Z", "end": "2026-11-08T00:00:00Z"},
+ "prepaidBalance": {"val": 1250}
+ }}));
+ assert_eq!(w[0].label, "Weekly");
+ assert!((w[0].percent - 42.5).abs() < 1e-9);
+ assert!(w[0].resets_at.is_some());
+ assert_eq!(w[1].text.as_deref(), Some("$12.50"));
+ }
+
+ #[test]
+ fn nothing_recognizable_is_no_reading() {
+ assert_eq!(parse(&json!({})), []);
+ assert_eq!(parse(&json!({"config": {"prepaidBalance": {"val": 0}}})), []);
+ }
+}
diff --git a/host/src/usage/hermes.rs b/host/src/usage/hermes.rs
new file mode 100644
index 00000000..7e08740f
--- /dev/null
+++ b/host/src/usage/hermes.rs
@@ -0,0 +1,62 @@
+//! `hermes usage --json`: the account limits Hermes Agent reads for its configured provider, in a
+//! document it keeps stable for scripts, with no session. A provider it has no reading for exits
+//! non-zero with nothing on stdout.
+
+use crate::hub::Hub;
+use serde_json::Value;
+use std::time::Duration;
+
+use super::{Window, iso_ms, slug};
+
+pub(super) async fn collect(hub: &Hub) -> Option<Vec<Window>> {
+ super::command::json_windows(hub, "hermes", &["usage", "--json"], Duration::from_secs(30), parse).await
+}
+
+/// `None`: neither limits nor a reason why there are none, so the document changed.
+fn parse(document: &Value) -> Option<Vec<Window>> {
+ match document["windows"].as_array() {
+ Some(windows) => Some(windows.iter().filter_map(window).collect()),
+ None => document["unavailable_reason"].is_string().then(Vec::new),
+ }
+}
+
+fn window(value: &Value) -> Option<Window> {
+ let label = value["label"].as_str().filter(|label| !label.is_empty())?;
+ let id = slug(label);
+ let resets = value["resets_at"].as_str().and_then(iso_ms);
+ match value["used_percent"].as_f64().filter(|used| used.is_finite()) {
+ Some(used) => Some(Window::new(id, label, used.clamp(0.0, 100.0), resets)),
+ // Credits with no cap are a note. A window with neither is one the provider didn't report.
+ None => Some(Window::note(id, label, value["detail"].as_str().filter(|detail| !detail.is_empty())?)),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn the_documented_shape_reads_as_limits_and_notes() {
+ let w = parse(&json!({"provider": "openai-codex", "windows": [
+ {"label": "Session", "used_percent": 37.0, "resets_at": "2026-09-19T21:00:00+00:00", "detail": null},
+ {"label": "Weekly", "used_percent": 12.5, "resets_at": null, "detail": null},
+ {"label": "Credits", "used_percent": null, "resets_at": null, "detail": "$4.20 left"},
+ {"label": "Unknown", "used_percent": null, "resets_at": null, "detail": null}
+ ], "unavailable_reason": null}))
+ .unwrap();
+ assert_eq!(w.len(), 3, "a window nobody reported is dropped");
+ assert_eq!((w[0].id.as_str(), w[0].label.as_str()), ("session", "Session"));
+ assert!((w[0].percent - 37.0).abs() < 1e-9);
+ assert_eq!(w[0].resets_at, Some(1_789_851_600_000));
+ assert_eq!(w[1].resets_at, None);
+ assert_eq!(w[2].text.as_deref(), Some("$4.20 left"));
+ }
+
+ #[test]
+ fn a_reason_is_an_empty_reading_and_anything_else_a_changed_format() {
+ assert_eq!(parse(&json!({"windows": [], "unavailable_reason": "nope"})), Some(vec![]));
+ assert_eq!(parse(&json!({"unavailable_reason": "nope"})), Some(vec![]));
+ assert_eq!(parse(&json!({"limits": []})), None);
+ }
+}
diff --git a/host/src/usage/junie.rs b/host/src/usage/junie.rs
index fce69eb3..7f68f392 100644
--- a/host/src/usage/junie.rs
+++ b/host/src/usage/junie.rs
@@ -18,6 +18,11 @@ pub(super) fn collect() -> Option<Vec<Window>> {
(!windows.is_empty()).then_some(windows)
}
+/// An IDE saved a quota here, with or without the `junie` CLI.
+pub(super) fn quota_saved() -> bool {
+ roots().iter().any(|root| !quota_files(root).is_empty())
+}
+
fn roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
for base in [dirs::config_dir(), dirs::data_local_dir()].into_iter().flatten() {
@@ -43,12 +48,7 @@ fn parse(xml: &str) -> Vec<Window> {
return Vec::new();
}
let percent = (used / maximum * 100.0).clamp(0.0, 100.0);
- let resets = option(xml, "nextRefill").and_then(|refill| {
- refill["next"]
- .as_str()
- .and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok())
- .map(|t| t.timestamp_millis())
- });
+ let resets = option(xml, "nextRefill").and_then(|refill| refill["next"].as_str().and_then(super::iso_ms));
vec![Window::new("monthly", "AI credits", percent, resets)]
}
diff --git a/host/src/usage/kilo.rs b/host/src/usage/kilo.rs
new file mode 100644
index 00000000..06ab4f22
--- /dev/null
+++ b/host/src/usage/kilo.rs
@@ -0,0 +1,39 @@
+//! `kilo profile --json`: the account's dollar balance, the only plan number the CLI prints. A note,
+//! as it has no cap or reset. Signed out, it exits non-zero with nothing on stdout.
+//! Read from the 7.8.18 CLI's source; no signed-in computer has run it yet.
+
+use crate::hub::Hub;
+use serde_json::Value;
+use std::time::Duration;
+
+use super::Window;
+
+pub(super) async fn collect(hub: &Hub) -> Option<Vec<Window>> {
+ let parse = |profile: &Value| Some(parse(profile));
+ super::command::json_windows(hub, "kilo", &["profile", "--json"], Duration::from_secs(20), parse).await
+}
+
+/// The CLI prints a balance of 0 when its own balance request fails, so a zero is an empty reading:
+/// the row goes until the next poll, rather than claim the account is empty or keep an old balance.
+fn parse(profile: &Value) -> Vec<Window> {
+ let balance = profile["balance"].as_f64().filter(|balance| balance.is_finite() && *balance > 0.0);
+ balance.map(|balance| Window::note("balance", "Balance", format!("${balance:.2}"))).into_iter().collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn the_balance_is_a_note() {
+ let w = parse(&json!({"name": "n", "team": null, "balance": 4.2}));
+ assert_eq!(w[0].text.as_deref(), Some("$4.20"));
+ }
+
+ #[test]
+ fn a_zero_or_a_missing_balance_is_an_empty_reading() {
+ assert_eq!(parse(&json!({"balance": 0})), []);
+ assert_eq!(parse(&json!({"name": "n"})), []);
+ }
+}
diff --git a/host/src/usage/kiro.rs b/host/src/usage/kiro.rs
index cfdfc3e6..225bc7d4 100644
--- a/host/src/usage/kiro.rs
+++ b/host/src/usage/kiro.rs
@@ -6,15 +6,8 @@ use std::time::Duration;
use super::Window;
pub(super) async fn collect() -> Option<Vec<Window>> {
- let bin = super::command::program("kiro-cli")?;
- let text = super::command::output(&bin, &[], Some("/usage\n/quit\n"), Duration::from_secs(30)).await?;
- let windows = parse(&text, crate::store::now_ms());
- if windows.is_empty() {
- tracing::debug!("kiro-cli usage output had no credit lines");
- None
- } else {
- Some(windows)
- }
+ let parse = |text: &str| parse(text, crate::store::now_ms());
+ super::command::windows("kiro-cli", &[], Some("/usage\n/quit\n"), Duration::from_secs(30), parse).await
}
fn parse(text: &str, now_ms: i64) -> Vec<Window> {
diff --git a/host/src/usage/mod.rs b/host/src/usage/mod.rs
index b73c8bee..d9195793 100644
--- a/host/src/usage/mod.rs
+++ b/host/src/usage/mod.rs
@@ -3,36 +3,52 @@
//! Claude: `claude -p /usage`, the status line, and the ACP rate-limit event.
//! Codex: the CLI's live account rate limits. The other agents Codync runs are
//! read the same way when they can report locally: `omp usage`, `amp usage`,
-//! `kiro-cli /usage`, a `kimi` screen, Antigravity's language server, OpenCode's
-//! database, Vibe's session logs, and the `JetBrains` IDE quota file.
+//! `hermes usage`, `auggie account status`, `kilo profile`, `kiro-cli /usage`, a `kimi`
+//! screen, Antigravity's ACP `/usage` command or its IDE's language server, Copilot's
+//! headless server, Grok's ACP billing extension, OpenCode's database, Vibe's session logs,
+//! and the `JetBrains` IDE quota file. Which of them get read and shown: [`services`].
+//! Failures: [`reading`].
//!
//! Cursor's saved CLI or app login reads the dashboard service's weekly unified
//! allowance, or the website's usage summary for legacy monthly plans. These are
//! the only provider requests, and the token is never logged.
+mod acp_read;
mod amp;
mod antigravity;
+mod auggie;
mod claude;
mod codex;
mod command;
+mod copilot;
mod cursor;
+mod grok;
+mod hermes;
mod junie;
+mod kilo;
mod kimi;
mod kiro;
mod omp;
mod opencode;
+mod reading;
+mod services;
mod vibe;
pub use claude::{ingest_claude_rate_limit, ingest_statusline};
pub(crate) use command::strip_ansi;
+pub use services::{bots_changed, set_shown};
use crate::LockExt;
use crate::hub::Hub;
+use futures::stream::{FuturesUnordered, StreamExt};
use serde::Serialize;
+use services::{Reader, Service};
use std::sync::Arc;
use std::time::Duration;
const POLL_EVERY: Duration = Duration::from_mins(5);
+/// How long a forced refresh holds up whoever asked. A slower reader lands through `usage` events.
+const REFRESH_WAIT: Duration = Duration::from_mins(1);
/// Usage of a plan above which background work (dreaming, the lead's check-ins) waits.
const HEADROOM_PERCENT: f64 = 75.0;
@@ -50,6 +66,8 @@ fn over_headroom(windows: &[Window]) -> bool {
#[derive(Serialize, Clone, Debug, Default, PartialEq)]
pub struct Usage {
pub providers: Vec<Provider>,
+ /// The agents the user can choose among in the Usage screen.
+ pub services: Vec<Service>,
}
#[derive(Serialize, Clone, Debug, PartialEq)]
@@ -57,6 +75,9 @@ pub struct Usage {
pub struct Provider {
pub id: &'static str,
pub name: &'static str,
+ /// The agent's ACP registry id, which its logo goes by. Without one, its `id`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub registry: Option<&'static str>,
pub windows: Vec<Window>,
/// Where the numbers came from: `claude` (CLI), `statusline`, `agent`, `sessions`,
/// or a short phrase for the other agents.
@@ -94,6 +115,13 @@ impl Window {
}
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();
+ Self { providers, services: self.services.clone() }
+ }
+
/// One window at a time, for Claude's status line and rate-limit events.
/// The provider's other windows stay.
fn merge(&mut self, id: &'static str, name: &'static str, source: &'static str, new: Vec<Window>) {
@@ -102,7 +130,7 @@ impl Usage {
windows.extend(new);
windows.sort_by(|a, b| a.id.cmp(&b.id));
self.providers.retain(|p| p.id != id);
- self.providers.push(Provider { id, name, windows, source, updated_at: crate::store::now_ms() });
+ self.providers.push(Provider::new(id, name, source, windows));
self.providers.sort_by_key(|p| p.id);
}
@@ -115,68 +143,80 @@ impl Usage {
}
let mut windows = new;
windows.sort_by(|a, b| a.id.cmp(&b.id));
- self.providers.push(Provider { id, name, windows, source, updated_at: crate::store::now_ms() });
+ self.providers.push(Provider::new(id, name, source, windows));
self.providers.sort_by_key(|p| p.id);
}
}
+impl Provider {
+ fn new(id: &'static str, name: &'static str, source: &'static str, windows: Vec<Window>) -> Self {
+ Self { id, name, registry: services::registry(id), windows, source, updated_at: crate::store::now_ms() }
+ }
+}
+
pub(super) fn merge(hub: &Hub, id: &'static str, name: &'static str, source: &'static str, windows: Vec<Window>) {
- let mut usage = hub.usage.locked().clone();
- usage.merge(id, name, source, windows);
- hub.set_usage(usage);
+ hub.update_usage(|usage| usage.merge(id, name, source, windows));
}
pub async fn poll(hub: Arc<Hub>) {
loop {
- refresh(&hub).await;
- tokio::time::sleep(POLL_EVERY).await;
+ read_all(&hub).await;
+ let next = tokio::time::Instant::now() + POLL_EVERY;
+ // An agent that just became wanted (a new bot's, one the user turned on) reads right away.
+ while tokio::time::timeout_at(next, hub.usage_wake.notified()).await.is_ok() {
+ read(&hub, readers(&hub, services::unread_readers).await).await;
+ }
}
}
-pub async fn refresh(hub: &Hub) {
+/// A forced read for a caller that's waiting, which gets what has landed by [`REFRESH_WAIT`].
+pub async fn refresh(hub: &Arc<Hub>) {
+ let reading = tokio::spawn({
+ let hub = hub.clone();
+ async move { read_all(&hub).await }
+ });
+ // Past the wait the reading carries on by itself.
+ if let Ok(Err(error)) = tokio::time::timeout(REFRESH_WAIT, reading).await {
+ tracing::warn!(%error, "a usage refresh failed");
+ }
+}
+
+async fn read_all(hub: &Arc<Hub>) {
+ let wanted = |hub: &Hub| {
+ services::sync(hub);
+ services::wanted_readers(&hub.store)
+ };
+ read(hub, readers(hub, wanted).await).await;
+}
+
+/// The readers `pick` names, away from the async workers: it goes to the database and the disk.
+async fn readers(hub: &Arc<Hub>, pick: fn(&Hub) -> Vec<&'static Reader>) -> Vec<&'static Reader> {
+ let hub = hub.clone();
+ tokio::task::spawn_blocking(move || pick(&hub)).await.unwrap_or_else(|error| {
+ tracing::warn!(%error, "couldn't list the agents to read");
+ Vec::new()
+ })
+}
+
+/// Each reading lands as it comes in: a slow agent doesn't hold back the others.
+async fn read(hub: &Hub, readers: Vec<&'static Reader>) {
if crate::agent::backends::agent_checks_off() {
return;
}
- let (
- codex,
- claude,
- omp_windows,
- amp_windows,
- kiro_windows,
- kimi_windows,
- antigravity,
- opencode,
- vibe_notes,
- junie,
- cursor_windows,
- ) = tokio::join!(
- codex::collect(),
- claude::collect(),
- omp::collect(),
- amp::collect(),
- kiro::collect(),
- tokio::task::spawn_blocking(kimi::collect),
- antigravity::collect(),
- tokio::task::spawn_blocking(opencode::collect),
- tokio::task::spawn_blocking(vibe::collect),
- tokio::task::spawn_blocking(junie::collect),
- cursor::collect(),
- );
- apply(hub, codex, "codex", "Codex", "Codex CLI");
- apply(hub, claude, "claude", "Claude", "claude");
- apply(hub, omp_windows, "omp", "oh-my-pi", "omp usage");
- apply(hub, amp_windows, "amp", "Amp", "amp usage");
- apply(hub, kiro_windows, "kiro", "Kiro CLI", "kiro-cli");
- apply(hub, joined(kimi_windows), "kimi", "Kimi Code", "kimi");
- apply(hub, antigravity, "antigravity", "Google Antigravity", "antigravity");
- apply(hub, joined(opencode), "opencode", "OpenCode", "opencode database");
- apply(hub, joined(vibe_notes), "vibe", "Mistral Vibe", "vibe logs");
- apply(hub, joined(junie), "junie", "Junie", "JetBrains IDE");
- apply(hub, cursor_windows, "cursor", "Cursor", "Cursor");
-}
-
-fn joined(result: Result<Option<Vec<Window>>, tokio::task::JoinError>) -> Option<Vec<Window>> {
- result.ok().flatten()
+ let mut readings: FuturesUnordered<_> =
+ readers.into_iter().map(|reader| async move { (reader, (reader.read)(hub).await) }).collect();
+ while let Some((reader, windows)) = readings.next().await {
+ apply(hub, windows, reader.id, reader.name, reader.source);
+ }
+}
+
+fn iso_ms(text: &str) -> Option<i64> {
+ chrono::DateTime::parse_from_rfc3339(text).ok().map(|at| at.timestamp_millis())
+}
+
+/// A window id made from its label.
+fn slug(label: &str) -> String {
+ label.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect()
}
pub(super) fn finite_i64(n: f64) -> Option<i64> {
@@ -195,9 +235,7 @@ pub(super) fn finite_i64(n: f64) -> Option<i64> {
fn apply(hub: &Hub, windows: Option<Vec<Window>>, id: &'static str, name: &'static str, source: &'static str) {
let Some(windows) = windows else { return };
- let mut usage = hub.usage.locked().clone();
- usage.replace(id, name, source, windows);
- hub.set_usage(usage);
+ hub.update_usage(|usage| usage.replace(id, name, source, windows));
}
#[cfg(test)]
@@ -246,6 +284,34 @@ mod tests {
assert!(value.get("resetsText").is_none());
}
+ #[test]
+ fn the_apps_get_only_what_the_user_shows() {
+ let window = Window::new("weekly", "Weekly", 10.0, None);
+ let provider = |id| Provider { windows: vec![window.clone()], ..Provider::new(id, id, "test", Vec::new()) };
+ let usage = Usage {
+ providers: vec![provider("claude"), provider("cursor"), provider("codex")],
+ services: vec![
+ Service { id: "claude", name: "Claude", registry: None, shown: true },
+ Service { id: "cursor", name: "Cursor", registry: None, shown: false },
+ ],
+ };
+ let visible = usage.visible();
+ let ids: Vec<_> = visible.providers.iter().map(|p| p.id).collect();
+ // A reading with no row yet (a status line before the first sync) isn't lost.
+ assert_eq!(ids, ["claude", "codex"]);
+ assert_eq!(visible.services.len(), 2, "the chooser still lists the hidden one");
+ }
+
+ #[test]
+ fn a_reading_names_the_registry_id_its_logo_goes_by() {
+ let mut u = Usage::default();
+ u.replace("copilot", "GitHub Copilot", "test", vec![Window::note("plan", "Plan", "Unlimited")]);
+ u.replace("hermes", "Hermes Agent", "test", vec![Window::note("plan", "Plan", "Unlimited")]);
+ let value = serde_json::to_value(&u).unwrap();
+ assert_eq!(value["providers"][0]["registry"], "github-copilot-cli");
+ assert!(value["providers"][1].get("registry").is_none(), "no registry entry: clients use the id");
+ }
+
#[test]
fn a_note_does_not_count_as_the_plan_running_out() {
let note = Window { percent: 99.0, ..Window::note("cost", "Cost today", "$9") };
diff --git a/host/src/usage/omp.rs b/host/src/usage/omp.rs
index fb98b879..49c28290 100644
--- a/host/src/usage/omp.rs
+++ b/host/src/usage/omp.rs
@@ -9,15 +9,7 @@ use std::time::Duration;
use super::Window;
pub(super) async fn collect() -> Option<Vec<Window>> {
- let bin = super::command::program("omp")?;
- let text = super::command::output(&bin, &["usage", "--json"], None, Duration::from_secs(30)).await?;
- let windows = parse(&text);
- if windows.is_empty() {
- tracing::debug!("omp usage output had no limits");
- None
- } else {
- Some(windows)
- }
+ super::command::windows("omp", &["usage", "--json"], None, Duration::from_secs(30), parse).await
}
fn parse(text: &str) -> Vec<Window> {
diff --git a/host/src/usage/reading.rs b/host/src/usage/reading.rs
new file mode 100644
index 00000000..211f1deb
--- /dev/null
+++ b/host/src/usage/reading.rs
@@ -0,0 +1,88 @@
+//! How a reading of an agent ends, and one reading at a time of those the host has to start.
+
+use crate::LockExt;
+use crate::analytics::{self, Event};
+use crate::hub::Hub;
+use serde::Serialize;
+use serde_json::json;
+use std::collections::BTreeSet;
+use std::future::Future;
+use std::sync::Mutex;
+
+use super::Window;
+
+/// Where reading an agent's usage stopped (`usage_read_failed`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(super) enum UsageReadStage {
+ /// The agent didn't start.
+ Start,
+ /// It wouldn't open or resume a session.
+ Session,
+ /// The session doesn't offer the command, so it was never sent.
+ NoCommand,
+ /// The agent refused the request or closed on it.
+ Prompt,
+ /// It didn't finish in time (a signed-out agent waits here).
+ Timeout,
+ /// Its report wasn't one the host can read: the agent's format changed.
+ Parse,
+}
+
+/// Agents being read: a refresh during a poll doesn't start a second copy.
+static READING: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
+/// Agents whose last reading failed, so a failure is reported once, not every poll.
+static FAILING: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
+
+struct Reading(String);
+
+impl Reading {
+ fn start(agent: &str) -> Option<Self> {
+ READING.locked().insert(agent.to_owned()).then(|| Self(agent.to_owned()))
+ }
+}
+
+impl Drop for Reading {
+ fn drop(&mut self) {
+ READING.locked().remove(&self.0);
+ }
+}
+
+/// What `reading` finds, unless `agent` is being read already. `None`: no reading this time.
+pub(super) async fn guarded(
+ hub: &Hub,
+ agent: &str,
+ reading: impl Future<Output = Result<Vec<Window>, UsageReadStage>>,
+) -> Option<Vec<Window>> {
+ let _reading = Reading::start(agent)?;
+ let outcome = reading.await;
+ report(hub, agent, &outcome);
+ outcome.ok()
+}
+
+/// How a reading ended, for usage analytics: a failure once, not on every poll.
+pub(super) fn report<T>(hub: &Hub, agent: &str, reading: &Result<T, UsageReadStage>) {
+ let Err(stage) = reading else {
+ FAILING.locked().remove(agent);
+ return;
+ };
+ tracing::debug!(agent, ?stage, "couldn't read the agent's usage");
+ if FAILING.locked().insert(agent.to_owned()) {
+ let properties = json!({"agent": agent, "stage": stage});
+ analytics::capture(hub, Event::UsageReadFailed, properties.as_object().cloned().unwrap_or_default());
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_second_reading_of_the_same_agent_waits_for_the_first() {
+ let first = Reading::start("test-agent").expect("nothing is reading it");
+ assert!(Reading::start("test-agent").is_none());
+ assert!(Reading::start("another-test-agent").is_some(), "other agents read meanwhile");
+ drop(first);
+ assert!(Reading::start("test-agent").is_some());
+ }
+}
diff --git a/host/src/usage/services.rs b/host/src/usage/services.rs
new file mode 100644
index 00000000..b98764b8
--- /dev/null
+++ b/host/src/usage/services.rs
@@ -0,0 +1,358 @@
+//! Which agents' usage this computer reads and shows.
+//!
+//! An agent shows when a bot here runs it, as its own agent or a fallback, unless the user said
+//! otherwise in the Usage screen. Reading follows the same list: an agent nobody runs or asked
+//! for is never started and its saved login never read. One hidden while a bot still runs it keeps
+//! being read, because background work and fallbacks go by its limits.
+
+use super::{
+ Window, amp, antigravity, auggie, claude, codex, copilot, cursor, grok, hermes, junie, kilo, kimi, kiro, omp,
+ opencode, vibe,
+};
+use crate::LockExt;
+use crate::agent::backends;
+use crate::hub::Hub;
+use crate::store::Store;
+use anyhow::{Context, Result};
+use futures::future::BoxFuture;
+use serde::Serialize;
+use std::collections::HashSet;
+
+/// An agent the apps can list in the Usage screen's chooser.
+#[derive(Serialize, Clone, Debug, PartialEq)]
+pub struct Service {
+ pub id: &'static str,
+ pub name: &'static str,
+ /// The agent's ACP registry id, which its logo goes by. Without one, its `id`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub registry: Option<&'static str>,
+ pub shown: bool,
+}
+
+pub(super) struct Reader {
+ pub(super) id: &'static str,
+ pub(super) name: &'static str,
+ pub(super) source: &'static str,
+ /// Something to read without the agent's CLI: an app's saved login or quota file.
+ pub(super) found_without_cli: Option<fn() -> bool>,
+ pub(super) read: for<'a> fn(&'a Hub) -> BoxFuture<'a, Option<Vec<Window>>>,
+}
+
+fn blocking(read: fn() -> Option<Vec<Window>>) -> BoxFuture<'static, Option<Vec<Window>>> {
+ Box::pin(async move { tokio::task::spawn_blocking(read).await.ok().flatten() })
+}
+
+/// Every agent the host can read, in the order the chooser lists them.
+pub(super) const READERS: &[Reader] = &[
+ Reader {
+ id: "claude",
+ name: "Claude",
+ source: "claude",
+ found_without_cli: None,
+ read: |_| Box::pin(claude::collect()),
+ },
+ Reader {
+ id: "codex",
+ name: "Codex",
+ source: "Codex CLI",
+ found_without_cli: None,
+ read: |_| Box::pin(codex::collect()),
+ },
+ Reader {
+ id: "antigravity",
+ name: "Google Antigravity",
+ source: "antigravity",
+ found_without_cli: None,
+ read: |hub| Box::pin(antigravity::collect(hub)),
+ },
+ Reader {
+ id: "cursor",
+ name: "Cursor",
+ source: "Cursor",
+ found_without_cli: Some(cursor::login_saved),
+ read: |_| Box::pin(cursor::collect()),
+ },
+ Reader {
+ id: "copilot",
+ name: "GitHub Copilot",
+ source: "Copilot CLI",
+ found_without_cli: None,
+ read: |hub| Box::pin(copilot::collect(hub)),
+ },
+ Reader {
+ id: "grok",
+ name: "Grok Build",
+ source: "Grok CLI",
+ found_without_cli: None,
+ read: |hub| Box::pin(grok::collect(hub)),
+ },
+ Reader { id: "amp", name: "Amp", source: "amp usage", found_without_cli: None, read: |_| Box::pin(amp::collect()) },
+ Reader {
+ id: "auggie",
+ name: "Auggie",
+ source: "auggie account status",
+ found_without_cli: None,
+ read: |hub| Box::pin(auggie::collect(hub)),
+ },
+ Reader {
+ id: "hermes",
+ name: "Hermes Agent",
+ source: "hermes usage",
+ found_without_cli: None,
+ read: |hub| Box::pin(hermes::collect(hub)),
+ },
+ Reader {
+ id: "junie",
+ name: "Junie",
+ source: "JetBrains IDE",
+ found_without_cli: Some(junie::quota_saved),
+ read: |_| blocking(junie::collect),
+ },
+ Reader {
+ id: "kilo",
+ name: "Kilo",
+ source: "kilo profile",
+ found_without_cli: None,
+ read: |hub| Box::pin(kilo::collect(hub)),
+ },
+ Reader {
+ id: "kimi",
+ name: "Kimi Code",
+ source: "kimi",
+ found_without_cli: None,
+ read: |_| blocking(kimi::collect),
+ },
+ Reader {
+ id: "kiro",
+ name: "Kiro CLI",
+ source: "kiro-cli",
+ found_without_cli: None,
+ read: |_| Box::pin(kiro::collect()),
+ },
+ Reader {
+ id: "vibe",
+ name: "Mistral Vibe",
+ source: "vibe logs",
+ found_without_cli: None,
+ read: |_| blocking(vibe::collect),
+ },
+ Reader {
+ id: "omp",
+ name: "oh-my-pi",
+ source: "omp usage",
+ found_without_cli: None,
+ read: |_| Box::pin(omp::collect()),
+ },
+ Reader {
+ id: "opencode",
+ name: "OpenCode",
+ source: "opencode database",
+ found_without_cli: None,
+ read: |_| blocking(opencode::collect),
+ },
+];
+
+fn choice_key(id: &str) -> String {
+ format!("usage.shown.{id}")
+}
+
+/// What the user chose for `id`, when they did.
+fn chosen(store: &Store, id: &str) -> Option<bool> {
+ store.kv_get(&choice_key(id)).map(|value| value == "1")
+}
+
+/// `id`'s ACP registry entry, when it has one.
+pub(super) fn registry(id: &str) -> Option<&'static str> {
+ backends::harness(id).and_then(|harness| harness.registry)
+}
+
+/// A bot here runs this agent, as its own or a fallback.
+pub(super) fn runs(store: &Store, backend: &str) -> bool {
+ backends::harness_of(backend).is_some_and(|harness| used_agents(store).contains(harness.id))
+}
+
+/// The agents this computer's bots run, by their readers' ids.
+fn used_agents(store: &Store) -> HashSet<&'static str> {
+ let bots = store.bots().unwrap_or_else(|error| {
+ tracing::warn!(error = format!("{error:#}"), "couldn't list the bots for their usage");
+ Vec::new()
+ });
+ bots.iter()
+ .filter(|bot| !bot.deleted)
+ .flat_map(|bot| {
+ let fallbacks = bot.config.fallbacks.iter().map(|fallback| fallback.backend.as_str());
+ std::iter::once(bot.config.backend.as_str()).chain(fallbacks)
+ })
+ .filter_map(|backend| backends::harness_of(backend).map(|harness| harness.id))
+ .collect()
+}
+
+/// Whether the agent gets read: a bot runs it, or the user asked for it.
+fn wanted(id: &str, used: &HashSet<&str>, store: &Store) -> bool {
+ used.contains(id) || chosen(store, id) == Some(true)
+}
+
+/// Whether the chooser lists it: there is something on this computer to read it from.
+fn listed(reader: &Reader, used: &HashSet<&str>, store: &Store, held: &HashSet<&str>) -> bool {
+ wanted(reader.id, used, store)
+ || held.contains(reader.id)
+ || backends::installed(reader.id)
+ || reader.found_without_cli.is_some_and(|found| found())
+}
+
+/// Every reader this computer should run.
+pub(super) fn wanted_readers(store: &Store) -> Vec<&'static Reader> {
+ let used = used_agents(store);
+ READERS.iter().filter(|reader| wanted(reader.id, &used, store)).collect()
+}
+
+/// The wanted readers with no reading yet.
+pub(super) fn unread_readers(hub: &Hub) -> Vec<&'static Reader> {
+ let held = held_readings(hub);
+ wanted_readers(&hub.store).into_iter().filter(|reader| !held.contains(reader.id)).collect()
+}
+
+fn held_readings(hub: &Hub) -> HashSet<&'static str> {
+ hub.usage.locked().providers.iter().map(|provider| provider.id).collect()
+}
+
+/// Brings the chooser's list up to date and drops readings nobody wants any more.
+pub(super) fn sync(hub: &Hub) {
+ let store = &hub.store;
+ 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
+ .iter()
+ .filter(|reader| listed(reader, &used, store, &held))
+ .map(|reader| Service {
+ id: reader.id,
+ name: reader.name,
+ registry: registry(reader.id),
+ shown: chosen(store, reader.id).unwrap_or_else(|| used.contains(reader.id)),
+ })
+ .collect();
+ let keep: HashSet<&str> = READERS.iter().map(|reader| reader.id).filter(|id| wanted(id, &used, store)).collect();
+ hub.update_usage(|usage| {
+ usage.services = services;
+ usage.providers.retain(|provider| keep.contains(provider.id));
+ });
+}
+
+fn changed(hub: &Hub) {
+ sync(hub);
+ if !unread_readers(hub).is_empty() {
+ hub.usage_wake.notify_one();
+ }
+}
+
+/// A bot was added, removed or moved to other agents.
+pub fn bots_changed(hub: &Hub) {
+ changed(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" })?;
+ changed(hub);
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::{Provider, near_limit};
+ use super::*;
+ use crate::remote::identity::Identity;
+ use crate::store::{BotConfig, Fallback};
+
+ fn hub() -> std::sync::Arc<Hub> {
+ let dir = std::env::temp_dir().join(format!("codync-usage-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let identity = Identity::load_or_create(&dir).unwrap();
+ Hub::new(store, "h".into(), identity, "t".into(), 0)
+ }
+
+ fn bot(id: &str, backend: &str, fallback: Option<&str>) -> BotConfig {
+ let fallbacks = fallback.map(|backend| Fallback { backend: backend.into(), ..Fallback::default() });
+ BotConfig {
+ id: id.into(),
+ backend: backend.into(),
+ fallbacks: fallbacks.into_iter().collect(),
+ ..serde_json::from_value(serde_json::json!({"id": id, "name": id})).unwrap()
+ }
+ }
+
+ fn reading(id: &'static str, percent: f64) -> Provider {
+ Provider::new(id, id, "test", vec![Window::new("weekly", "Weekly", percent, None)])
+ }
+
+ fn shown(hub: &Hub, id: &str) -> Option<bool> {
+ hub.usage.locked().services.iter().find(|service| service.id == id).map(|service| service.shown)
+ }
+
+ #[test]
+ fn only_the_agents_bots_run_are_shown_and_read_by_default() {
+ let hub = hub();
+ hub.store.save_bot(&bot("b1", "antigravity", Some("codex"))).unwrap();
+ // A registry id is the same agent.
+ hub.store.save_bot(&bot("b2", "claude-acp", None)).unwrap();
+ hub.store.save_bot(&bot("gone", "cursor", None)).unwrap();
+ hub.store.delete_bot("gone").unwrap();
+ sync(&hub);
+ assert_eq!(shown(&hub, "antigravity"), Some(true));
+ assert_eq!(shown(&hub, "codex"), Some(true), "a fallback counts");
+ assert_eq!(shown(&hub, "claude"), Some(true));
+ assert_ne!(shown(&hub, "cursor"), Some(true), "no bot runs Cursor");
+ let read: Vec<_> = wanted_readers(&hub.store).iter().map(|reader| reader.id).collect();
+ assert_eq!(read, ["claude", "codex", "antigravity"], "Cursor's saved login is left alone");
+ }
+
+ #[test]
+ fn hiding_an_agent_a_bot_runs_keeps_reading_it_for_its_limits() {
+ let hub = hub();
+ hub.store.save_bot(&bot("b1", "codex", None)).unwrap();
+ hub.update_usage(|usage| usage.providers = vec![reading("codex", 90.0)]);
+ set_shown(&hub, "codex", false).unwrap();
+ assert_eq!(shown(&hub, "codex"), Some(false));
+ assert_eq!(hub.usage.locked().visible().providers, []);
+ assert!(near_limit(&hub, "codex"), "background work still goes by its limits");
+ assert_eq!(wanted_readers(&hub.store).len(), 1);
+ }
+
+ #[test]
+ fn turning_an_agent_on_reads_it_without_a_bot_and_off_drops_its_reading() {
+ let hub = hub();
+ set_shown(&hub, "cursor", true).unwrap();
+ assert_eq!(shown(&hub, "cursor"), Some(true));
+ assert_eq!(unread_readers(&hub).len(), 1, "it gets read right away");
+ hub.update_usage(|usage| usage.providers.push(reading("cursor", 10.0)));
+ assert_eq!(hub.usage.locked().visible().providers.len(), 1);
+ set_shown(&hub, "cursor", false).unwrap();
+ assert_eq!(hub.usage.locked().providers, [], "no stale reading stays behind");
+ assert!(wanted_readers(&hub.store).is_empty());
+ }
+
+ #[test]
+ fn a_bot_runs_an_agent_by_either_of_its_ids() {
+ let hub = hub();
+ hub.store.save_bot(&bot("b1", "grok-build", Some("antigravity"))).unwrap();
+ assert!(runs(&hub.store, "grok"));
+ assert!(runs(&hub.store, "antigravity-acp"), "a fallback counts");
+ assert!(!runs(&hub.store, "cursor"));
+ }
+
+ /// A reader whose id is no harness's is unreachable: no bot's `backend` finds it, and its CLI is never seen.
+ #[test]
+ fn every_reader_is_a_harness() {
+ assert_eq!(READERS.iter().map(|reader| reader.id).find(|id| backends::harness(id).is_none()), None);
+ }
+
+ #[test]
+ fn only_a_known_agent_can_be_chosen() {
+ let hub = hub();
+ assert!(set_shown(&hub, "not-an-agent", true).is_err());
+ assert_eq!(hub.store.kv_get(&choice_key("not-an-agent")), None);
+ }
+}
diff --git a/host/src/usage/vibe.rs b/host/src/usage/vibe.rs
index b5db7c99..72141ed9 100644
--- a/host/src/usage/vibe.rs
+++ b/host/src/usage/vibe.rs
@@ -123,7 +123,7 @@ fn token_count(value: &Value) -> Option<f64> {
fn message_time(value: &Value) -> Option<i64> {
let stamp = ["created_at", "timestamp"].iter().find_map(|key| value.get(*key).filter(|v| !v.is_null()))?;
if let Some(text) = stamp.as_str() {
- return chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis());
+ return super::iso_ms(text);
}
let n = stamp.as_i64().or_else(|| stamp.as_f64().and_then(super::finite_i64))?;
Some(if n > 100_000_000_000 { n } else { n.saturating_mul(1000) })
diff --git a/host/tests/agent_checks_e2e.rs b/host/tests/agent_checks_e2e.rs
index 37977b70..339316b9 100644
--- a/host/tests/agent_checks_e2e.rs
+++ b/host/tests/agent_checks_e2e.rs
@@ -32,7 +32,7 @@ fn call(base: &str, home: &Path, method: &str) -> reqwest::RequestBuilder {
reqwest::Client::new()
.post(format!("{base}/api/{method}"))
.bearer_auth(token.trim())
- .json(&serde_json::json!({"refresh": true, "backend": "cursor"}))
+ .json(&serde_json::json!({"refresh": true, "backend": "cursor", "id": "claude", "shown": true}))
}
fn alive(pid: &str) -> bool {
@@ -52,6 +52,8 @@ async fn a_stopped_host_ends_the_checks_it_was_running() {
("CODYNC_AGENT_CHECKS", "on".as_ref()),
];
let (mut host, base) = common::serve_with(&home, &env).await;
+ // No bot runs Claude here, so its usage is only read once it's asked for.
+ assert!(call(&base, &home, "setUsageShown").send().await.unwrap().status().is_success());
// A check that starts the agent, which never answers: the host is still waiting when it stops.
tokio::spawn(call(&base, &home, "agentAuth").send());
let read = || std::fs::read_to_string(&log).unwrap_or_default();
@@ -72,13 +74,63 @@ async fn a_stopped_host_ends_the_checks_it_was_running() {
let _ = std::fs::remove_dir_all(&home);
}
+/// The background reading starts the agent so that it can't open a browser, and asks it without a session.
+#[tokio::test]
+async fn a_usage_reading_starts_the_agent_with_no_browser_to_open() {
+ if common::python_missing() {
+ return;
+ }
+ let home = std::env::temp_dir().join(format!("codync-agent-checks-{}", uuid::Uuid::new_v4()));
+ let bin = home.join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/usage_command_agent.py");
+ // Each start logs to a file named for the `BROWSER` it got: the host's sign-in checks start the agent too.
+ let script = format!(
+ "#!/bin/sh\nUSAGE_AGENT_LOG=\"{home}/calls-${{BROWSER:-none}}.log\" USAGE_AGENT_COMMAND=usage PATH='{path}' exec {python} '{fixture}'\n",
+ home = home.display(),
+ path = std::env::var("PATH").unwrap(),
+ python = common::python(),
+ fixture = fixture.display(),
+ );
+ let file = bin.join("grok");
+ std::fs::write(&file, script).unwrap();
+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let path = std::env::join_paths([bin.as_path(), Path::new("/usr/bin"), Path::new("/bin")]).unwrap();
+ let env = [
+ ("PATH", path.as_os_str()),
+ ("HOME", home.as_os_str()),
+ ("ZDOTDIR", home.as_os_str()),
+ ("CODYNC_AGENT_CHECKS", "on".as_ref()),
+ ];
+ let (mut host, base) = common::serve_with(&home, &env).await;
+ let token = std::fs::read_to_string(home.join("token")).unwrap();
+ let client = reqwest::Client::new();
+ let post = |method: &str, body: serde_json::Value| {
+ client.post(format!("{base}/api/{method}")).bearer_auth(token.trim()).json(&body).send()
+ };
+ let turned_on = post("setUsageShown", serde_json::json!({"id": "grok", "shown": true})).await.unwrap();
+ assert!(turned_on.status().is_success());
+ let read = || std::fs::read_to_string(home.join("calls-true.log")).unwrap_or_default();
+ common::eventually("the host read Grok's plan", Duration::from_secs(30), async || read().contains("x.ai/billing"))
+ .await;
+ let calls = read();
+ assert!(!calls.contains("session/"), "no session and no prompt: {calls}");
+ common::eventually("Grok's reading landed", Duration::from_secs(10), async || {
+ let usage: serde_json::Value = post("usage", serde_json::json!({})).await.unwrap().json().await.unwrap();
+ usage["providers"][0]["id"] == "grok" && usage["providers"][0]["windows"][0]["label"] == "Weekly"
+ })
+ .await;
+ common::stop(&mut host);
+ let _ = std::fs::remove_dir_all(&home);
+}
+
#[tokio::test]
async fn a_test_host_never_runs_the_agent_clis() {
let home = std::env::temp_dir().join(format!("codync-agent-checks-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&home).unwrap();
let (path, log) = slow_agents(&home);
let (mut host, base) = common::serve_with(&home, &[("PATH", path.as_os_str())]).await;
- for method in ["refreshBackends", "usage", "agentAuth"] {
+ for method in ["refreshBackends", "setUsageShown", "usage", "agentAuth"] {
let response = call(&base, &home, method).send().await.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
diff --git a/host/tests/fixtures/usage_command_agent.py b/host/tests/fixtures/usage_command_agent.py
new file mode 100644
index 00000000..a3934019
--- /dev/null
+++ b/host/tests/fixtures/usage_command_agent.py
@@ -0,0 +1,49 @@
+# A minimal ACP agent for the usage readings: logs each method it's asked, advertises the slash
+# command named by USAGE_AGENT_COMMAND once a session opens, answers a prompt with a report, and
+# answers Grok's billing extension.
+import json, os, sys
+
+log = os.environ["USAGE_AGENT_LOG"]
+command = os.environ["USAGE_AGENT_COMMAND"]
+
+
+def send(message):
+ sys.stdout.write(json.dumps(message) + "\n")
+ sys.stdout.flush()
+
+
+def update(session, body):
+ send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": session, "update": body}})
+
+
+def answer(request, result):
+ send({"jsonrpc": "2.0", "id": request["id"], "result": result})
+
+
+def advertise(session):
+ update(session, {"sessionUpdate": "available_commands_update", "availableCommands": [{"name": command}]})
+
+
+for line in sys.stdin:
+ request = json.loads(line)
+ method = request.get("method")
+ if method is None:
+ continue
+ with open(log, "a") as calls:
+ calls.write(method + "\n")
+ if method == "initialize":
+ answer(request, {"protocolVersion": 1, "agentCapabilities": {"sessionCapabilities": {"resume": {}}}})
+ elif method == "x.ai/billing":
+ period = {"type": "USAGE_PERIOD_TYPE_WEEKLY"}
+ answer(request, {"config": {"creditUsagePercent": 42.5, "currentPeriod": period}})
+ elif method == "session/new":
+ answer(request, {"sessionId": "s1"})
+ advertise("s1")
+ elif method == "session/resume":
+ # A resumed session replays its history, which isn't the command's reply.
+ update("s1", {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "old "}})
+ answer(request, {})
+ advertise("s1")
+ elif method == "session/prompt":
+ update("s1", {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "the report"}})
+ answer(request, {"stopReason": "end_turn"})
diff --git a/host/tests/usage_chooser_e2e.rs b/host/tests/usage_chooser_e2e.rs
new file mode 100644
index 00000000..d5b59b3e
--- /dev/null
+++ b/host/tests/usage_chooser_e2e.rs
@@ -0,0 +1,87 @@
+//! 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.
+
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+mod common;
+
+use common::host::Host;
+use serde_json::{Value, json};
+use std::time::Duration;
+use tokio::sync::mpsc::UnboundedReceiver;
+
+/// The next `usage` a client gets that `holds`: from a catch-up's `hello`, or a live event.
+async fn usage_until(events: &mut UnboundedReceiver<Value>, what: &str, holds: impl Fn(&Value) -> bool) -> Value {
+ let wait = async {
+ loop {
+ let event = events.recv().await.expect("the stream stays open");
+ if matches!(event["type"].as_str(), Some("hello" | "usage")) && holds(&event["usage"]) {
+ return event;
+ }
+ }
+ };
+ tokio::time::timeout(Duration::from_secs(20), wait).await.unwrap_or_else(|_| panic!("no usage where {what}"))
+}
+
+fn shown(usage: &Value, id: &str) -> Option<bool> {
+ usage["services"].as_array()?.iter().find(|service| service["id"] == id)?["shown"].as_bool()
+}
+
+fn has_reading(usage: &Value, id: &str) -> bool {
+ usage["providers"].as_array().is_some_and(|providers| providers.iter().any(|provider| provider["id"] == id))
+}
+
+/// Claude's status line, which needs no CLI: the one reading a test host can get.
+async fn claude_reading(host: &Host) {
+ let response = reqwest::Client::new()
+ .post(format!("{}/ingest/statusline", host.base))
+ .bearer_auth(&host.token)
+ .json(&json!({"rate_limits": {"five_hour": {"used_percentage": 12.0}}}))
+ .send()
+ .await
+ .unwrap();
+ assert!(response.status().is_success());
+}
+
+#[tokio::test]
+async fn a_choice_reaches_the_other_clients_and_a_hidden_reading_stays_on_the_host() {
+ let host = Host::start().await;
+ let mut other_client = host.events().await;
+ let bot = json!({"name": "Claude bot", "backend": "claude", "connectors": [], "permission": "ask"});
+ host.call("createBot", bot).await;
+
+ usage_until(&mut other_client, "a new bot's agent is listed and on", |usage| shown(usage, "claude") == Some(true))
+ .await;
+ claude_reading(&host).await;
+ let landed = usage_until(&mut other_client, "Claude's reading landed", |usage| has_reading(usage, "claude")).await;
+ assert_eq!(landed["usage"]["providers"][0]["registry"], "claude-acp");
+
+ let answer = host.call("setUsageShown", json!({"id": "claude", "shown": false})).await;
+ assert_eq!(shown(&answer, "claude"), Some(false));
+ assert!(!has_reading(&answer, "claude"), "{answer}");
+ usage_until(&mut other_client, "Claude was hidden", |usage| {
+ shown(usage, "claude") == Some(false) && !has_reading(usage, "claude")
+ })
+ .await;
+
+ let mut reconnected = host.events().await;
+ let hello = reconnected.recv().await.unwrap();
+ assert_eq!(hello["type"], "hello", "{hello}");
+ assert_eq!(shown(&hello["usage"], "claude"), Some(false));
+ assert!(!has_reading(&hello["usage"], "claude"), "{hello}");
+ assert!(!has_reading(&host.call("usage", json!({})).await, "claude"));
+
+ // A bot still runs Claude, so the host kept reading it: the bars are back as soon as it's on.
+ host.call("setUsageShown", json!({"id": "claude", "shown": true})).await;
+ usage_until(&mut other_client, "Claude was shown again", |usage| {
+ shown(usage, "claude") == Some(true) && has_reading(usage, "claude")
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn an_agent_it_does_not_know_can_not_be_chosen() {
+ let host = Host::start().await;
+ let error = host.refused("setUsageShown", json!({"id": "not-an-agent", "shown": true})).await;
+ assert!(error.contains("unknown usage service"), "{error}");
+}
diff --git a/web/app/privacy/page.tsx b/web/app/privacy/page.tsx
index eae819ba..b9467d53 100644
--- a/web/app/privacy/page.tsx
+++ b/web/app/privacy/page.tsx
@@ -9,7 +9,7 @@ export default function Privacy() {
<main className="flex-1 flex flex-col items-center px-6 py-16">
<article className="max-w-2xl w-full space-y-6">
<h1 className="text-3xl font-bold text-white">Privacy Policy</h1>
- <p className="text-neutral-400 text-sm">Last updated: November 3, 2026</p>
+ <p className="text-neutral-400 text-sm">Last updated: November 6, 2026</p>
<Section title="Overview">
Codync is an independent open-source project by leepokai (&quot;we&quot;, &quot;us&quot;). It lets you message the AI agents that run on your own computer. It is built so that your files, conversations and credentials stay on your devices.
@@ -20,7 +20,7 @@ export default function Privacy() {
<li><strong>Bots and conversations</strong> are stored by the Codync host on your computer (in <code>~/.codync</code>). Your phone keeps a cache so the app opens instantly.</li>
<li><strong>Your phone talks to your computer</strong> directly over your local network or Tailscale, or, away from home, through our relay, which only forwards end-to-end encrypted data it can&apos;t read. A message you send while your computer is offline waits in the relay, still encrypted for your computer, for up to 24 hours, and is deleted once delivered. If you point a computer at a relay you run yourself, its traffic goes through that relay instead of ours and we receive none of it; its notifications still go through our push relay.</li>
<li><strong>Agents run with your own logins</strong> (Claude Code, Codex, Cursor and others). Codync never sees or stores their credentials.</li>
- <li><strong>Usage limits</strong> are read locally from the agents installed on your computer. Only percentages reach your phone.</li>
+ <li><strong>Usage limits</strong> are read on your computer, only for the agents your bots run and the ones you turn on. Your phone gets the limits as percentages, plus any balance or credits an agent reports as text.</li>
</ul>
</Section>
diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdx
index 583e1b6c..c3600e88 100644
--- a/web/content/docs/agents.mdx
+++ b/web/content/docs/agents.mdx
@@ -6,7 +6,11 @@ If an agent's login stops working (for example, signing in somewhere else revoke
## Usage limits
-On desktop, open **Settings > Usage** to see the limits reported by your connected computers, including Cursor. The host refreshes usage every five minutes. Unified Cursor plans, including Super, show one **Weekly** allowance with its next reset. Older Cursor plans retain their monthly usage readings.
+On 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.
+
+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.
Cursor usage works with the CLI's saved sign-in file on Linux and Windows, or the Cursor desktop app's sign-in. On macOS, a CLI login stored only in Keychain needs the desktop app signed in too; CLI file storage also works. You do not need to install the Cursor desktop app on a Linux or Windows host just to report usage.
diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdx
index 1bc52eea..e60dcec2 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 from the agents installed on your computer. Claude Code uses its usage report and status line. The signed-in Codex CLI reports current account limits without starting a conversation or model turn. oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie are read the same way, from a command, a local database or an IDE file. Cursor has no usage command: Codync uses the sign-in saved by the Cursor app or CLI on this computer and asks Cursor's dashboard service for unified-plan usage, or cursor.com for a legacy-plan summary. Nothing else is sent with an agent's login. To see them:
+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:
-- **iPhone:** the **State** tab, then **Usage limits**. There's also a Usage widget.
+- **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`.
+- **Terminal UI:** press `U`, then `s` for the switches.
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.
diff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdx
index 4af34d58..17f07394 100644
--- a/web/content/docs/privacy.mdx
+++ b/web/content/docs/privacy.mdx
@@ -5,7 +5,7 @@ Codync keeps your work on your computer. The phone and desktop apps are windows
- **Bots, conversations, routines and memory** are kept by the host in `~/.codync` on your computer. Your phone keeps a cache so the app opens quickly.
- **Agents run with their own logins.** Claude Code, Codex and the other agents use the sign-ins you set up on the computer. Your prompts go from the agent to its provider, as they would without Codync.
- **Secrets are encrypted.** Connector credentials, voice API keys and other keys you enter in Codync are stored encrypted on the computer. The encryption key is held by the system's credential store (Keychain on macOS, Secret Service on Linux, Credential Manager on Windows). They're never sent to Codync's cloud.
-- **Usage limits are read on your computer.** The host reads them from the agents installed there: Claude Code's usage command and status line, the Codex CLI's read-only current-account query, and the same kind of local report from oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie. The Codex query does not start a conversation or model turn, and its CLI manages its own sign-in. Cursor is the exception. It has no local report, so the host reads the sign-in Cursor saved and asks Cursor's dashboard service for unified-plan usage, or cursor.com for a legacy-plan summary. That token is not logged, and Codync does not call any other provider's API with an agent's login. To read Claude Code's limits, `codync-host install` routes its status line through `codync-host statusline`; a status line you already had keeps working and is restored when you uninstall.
+- **Usage limits are read on your computer,** and only for the agents your bots run and the ones you turn on in the Usage screen. An agent you don't use is never started, and its saved sign-in is never read. Claude Code uses its usage command and status line, and the Codex CLI a read-only current-account query. oh-my-pi, Amp, Hermes Agent, Auggie, Kilo, Kiro, Kimi, OpenCode, Mistral Vibe and Junie report through their own command, a local database or an IDE file. GitHub Copilot (`account.getQuota`), Grok Build (`x.ai/billing`) and Antigravity (`/usage`, or its running app) are read by starting the agent's own server on your computer, which asks its provider with the agent's login; the host never handles that login. None of these starts a conversation or model turn. Cursor is the exception. It has no such report, so the host reads the sign-in Cursor saved and asks Cursor's dashboard service for unified-plan usage, or cursor.com for a legacy-plan summary. That token is not logged, and Codync does not call any other provider's API with an agent's login. To read Claude Code's limits, `codync-host install` routes its status line through `codync-host statusline`; a status line you already had keeps working and is restored when you uninstall.
## The relay