Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: show plan limits for the other installed agents
forwardxub8f76feaf57f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2b12f5e4..3e98f278 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).-- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.+- 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`, Codex rollout files, and the other agents' local commands, databases and IDE files. Cursor is the one provider call: the token Cursor saved, then `cursor.com/api/usage-summary`. Never call any other provider API with agent credentials.- 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 changesdiff --git a/README.md b/README.mdindex d296997a..af25cdc0 100644--- a/README.md+++ b/README.md@@ -90,7 +90,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 your local installs, with no extra login: Claude via `claude -p /usage` (a local command, no model call) plus Claude Code's status line, Codex via `~/.codex/sessions`. The phone, widgets and menu bar only see percentages.+- **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 Codex uses `~/.codex/sessions`. 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.- **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.mdindex 38db4f65..14716044 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -15,6 +15,7 @@ else a generic "Bug fixes and improvements" line. Delete old sections.- 擴充套件一次顯示一個分類:智慧體、聯結器或技能,每個列表都分頁。點列表兩側的圓形按鈕或左右滑動翻頁,每頁可選 6、10、20 或 50 筆。- 電腦使用自建中繼時,設定和連線狀態會顯示該中繼的地址,不再一律寫成 Cloudflare。- 可以建立使用 WorkBuddy 的 Bot,在聊天裡登入即可。+- 用量也會顯示這台電腦上其他 agent 的額度。Cursor 會用本機登入向 cursor.com 查詢。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.@@ -22,6 +23,7 @@ else a generic "Bug fixes and improvements" line. Delete old sections.- Extensions shows Agents, Connectors or Skills in pages: tap the round buttons or swipe, 6 to 50 per page.- A private relay shows its address in Settings and status.- Bots can run WorkBuddy; sign in from the chat.+- Adds other agents' limits. Cursor asks cursor.com.## 2.26.0diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.ktindex 0c1dbfe6..baf06501 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@@ -50,6 +50,6 @@ class UsageScreenTest {compose.onNodeWithText("Usage shows up once a computer is connected.").assertIsDisplayed()compose.runOnUiThread { state.value = state.value.copy(computers = listOf(Computer("fixture", "Acceptance computer", "fixture"))) }compose.onNodeWithText("No usage yet").assertIsDisplayed()- compose.onNodeWithText("Your computer reads the limits from Claude Code and Codex.").assertIsDisplayed()+ compose.onNodeWithText("Your computer reads plan limits from the agents installed on it.").assertIsDisplayed()}}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.ktindex 05989a28..a7243b49 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@@ -190,7 +190,7 @@ private fun dark(context: Context) = context.resources.configuration.uiMode andText("${phrase(top.title)} · ${phrase("highest usage")}", GlanceModifier.padding(bottom = 6.dp), style = style(11f, secondary), maxLines = 2)}}- for (window in provider.windows.take(if (layout == ProviderLayout.Large) 4 else 2)) WindowRow(context, window, tint)+ for (window in provider.limits.take(if (layout == ProviderLayout.Large) 4 else 2)) WindowRow(context, window, tint)}}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.ktindex cff66214..4568851a 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@@ -35,6 +35,7 @@ import androidx.compose.ui.unit.dpimport com.codync.android.core.LinkStateimport com.codync.android.core.UsageProviderimport com.codync.android.core.UsageReport+import com.codync.android.core.UsageWindowimport com.codync.android.design.*import com.kyant.shapes.RoundedRectangleimport java.time.Instant@@ -63,7 +64,7 @@ import kotlin.math.roundToIntPullToRefresh({ 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 the limits from Claude Code and Codex.")+ if (report.providers.isEmpty()) EmptyUsage("No usage yet", "Your computer reads plan limits from the agents installed on it.")}}}@@ -106,7 +107,7 @@ import kotlin.math.roundToIntexit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {for (window in provider.windows) {- DetailRow(tr(window.title), percent(window.percent))+ DetailRow(tr(window.title), reading(window))val reset = window.resetsShort()if (reset != null) DetailRow(tr("Resets"), resetLine(reset))}@@ -117,6 +118,8 @@ import kotlin.math.roundToInt}}+private fun reading(window: UsageWindow) = window.text?.takeIf { it.isNotBlank() } ?: percent(window.percent)+private fun percent(value: Double?) = value?.takeIf { it.isFinite() }?.let { "${it.roundToInt()}%" } ?: "—"/** "Oct 17, 2026 at 10:20 PM", as iOS formats an abbreviated date with a short time. */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.ktindex ca4592f7..164d9a42 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@@ -184,7 +184,7 @@ internal fun until(at: Long, now: Long): String {color = if ((top.percent ?: 0.0) >= 90) Palette.danger else Palette.text)Text("${tr(top.title)} · ${tr("highest usage")}", Modifier.padding(bottom = 6.dp), style = Type.system(11f), color = Palette.secondary, maxLines = 2, overflow = TextOverflow.Ellipsis)}- for (window in provider.windows.take(if (layout == ProviderLayout.Large) 4 else 2)) {+ for (window in provider.limits.take(if (layout == ProviderLayout.Large) 4 else 2)) {Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {Row(verticalAlignment = Alignment.CenterVertically) {Text(tr(window.title), Modifier.weight(1f), style = Type.system(11f).medium, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.ktindex ab2d26f0..a5bdac38 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@@ -15,7 +15,8 @@ import java.util.Locale@Serializable data class UsageProvider(val id: String, val name: String, val windows: List<UsageWindow> = emptyList(),val source: String = "", val updatedAt: Long? = null) {- val tightest: UsageWindow? get() = windows.filter { it.percent?.isFinite() == true }.maxByOrNull { requireNotNull(it.percent) }+ val limits: List<UsageWindow> get() = windows.filter { it.text.isNullOrBlank() }+ val tightest: UsageWindow? get() = limits.filter { it.percent?.isFinite() == true }.maxByOrNull { requireNotNull(it.percent) }val sourceLabel: String get() = when (source) {"claude" -> "Claude Code"; "statusline" -> "Claude Code status line""agent" -> "A running bot"; "sessions" -> "Codex sessions"; "" -> "Unknown source"; else -> source@@ -23,7 +24,7 @@ import java.util.Locale}@Serializable data class UsageWindow(val id: String, val label: String, val percent: Double? = null,- val resetsAt: Long? = null, val resetsText: String? = null) {+ val resetsAt: Long? = null, val resetsText: String? = null, val text: String? = null) {val reportedPercent: Double? get() = percent?.takeIf { it.isFinite() }val barFraction: Float? get() = reportedPercent?.coerceIn(0.0, 100.0)?.div(100)?.toFloat()diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.ktindex 91328ef9..d22ad445 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt@@ -17,7 +17,7 @@ data class ProviderLimit(val provider: String, val window: UsageWindow)/** Every provider's limits for the Usage limits widget: the tightest first (its headline), then the rest in report order. */fun usageLimits(report: UsageReport): List<ProviderLimit> {- val all = report.providers.flatMap { provider -> provider.windows.map { ProviderLimit(provider.name, it) } }+ val all = report.providers.flatMap { provider -> provider.limits.map { ProviderLimit(provider.name, it) } }val top = all.withIndex().maxByOrNull { it.value.window.reportedPercent ?: -1.0 } ?: return emptyList()return listOf(top.value) + all.filterIndexed { index, _ -> index != top.index }}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.ktindex 661a1cc3..19d0fde2 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@@ -13,6 +13,11 @@ class UsageTest {assertNull(provider.windows.first().barFraction)assertEquals("zero", provider.tightest?.id)assertEquals(0.0, provider.windows.last().reportedPercent!!, 0.0)+ val noted = UsageProvider("vibe", "Mistral Vibe", listOf(+ UsageWindow("cost", "Cost today", 90.0, text = "$1.50"),+ UsageWindow("five_hour", "5-hour", 10.0)))+ assertEquals(listOf("five_hour"), noted.limits.map { it.id })+ assertEquals("five_hour", noted.tightest?.id)assertTrue(UsageReport.decode(WireJson.parseToJsonElement("{}" )).providers.isEmpty())}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.ktindex 51efc0ec..9f8c4595 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt@@ -26,6 +26,8 @@ class WidgetFeedTest {assertEquals(listOf("Codex Weekly"), usageLimits(UsageReport(listOf(UsageProvider("codex", "Codex",listOf(UsageWindow("secondary", "Weekly")))))).map { "${it.provider} ${it.window.label}" })assertTrue(usageLimits(UsageReport()).isEmpty())+ val noted = UsageReport(listOf(UsageProvider("vibe", "Mistral Vibe", listOf(UsageWindow("cost", "Cost today", 0.0, text = "$1.50")))))+ assertTrue(usageLimits(noted).isEmpty())}@Test fun `the most urgent bot is the first at work and nobody when all are quiet`() {diff --git a/apps/desktop/src/renderer/views/island/IslandUsage.tsx b/apps/desktop/src/renderer/views/island/IslandUsage.tsxindex 20b72f2c..0a034560 100644--- a/apps/desktop/src/renderer/views/island/IslandUsage.tsx+++ b/apps/desktop/src/renderer/views/island/IslandUsage.tsx@@ -4,7 +4,7 @@ import { usePixelRatio } from '../../lib/theme'import { useResetLine, useTr } from '../../lib/use-language'import { UsageBar } from '../usage/UsageBar'import { mascotDataURL } from '../usage/ProviderMascot'-import { providerTintCSS, resetDescription, tightest, windowTitle } from '../usage/usage-model'+import { providerTintCSS, resetDescription, tightest, windowReading, windowTitle } from '../usage/usage-model'import type { IslandModel } from './island-model'// Codync's own part of the island: the plan limits the menu bar already tracks (local usage@@ -64,7 +64,7 @@ export function UsageView({ model }: { model: IslandModel }) {<div className="island-card island-empty"><span className="island-empty-text"><span className="island-title">No usage yet.</span>- <span className="island-subtitle">Claude Code and Codex limits show up here once a bot has used them.</span>+ <span className="island-subtitle">{tr('Plan limits show up here once an agent reports them.')}</span></span></div>)@@ -80,9 +80,15 @@ export function UsageView({ model }: { model: IslandModel }) {{provider.windows.slice(0, 3).map((w) => (<div key={w.id} className="island-usage-row"><span className="island-usage-title">{tr(windowTitle(w))}</span>- <UsageBar percent={w.percent} tint={providerTintCSS(provider.id)} />- <span className="island-usage-value">{`${Math.round(w.percent)}%`}</span>- <span className="island-usage-reset">{line(resetDescription(w) ?? '')}</span>+ {w.text ? (+ <span className="island-usage-note">{w.text}</span>+ ) : (+ <>+ <UsageBar percent={w.percent} tint={providerTintCSS(provider.id)} />+ <span className="island-usage-value">{windowReading(w)}</span>+ <span className="island-usage-reset">{line(resetDescription(w) ?? '')}</span>+ </>+ )}</div>))}</div>diff --git a/apps/desktop/src/renderer/views/island/island-views.css b/apps/desktop/src/renderer/views/island/island-views.cssindex 10115290..8a82d79d 100644--- a/apps/desktop/src/renderer/views/island/island-views.css+++ b/apps/desktop/src/renderer/views/island/island-views.css@@ -319,6 +319,13 @@text-align: right;font-variant-numeric: tabular-nums;}+.island-usage-note {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ text-align: right;+}.island-usage-reset {width: 66px;flex: none;diff --git a/apps/desktop/src/renderer/views/settings/UsageLimits.tsx b/apps/desktop/src/renderer/views/settings/UsageLimits.tsxindex d975873b..95f01c6c 100644--- a/apps/desktop/src/renderer/views/settings/UsageLimits.tsx+++ b/apps/desktop/src/renderer/views/settings/UsageLimits.tsx@@ -5,7 +5,7 @@ import { prefs, usePref } from '../../lib/prefs'import { useResetLine } from '../../lib/use-language'import { ProviderMascot } from '../usage/ProviderMascot'import { UsageBar } from '../usage/UsageBar'-import { providerTintCSS, resetDescription, windowTitle } from '../usage/usage-model'+import { providerTintCSS, resetDescription, windowReading, windowTitle } from '../usage/usage-model'import './settings.css'/** Every limit as a bar under its provider, the way the menu bar lists them. */@@ -23,9 +23,15 @@ export function UsageLimits({ usage }: { usage: Usage }) {{provider.windows.map((w) => (<HStack key={w.id} gap={10} className="settings-usage-row"><Text tone="text" truncate className="settings-usage-title">{windowTitle(w)}</Text>- <UsageBar percent={w.percent} tint={providerTintCSS(provider.id)} />- <Text tone="text" tabular className="settings-usage-percent">{Math.round(w.percent)}%</Text>- <Text tone="secondary" truncate className="settings-usage-reset">{resetLine(resetDescription(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)}</Text>+ <Text tone="secondary" truncate className="settings-usage-reset">{resetLine(resetDescription(w) ?? '')}</Text>+ </>+ )}</HStack>))}</VStack>diff --git a/apps/desktop/src/renderer/views/settings/settings.css b/apps/desktop/src/renderer/views/settings/settings.cssindex 897d9263..be43d0e7 100644--- a/apps/desktop/src/renderer/views/settings/settings.css+++ b/apps/desktop/src/renderer/views/settings/settings.css@@ -148,6 +148,11 @@flex: none;text-align: right;}+.settings-usage-note {+ flex: 1;+ min-width: 0;+ text-align: right;+}.settings-usage-reset {width: 130px;flex: none;diff --git a/apps/desktop/src/renderer/views/tray-summary.ts b/apps/desktop/src/renderer/views/tray-summary.tsindex 2281d04e..85690221 100644--- a/apps/desktop/src/renderer/views/tray-summary.ts+++ b/apps/desktop/src/renderer/views/tray-summary.ts@@ -7,7 +7,7 @@ import { resetLine, resolvedLanguage, translate } from '../lib/l10n'import { prefs, usePref } from '../lib/prefs'import { avatarColor, isDark, palette } from '../lib/theme'import type { AppModel } from '../store/app-model'-import { providerTint, resetDate, untilText, windowTitle } from './usage/usage-model'+import { providerTint, resetDate, untilText, windowReading, windowTitle } from './usage/usage-model'import { drawMascot, nearlyUsedUp } from './usage/ProviderMascot'const isMac = window.codync.platform === 'darwin'@@ -89,7 +89,8 @@ function usageLine(w: UsageWindow) {const title = translate(windowTitle(w), preference, system)const reset = resetDate(w)const spoken = reset ? resetLine(`resets in ${untilText(reset)}`, preference, system) : ''- return `${title} · ${Math.round(w.percent)}%${spoken ? ` · ${spoken}` : ''}`+ const reading = windowReading(w)+ return `${title} · ${reading}${spoken ? ` · ${spoken}` : ''}`}/** Sends what the menu bar shows whenever the stores change. */@@ -125,7 +126,7 @@ export function useTraySummary(app: AppModel) {usage: (local?.usage.providers ?? []).map((p) => ({name: p.name,icon: canvasImage(`mascot|${p.id}|${iconStyle}|${nearlyUsedUp(p)}`, 16, 16, (ctx) => drawMascot(ctx, p, 16, iconStyle, isDark())),- lines: p.windows.map((w) => ({ title: usageLine(w), bar: barIcon(p.id, w) })),+ lines: p.windows.map((w) => ({ title: usageLine(w), bar: w.text ? null : barIcon(p.id, w) })),})),screen: screen? {diff --git a/apps/desktop/src/renderer/views/usage/usage-model.ts b/apps/desktop/src/renderer/views/usage/usage-model.tsindex a5f6fb49..8887d709 100644--- a/apps/desktop/src/renderer/views/usage/usage-model.ts+++ b/apps/desktop/src/renderer/views/usage/usage-model.ts@@ -15,7 +15,16 @@ export const providerRegistry = (id: string) => (['claude', 'codex'].includes(id/** The character that stands for this provider. */export const mascotShape = (id: string) => (id === 'codex' ? 'hex' : 'blob')-export const tightest = (p: UsageProvider) => p.windows.reduce<UsageWindow | null>((a, w) => (!a || w.percent > a.percent ? w : a), null)+/** A plan window. Notes (today's tokens, a dollar balance) are not limits. */+export const isLimit = (w: UsageWindow) => !w.text++export const tightest = (p: UsageProvider) =>+ p.windows.filter(isLimit).reduce<UsageWindow | null>((a, w) => (!a || w.percent > a.percent ? w : a), null)++/** The percent, or the note when this window isn't a share of a cap. */+export function windowReading(w: UsageWindow) {+ return w.text || `${Math.round(w.percent)}%`+}/** "Session" for the 5-hour window, "Opus" for "Weekly · Opus", else the label. */export function windowTitle(w: UsageWindow) {diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex cdc5b592..0547e80f 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -377,6 +377,8 @@ export interface UsageWindow {percent: numberresetsAt?: number | nullresetsText?: string | null+ /** A reading that isn't a share of a cap. Shown instead of the percent, and never the tightest limit. */+ text?: string | null}export interface UsageProvider {diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swift b/apps/ios/Kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swiftindex c604954d..2d52dc94 100644--- a/apps/ios/Kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swift@@ -20,7 +20,7 @@ public struct AccessoryWidgetCard: View {private var count: Int { needs > 0 ? needs : working > 0 ? working : bots.count }private var botLabel: String { needs > 0 ? (needs == 1 ? "needs you" : "need you") : working > 0 ? "working" : (bots.count == 1 ? "bot" : "bots") }private var top: (name: String, window: UsageWindow)? {- usage.providers.flatMap { p in p.windows.map { (name: p.name, window: $0) } }+ usage.providers.flatMap { p in p.limits.map { (name: p.name, window: $0) } }.max { $0.window.percent < $1.window.percent }}private var headline: String {diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swiftindex f8573e65..5dbcd9be 100644--- a/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/ProviderMascot.swift@@ -34,7 +34,10 @@ public extension UsageProvider {/// The character that stands for this provider.var mascotShape: String { id == "codex" ? "hex" : "blob" }- var tightest: UsageWindow? { windows.max { $0.percent < $1.percent } }+ /// Plan windows. A note (today's tokens, a dollar balance) is not a limit.+ var limits: [UsageWindow] { windows.filter { $0.text == nil } }++ var tightest: UsageWindow? { limits.max { $0.percent < $1.percent } }}public extension UsageWindow {diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/WidgetCards.swift b/apps/ios/Kit/Sources/CodyncKit/Design/WidgetCards.swiftindex f67d7464..04a2f87f 100644--- a/apps/ios/Kit/Sources/CodyncKit/Design/WidgetCards.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/WidgetCards.swift@@ -62,7 +62,7 @@ public struct ProviderWidgetCard: View {}.padding(.vertical, 4)}- ForEach(provider.windows.prefix(layout == .large ? 4 : 2)) { window in+ ForEach(provider.limits.prefix(layout == .large ? 4 : 2)) { window inVStack(alignment: .leading, spacing: 3) {HStack(alignment: .firstTextBaseline) {Text(L10n.tr(window.title))@@ -95,7 +95,7 @@ public struct ProviderWidgetCard: View {}private var accessibleUsage: String {- let windows = layout == .small ? provider.tightest.map { [$0] } ?? [] : Array(provider.windows.prefix(layout == .large ? 4 : 2))+ let windows = layout == .small ? provider.tightest.map { [$0] } ?? [] : Array(provider.limits.prefix(layout == .large ? 4 : 2))return windows.map { window in"\(window.title), \(Int(window.percent.rounded())) percent" +(window.resetsShort(now: date).map { ", \($0)" } ?? "")diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex 4c8b40ae..a6db2232 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -112,6 +112,8 @@ public struct UsageWindow: Codable, Hashable, Sendable, Identifiable {public var resetsAt: Int64?/// Human text when only that is known ("Sep 26 at 12pm (Asia/Taipei)").public var resetsText: String?+ /// A reading that isn't a share of a cap ("$4.20", "1.2M tokens", "Unlimited"). Shown instead of the percent.+ public var text: String? = nilpublic var resetDate: Date? { resetsAt.map(Date.init(milliseconds:)) ?? resetsText.flatMap { Self.parseReset($0) } }/// Claude Code's text: "Sep 26 at 12pm (Asia/Taipei)", "Sep 25 at 7:30pm (Asia/Taipei)", or just "7:30pm (…)".diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex a9aaf022..834bb22a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "Dein Computer liest die Limits von Claude Code und Codex aus.",+ "Your computer reads plan limits from the agents installed on it.": "Dein Computer liest die Planlimits der darauf installierten Agents.","or download the Mac app": "oder lade die Mac-App herunter","or install with Homebrew": "oder installiere mit Homebrew","search bots": "Bots suchen",@@ -900,7 +900,7 @@"Checking for a saved account…": "Gespeichertes Konto wird gesucht…","Choose a bot": "Bot wählen","Choose key file": "Schlüsseldatei wählen",- "Claude Code and Codex limits show up here once a bot has used them.": "Die Limits von Claude Code und Codex erscheinen hier, sobald ein Bot sie verwendet hat.",+ "Plan limits show up here once an agent reports them.": "Planlimits erscheinen hier, sobald ein Agent sie meldet.","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync ist kostenlos und Open Source. Mit einem Stern auf GitHub hilfst du anderen, es zu finden.","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync öffnet einen SSH-Tunnel zu codync-host auf der Loopback-Adresse dieses Computers. Es nutzt deine SSH-Konfiguration und ssh-agent; Agent-Weiterleitung bleibt deaktiviert.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex d90bb38c..da4b23a1 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "Tu computadora lee los límites de Claude Code y Codex.",+ "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.","or download the Mac app": "o descarga la app para Mac","or install with Homebrew": "o instala con Homebrew","search bots": "buscar bots",@@ -900,7 +900,7 @@"Checking for a saved account…": "Buscando una cuenta guardada…","Choose a bot": "Elegir un bot","Choose key file": "Elegir archivo de clave",- "Claude Code and Codex limits show up here once a bot has used them.": "Los límites de Claude Code y Codex aparecen aquí cuando un bot los haya utilizado.",+ "Plan limits show up here once an agent reports them.": "Los límites del plan aparecen aquí cuando un agente los informa.","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync es gratis y de código abierto. Una estrella en GitHub ayuda a que otras personas lo descubran.","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync abre un túnel SSH a codync-host en la interfaz local de esa computadora. Usa tu configuración SSH y ssh-agent; el reenvío del agente permanece desactivado.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 913c8c9d..5a180043 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "Votre ordinateur lit les limites de Claude Code et Codex.",+ "Your computer reads plan limits from the agents installed on it.": "Votre ordinateur lit les limites des forfaits des agents installés dessus.","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",@@ -900,7 +900,7 @@"Checking for a saved account…": "Recherche d’un compte enregistré…","Choose a bot": "Choisir un bot","Choose key file": "Choisir un fichier de clé",- "Claude Code and Codex limits show up here once a bot has used them.": "Les limites de Claude Code et Codex apparaissent ici dès qu’un bot les a utilisés.",+ "Plan limits show up here once an agent reports them.": "Les limites de forfait apparaissent ici dès qu’un agent les signale.","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync est gratuit et open source. Une étoile sur GitHub aide d’autres personnes à le découvrir.","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync ouvre un tunnel SSH vers codync-host sur l’interface de boucle locale de cet ordinateur. Il utilise votre configuration SSH et ssh-agent ; le transfert d’agent reste désactivé.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 5c6b3968..5ded5d1b 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "コンピューターは Claude Code および Codex から制限を読み取ります。",+ "Your computer reads plan limits from the agents installed on it.": "このコンピュータに入っているエージェントから、プランの上限を読み取ります。","or download the Mac app": "またはMacアプリをダウンロードしてください","or install with Homebrew": "またはHomebrewでインストールする","search bots": "ボットを検索",@@ -900,7 +900,7 @@"Checking for a saved account…": "保存されたアカウントを確認しています…","Choose a bot": "ボットを選択してください","Choose key file": "キーファイルを選択してください",- "Claude Code and Codex limits show up here once a bot has used them.": "Claude Code と Codex の制限は、ボットが使用するとここに表示されます。",+ "Plan limits show up here once an agent reports them.": "エージェントが報告すると、プランの上限がここに表示されます。","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync は無料のオープンソースです。 GitHub のスターは、他の人がそれを見つける方法です。","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync は、そのコンピューターのループバックで codync-host への SSH トンネルを開きます。 SSH 設定と ssh-agent を使用します。エージェント転送はオフのままです。",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 92e13392..97f1cf0a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "컴퓨터는 Claude Code 및 Codex의 제한을 읽습니다.",+ "Your computer reads plan limits from the agents installed on it.": "이 컴퓨터에 설치된 에이전트의 요금제 한도를 읽습니다.","or download the Mac app": "또는 Mac 앱을 다운로드하세요.","or install with Homebrew": "또는 Homebrew로 설치","search bots": "검색 봇",@@ -900,7 +900,7 @@"Checking for a saved account…": "저장된 계정 확인 중…","Choose a bot": "봇 선택","Choose key file": "키 파일 선택",- "Claude Code and Codex limits show up here once a bot has used them.": "봇이 Claude Code나 Codex를 사용하면 한도가 여기에 표시됩니다.",+ "Plan limits show up here once an agent reports them.": "에이전트가 한도를 보고하면 여기에 표시됩니다.","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync는 무료 오픈 소스입니다. GitHub의 별표는 다른 사람들이 발견하는 데 도움이 됩니다.","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync는 해당 컴퓨터의 루프백에 있는 codync-host로 SSH 터널을 엽니다. SSH 설정과 ssh-agent를 사용하며 에이전트 전달은 꺼진 상태로 유지됩니다.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 247fb64d..0a1f46ad 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "电脑会从 Claude Code 和 Codex 读取用量上限。",+ "Your computer reads plan limits from the agents installed on it.": "电脑会从这台电脑上安装的 agent 读取用量上限。","or download the Mac app": "或下载 Mac 应用","or install with Homebrew": "或用 Homebrew 安装","search bots": "搜索 Bot",@@ -900,7 +900,7 @@"Checking for a saved account…": "正在查找已保存的账户…","Choose a bot": "选择一个 Bot","Choose key file": "选择密钥文件",- "Claude Code and Codex limits show up here once a bot has used them.": "Bot 用过之后,Claude Code 和 Codex 的限额会显示在这里。",+ "Plan limits show up here once an agent reports them.": "Agent 回报用量后,方案上限会显示在这里。","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync 免费且开源。在 GitHub 上加一颗星,别人就能找到它。","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync 通过 SSH 隧道连到那台电脑本机的 codync-host。它使用你的 SSH 配置和 ssh-agent,不会开启代理转发。",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 6b78c817..6c3df1ea 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -317,7 +317,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 the limits from Claude Code and Codex.": "電腦會從 Claude Code 和 Codex 讀取用量上限。",+ "Your computer reads plan limits from the agents installed on it.": "電腦會從這台電腦上安裝的 agent 讀取用量上限。","or download the Mac app": "或下載 Mac 應用","or install with Homebrew": "或用 Homebrew 安裝","search bots": "搜尋 Bot",@@ -900,7 +900,7 @@"Checking for a saved account…": "正在查詢已儲存的賬戶…","Choose a bot": "選擇一個 Bot","Choose key file": "選擇金鑰檔案",- "Claude Code and Codex limits show up here once a bot has used them.": "Bot 用過之後,Claude Code 和 Codex 的限額會顯示在這裡。",+ "Plan limits show up here once an agent reports them.": "Agent 回報用量後,方案上限會顯示在這裡。","Codync Screen": "Codync Screen","Codync is free and open source. A star on GitHub is how other people find it.": "Codync 免費且開源。在 GitHub 上加一顆星,別人就能找到它。","Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.": "Codync 透過 SSH 隧道連到那臺電腦本機的 codync-host。它使用你的 SSH 配置和 ssh-agent,不會開啟代理轉發。",diff --git a/apps/ios/Views/UsageView.swift b/apps/ios/Views/UsageView.swiftindex ffbcd823..4a9393f4 100644--- a/apps/ios/Views/UsageView.swift+++ b/apps/ios/Views/UsageView.swift@@ -20,7 +20,7 @@ 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 the limits from Claude Code and Codex."))+ Text(L10n.tr("Your computer reads plan limits from the agents installed on it.")).font(.subheadline).foregroundStyle(Palette.secondary)}.multilineTextAlignment(.center)@@ -76,7 +76,7 @@ private struct ProviderCard: View {if !collapsed {VStack(spacing: 8) {ForEach(provider.windows) { w in- row(L10n.tr(w.title), "\(Int(w.percent.rounded()))%")+ row(L10n.tr(w.title), w.text ?? "\(Int(w.percent.rounded()))%")if let reset = w.resetsShort() { row(L10n.tr("Resets"), L10n.resetLine(reset)) }}row("Source", source)diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex 909afdd6..5e28fb38 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -16,6 +16,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自分類的列表上方。- 電腦使用自建中繼時,設定和連線狀態會顯示該中繼的地址,不再一律寫成 Cloudflare。- 可以建立使用 WorkBuddy 的 Bot:Codync 會使用 WorkBuddy 桌面 App 內附的 CLI,並在聊天裡請你登入。+- 用量也會顯示這台電腦上其他 agent 的額度,包括 oh-my-pi、Amp、Kiro、Kimi、Antigravity、OpenCode、Mistral Vibe 和 Junie。Cursor 會用本機已登入的帳號向 cursor.com 查詢用量。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.@@ -25,6 +26,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- Credentials sits beside the computer's name at the top, and Custom connector and Your own skill sit above their lists.- When a computer uses a private relay, Settings and connection status show that relay's address instead of always saying Cloudflare.- Create bots that run WorkBuddy: Codync uses the CLI inside the WorkBuddy desktop app and asks you to sign in from the chat.+- Usage limits now include the other agents installed on your computer: oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie. Cursor asks cursor.com with the sign-in saved on that computer.## 2.26.1diff --git a/apps/ios/Widgets/CodyncWidgets.swift b/apps/ios/Widgets/CodyncWidgets.swiftindex b858198d..af68fe16 100644--- a/apps/ios/Widgets/CodyncWidgets.swift+++ b/apps/ios/Widgets/CodyncWidgets.swift@@ -375,7 +375,7 @@ struct UsageWidgetView: View {@Environment(\.widgetFamily) private var familyprivate var windows: [(provider: String, window: UsageWindow)] {- entry.usage.providers.flatMap { p in p.windows.map { (p.name, $0) } }+ entry.usage.providers.flatMap { p in p.limits.map { (p.name, $0) } }}private var tightest: (provider: String, window: UsageWindow)? { windows.max { $0.window.percent < $1.window.percent } }@@ -579,7 +579,7 @@ struct ProviderUsageView: View {var body: some View {Group {- if let provider, !provider.windows.isEmpty {+ if let provider, !provider.limits.isEmpty {ProviderWidgetCard(provider: provider, layout: family == .systemSmall ? .small : family == .systemLarge ? .large : .medium, date: entry.date)} else {EmptyWidget(text: L10n.tr("Open Codync to connect a computer and check {provider} usage.").replacingOccurrences(of: "{provider}", with: entry.provider.capitalized))diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex eb25632a..8f4bfc90 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -86,7 +86,7 @@ The TUI connects to one host at a time, so it keeps its single roster.Agents start through `cmd /c` (`host/src/shell.rs`), setup terminals use ConPTY(`portable-pty`), and the vault key lives in Credential Manager. Not on Windows yet: Remotescreen and the `computer` MCP (no screen helper), on-device speech, the Claude Code status- line hook (usage still comes from `claude -p /usage` and ACP), SSH tunnels to other+ line hook (usage still comes from `claude -p /usage`, ACP and each agent's own report), SSH tunnels to othercomputers, and `curl | bash` installers (npm installs and Claude Code's PowerShell installerwork). The tray icon is the app icon; left-click opens the chat, right-click the menu.- **Remote screen** on macOS registers `CodyncScreen.app` (built from the Xcode `Screen` target)diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex cfe81198..c2325f80 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -11,7 +11,7 @@ Codync/│ │ ├── main.rs # CLI entry, shared helpers (LockExt, http)│ │ ├── hub.rs, store/ # Shared state + event fan-out / SQLite persistence (schema, model, bots, entries, devices)│ │ ├── service/ # Data dir, launchd/systemd/Windows install, keep-awake-│ │ ├── usage.rs, mcp.rs # mcp.rs: built-in stdio MCP servers; mcp/remote.rs: remote connector proxy+│ │ ├── usage/, mcp.rs # usage/: plan limits from each agent; mcp.rs: built-in stdio MCP servers; mcp/remote.rs: remote connector proxy│ │ ├── screen/ # Remote screen: helper protocol, helper socket, phone viewers, bot computer use (cua-driver)│ │ ├── api/ # Dispatch (mod.rs), HTTP/SSE routes (http.rs, events.rs), method groups (bots.rs, host.rs, marketplace.rs, remote.rs), caller permissions (devices.rs)│ │ ├── agent/ # ACP client, harness discovery, registry, sign-in, setup PTYs, bot actor, new bot defaults (new_bot.rs)diff --git a/host/src/chat/lead/tests.rs b/host/src/chat/lead/tests.rsindex 15cb4681..70cd07b7 100644--- a/host/src/chat/lead/tests.rs+++ b/host/src/chat/lead/tests.rs@@ -111,6 +111,7 @@ async fn check_ins_wait_while_the_plan_is_nearly_used_up() {percent,resets_at: None,resets_text: None,+ text: None,}],source: "agent",updated_at: 0,diff --git a/host/src/tui/view/usage.rs b/host/src/tui/view/usage.rsindex 07cf90c1..a69f9a3c 100644--- a/host/src/tui/view/usage.rs+++ b/host/src/tui/view/usage.rs@@ -25,41 +25,46 @@ pub(super) fn usage(buf: &mut Buffer, area: Rect, app: &App) {put(buf, inner.x, y, inner.width, p["name"].as_str().unwrap_or_default(), t.bold.patch(t.panel));y += 1;for win in p["windows"].as_array().into_iter().flatten() {- let pct = win["percent"].as_f64().unwrap_or(0.0).clamp(0.0, 100.0);- let on = filled(pct, 16);- put(- buf,- inner.x + 2,- y,- 18,- &truncate(win["label"].as_str().unwrap_or_default(), 18),- t.secondary.patch(t.panel),- );- let mut x = put(- buf,- inner.x + 21,- y,- 16,- &"▰".repeat(on.min(16)),- if pct >= 80.0 { t.amber } else { t.text }.patch(t.panel),- );- x = put(buf, x, y, 16, &"▱".repeat(16 - on.min(16)), t.line.patch(t.panel));- put(buf, x + 1, y, 5, &format!("{pct:>3.0}%"), t.text.patch(t.panel));- let reset = win["resetsAt"]- .as_i64()- .map(|ms| format!("resets {}", when_future(ms)))- .or_else(|| {- // "Sep 26 at 11:59am (Asia/Taipei)": the zone is this computer's own.- win["resetsText"].as_str().map(|s| truncate(s.split(" (").next().unwrap_or(s), 24))- })- .unwrap_or_default();- let reset = crate::tui::l10n::reset_line(&reset);- rput(buf, inner.right(), y, &reset, t.dim.patch(t.panel));+ let label = truncate(win["label"].as_str().unwrap_or_default(), 18);+ put(buf, inner.x + 2, y, 18, &label, t.secondary.patch(t.panel));+ if let Some(text) = win["text"].as_str().filter(|text| !text.is_empty()) {+ put(buf, inner.x + 21, y, inner.width.saturating_sub(23), &truncate(text, 40), t.text.patch(t.panel));+ } else {+ let pct = win["percent"].as_f64().unwrap_or(0.0).clamp(0.0, 100.0);+ let on = filled(pct, 16);+ let mut x = put(+ buf,+ inner.x + 21,+ y,+ 16,+ &"▰".repeat(on.min(16)),+ if pct >= 80.0 { t.amber } else { t.text }.patch(t.panel),+ );+ x = put(buf, x, y, 16, &"▱".repeat(16 - on.min(16)), t.line.patch(t.panel));+ put(buf, x + 1, y, 5, &format!("{pct:>3.0}%"), t.text.patch(t.panel));+ let reset = win["resetsAt"]+ .as_i64()+ .map(|ms| format!("resets {}", when_future(ms)))+ .or_else(|| {+ // "Sep 26 at 11:59am (Asia/Taipei)": the zone is this computer's own.+ win["resetsText"].as_str().map(|s| truncate(s.split(" (").next().unwrap_or(s), 24))+ })+ .unwrap_or_default();+ let reset = crate::tui::l10n::reset_line(&reset);+ rput(buf, inner.right(), y, &reset, t.dim.patch(t.panel));+ }y += 1;}y += 1;}- put(buf, inner.x, inner.bottom() - 1, inner.width, "From your local installs. esc close", t.dim.patch(t.panel));+ put(+ buf,+ inner.x,+ inner.bottom() - 1,+ inner.width,+ "Read from the agents on this computer. esc close",+ t.dim.patch(t.panel),+ );}pub(in crate::tui) fn when_future(ms: i64) -> String {diff --git a/host/src/usage.rs b/host/src/usage.rsdeleted file mode 100644index 5cc95b99..00000000--- a/host/src/usage.rs+++ /dev/null@@ -1,289 +0,0 @@-//! Subscription usage limits, read locally on the host — no extra login.-//!-//! Claude: asks the installed `claude` binary (`claude -p /usage`, a local-//! command that costs nothing), plus the `rate_limits` Claude Code hands its-//! status line and the Claude ACP adapter's rate-limit events. Codex: the-//! newest `rate_limits` event in `~/.codex/sessions` rollout files.--use crate::LockExt;-use crate::hub::Hub;-use serde::Serialize;-use serde_json::Value;-use std::path::{Path, PathBuf};-use std::sync::Arc;-use std::time::Duration;--const POLL_EVERY: Duration = Duration::from_secs(5 * 60);-/// Usage of a plan above which background work (dreaming, the lead's check-ins) waits.-const HEADROOM_PERCENT: f64 = 75.0;--/// Usage of harness `backend`'s plan above [`HEADROOM_PERCENT`] in any window.-pub fn near_limit(hub: &Hub, backend: &str) -> bool {- hub.usage- .locked()- .providers- .iter()- .filter(|p| p.id == backend)- .flat_map(|p| &p.windows)- .any(|w| w.percent > HEADROOM_PERCENT)-}--/// Everything the apps show about limits (wire shape of the `usage` event).-#[derive(Serialize, Clone, Debug, Default, PartialEq)]-pub struct Usage {- pub providers: Vec<Provider>,-}--#[derive(Serialize, Clone, Debug, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct Provider {- pub id: &'static str,- pub name: &'static str,- pub windows: Vec<Window>,- /// Where the numbers came from: `claude` (CLI), `statusline`, `agent`, `sessions`.- pub source: &'static str,- pub updated_at: i64,-}--#[derive(Serialize, Clone, Debug, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct Window {- pub id: String,- pub label: String,- pub percent: f64,- /// Epoch milliseconds, when known.- pub resets_at: Option<i64>,- /// Human text when only that is known ("Sep 26 at 12pm (Asia/Taipei)").- #[serde(skip_serializing_if = "Option::is_none")]- pub resets_text: Option<String>,-}--impl Window {- fn new(id: impl Into<String>, label: impl Into<String>, percent: f64, resets_at: Option<i64>) -> Self {- Self { id: id.into(), label: label.into(), percent, resets_at, resets_text: None }- }-}--impl Usage {- /// Replaces `new` windows (by id) in provider `id`, keeping the provider's other windows.- fn merge(&mut self, id: &'static str, name: &'static str, source: &'static str, new: Vec<Window>) {- let mut windows = self.providers.iter().find(|p| p.id == id).map(|p| p.windows.clone()).unwrap_or_default();- windows.retain(|w| !new.iter().any(|n| n.id == w.id));- 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.sort_by_key(|p| p.id);- }-}--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);-}--pub async fn poll(hub: Arc<Hub>) {- loop {- refresh(&hub).await;- tokio::time::sleep(POLL_EVERY).await;- }-}--pub async fn refresh(hub: &Hub) {- if let Some(windows) = tokio::task::spawn_blocking(codex_usage).await.ok().flatten() {- merge(hub, "codex", "Codex", "sessions", windows);- }- if let Some(windows) = claude_cli_usage().await {- merge(hub, "claude", "Claude", "claude", windows);- }-}--/// `claude -p /usage`: Claude Code's own local usage report, no model call.-async fn claude_cli_usage() -> Option<Vec<Window>> {- let bin = crate::agent::backends::which("claude")?;- let out = tokio::time::timeout(- Duration::from_secs(60),- tokio::process::Command::new(bin)- .args(["-p", "/usage", "--output-format", "json", "--no-session-persistence"])- .current_dir(dirs::home_dir()?)- .stdin(std::process::Stdio::null())- .kill_on_drop(true)- .output(),- )- .await- .ok()?- .ok()?;- let v: Value = serde_json::from_slice(&out.stdout).ok()?;- let windows = parse_claude_usage(v["result"].as_str()?);- (!windows.is_empty()).then_some(windows)-}--/// Lines like `Current week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)`.-pub fn parse_claude_usage(text: &str) -> Vec<Window> {- text.lines()- .filter_map(|line| {- let (name, rest) = line.trim().split_once(": ")?;- let percent: f64 = rest.split_once("% used")?.0.trim().parse().ok()?;- let resets = rest.split_once("resets ").map(|(_, r)| r.trim().to_owned());- let (id, label) = match name {- "Current session" => ("five_hour".to_owned(), "5-hour".to_owned()),- "Current week (all models)" => ("seven_day".to_owned(), "Weekly".to_owned()),- n => {- let model = n.strip_prefix("Current week (")?.strip_suffix(')')?;- (format!("seven_day_{}", model.to_lowercase()), format!("Weekly · {model}"))- }- };- Some(Window { resets_text: resets, ..Window::new(id, label, percent, None) })- })- .collect()-}--/// `POST /ingest/statusline` body: Claude Code's statusline JSON.-pub fn ingest_statusline(hub: &Hub, body: &Value) {- let rl = &body["rate_limits"];- let windows: Vec<Window> = [("five_hour", "5-hour"), ("seven_day", "Weekly")]- .into_iter()- .filter_map(|(key, label)| {- let percent = rl[key]["used_percentage"].as_f64()?;- Some(Window::new(key, label, percent, rl[key]["resets_at"].as_i64().map(|s| s.saturating_mul(1000))))- })- .collect();- if !windows.is_empty() {- merge(hub, "claude", "Claude", "statusline", windows);- }-}--/// Claude ACP adapter: `usage_update._meta["_claude/rateLimit"]` (the SDK's `SDKRateLimitInfo`).-pub fn ingest_claude_rate_limit(hub: &Hub, info: &Value) {- if let Some(w) = claude_window(info) {- merge(hub, "claude", "Claude", "agent", vec![w]);- }-}--fn claude_window(info: &Value) -> Option<Window> {- let kind = info["rateLimitType"].as_str()?;- let label = match kind {- "five_hour" => "5-hour",- "seven_day" => "Weekly",- "seven_day_opus" => "Weekly · Opus",- "seven_day_sonnet" => "Weekly · Sonnet",- _ => return None,- };- let u = info["utilization"].as_f64()?;- // The SDK reports a 0–1 fraction (from the unified rate-limit headers).- let percent = if u <= 1.0 { u * 100.0 } else { u };- // Seconds, but accept milliseconds too.- let resets = info["resetsAt"].as_i64().map(|t| if t > 100_000_000_000 { t } else { t.saturating_mul(1000) });- Some(Window::new(kind, label, percent, resets))-}--/// Blocking. `sessions/YYYY/MM/DD/rollout-*.jsonl`: descend into the largest dir each level.-fn newest_rollout(root: &Path) -> Option<PathBuf> {- let mut dir = root.to_path_buf();- for _ in 0..3 {- let mut subs: Vec<PathBuf> =- std::fs::read_dir(&dir).ok()?.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();- subs.sort();- dir = subs.pop()?;- }- std::fs::read_dir(&dir)- .ok()?- .filter_map(Result::ok)- .map(|e| e.path())- .filter(|p| p.extension().is_some_and(|x| x == "jsonl"))- .max_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())-}--/// Blocking: reads the newest Codex rollout file.-fn codex_usage() -> Option<Vec<Window>> {- let path = newest_rollout(&dirs::home_dir()?.join(".codex/sessions"))?;- let text = std::fs::read_to_string(&path).ok()?;- let line = text.lines().rev().find(|l| l.contains("\"rate_limits\""))?;- let v: Value = serde_json::from_str(line).ok()?;- let rl = if v["payload"]["rate_limits"].is_object() { &v["payload"]["rate_limits"] } else { &v["rate_limits"] };- let modified_ms = std::fs::metadata(&path)- .and_then(|m| m.modified())- .ok()- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())- .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));- let windows = parse_codex(rl, modified_ms);- (!windows.is_empty()).then_some(windows)-}--pub fn parse_codex(rl: &Value, observed_ms: i64) -> Vec<Window> {- ["primary", "secondary"]- .into_iter()- .filter_map(|k| {- let w = &rl[k];- let percent = w["used_percent"].as_f64()?;- let minutes = w["window_minutes"].as_i64().unwrap_or(0);- let label = match minutes {- 300 => "5-hour".to_owned(),- 10080 => "Weekly".to_owned(),- m if m > 0 && m % 1440 == 0 => format!("{}-day", m / 1440),- m if m > 0 => format!("{}-hour", m / 60),- _ => k.to_owned(),- };- let resets = w["resets_at"].as_i64().map(|s| s.saturating_mul(1000)).or_else(|| {- w["resets_in_seconds"].as_i64().map(|s| observed_ms.saturating_add(s.saturating_mul(1000)))- });- Some(Window::new(k, label, percent, resets))- })- .collect()-}--#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn parses_codex_rollout_limits() {- let x = parse_codex(- &json!({"primary": {"used_percent": 3.0, "window_minutes": 300, "resets_in_seconds": 10},- "secondary": {"used_percent": 40.0, "window_minutes": 10080, "resets_at": 100}}),- 1000,- );- assert_eq!(x[0].label, "5-hour");- assert_eq!(x[0].resets_at, Some(11_000));- assert_eq!(x[1].resets_at, Some(100_000));- }-- #[test]- fn parses_claude_usage_report() {- let w = parse_claude_usage(- "You are currently using your subscription\n\nCurrent session: 11% used · resets Sep 25 at 5am (Asia/Taipei)\nCurrent week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)\nCurrent week (Fable): 83% used · resets Sep 26 at 12pm (Asia/Taipei)\n\nLast 24h · 794 requests",- );- assert_eq!(w.len(), 3);- assert_eq!(w[0].id, "five_hour");- assert!((w[0].percent - 11.0).abs() < f64::EPSILON);- assert_eq!(w[0].resets_text.as_deref(), Some("Sep 25 at 5am (Asia/Taipei)"));- assert_eq!(w[2].label, "Weekly · Fable");- }-- #[test]- fn claude_rate_limit_fraction_becomes_percent() {- let w = claude_window(&json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 1_790_000_000}))- .unwrap();- assert!((w.percent - 42.0).abs() < 1e-9);- assert_eq!(w.resets_at, Some(1_790_000_000_000));- assert!(claude_window(&json!({"rateLimitType": "overage", "utilization": 0.1})).is_none());- }-- #[test]- fn merge_replaces_only_matching_windows() {- let mut u = Usage::default();- u.merge(- "claude",- "Claude",- "claude",- vec![Window::new("five_hour", "5-hour", 10.0, None), Window::new("seven_day", "Weekly", 50.0, None)],- );- u.merge("claude", "Claude", "statusline", vec![Window::new("five_hour", "5-hour", 12.0, None)]);- let c = &u.providers[0];- assert_eq!((c.windows.len(), c.source), (2, "statusline"));- assert!((c.windows[0].percent - 12.0).abs() < f64::EPSILON, "five_hour updated");- assert_eq!(serde_json::to_value(&u).unwrap()["providers"][0]["windows"][1]["resetsAt"], Value::Null);- }-}diff --git a/host/src/usage/amp.rs b/host/src/usage/amp.rsnew file mode 100644index 00000000..f28798a9--- /dev/null+++ b/host/src/usage/amp.rs@@ -0,0 +1,73 @@+//! `amp usage --no-color`: the free allowance as a used share, and any+//! balance that has no ceiling as text.++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)+ }+}++fn parse(text: &str) -> Vec<Window> {+ let mut windows = Vec::new();+ for line in text.lines() {+ let Some((raw, rest)) = line.split_once(':') else { continue };+ let rest = rest.trim();+ let Some(money) = rest.strip_prefix('$') else { continue };+ let label = amp_label(raw.trim());+ let id = label.to_ascii_lowercase().replace(' ', "_");+ // "$17.59/$20 remaining …" or "$0 remaining …".+ let head = money.split(" remaining").next().unwrap_or(money).trim();+ if let Some((left, total)) = head.split_once('/') {+ let (Some(left), Some(total)) = (dollars(left), dollars(total.trim_start_matches('$'))) else { continue };+ if total <= 0.0 {+ continue;+ }+ let percent = ((total - left) / total * 100.0).clamp(0.0, 100.0);+ windows.push(Window::new(id, label, percent, None));+ } else if let Some(left) = dollars(head) {+ windows.push(Window::note(id, label, format!("${left:.2} left")));+ }+ }+ windows+}++fn amp_label(raw: &str) -> String {+ match raw {+ "Amp Free" => "Free".to_owned(),+ "Individual credits" => "Individual".to_owned(),+ other => other.to_owned(),+ }+}++fn dollars(text: &str) -> Option<f64> {+ let text = text.trim().trim_start_matches('$');+ let n: f64 = text.parse().ok()?;+ n.is_finite().then_some(n)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn free_allowance_is_the_share_used_and_a_balance_is_text() {+ let text = "\+Signed in as [email protected] (username)\n\+Amp Free: $17.59/$20 remaining (replenishes +$0.83/hour)\n\+Individual credits: $0 remaining - https://ampcode.com\n";+ let w = parse(text);+ assert_eq!(w[0].id, "free");+ assert!((w[0].percent - 12.05).abs() < 0.01, "{}", w[0].percent);+ assert_eq!(w[1].text.as_deref(), Some("$0.00 left"));+ }+}diff --git a/host/src/usage/antigravity.rs b/host/src/usage/antigravity.rsnew file mode 100644index 00000000..acd4ce4b--- /dev/null+++ b/host/src/usage/antigravity.rs@@ -0,0 +1,264 @@+//! 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.++use serde_json::Value;+use std::time::Duration;++use super::Window;++const BODY: &str =+ r#"{"metadata":{"ideName":"antigravity","extensionName":"antigravity","ideVersion":"unknown","locale":"en"}}"#;++pub(super) async fn collect() -> Option<Vec<Window>> {+ let target = tokio::task::spawn_blocking(find_server).await.ok().flatten()?;+ let client = reqwest::Client::builder()+ .danger_accept_invalid_certs(true)+ .redirect(reqwest::redirect::Policy::none())+ .timeout(Duration::from_secs(5))+ .build()+ .ok()?;+ for port in &target.https {+ if let Some(windows) = ask(&client, &format!("https://127.0.0.1:{port}"), &target.csrf).await {+ return Some(windows);+ }+ }+ if let Some(port) = target.http+ && let Some(windows) = ask(&client, &format!("http://127.0.0.1:{port}"), &target.csrf).await+ {+ return Some(windows);+ }+ tracing::debug!("antigravity language server had no quota");+ None+}++struct Server {+ csrf: String,+ https: Vec<u16>,+ http: Option<u16>,+}++async fn ask(client: &reqwest::Client, base: &str, csrf: &str) -> Option<Vec<Window>> {+ for method in ["RetrieveUserQuotaSummary", "GetUserStatus"] {+ let url = format!("{base}/exa.language_server_pb.LanguageServerService/{method}");+ let response = client+ .post(&url)+ .header("X-Codeium-Csrf-Token", csrf)+ .header("Connect-Protocol-Version", "1")+ .header("Content-Type", "application/json")+ .body(BODY)+ .send()+ .await+ .ok()?;+ if !response.status().is_success() {+ continue;+ }+ let body: Value = response.json().await.ok()?;+ let windows = parse(&body);+ if !windows.is_empty() {+ return Some(windows);+ }+ }+ None+}++fn find_server() -> Option<Server> {+ let processes = processes();+ let (pid, command) = processes.into_iter().find(|(_, command)| is_antigravity(command))?;+ let csrf = flag(&command, "--csrf_token")?;+ let https = listen_ports(pid);+ let http = flag(&command, "--extension_server_port").and_then(|p| p.parse().ok());+ Some(Server { csrf, https, http })+}++fn is_antigravity(command: &str) -> bool {+ let lower = command.to_ascii_lowercase();+ let named = lower.contains("language_server") || lower.contains("agy");+ let ours = lower.contains("antigravity") || lower.contains("--app_data_dir");+ named && ours && command.contains("--csrf_token")+}++fn flag(command: &str, name: &str) -> Option<String> {+ let mut parts = command.split_whitespace();+ while let Some(part) = parts.next() {+ if let Some(value) = part.strip_prefix(name).and_then(|rest| rest.strip_prefix('=')).filter(|s| !s.is_empty()) {+ return Some(value.to_owned());+ }+ if part == name {+ return parts.next().filter(|s| !s.is_empty()).map(str::to_owned);+ }+ }+ None+}++#[cfg(unix)]+fn processes() -> Vec<(u32, String)> {+ let Ok(out) = std::process::Command::new("pgrep").args(["-a", "-f", "language_server|agy"]).output() else {+ return Vec::new();+ };+ String::from_utf8_lossy(&out.stdout)+ .lines()+ .filter_map(|line| {+ let (pid, command) = line.split_once(' ')?;+ Some((pid.parse().ok()?, command.to_owned()))+ })+ .collect()+}++#[cfg(windows)]+fn processes() -> Vec<(u32, String)> {+ let Ok(out) = std::process::Command::new("powershell")+ .args([+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'antigravity' } | Select-Object ProcessId, CommandLine | ConvertTo-Json -Compress",+ ])+ .output()+ else {+ return Vec::new();+ };+ let Ok(value) = serde_json::from_slice::<Value>(&out.stdout) else { return Vec::new() };+ let rows = value.as_array().cloned().unwrap_or_else(|| vec![value]);+ rows.into_iter()+ .filter_map(|row| {+ let pid = u32::try_from(row["ProcessId"].as_i64()?).ok()?;+ Some((pid, row["CommandLine"].as_str()?.to_owned()))+ })+ .collect()+}++#[cfg(unix)]+fn listen_ports(pid: u32) -> Vec<u16> {+ let out = std::process::Command::new("lsof")+ .args(["-nP", "-iTCP", "-sTCP:LISTEN", "-a", "-p", &pid.to_string()])+ .output()+ .ok();+ let text = out.map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();+ ports_in(&text)+}++#[cfg(windows)]+fn listen_ports(pid: u32) -> Vec<u16> {+ let out = std::process::Command::new("netstat").args(["-ano", "-p", "tcp"]).output().ok();+ let text = out.map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();+ let pid_text = pid.to_string();+ text.lines()+ .filter(|line| line.contains("LISTENING") && line.split_whitespace().next_back() == Some(pid_text.as_str()))+ .filter_map(|line| line.split(':').nth(1)?.split_whitespace().next()?.parse().ok())+ .collect()+}++fn ports_in(text: &str) -> Vec<u16> {+ let mut ports = Vec::new();+ for token in text.split(|c: char| !c.is_ascii_digit() && c != ':') {+ let Some(port) = token.rsplit(':').next().filter(|s| !s.is_empty()) else { continue };+ if token.contains(':')+ && let Ok(port) = port.parse()+ && !ports.contains(&port)+ {+ ports.push(port);+ }+ }+ ports+}++pub(super) fn parse(body: &Value) -> Vec<Window> {+ let groups = body["response"]["groups"].as_array().or_else(|| body["groups"].as_array());+ if let Some(groups) = groups {+ let windows = summary(groups);+ if !windows.is_empty() {+ return windows;+ }+ }+ models(body)+}++fn summary(groups: &[Value]) -> Vec<Window> {+ let mut by_id: std::collections::HashMap<&str, &Value> = std::collections::HashMap::new();+ for group in groups {+ if let Some(buckets) = group["buckets"].as_array() {+ for bucket in buckets {+ if let Some(id) = bucket["bucketId"].as_str() {+ by_id.entry(id).or_insert(bucket);+ }+ }+ }+ }+ [+ ("gemini-5h", "five_hour", "5-hour"),+ ("gemini-weekly", "seven_day", "Weekly"),+ ("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()+}++fn models(body: &Value) -> Vec<Window> {+ let configs = body["userStatus"]["cascadeModelConfigData"]["clientModelConfigs"]+ .as_array()+ .or_else(|| body["clientModelConfigs"].as_array());+ let Some(configs) = configs else { return Vec::new() };+ configs+ .iter()+ .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,+ label,+ ((1.0 - left) * 100.0).clamp(0.0, 100.0),+ epoch_ms(&item["quotaInfo"]["resetTime"]),+ ))+ })+ .collect()+}++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());+ }+ 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) })+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn a_summary_is_the_share_used() {+ let body = json!({"response":{"groups":[{"buckets":[+ {"bucketId":"gemini-5h","remainingFraction":0.2,"resetTime":"2026-10-25T12:00:00Z"},+ {"bucketId":"3p-weekly","remainingFraction":0.5}+ ]}]}});+ let w = parse(&body);+ assert_eq!(w[0].label, "5-hour");+ assert!((w[0].percent - 80.0).abs() < 1e-9);+ assert!(w[0].resets_at.is_some());+ assert_eq!(w[1].label, "Claude 7d");+ assert!((w[1].percent - 50.0).abs() < 1e-9);+ }++ #[test]+ fn the_csrf_flag_and_an_unrelated_process_are_told_apart() {+ let line =+ "/Applications/Antigravity.app/language_server_macos --csrf_token secret --extension_server_port 1234";+ assert!(is_antigravity(line));+ assert_eq!(flag(line, "--csrf_token").as_deref(), Some("secret"));+ assert_eq!(flag(line, "--extension_server_port").as_deref(), Some("1234"));+ assert!(!is_antigravity("agy --help"));+ }+}diff --git a/host/src/usage/claude.rs b/host/src/usage/claude.rsnew file mode 100644index 00000000..9129efa6--- /dev/null+++ b/host/src/usage/claude.rs@@ -0,0 +1,112 @@+//! Claude plan windows: the CLI's `/usage` report, the status-line hook, and+//! the ACP adapter's rate-limit event.++use serde_json::Value;++use super::Window;++/// `claude -p /usage`: Claude Code's own local usage report, no model call.+pub(super) async fn collect() -> Option<Vec<Window>> {+ let bin = super::command::program("claude")?;+ let out = tokio::time::timeout(+ std::time::Duration::from_secs(60),+ tokio::process::Command::new(bin)+ .args(["-p", "/usage", "--output-format", "json", "--no-session-persistence"])+ .current_dir(dirs::home_dir()?)+ .stdin(std::process::Stdio::null())+ .kill_on_drop(true)+ .output(),+ )+ .await+ .ok()?+ .ok()?;+ let v: Value = serde_json::from_slice(&out.stdout).ok()?;+ let windows = parse_claude_usage(v["result"].as_str()?);+ (!windows.is_empty()).then_some(windows)+}++/// Lines like `Current week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)`.+pub fn parse_claude_usage(text: &str) -> Vec<Window> {+ text.lines()+ .filter_map(|line| {+ let (name, rest) = line.trim().split_once(": ")?;+ let percent: f64 = rest.split_once("% used")?.0.trim().parse().ok()?;+ let resets = rest.split_once("resets ").map(|(_, r)| r.trim().to_owned());+ let (id, label) = match name {+ "Current session" => ("five_hour".to_owned(), "5-hour".to_owned()),+ "Current week (all models)" => ("seven_day".to_owned(), "Weekly".to_owned()),+ n => {+ let model = n.strip_prefix("Current week (")?.strip_suffix(')')?;+ (format!("seven_day_{}", model.to_lowercase()), format!("Weekly · {model}"))+ }+ };+ Some(Window { resets_text: resets, ..Window::new(id, label, percent, None) })+ })+ .collect()+}++/// `POST /ingest/statusline` body: Claude Code's statusline JSON.+pub fn ingest_statusline(hub: &crate::hub::Hub, body: &Value) {+ let rl = &body["rate_limits"];+ let windows: Vec<Window> = [("five_hour", "5-hour"), ("seven_day", "Weekly")]+ .into_iter()+ .filter_map(|(key, label)| {+ let percent = rl[key]["used_percentage"].as_f64()?;+ Some(Window::new(key, label, percent, rl[key]["resets_at"].as_i64().map(|s| s.saturating_mul(1000))))+ })+ .collect();+ if !windows.is_empty() {+ super::merge(hub, "claude", "Claude", "statusline", windows);+ }+}++/// Claude ACP adapter: `usage_update._meta["_claude/rateLimit"]` (the SDK's `SDKRateLimitInfo`).+pub fn ingest_claude_rate_limit(hub: &crate::hub::Hub, info: &Value) {+ if let Some(w) = claude_window(info) {+ super::merge(hub, "claude", "Claude", "agent", vec![w]);+ }+}++fn claude_window(info: &Value) -> Option<Window> {+ let kind = info["rateLimitType"].as_str()?;+ let label = match kind {+ "five_hour" => "5-hour",+ "seven_day" => "Weekly",+ "seven_day_opus" => "Weekly · Opus",+ "seven_day_sonnet" => "Weekly · Sonnet",+ _ => return None,+ };+ let u = info["utilization"].as_f64()?;+ // The SDK reports a 0–1 fraction (from the unified rate-limit headers).+ let percent = if u <= 1.0 { u * 100.0 } else { u };+ // Seconds, but accept milliseconds too.+ let resets = info["resetsAt"].as_i64().map(|t| if t > 100_000_000_000 { t } else { t.saturating_mul(1000) });+ Some(Window::new(kind, label, percent, resets))+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn parses_claude_usage_report() {+ let w = parse_claude_usage(+ "You are currently using your subscription\n\nCurrent session: 11% used · resets Sep 25 at 5am (Asia/Taipei)\nCurrent week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)\nCurrent week (Fable): 83% used · resets Sep 26 at 12pm (Asia/Taipei)\n\nLast 24h · 794 requests",+ );+ assert_eq!(w.len(), 3);+ assert_eq!(w[0].id, "five_hour");+ assert!((w[0].percent - 11.0).abs() < f64::EPSILON);+ assert_eq!(w[0].resets_text.as_deref(), Some("Sep 25 at 5am (Asia/Taipei)"));+ assert_eq!(w[2].label, "Weekly · Fable");+ }++ #[test]+ fn claude_rate_limit_fraction_becomes_percent() {+ let w = claude_window(&json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 1_790_000_000}))+ .unwrap();+ assert!((w.percent - 42.0).abs() < 1e-9);+ assert_eq!(w.resets_at, Some(1_790_000_000_000));+ assert!(claude_window(&json!({"rateLimitType": "overage", "utilization": 0.1})).is_none());+ }+}diff --git a/host/src/usage/codex.rs b/host/src/usage/codex.rsnew file mode 100644index 00000000..1aa7f13d--- /dev/null+++ b/host/src/usage/codex.rs@@ -0,0 +1,79 @@+//! Codex plan windows from the newest local rollout file.++use serde_json::Value;+use std::path::{Path, PathBuf};++use super::Window;++/// Blocking: reads the newest Codex rollout file.+pub(super) fn collect() -> Option<Vec<Window>> {+ let path = newest_rollout(&dirs::home_dir()?.join(".codex/sessions"))?;+ let text = std::fs::read_to_string(&path).ok()?;+ let line = text.lines().rev().find(|l| l.contains("\"rate_limits\""))?;+ let v: Value = serde_json::from_str(line).ok()?;+ let rl = if v["payload"]["rate_limits"].is_object() { &v["payload"]["rate_limits"] } else { &v["rate_limits"] };+ let modified_ms = std::fs::metadata(&path)+ .and_then(|m| m.modified())+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));+ let windows = parse_codex(rl, modified_ms);+ (!windows.is_empty()).then_some(windows)+}++/// Blocking. `sessions/YYYY/MM/DD/rollout-*.jsonl`: descend into the largest dir each level.+fn newest_rollout(root: &Path) -> Option<PathBuf> {+ let mut dir = root.to_path_buf();+ for _ in 0..3 {+ let mut subs: Vec<PathBuf> =+ std::fs::read_dir(&dir).ok()?.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();+ subs.sort();+ dir = subs.pop()?;+ }+ std::fs::read_dir(&dir)+ .ok()?+ .filter_map(Result::ok)+ .map(|e| e.path())+ .filter(|p| p.extension().is_some_and(|x| x == "jsonl"))+ .max_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())+}++pub fn parse_codex(rl: &Value, observed_ms: i64) -> Vec<Window> {+ ["primary", "secondary"]+ .into_iter()+ .filter_map(|k| {+ let w = &rl[k];+ let percent = w["used_percent"].as_f64()?;+ let minutes = w["window_minutes"].as_i64().unwrap_or(0);+ let label = match minutes {+ 300 => "5-hour".to_owned(),+ 10080 => "Weekly".to_owned(),+ m if m > 0 && m % 1440 == 0 => format!("{}-day", m / 1440),+ m if m > 0 => format!("{}-hour", m / 60),+ _ => k.to_owned(),+ };+ let resets = w["resets_at"].as_i64().map(|s| s.saturating_mul(1000)).or_else(|| {+ w["resets_in_seconds"].as_i64().map(|s| observed_ms.saturating_add(s.saturating_mul(1000)))+ });+ Some(Window::new(k, label, percent, resets))+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn parses_codex_rollout_limits() {+ let x = parse_codex(+ &json!({"primary": {"used_percent": 3.0, "window_minutes": 300, "resets_in_seconds": 10},+ "secondary": {"used_percent": 40.0, "window_minutes": 10080, "resets_at": 100}}),+ 1000,+ );+ assert_eq!(x[0].label, "5-hour");+ assert_eq!(x[0].resets_at, Some(11_000));+ assert_eq!(x[1].resets_at, Some(100_000));+ }+}diff --git a/host/src/usage/command.rs b/host/src/usage/command.rsnew file mode 100644index 00000000..35957d3d--- /dev/null+++ b/host/src/usage/command.rs@@ -0,0 +1,71 @@+//! Run an installed CLI for a usage probe. A missing program is silence: the+//! probe is skipped until the agent is installed.++use std::path::{Path, PathBuf};+use std::time::Duration;++/// `name` on the login-shell PATH.+pub(super) fn program(name: &str) -> Option<PathBuf> {+ crate::agent::backends::which(name)+}++/// Stdout of `program`, with terminal colour removed. Nothing when it isn't+/// installed, the process produces no output, or it doesn't finish in time.+/// A non-zero exit still returns stdout: the parser decides whether it is usage.+pub(super) async fn output(+ program: &Path,+ args: &[&str],+ stdin_text: Option<&str>,+ timeout: Duration,+) -> Option<String> {+ let mut cmd = tokio::process::Command::new(program);+ cmd.args(args)+ .kill_on_drop(true)+ .stdin(if stdin_text.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() })+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::null());+ if let Some(home) = dirs::home_dir() {+ cmd.current_dir(home);+ }+ let mut child = cmd.spawn().ok()?;+ if let Some(text) = stdin_text+ && let Some(mut input) = child.stdin.take()+ {+ use tokio::io::AsyncWriteExt;+ let _ = input.write_all(text.as_bytes()).await;+ }+ let done = tokio::time::timeout(timeout, child.wait_with_output()).await.ok()?.ok()?;+ let text = strip_ansi(&String::from_utf8_lossy(&done.stdout));+ (!text.trim().is_empty()).then_some(text)+}++/// Drop CSI colour sequences (`ESC [ … m`). Other characters stay, including+/// the cursor-position query a Windows console sends.+pub(super) fn strip_ansi(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ let mut chars = text.chars().peekable();+ while let Some(c) = chars.next() {+ if c == '\u{1b}' && chars.peek() == Some(&'[') {+ chars.next();+ for d in chars.by_ref() {+ if d.is_ascii_alphabetic() {+ break;+ }+ }+ continue;+ }+ out.push(c);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn colour_codes_drop_out_of_a_usage_line() {+ let raw = "Credits \u{1b}[32m(12 of 100\u{1b}[0m covered)";+ assert_eq!(strip_ansi(raw), "Credits (12 of 100 covered)");+ }+}diff --git a/host/src/usage/cursor.rs b/host/src/usage/cursor.rsnew file mode 100644index 00000000..781ab1ad--- /dev/null+++ b/host/src/usage/cursor.rs@@ -0,0 +1,192 @@+//! Cursor's usage summary. Cursor has no usage command: the token is the one+//! the Cursor app saved in `state.vscdb`, and the summary is+//! `GET https://cursor.com/api/usage-summary`. The token is never logged.++use base64::Engine as _;+use base64::engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD};+use rusqlite::{Connection, OpenFlags};+use serde_json::Value;+use std::path::PathBuf;+use std::time::Duration;++use super::Window;++pub(super) async fn collect() -> Option<Vec<Window>> {+ let token = tokio::task::spawn_blocking(read_token).await.ok().flatten()?;+ let sub = jwt_sub(&token)?;+ let cookie = cookie(&sub, &token)?;+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(15))+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .ok()?;+ let response = client+ .get("https://cursor.com/api/usage-summary")+ .header("Cookie", cookie)+ .header("Accept", "application/json")+ .send()+ .await+ .ok()?;+ if !response.status().is_success() {+ tracing::debug!(status = %response.status(), "cursor usage summary was refused");+ return None;+ }+ let body: Value = response.json().await.ok()?;+ let windows = parse(&body);+ (!windows.is_empty()).then_some(windows)+}++fn db_path() -> Option<PathBuf> {+ let path = dirs::config_dir()?.join("Cursor/User/globalStorage/state.vscdb");+ path.is_file().then_some(path)+}++fn read_token() -> Option<String> {+ let path = db_path()?;+ let conn = Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).ok()?;+ conn.busy_timeout(Duration::from_millis(200)).ok()?;+ let raw =+ conn.query_row("SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken'", [], stored_text).ok()?;+ let token = token_text(&raw);+ (!token.is_empty()).then_some(token)+}++/// `state.vscdb` stores the token as text or as a blob.+fn stored_text(row: &rusqlite::Row<'_>) -> rusqlite::Result<String> {+ let (rusqlite::types::ValueRef::Text(bytes) | rusqlite::types::ValueRef::Blob(bytes)) = row.get_ref(0)? else {+ return Ok(String::new());+ };+ Ok(String::from_utf8_lossy(bytes).into_owned())+}++/// The column is sometimes the raw token and sometimes a JSON string.+fn token_text(raw: &str) -> String {+ let trimmed = raw.trim();+ serde_json::from_str::<String>(trimmed).unwrap_or_else(|_| trimmed.to_owned())+}++fn jwt_sub(token: &str) -> Option<String> {+ let payload = token.split('.').nth(1)?;+ let bytes = URL_SAFE_NO_PAD.decode(payload).or_else(|_| URL_SAFE.decode(payload)).ok()?;+ let value: Value = serde_json::from_slice(&bytes).ok()?;+ let sub = value["sub"].as_str().filter(|s| !s.is_empty())?;+ Some(sub.to_owned())+}++fn cookie(sub: &str, token: &str) -> Option<String> {+ if sub.contains([';', ' ', '\r', '\n']) || token.contains([';', ' ', '\r', '\n']) {+ return None;+ }+ Some(format!("WorkosCursorSessionToken={sub}::{token}"))+}++fn parse(body: &Value) -> Vec<Window> {+ let mut windows = Vec::new();+ let resets = body["billingCycleEnd"].as_str().and_then(iso_ms);+ let plan = &body["individualUsage"]["plan"];+ if body["isUnlimited"].as_bool() == Some(true) {+ windows.push(Window::note("unlimited", "Monthly", "Unlimited"));+ } else if plan["enabled"].as_bool().unwrap_or(true)+ && let Some(percent) = non_negative(plan["totalPercentUsed"].as_f64())+ {+ windows.push(Window::new("monthly", "Monthly", percent, resets));+ }+ if let Some(percent) = non_negative(plan["autoPercentUsed"].as_f64()) {+ windows.push(Window::new("auto", "Auto", percent, resets));+ }+ if let Some(percent) = non_negative(plan["apiPercentUsed"].as_f64()) {+ windows.push(Window::new("api", "API", percent, resets));+ }+ if let Some(window) = spend("on_demand", "On-Demand", &body["individualUsage"]["onDemand"], resets) {+ windows.push(window);+ }+ if body["limitType"].as_str() == Some("team")+ && let Some(window) = spend("team", "Team", &body["teamUsage"]["onDemand"], resets)+ {+ windows.push(window);+ }+ windows+}++fn spend(id: &str, label: &str, node: &Value, resets: Option<i64>) -> Option<Window> {+ if node["enabled"].as_bool() == Some(false) {+ return None;+ }+ let limit = node["limit"].as_f64().filter(|n| *n > 0.0)?;+ let used = node["used"].as_f64().unwrap_or(0.0);+ Some(Window::new(id, label, (used / limit * 100.0).clamp(0.0, 100.0), resets))+}++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::*;+ use serde_json::json;++ #[test]+ fn the_summary_keeps_each_percent_the_api_reports() {+ let body = json!({+ "limitType": "team",+ "isUnlimited": false,+ "billingCycleEnd": "2026-04-01T00:00:00.000Z",+ "individualUsage": {+ "plan": {"enabled": true, "totalPercentUsed": 28.32, "autoPercentUsed": 23.05, "apiPercentUsed": 63.44},+ "onDemand": {"enabled": false, "used": 0, "limit": null}+ },+ "teamUsage": {"onDemand": {"enabled": true, "used": 0, "limit": 10000}}+ });+ let w = parse(&body);+ assert_eq!(w[0].label, "Monthly");+ assert!((w[0].percent - 28.32).abs() < 1e-9);+ assert!(w[0].resets_at.is_some());+ assert_eq!(w[1].label, "Auto");+ assert_eq!(w[2].label, "API");+ assert_eq!(w[3].label, "Team");+ assert!(w[3].percent.abs() < f64::EPSILON);+ assert_eq!(w.len(), 4, "a disabled on-demand row is absent");+ }++ #[test]+ fn an_unlimited_plan_is_a_note() {+ let w = parse(&json!({"isUnlimited": true, "individualUsage": {"plan": {"totalPercentUsed": 10}}}));+ assert_eq!(w[0].text.as_deref(), Some("Unlimited"));+ assert!(w.iter().all(|window| window.id != "monthly" || window.text.is_some()));+ }++ #[test]+ fn the_subject_comes_out_of_the_token_payload() {+ let payload = URL_SAFE_NO_PAD.encode(br#"{"sub":"user_123"}"#);+ let token = format!("eyJhbGciOiJub25lIn0.{payload}.sig");+ assert_eq!(jwt_sub(&token).as_deref(), Some("user_123"));+ assert_eq!(token_text("\"abc.def.ghi\""), "abc.def.ghi");+ assert!(cookie("user_123", &token).unwrap().starts_with("WorkosCursorSessionToken=user_123::"));+ assert!(cookie("a;b", "t").is_none());+ }++ #[test]+ fn a_database_value_is_the_saved_token() {+ let path = std::env::temp_dir().join(format!("codync-cursor-{}.db", std::process::id()));+ let _ = std::fs::remove_file(&path);+ let conn = Connection::open(&path).unwrap();+ conn.execute("CREATE TABLE ItemTable (key TEXT, value BLOB)", []).unwrap();+ conn.execute(+ "INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/accessToken', ?1)",+ [rusqlite::types::Value::Blob(br#""tok""#.to_vec())],+ )+ .unwrap();+ drop(conn);+ let conn = Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();+ let raw = conn+ .query_row("SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken'", [], stored_text)+ .unwrap();+ let _ = std::fs::remove_file(&path);+ assert_eq!(token_text(&raw), "tok");+ }+}diff --git a/host/src/usage/junie.rs b/host/src/usage/junie.rsnew file mode 100644index 00000000..fce69eb3--- /dev/null+++ b/host/src/usage/junie.rs@@ -0,0 +1,115 @@+//! `JetBrains` AI credits, the monthly quota the IDE saves after AI Assistant+//! (and Junie) has been used. The newest IDE file wins. Nothing is requested.++use std::path::{Path, PathBuf};++use super::Window;++const FILE: &str = "options/AIAssistantQuotaManager2.xml";++pub(super) fn collect() -> Option<Vec<Window>> {+ let mut files = Vec::new();+ for root in roots() {+ files.extend(quota_files(&root));+ }+ let newest = files.into_iter().max_by_key(|path| std::fs::metadata(path).and_then(|m| m.modified()).ok())?;+ let text = std::fs::read_to_string(&newest).ok()?;+ let windows = parse(&text);+ (!windows.is_empty()).then_some(windows)+}++fn roots() -> Vec<PathBuf> {+ let mut roots = Vec::new();+ for base in [dirs::config_dir(), dirs::data_local_dir()].into_iter().flatten() {+ roots.push(base.join("JetBrains"));+ roots.push(base.join("Google"));+ }+ roots+}++fn quota_files(root: &Path) -> Vec<PathBuf> {+ let Ok(entries) = std::fs::read_dir(root) else { return Vec::new() };+ entries.filter_map(Result::ok).map(|entry| entry.path().join(FILE)).filter(|path| path.is_file()).collect()+}++fn parse(xml: &str) -> Vec<Window> {+ let Some(info) = option(xml, "quotaInfo") else { return Vec::new() };+ if let Some("Unknown" | "Error") = info["type"].as_str() {+ return Vec::new();+ }+ let Some(used) = number(&info["current"]) else { return Vec::new() };+ let Some(maximum) = number(&info["maximum"]) else { return Vec::new() };+ if maximum <= 0.0 {+ 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())+ });+ vec![Window::new("monthly", "AI credits", percent, resets)]+}++fn option(xml: &str, name: &str) -> Option<serde_json::Value> {+ let marker = format!("name=\"{name}\"");+ let at = xml.find(&marker)?;+ let value_at = xml[at..].find("value=\"")? + at + "value=\"".len();+ let end = xml[value_at..].find('"')? + value_at;+ let text = decode(&xml[value_at..end]);+ serde_json::from_str(&text).ok()+}++fn decode(text: &str) -> String {+ let mut out = text.replace(" ", "\n");+ // Numeric entities, then the named ones. `&` is last so `"` survives.+ let mut decoded = String::new();+ let mut rest = out.as_str();+ while let Some(at) = rest.find("&#") {+ decoded.push_str(&rest[..at]);+ let after = &rest[at + 2..];+ let Some(end) = after.find(';') else {+ decoded.push_str(&rest[at..]);+ rest = "";+ break;+ };+ if let Ok(code) = after[..end].parse::<u32>()+ && let Some(c) = char::from_u32(code)+ {+ decoded.push(c);+ }+ rest = &after[end + 1..];+ }+ decoded.push_str(rest);+ out = decoded;+ out = out.replace(""", "\"").replace("'", "'").replace("<", "<").replace(">", ">");+ out.replace("&", "&")+}++fn number(value: &serde_json::Value) -> Option<f64> {+ value.as_f64().or_else(|| value.as_str().and_then(|text| text.trim().parse().ok())).filter(|n| n.is_finite())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_ide_file_is_a_used_share_with_its_refill() {+ let xml = r#"<application><component name="AIAssistantQuotaManager2">+ <option name="quotaInfo" value="{"type":"Known","current":"10","maximum":"100"}" />+ <option name="nextRefill" value="{"next":"2026-11-01T00:00:00Z"}" />+ </component></application>"#;+ let w = parse(xml);+ assert_eq!(w[0].label, "AI credits");+ assert!((w[0].percent - 10.0).abs() < 1e-9);+ assert!(w[0].resets_at.is_some());+ }++ #[test]+ fn an_ide_that_failed_to_fetch_is_not_a_zero() {+ let xml = r#"<option name="quotaInfo" value="{"type":"Error"}" />"#;+ assert_eq!(parse(xml), Vec::new());+ }+}diff --git a/host/src/usage/kimi.rs b/host/src/usage/kimi.rsnew file mode 100644index 00000000..83373159--- /dev/null+++ b/host/src/usage/kimi.rs@@ -0,0 +1,213 @@+//! Interactive `kimi` in a terminal: wait until it accepts input, type+//! `/usage`, and read the plan lines. The TUI needs a terminal, so this is a+//! PTY rather than a pipe. Parsing covers the three layouts the CLI has shipped.++use portable_pty::{CommandBuilder, PtySize, native_pty_system};+use std::io::{Read, Write};+use std::path::Path;+use std::time::{Duration, Instant};++use super::Window;++const WAIT: Duration = Duration::from_secs(20);++pub(super) fn collect() -> Option<Vec<Window>> {+ let bin = super::command::program("kimi")?;+ let dir = probe_dir()?;+ let screen = capture(&bin, &dir)?;+ let windows = parse(&screen, crate::store::now_ms());+ if windows.is_empty() {+ tracing::debug!("kimi /usage screen had no plan lines");+ None+ } else {+ Some(windows)+ }+}++fn probe_dir() -> Option<std::path::PathBuf> {+ let dir = dirs::home_dir()?.join(".codync/probe");+ std::fs::create_dir_all(&dir).ok()?;+ Some(dir)+}++/// One `/usage` screen, or nothing if the CLI never settles.+fn capture(bin: &Path, dir: &Path) -> Option<String> {+ let pair = native_pty_system().openpty(PtySize { rows: 40, cols: 120, pixel_width: 0, pixel_height: 0 }).ok()?;+ let mut cmd = CommandBuilder::new(bin);+ cmd.cwd(dir);+ cmd.env("TERM", "xterm-256color");+ cmd.env("COLORTERM", "truecolor");+ // An inherited key would answer for a different login than `kimi login`.+ cmd.env_remove("KIMI_AUTH_TOKEN");+ cmd.env_remove("KIMI_API_KEY");+ cmd.env_remove("KIMI_BASE_URL");+ let mut child = pair.slave.spawn_command(cmd).ok()?;+ drop(pair.slave);+ let mut reader = pair.master.try_clone_reader().ok()?;+ let mut writer = pair.master.take_writer().ok()?;+ let (tx, rx) = std::sync::mpsc::channel::<Vec<u8>>();+ std::thread::spawn(move || {+ let mut buf = [0_u8; 4096];+ loop {+ match reader.read(&mut buf) {+ Ok(0) | Err(_) => break,+ Ok(n) => {+ if tx.send(buf[..n].to_vec()).is_err() {+ break;+ }+ }+ }+ }+ });+ let started = Instant::now();+ let mut raw = Vec::new();+ let mut typed = 0_u8;+ let mut trusted = false;+ let mut answered = false;+ while started.elapsed() < WAIT {+ while let Ok(chunk) = rx.try_recv() {+ raw.extend_from_slice(&chunk);+ }+ if !answered && raw.windows(b"\x1b[6n".len()).any(|window| window == b"\x1b[6n") {+ let _ = writer.write_all(b"\x1b[2;1R");+ let _ = writer.flush();+ answered = true;+ }+ let screen = String::from_utf8_lossy(&raw);+ if !trusted && (screen.contains("Trust this folder?") || screen.contains("Yes, I trust")) {+ let _ = writer.write_all(b"\r");+ let _ = writer.flush();+ trusted = true;+ }+ let ready = screen.contains("context:") || screen.contains('💫');+ let settled = started.elapsed() >= Duration::from_millis(1500);+ if typed == 0 && settled && (ready || started.elapsed() >= Duration::from_secs(8)) {+ let _ = writer.write_all(b"/usage\r");+ let _ = writer.flush();+ typed = 1;+ } else if typed == 1 && started.elapsed() >= Duration::from_secs(12) && !done(&screen) {+ let _ = writer.write_all(b"/usage\r");+ let _ = writer.flush();+ typed = 2;+ }+ if typed > 0 && done(&screen) {+ break;+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ let _ = child.kill();+ let _ = child.wait();+ let screen = super::command::strip_ansi(&String::from_utf8_lossy(&raw));+ (!screen.trim().is_empty()).then_some(screen)+}++fn done(screen: &str) -> bool {+ screen.contains("% used")+ || screen.contains("% left")+ || screen.contains("Authorization failed")+ || screen.contains("not logged in")+}++fn parse(text: &str, now_ms: i64) -> Vec<Window> {+ let mut seen = std::collections::HashSet::new();+ let mut windows = Vec::new();+ for line in text.lines() {+ let Some((id, label)) = kind(line) else { continue };+ if !seen.insert(id) {+ continue;+ }+ let Some(percent) = percent_used(line) else { continue };+ let resets = resets_in(line).map(|ms| now_ms.saturating_add(ms));+ windows.push(Window::new(id, label, percent, resets));+ }+ windows+}++fn kind(line: &str) -> Option<(&'static str, &'static str)> {+ let lower = line.to_ascii_lowercase();+ if lower.contains("weekly") {+ Some(("seven_day", "Weekly"))+ } else if lower.contains("monthly") {+ Some(("monthly", "Monthly"))+ } else if lower.contains("5h") || lower.contains("hour") {+ Some(("five_hour", "5-hour"))+ } else {+ None+ }+}++fn percent_used(line: &str) -> Option<f64> {+ if let Some(n) = before_suffix(line, "% used") {+ return Some(n.clamp(0.0, 100.0));+ }+ before_suffix(line, "% left").map(|n| (100.0 - n).clamp(0.0, 100.0))+}++fn before_suffix(line: &str, suffix: &str) -> Option<f64> {+ let at = line.find(suffix)?;+ let head = line[..at].trim_end();+ let token: String = head.chars().rev().take_while(|c| c.is_ascii_digit() || *c == '.').collect();+ token.chars().rev().collect::<String>().parse().ok()+}++/// `resets in 6d 23h 22m` → milliseconds from now.+fn resets_in(line: &str) -> Option<i64> {+ let rest = line.split("resets in ").nth(1)?;+ let mut total = 0_i64;+ let mut number = String::new();+ let mut any = false;+ for c in rest.chars() {+ if c.is_ascii_digit() {+ number.push(c);+ continue;+ }+ if let Some(unit) = unit_ms(c)+ && let Ok(n) = number.parse::<i64>()+ {+ total = total.saturating_add(n.saturating_mul(unit));+ any = true;+ }+ number.clear();+ if c == ')' || c == '\n' {+ break;+ }+ }+ any.then_some(total)+}++fn unit_ms(c: char) -> Option<i64> {+ Some(match c {+ 'd' => 86_400_000,+ 'h' => 3_600_000,+ 'm' => 60_000,+ 's' => 1_000,+ _ => return None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn three_layouts_become_used_percent_and_a_reset() {+ let old = "Weekly limit 100% left (resets in 6d 23h)\n5h limit 80% left (resets in 4h 22m)";+ let mid = "Weekly limit 90% used resets in 35m\n5h limit 12% used resets in 3h 35m";+ let new =+ "5h limit 0% used resets in 2h 41m\nMonthly limit 2% used resets in 24d 16h 42m\nkimi 2% · code 0%";+ let now = 1_000_000_i64;+ let a = parse(old, now);+ assert_eq!(a[0].id, "seven_day");+ assert!(a[0].percent.abs() < 1e-9);+ assert_eq!(a[0].resets_at, Some(now + 6 * 86_400_000 + 23 * 3_600_000));+ assert!((a[1].percent - 20.0).abs() < 1e-9);+ let b = parse(mid, now);+ assert!((b[0].percent - 90.0).abs() < 1e-9);+ assert_eq!(b[0].resets_at, Some(now + 35 * 60_000));+ let c = parse(new, now);+ assert_eq!(c[0].id, "five_hour");+ assert_eq!(c[1].label, "Monthly");+ assert!((c[1].percent - 2.0).abs() < 1e-9);+ assert_eq!(c.len(), 2, "the context mix line is not a plan window");+ }+}diff --git a/host/src/usage/kiro.rs b/host/src/usage/kiro.rsnew file mode 100644index 00000000..cfdfc3e6--- /dev/null+++ b/host/src/usage/kiro.rs@@ -0,0 +1,104 @@+//! `kiro-cli` given `/usage` then `/quit` on stdin. Monthly plan credits and+//! bonus credits, as a share used.++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)+ }+}++fn parse(text: &str, now_ms: i64) -> Vec<Window> {+ let text = super::command::strip_ansi(text);+ let mut windows = Vec::new();+ if let Some(w) = pair(&text, "Bonus credits:", "bonus", "Bonus credits", expiry_ms(&text, now_ms)) {+ windows.push(w);+ }+ if let Some(w) = credits(&text, now_ms) {+ windows.push(w);+ }+ windows+}++/// `Bonus credits: X/Y` — X is the amount already used.+fn pair(text: &str, marker: &str, id: &str, label: &str, resets: Option<i64>) -> Option<Window> {+ let at = text.find(marker)?;+ let rest = text[at + marker.len()..].trim_start();+ let (left, right) = rest.split_once('/')?;+ let used: f64 = take_number(left)?;+ let total: f64 = take_number(right)?;+ if total <= 0.0 {+ return None;+ }+ Some(Window::new(id, label, (used / total * 100.0).clamp(0.0, 100.0), resets))+}++fn credits(text: &str, now_ms: i64) -> Option<Window> {+ let at = text.find("Credits (")?;+ let rest = &text[at + "Credits (".len()..];+ let (used_text, after) = rest.split_once(" of ")?;+ let used: f64 = take_number(used_text)?;+ let total: f64 = take_number(after)?;+ if total <= 0.0 {+ return None;+ }+ Some(Window::new("monthly", "Monthly", (used / total * 100.0).clamp(0.0, 100.0), reset_on(text, now_ms)))+}++fn expiry_ms(text: &str, now_ms: i64) -> Option<i64> {+ let at = text.find("expires in ")?;+ let days: i64 = take_number(&text[at + "expires in ".len()..])?;+ Some(now_ms.saturating_add(days.saturating_mul(86_400_000)))+}++/// `resets on MM/DD`: this year's date, or next year's once that midnight has passed.+fn reset_on(text: &str, now_ms: i64) -> Option<i64> {+ let at = text.find("resets on ")?;+ let rest = text[at + "resets on ".len()..].trim_start();+ let (month, day) = rest.split_once('/')?;+ let month: u32 = month.trim().parse().ok()?;+ let day: u32 = take_number(day)?;+ let now = chrono::DateTime::from_timestamp_millis(now_ms)?.with_timezone(&chrono::Local);+ next_month_day(month, day, now)+}++fn next_month_day(month: u32, day: u32, now: chrono::DateTime<chrono::Local>) -> Option<i64> {+ use chrono::{Datelike, TimeZone};+ let year = now.year();+ let at = |y: i32| chrono::Local.with_ymd_and_hms(y, month, day, 0, 0, 0).single();+ let date = at(year).filter(|d| *d >= now).or_else(|| at(year + 1))?;+ Some(date.timestamp_millis())+}++fn take_number<T: std::str::FromStr>(text: &str) -> Option<T> {+ let token: String = text.trim_start().chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();+ token.parse().ok()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn monthly_credits_and_bonus_are_shares_used() {+ let text =+ "Bonus credits: 20/100 left, expires in 12 days\nCredits (25 of 200 covered in plan) resets on 11/02\n";+ let w = parse(text, 1_761_400_000_000);+ assert_eq!(w.len(), 2);+ assert_eq!(w[0].label, "Bonus credits");+ assert!((w[0].percent - 20.0).abs() < 1e-9);+ assert_eq!(w[0].resets_at, Some(1_761_400_000_000 + 12 * 86_400_000));+ assert_eq!(w[1].label, "Monthly");+ assert!((w[1].percent - 12.5).abs() < 1e-9);+ assert!(w[1].resets_at.is_some());+ }+}diff --git a/host/src/usage/mod.rs b/host/src/usage/mod.rsnew file mode 100644index 00000000..d0bf3981--- /dev/null+++ b/host/src/usage/mod.rs@@ -0,0 +1,220 @@+//! Subscription usage, read on the host.+//!+//! Claude: `claude -p /usage`, the status line, and the ACP rate-limit event.+//! Codex: the newest rollout's `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.+//!+//! Cursor has no local report. The host reads the token the Cursor app saved+//! and asks `cursor.com/api/usage-summary`. That is the only provider call, and+//! the token is never logged.++mod amp;+mod antigravity;+mod claude;+mod codex;+mod command;+mod cursor;+mod junie;+mod kimi;+mod kiro;+mod omp;+mod opencode;+mod vibe;++pub use claude::{ingest_claude_rate_limit, ingest_statusline};++use crate::LockExt;+use crate::hub::Hub;+use serde::Serialize;+use std::sync::Arc;+use std::time::Duration;++const POLL_EVERY: Duration = Duration::from_secs(5 * 60);+/// Usage of a plan above which background work (dreaming, the lead's check-ins) waits.+const HEADROOM_PERCENT: f64 = 75.0;++/// Usage of harness `backend`'s plan above [`HEADROOM_PERCENT`] in any window.+/// A note (today's tokens, a dollar balance) is not a plan window.+pub fn near_limit(hub: &Hub, backend: &str) -> bool {+ hub.usage.locked().providers.iter().filter(|p| p.id == backend).any(|p| over_headroom(&p.windows))+}++fn over_headroom(windows: &[Window]) -> bool {+ windows.iter().any(|w| w.text.is_none() && w.percent > HEADROOM_PERCENT)+}++/// Everything the apps show about limits (wire shape of the `usage` event).+#[derive(Serialize, Clone, Debug, Default, PartialEq)]+pub struct Usage {+ pub providers: Vec<Provider>,+}++#[derive(Serialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct Provider {+ pub id: &'static str,+ pub name: &'static str,+ pub windows: Vec<Window>,+ /// Where the numbers came from: `claude` (CLI), `statusline`, `agent`, `sessions`,+ /// or a short phrase for the other agents.+ pub source: &'static str,+ pub updated_at: i64,+}++#[derive(Serialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct Window {+ pub id: String,+ pub label: String,+ /// Share of the cap already used, 0–100. Zero when [`Self::text`] is set.+ pub percent: f64,+ /// Epoch milliseconds, when known.+ pub resets_at: Option<i64>,+ /// Human text when only that is known ("Sep 26 at 12pm (Asia/Taipei)").+ #[serde(skip_serializing_if = "Option::is_none")]+ pub resets_text: Option<String>,+ /// A reading that isn't a share of a cap ("$4.20", "1.2M tokens", "Unlimited").+ /// Clients show this instead of the percent, and it never counts as the tightest limit.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,+}++impl Window {+ fn new(id: impl Into<String>, label: impl Into<String>, percent: f64, resets_at: Option<i64>) -> Self {+ Self { id: id.into(), label: label.into(), percent, resets_at, resets_text: None, text: None }+ }++ /// A row with no bar: today's tokens, an uncapped balance, an unlimited plan.+ fn note(id: impl Into<String>, label: impl Into<String>, text: impl Into<String>) -> Self {+ Self { text: Some(text.into()), ..Self::new(id, label, 0.0, None) }+ }+}++impl Usage {+ /// Replaces `new` windows (by id) in provider `id`, keeping the provider's other windows.+ fn merge(&mut self, id: &'static str, name: &'static str, source: &'static str, new: Vec<Window>) {+ let mut windows = self.providers.iter().find(|p| p.id == id).map(|p| p.windows.clone()).unwrap_or_default();+ windows.retain(|w| !new.iter().any(|n| n.id == w.id));+ 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.sort_by_key(|p| p.id);+ }+}++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);+}++pub async fn poll(hub: Arc<Hub>) {+ loop {+ refresh(&hub).await;+ tokio::time::sleep(POLL_EVERY).await;+ }+}++pub async fn refresh(hub: &Hub) {+ let (+ codex,+ claude,+ omp_windows,+ amp_windows,+ kiro_windows,+ kimi_windows,+ antigravity,+ opencode,+ vibe_notes,+ junie,+ cursor_windows,+ ) = tokio::join!(+ tokio::task::spawn_blocking(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, joined(codex), "codex", "Codex", "sessions");+ 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()+}++pub(super) fn finite_i64(n: f64) -> Option<i64> {+ if !n.is_finite() {+ return None;+ }+ let rounded = n.round();+ #[allow(clippy::cast_precision_loss)]+ let (min, max) = (i64::MIN as f64, i64::MAX as f64);+ if !(min..=max).contains(&rounded) {+ return None;+ }+ #[allow(clippy::cast_possible_truncation)]+ Some(rounded as i64)+}++fn apply(hub: &Hub, windows: Option<Vec<Window>>, id: &'static str, name: &'static str, source: &'static str) {+ if let Some(windows) = windows.filter(|windows| !windows.is_empty()) {+ merge(hub, id, name, source, windows);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::Value;++ #[test]+ fn merge_replaces_only_matching_windows() {+ let mut u = Usage::default();+ u.merge(+ "claude",+ "Claude",+ "claude",+ vec![Window::new("five_hour", "5-hour", 10.0, None), Window::new("seven_day", "Weekly", 50.0, None)],+ );+ u.merge("claude", "Claude", "statusline", vec![Window::new("five_hour", "5-hour", 12.0, None)]);+ let c = &u.providers[0];+ assert_eq!((c.windows.len(), c.source), (2, "statusline"));+ assert!((c.windows[0].percent - 12.0).abs() < f64::EPSILON, "five_hour updated");+ assert_eq!(serde_json::to_value(&u).unwrap()["providers"][0]["windows"][1]["resetsAt"], Value::Null);+ }++ #[test]+ fn a_note_is_not_serialized_as_a_missing_percent() {+ let window = Window::note("cost", "Cost today", "$1.50");+ let value = serde_json::to_value(&window).unwrap();+ assert_eq!(value["text"], "$1.50");+ assert_eq!(value["percent"], 0.0);+ assert!(value.get("resetsText").is_none());+ }++ #[test]+ fn a_note_does_not_count_as_the_plan_running_out() {+ let note = Window { percent: 99.0, ..Window::note("cost", "Cost today", "$9") };+ assert!(!over_headroom(&[note]));+ assert!(over_headroom(&[Window::new("five_hour", "5-hour", 80.0, None)]));+ }+}diff --git a/host/src/usage/omp.rs b/host/src/usage/omp.rsnew file mode 100644index 00000000..5cd7cbcd--- /dev/null+++ b/host/src/usage/omp.rs@@ -0,0 +1,165 @@+//! `omp usage --json`: one window per upstream limit oh-my-pi reports.+//! Claude and Codex stay on their own cards; these windows belong to oh-my-pi,+//! labeled with the upstream, so a second login isn't written over the CLI's.++use serde_json::Value;+use std::collections::{HashMap, HashSet};+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)+ }+}++fn parse(text: &str) -> Vec<Window> {+ let Some(start) = text.find('{') else { return Vec::new() };+ let Some(end) = text.rfind('}') else { return Vec::new() };+ if end <= start {+ return Vec::new();+ }+ let Ok(payload) = serde_json::from_str::<Value>(&text[start..=end]) else { return Vec::new() };+ let Some(reports) = payload["reports"].as_array() else { return Vec::new() };+ let mut per_provider: HashMap<&str, usize> = HashMap::new();+ for report in reports {+ if let Some(id) = report["provider"].as_str() {+ *per_provider.entry(id).or_insert(0) += 1;+ }+ }+ let mut windows = Vec::new();+ for (index, report) in reports.iter().enumerate() {+ let Some(provider) = report["provider"].as_str() else { continue };+ let name = provider_name(provider);+ let suffix = (per_provider.get(provider).copied().unwrap_or(0) > 1).then(|| discriminator(report, index));+ let mut pools = HashSet::new();+ let Some(limits) = report["limits"].as_array() else { continue };+ for (n, limit) in limits.iter().enumerate() {+ if let Some(pool) = limit["scope"]["sharedGroup"].as_str().filter(|s| !s.is_empty())+ && !pools.insert(pool.to_owned())+ {+ continue;+ }+ let Some(window) = one_limit(&name, suffix.as_deref(), provider, n, limit) else { continue };+ windows.push(window);+ }+ }+ windows+}++fn one_limit(name: &str, suffix: Option<&str>, provider: &str, n: usize, limit: &Value) -> Option<Window> {+ let amount = &limit["amount"];+ let window_id = limit["scope"]["windowId"].as_str().or_else(|| limit["window"]["id"].as_str()).unwrap_or("limit");+ let raw_label = limit["label"].as_str().map(str::trim).filter(|s| !s.is_empty());+ let label = match (raw_label, suffix) {+ (Some(label), Some(suffix)) => format!("{label} · {suffix}"),+ (Some(label), None) => label.to_owned(),+ (None, Some(suffix)) => format!("{name} · {suffix}"),+ (None, None) => name.to_owned(),+ };+ let id = format!("{provider}:{window_id}:{n}");+ let resets = epoch_ms(&limit["window"]["resetsAt"]);+ if amount["unit"].as_str().is_some_and(|u| u.eq_ignore_ascii_case("usd")) && amount["limit"].is_null() {+ let spent = amount["used"].as_f64()?;+ return Some(Window::note(id, label, format!("${spent:.2} spent")));+ }+ let percent = used_percent(amount)?;+ Some(Window::new(id, label, percent, resets))+}++/// Used share, 0–100. Fractions are 0–1; `used`/`limit` is a count or dollars.+fn used_percent(amount: &Value) -> Option<f64> {+ if let Some(used) = amount["usedFraction"].as_f64() {+ return Some((used * 100.0).clamp(0.0, 100.0));+ }+ if let Some(left) = amount["remainingFraction"].as_f64() {+ return Some(((1.0 - left) * 100.0).clamp(0.0, 100.0));+ }+ let used = amount["used"].as_f64()?;+ let limit = amount["limit"].as_f64().filter(|n| *n > 0.0)?;+ Some((used / limit * 100.0).clamp(0.0, 100.0))+}++fn epoch_ms(v: &Value) -> Option<i64> {+ 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) })+}++fn discriminator(report: &Value, index: usize) -> String {+ let email = report["metadata"]["email"].as_str().filter(|s| s.contains('@'));+ if let Some(email) = email {+ return email.split('@').next().unwrap_or(email).chars().take(16).collect();+ }+ report["metadata"]["accountId"].as_str().map_or_else(|| format!("#{}", index + 1), |s| s.chars().take(8).collect())+}++fn provider_name(id: &str) -> String {+ match id {+ "anthropic" => "Claude",+ "openai-codex" => "Codex",+ "zai" => "Z.ai",+ "google-gemini-cli" => "Gemini",+ "google-antigravity" => "Antigravity",+ "github-copilot" => "Copilot",+ "kimi-code" => "Kimi",+ "minimax-code" => "MiniMax",+ "minimax-code-cn" => "MiniMax CN",+ "opencode-go" => "OpenCode Go",+ "alibaba-token-plan" => "Qwen Cloud",+ "xai-oauth" => "Grok",+ other => return title_case(other),+ }+ .to_owned()+}++fn title_case(id: &str) -> String {+ id.split('-')+ .map(|part| {+ let mut chars = part.chars();+ match chars.next() {+ Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),+ None => String::new(),+ }+ })+ .collect::<Vec<_>>()+ .join(" ")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_a_used_fraction_and_a_dollar_cap() {+ let text = r#"status+{"reports":[+ {"provider":"anthropic","limits":[{"label":"Claude 5 Hour","scope":{"windowId":"5h"},+ "window":{"id":"5h","resetsAt":1783885200000},+ "amount":{"usedFraction":0.08,"unit":"percent"}}]},+ {"provider":"xai-oauth","limits":[{"label":"Spend","scope":{"windowId":"monthly"},+ "amount":{"used":4.5,"limit":20,"unit":"usd"}}]}+]}"#;+ let w = parse(text);+ assert_eq!(w[0].label, "Claude 5 Hour");+ assert!((w[0].percent - 8.0).abs() < 1e-9);+ assert_eq!(w[0].resets_at, Some(1_783_885_200_000));+ assert!((w[1].percent - 22.5).abs() < 1e-9);+ assert_eq!(w[1].label, "Spend");+ }++ #[test]+ fn an_uncapped_dollar_spend_is_a_note() {+ let text = r#"{"reports":[{"provider":"openai","limits":[+ {"label":"API","amount":{"used":3.2,"unit":"usd"}}]}]}"#;+ let w = parse(text);+ assert_eq!(w[0].text.as_deref(), Some("$3.20 spent"));+ assert!(w[0].percent.abs() < f64::EPSILON);+ }+}diff --git a/host/src/usage/opencode-both.sql b/host/src/usage/opencode-both.sqlnew file mode 100644index 00000000..0859c8be--- /dev/null+++ b/host/src/usage/opencode-both.sql@@ -0,0 +1 @@+WITH spent AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM session_message WHERE type = 'assistant' AND json_valid(data) AND json_extract(data, '$.model.providerID') = 'opencode-go' AND json_type(data, '$.cost') IN ('integer', 'real') UNION ALL SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM message WHERE json_valid(data) AND json_extract(data, '$.providerID') = 'opencode-go' AND json_extract(data, '$.role') = 'assistant' AND json_type(data, '$.cost') IN ('integer', 'real') ), rows AS ( SELECT id, MAX(t) AS t, MAX(cost) AS cost FROM spent GROUP BY id ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_msdiff --git a/host/src/usage/opencode-message.sql b/host/src/usage/opencode-message.sqlnew file mode 100644index 00000000..71368095--- /dev/null+++ b/host/src/usage/opencode-message.sql@@ -0,0 +1 @@+WITH rows AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM message WHERE json_valid(data) AND json_extract(data, '$.providerID') = 'opencode-go' AND json_extract(data, '$.role') = 'assistant' AND json_type(data, '$.cost') IN ('integer', 'real') ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_msdiff --git a/host/src/usage/opencode-session.sql b/host/src/usage/opencode-session.sqlnew file mode 100644index 00000000..c84e9de4--- /dev/null+++ b/host/src/usage/opencode-session.sql@@ -0,0 +1 @@+WITH rows AS ( SELECT id, CAST(COALESCE(json_extract(data, '$.time.created'), time_created) AS INTEGER) AS t, CAST(json_extract(data, '$.cost') AS REAL) AS cost FROM session_message WHERE type = 'assistant' AND json_valid(data) AND json_extract(data, '$.model.providerID') = 'opencode-go' AND json_type(data, '$.cost') IN ('integer', 'real') ), clock AS ( SELECT CAST(strftime('%s', 'now') AS INTEGER) * 1000 AS now_ms, CAST(strftime('%s', date('now', '-6 days', 'weekday 1')) AS INTEGER) * 1000 AS week_ms ), anchor AS ( SELECT MIN(t) AS ms, CAST(strftime('%d', MIN(t) / 1000, 'unixepoch') AS INTEGER) AS day, strftime('%H:%M:%S', MIN(t) / 1000, 'unixepoch') AS at FROM rows ), months AS ( SELECT ms, day, at, date('now', 'start of month', '-1 month') AS m0, date('now', 'start of month') AS m1, date('now', 'start of month', '+1 month') AS m2 FROM anchor WHERE ms IS NOT NULL ), starts AS ( SELECT datetime(date(m0, '+' || (MIN(day, CAST(strftime('%d', date(m0, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s0, datetime(date(m1, '+' || (MIN(day, CAST(strftime('%d', date(m1, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s1, datetime(date(m2, '+' || (MIN(day, CAST(strftime('%d', date(m2, '+1 month', '-1 day')) AS INTEGER)) - 1) || ' days') || ' ' || at) AS s2 FROM months ), month AS ( SELECT CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s1 ELSE s0 END) AS INTEGER) * 1000 AS start_ms, CAST(strftime('%s', CASE WHEN s1 <= datetime('now') THEN s2 ELSE s1 END) AS INTEGER) * 1000 AS end_ms FROM starts ) SELECT (SELECT now_ms FROM clock) AS now_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_cost, (SELECT MIN(t) FROM rows, clock WHERE t >= now_ms - 18000000) AS five_hour_oldest_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, clock WHERE t >= week_ms) AS weekly_cost, (SELECT week_ms + 604800000 FROM clock) AS week_end_ms, (SELECT COALESCE(SUM(cost), 0) FROM rows, month WHERE t >= start_ms AND t < end_ms) AS monthly_cost, (SELECT start_ms FROM month) AS month_start_ms, (SELECT end_ms FROM month) AS month_end_msdiff --git a/host/src/usage/opencode.rs b/host/src/usage/opencode.rsnew file mode 100644index 00000000..bf41414a--- /dev/null+++ b/host/src/usage/opencode.rs@@ -0,0 +1,119 @@+//! OpenCode Go's plan, added up from this computer's opencode database.+//! The caps are the plan's ($12 / 5 h, $30 / week, $60 / month). This is an+//! estimate of what this machine spent, not the dashboard's own number.++use rusqlite::{Connection, OpenFlags};+use std::path::{Path, PathBuf};++use super::Window;++const CAP_5H: f64 = 12.0;+const CAP_WEEK: f64 = 30.0;+const CAP_MONTH: f64 = 60.0;++const QUERY_BOTH: &str = include_str!("opencode-both.sql");+const QUERY_SESSION: &str = include_str!("opencode-session.sql");+const QUERY_MESSAGE: &str = include_str!("opencode-message.sql");++pub(super) fn collect() -> Option<Vec<Window>> {+ from_db(&db_path()?)+}++fn db_path() -> Option<PathBuf> {+ let base = std::env::var_os("XDG_DATA_HOME")+ .map(PathBuf::from)+ .filter(|p| !p.as_os_str().is_empty())+ .or_else(|| dirs::home_dir().map(|home| home.join(".local/share")))?;+ let path = base.join("opencode/opencode.db");+ path.is_file().then_some(path)+}++fn from_db(path: &Path) -> Option<Vec<Window>> {+ let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).ok()?;+ conn.busy_timeout(std::time::Duration::from_millis(200)).ok()?;+ let query = if has_table(&conn, "message") && has_table(&conn, "session_message") {+ QUERY_BOTH+ } else if has_table(&conn, "session_message") {+ QUERY_SESSION+ } else if has_table(&conn, "message") {+ QUERY_MESSAGE+ } else {+ return None;+ };+ let row = conn+ .query_row(query, [], |row| {+ Ok((+ integer(row, 0),+ number(row, 1),+ integer(row, 2),+ number(row, 3),+ integer(row, 4),+ number(row, 5),+ integer(row, 7),+ ))+ })+ .ok()?;+ let (now_ms, five_hour, oldest, weekly, week_end, monthly, month_end) = row;+ let now_ms = now_ms?;+ let five_reset = oldest.unwrap_or(now_ms).saturating_add(18_000_000);+ Some(vec![+ Window::new("five_hour", "5-hour", share(five_hour?, CAP_5H), Some(five_reset)),+ Window::new("seven_day", "Weekly", share(weekly?, CAP_WEEK), week_end),+ Window::new("monthly", "Monthly", share(monthly?, CAP_MONTH), month_end),+ ])+}++fn share(spent: f64, cap: f64) -> f64 {+ if cap <= 0.0 { 0.0 } else { (spent / cap * 100.0).clamp(0.0, 100.0) }+}++fn has_table(conn: &Connection, name: &str) -> bool {+ conn.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1", [name], |_| Ok(())).is_ok()+}++fn number(row: &rusqlite::Row<'_>, index: usize) -> Option<f64> {+ match row.get_ref(index).ok()? {+ #[allow(clippy::cast_precision_loss)]+ rusqlite::types::ValueRef::Integer(n) => Some(n as f64),+ rusqlite::types::ValueRef::Real(n) => Some(n),+ rusqlite::types::ValueRef::Text(bytes) => std::str::from_utf8(bytes).ok()?.parse().ok(),+ _ => None,+ }+}++fn integer(row: &rusqlite::Row<'_>, index: usize) -> Option<i64> {+ match row.get_ref(index).ok()? {+ rusqlite::types::ValueRef::Integer(n) => Some(n),+ rusqlite::types::ValueRef::Real(n) => super::finite_i64(n),+ rusqlite::types::ValueRef::Null | rusqlite::types::ValueRef::Blob(_) => None,+ rusqlite::types::ValueRef::Text(bytes) => std::str::from_utf8(bytes).ok()?.parse().ok(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_go_message_fills_the_three_windows() {+ let path = std::env::temp_dir().join(format!("codync-opencode-{}.db", std::process::id()));+ let _ = std::fs::remove_file(&path);+ let conn = Connection::open(&path).unwrap();+ conn.execute("CREATE TABLE session_message (id TEXT, data TEXT, type TEXT, time_created INTEGER)", []).unwrap();+ let millis = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis();+ let now = i64::try_from(millis).unwrap();+ let data = format!(r#"{{"cost":6,"time":{{"created":{now}}},"model":{{"providerID":"opencode-go"}}}}"#);+ conn.execute(+ "INSERT INTO session_message (id, data, type, time_created) VALUES ('m', ?1, 'assistant', ?2)",+ rusqlite::params![data, now],+ )+ .unwrap();+ drop(conn);+ let windows = from_db(&path).unwrap();+ let _ = std::fs::remove_file(&path);+ assert!((windows[0].percent - 50.0).abs() < 0.01, "5-hour {}", windows[0].percent);+ assert!((windows[1].percent - 20.0).abs() < 0.01, "week {}", windows[1].percent);+ assert!((windows[2].percent - 10.0).abs() < 0.01, "month {}", windows[2].percent);+ assert!(windows[0].resets_at.is_some());+ }+}diff --git a/host/src/usage/vibe.rs b/host/src/usage/vibe.rsnew file mode 100644index 00000000..ed698680--- /dev/null+++ b/host/src/usage/vibe.rs@@ -0,0 +1,109 @@+//! Today's tokens and cost from Mistral Vibe's session logs. There is no plan+//! percent here — that lives behind a browser cookie — so these are notes,+//! not limit bars.++use std::path::Path;++use super::Window;++pub(super) fn collect() -> Option<Vec<Window>> {+ let root = dirs::home_dir()?.join(".vibe/logs/session");+ if !root.is_dir() {+ return None;+ }+ let now = crate::store::now_ms();+ let start = local_midnight(now)?;+ let mut tokens = 0.0;+ let mut cost = 0.0;+ let mut any = false;+ let entries = std::fs::read_dir(&root).ok()?;+ for entry in entries.filter_map(Result::ok) {+ let name = entry.file_name();+ let Some(name) = name.to_str() else { continue };+ let Some(at) = session_ms(name) else { continue };+ if at < start || at > now.saturating_add(86_400_000) {+ continue;+ }+ let meta = entry.path().join("meta.json");+ let Some((session_tokens, session_cost)) = read_meta(&meta) else { continue };+ any = true;+ tokens += session_tokens;+ cost += session_cost;+ }+ any.then(|| notes(tokens, cost))+}++fn notes(tokens: f64, cost: f64) -> Vec<Window> {+ let mut windows = Vec::new();+ if tokens > 0.0 {+ windows.push(Window::note("tokens", "Tokens today", token_text(tokens)));+ }+ if cost > 0.0 {+ windows.push(Window::note("cost", "Cost today", format!("${cost:.2}")));+ }+ windows+}++fn read_meta(path: &Path) -> Option<(f64, f64)> {+ let text = std::fs::read_to_string(path).ok()?;+ let value: serde_json::Value = serde_json::from_str(&text).ok()?;+ let stats = &value["stats"];+ let tokens = stats["session_total_llm_tokens"].as_f64().unwrap_or(0.0);+ let cost = stats["session_cost"].as_f64().unwrap_or(0.0);+ Some((tokens, cost))+}++/// `session_YYYYMMDD_HHMMSS`, the stamp Vibe puts on the folder, in UTC.+fn session_ms(name: &str) -> Option<i64> {+ let stamp = name.strip_prefix("session_")?;+ let (date, time) = stamp.split_once('_')?;+ if date.len() != 8 || time.len() < 6 {+ return None;+ }+ let year: i32 = date[0..4].parse().ok()?;+ let month: u32 = date[4..6].parse().ok()?;+ let day: u32 = date[6..8].parse().ok()?;+ let hour: u32 = time[0..2].parse().ok()?;+ let minute: u32 = time[2..4].parse().ok()?;+ let second: u32 = time[4..6].parse().ok()?;+ let at = chrono::NaiveDate::from_ymd_opt(year, month, day)?.and_hms_opt(hour, minute, second)?;+ Some(at.and_utc().timestamp_millis())+}++fn local_midnight(now_ms: i64) -> Option<i64> {+ let now = chrono::DateTime::from_timestamp_millis(now_ms)?.with_timezone(&chrono::Local);+ let day = now.date_naive();+ Some(day.and_hms_opt(0, 0, 0)?.and_local_timezone(chrono::Local).single()?.timestamp_millis())+}++fn token_text(n: f64) -> String {+ if n >= 1_000_000.0 {+ format!("{:.1}M tokens", n / 1_000_000.0)+ } else if n >= 1_000.0 {+ format!("{:.1}k tokens", n / 1_000.0)+ } else {+ format!("{n:.0} tokens")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_folder_stamp_is_utc_and_today_sums() {+ let at = session_ms("session_20261025_153045").unwrap();+ assert_eq!(+ at,+ chrono::NaiveDate::from_ymd_opt(2026, 10, 25)+ .unwrap()+ .and_hms_opt(15, 30, 45)+ .unwrap()+ .and_utc()+ .timestamp_millis()+ );+ let notes = notes(1_500_000.0, 1.5);+ assert_eq!(notes[0].text.as_deref(), Some("1.5M tokens"));+ assert_eq!(notes[1].text.as_deref(), Some("$1.50"));+ }+}diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex aad5ff3a..aa71723d 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -146,7 +146,7 @@ When you send a message from the iPhone, a Live Activity for that bot appears on## Usage limits-Codync reads usage limits for Claude Code and Codex from their installs on your computer, without signing in anywhere else. To see them:+Codync reads plan limits from the agents installed on your computer. Claude Code and Codex come from their own usage report and session files. 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 Cursor saved on this computer and asks cursor.com for the summary. Nothing else is sent with an agent's login. To see them:- **iPhone:** 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.diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdxindex 5c31a8d8..da94c9bc 100644--- a/web/content/docs/linux-servers.mdx+++ b/web/content/docs/linux-servers.mdx@@ -104,7 +104,7 @@ codync-host devices revoke <key> # removes one; it disconnects at once- **Saved secrets need a keyring.** Connector credentials, voice API keys and agent API keys are encrypted with a key kept in the Secret Service (for example GNOME Keyring). The host's user needs a session D-Bus and an unlocked Secret Service; without one, saving such a secret fails with an error, and new bots start with no connectors turned on. Codync never falls back to storing them in plain text.- **No desktop app on the server itself.** The Linux desktop app needs a graphical session. Use the phone, the desktop app on another computer over SSH, or the terminal UI.- **Keeping the machine awake does nothing.** VMs don't sleep; if the host can't hold off sleep, it only logs a warning.-- **Usage limits** come from the Claude Code and Codex installs on the server, the same as on a desktop.+- **Usage limits** come from the agents installed on the server, the same as on a desktop. Cursor asks cursor.com with the sign-in saved on that server.## Updatesdiff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdxindex 908d14fd..cadac7ca 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 locally.** The host reads them from the agents installed on the computer: Claude Code's own usage command and status line, and Codex's local session files. Codync doesn't call any provider's API with your agents' logins. 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.** The host reads them from the agents installed there: Claude Code's usage command and status line, Codex's session files, and the same kind of local report from oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie. Cursor is the exception. It has no local report, so the host reads the sign-in Cursor saved and asks cursor.com for the 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