Skip to content

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

fix(host): keep Cursor usage when the dashboard request fails

leepokai61e0f41111a3
diff --git a/CLAUDE.md b/CLAUDE.md
index 839f1da4..8959c931 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: read from the agents on the computer — Claude's `claude -p /usage --no-session-persistence`, the status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update`, the Codex CLI's `account/rateLimits/read` (`codex app-server`, no turn), and the other agents' local commands, databases and IDE files. Cursor is the one provider call: the token Cursor saved, then `cursor.com/api/usage-summary`. Never call any other provider API 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`, the Codex CLI's `account/rateLimits/read` (`codex app-server`, no turn), and the other agents' local commands, databases and IDE files. Cursor is the one provider call: the token Cursor saved, then its dashboard service (unified plans) or `cursor.com/api/usage-summary`. Never call any other provider API with agent credentials.
- The desktop app is thin: the Mac build bundles `codync-host` in `Contents/Resources` (Linux uses the installed host) and installs it as a launchd/systemd agent via `codync-host install`; the menu bar/tray shows status/pairing/usage and opens the chat window. Not sandboxed, not Mac App Store (the host must spawn CLIs).
## Cross-platform UI changes
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index 803e7e01..ccf9756c 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -58,7 +58,7 @@ The CLI must be signed in as the user running the host. Missing, rejected or una
Settings > Usage lists Cursor alongside every other provider the host reports. When no desktop login is available in the Cursor app's `state.vscdb`, the host reads the CLI's `accessToken` from its saved `auth.json`: `$XDG_CONFIG_HOME/cursor/auth.json` (normally `~/.config/cursor/auth.json`) on Linux, `%APPDATA%/Cursor/auth.json` on Windows, and `~/.cursor/auth.json` on macOS when the CLI uses file storage. A macOS CLI login stored only in Keychain still needs the desktop-app login for usage reporting.
-Every five minutes, the host calls `https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus` with the saved bearer token. A unified plan (`isUnified: true`, including Super) reports one **Weekly** window from `usagePercent`, resetting at `nextResetTimestampUtc`. Missing usage is not converted to zero. The legacy `https://cursor.com/api/usage-summary` endpoint is read only for non-unified plans, retaining their Monthly, Auto and API readings. Its monthly fields can report zero for a unified plan even when the unified allowance is partly used, so they never supply a unified reading. The host sends the existing `usage` event and never logs or changes the credentials. Existing client views render the weekly window without a client or protocol change.
+Every five minutes, the host calls `https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus` with the saved bearer token. A unified plan (`isUnified: true`, including Super) reports one **Weekly** window from `usagePercent`, resetting at `nextResetTimestampUtc`. Missing usage is not converted to zero. The legacy `https://cursor.com/api/usage-summary` endpoint is read for non-unified plans, retaining their Monthly, Auto and API readings, and also when the dashboard request fails unless the dashboard last named a unified plan; then that poll keeps the previous Weekly window. Its monthly fields can report zero for a unified plan even when the unified allowance is partly used, so they never supply a unified reading. The host sends the existing `usage` event and never logs or changes the credentials. Existing client views render the weekly window without a client or protocol change.
## WorkBuddy
diff --git a/host/src/usage/cursor.rs b/host/src/usage/cursor.rs
index 4a9ff7b1..59931feb 100644
--- a/host/src/usage/cursor.rs
+++ b/host/src/usage/cursor.rs
@@ -7,13 +7,25 @@ use base64::engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD};
use rusqlite::{Connection, OpenFlags};
use serde_json::Value;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use super::Window;
+/// Whether the dashboard last named a unified plan, so a failed poll keeps its weekly reading.
+static LAST_UNIFIED: AtomicBool = AtomicBool::new(false);
+
+/// Which reading a poll reports.
+#[derive(Debug, PartialEq)]
+enum Route {
+ /// The dashboard's weekly window, or `None` to keep the last one.
+ Unified(Option<Vec<Window>>),
+ /// The legacy plan's usage summary.
+ Summary,
+}
+
pub(super) async fn collect() -> Option<Vec<Window>> {
- let token_result = tokio::task::spawn_blocking(read_token).await;
- let token = token_result.ok().flatten()?;
+ let token = tokio::task::spawn_blocking(read_token).await.ok().flatten()?;
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.redirect(reqwest::redirect::Policy::none())
@@ -25,32 +37,35 @@ pub(super) async fn collect() -> Option<Vec<Window>> {
.bearer_auth(&token)
.header("Connect-Protocol-Version", "1")
.json(&serde_json::json!({}));
- let status_result = read_response(status_request).await;
- let status = status_result?;
- if status["isUnified"].as_bool() == Some(true) {
- return parse_unified(&status);
+ let status = read_response(status_request).await;
+ let route = choose(status.as_ref(), LAST_UNIFIED.load(Ordering::Relaxed));
+ LAST_UNIFIED.store(matches!(route, Route::Unified(_)), Ordering::Relaxed);
+ if let Route::Unified(windows) = route {
+ return windows;
}
- let sub = jwt_sub(&token)?;
- let cookie = cookie(&sub, &token)?;
let summary_request = client
.get("https://cursor.com/api/usage-summary")
- .header("Cookie", cookie)
+ .header("Cookie", session_cookie(&token)?)
.header("Accept", "application/json");
- let summary_result = read_response(summary_request).await;
- let summary = summary_result?;
+ let summary = read_response(summary_request).await?;
Some(parse(&summary))
}
+/// The dashboard service is internal: when it fails, a legacy plan still reads its summary,
+/// while a unified plan keeps its last weekly reading (its summary pools read zero).
+fn choose(status: Option<&Value>, last_unified: bool) -> Route {
+ let unified = status.map_or(last_unified, |s| s["isUnified"].as_bool() == Some(true));
+ if unified { Route::Unified(status.and_then(parse_unified)) } else { Route::Summary }
+}
+
async fn read_response(request: reqwest::RequestBuilder) -> Option<Value> {
- let response_result = request.send().await;
- let response = response_result.ok()?;
+ let response = request.send().await.ok()?;
if !response.status().is_success() {
tracing::debug!(status = %response.status(), "cursor usage request was refused");
return None;
}
- let body_result = response.json::<Value>().await;
- body_result.ok()
+ response.json::<Value>().await.ok()
}
fn parse_unified(status: &Value) -> Option<Vec<Window>> {
@@ -76,16 +91,14 @@ fn read_token() -> Option<String> {
fn read_saved_token(cli_path: Option<&Path>, app_path: Option<&Path>) -> Option<String> {
// A stale CLI login must not hide an already-working desktop login.
- app_path.and_then(read_app_token).or_else(|| read_cli_token(cli_path?))
+ let usable = |token: &String| session_cookie(token).is_some();
+ app_path.and_then(read_app_token).filter(usable).or_else(|| read_cli_token(cli_path?).filter(usable))
}
fn read_cli_token(path: &Path) -> Option<String> {
let raw = std::fs::read_to_string(path).ok()?;
let auth: Value = serde_json::from_str(&raw).ok()?;
- let token = token_text(auth["accessToken"].as_str()?);
- let sub = jwt_sub(&token)?;
- cookie(&sub, &token)?;
- Some(token)
+ Some(token_text(auth["accessToken"].as_str()?))
}
fn read_app_token(path: &Path) -> Option<String> {
@@ -119,6 +132,10 @@ fn jwt_sub(token: &str) -> Option<String> {
Some(sub.to_owned())
}
+fn session_cookie(token: &str) -> Option<String> {
+ cookie(&jwt_sub(token)?, token)
+}
+
fn cookie(sub: &str, token: &str) -> Option<String> {
if sub.contains([';', ' ', '\r', '\n']) || token.contains([';', ' ', '\r', '\n']) {
return None;
@@ -247,24 +264,27 @@ mod tests {
let path = std::env::temp_dir().join(format!("codync-cursor-{}.db", uuid::Uuid::new_v4()));
let conn = Connection::open(&path).unwrap();
conn.execute("CREATE TABLE ItemTable (key TEXT, value BLOB)", []).unwrap();
+ let app_token = test_token("user_app");
conn.execute(
"INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/accessToken', ?1)",
- [rusqlite::types::Value::Blob(br#""tok""#.to_vec())],
+ [rusqlite::types::Value::Blob(format!("\"{app_token}\"").into_bytes())],
)
.unwrap();
- drop(conn);
let cli_path = path.with_extension("json");
for raw in ["{", "{}", r#"{"accessToken":""}"#, r#"{"accessToken":"not-a-jwt"}"#] {
std::fs::write(&cli_path, raw).unwrap();
- assert_eq!(read_saved_token(Some(&cli_path), Some(&path)).as_deref(), Some("tok"));
+ assert_eq!(read_saved_token(Some(&cli_path), Some(&path)), Some(app_token.clone()));
assert_eq!(read_saved_token(Some(&cli_path), None), None);
}
- let token = test_token();
+ let token = test_token("user_cli");
std::fs::write(&cli_path, json!({"accessToken": token}).to_string()).unwrap();
- assert_eq!(read_saved_token(Some(&cli_path), Some(&path)).as_deref(), Some("tok"));
- assert_eq!(read_saved_token(Some(&cli_path), None), Some(token));
+ assert_eq!(read_saved_token(Some(&cli_path), Some(&path)), Some(app_token.clone()));
+ assert_eq!(read_saved_token(Some(&cli_path), None), Some(token.clone()));
+ conn.execute("UPDATE ItemTable SET value = 'tok'", []).unwrap();
+ assert_eq!(read_saved_token(Some(&cli_path), Some(&path)), Some(token), "a broken app value is not a login");
+ drop(conn);
std::fs::remove_file(&cli_path).unwrap();
- assert_eq!(read_saved_token(Some(&cli_path), Some(&path)).as_deref(), Some("tok"));
+ assert_eq!(read_saved_token(Some(&cli_path), Some(&path)), None);
std::fs::remove_file(&path).unwrap();
assert_eq!(read_saved_token(Some(&cli_path), Some(&path)), None);
assert!(!path.exists(), "reading an absent desktop database never creates one");
@@ -273,7 +293,7 @@ mod tests {
#[test]
fn a_cli_only_login_supplies_usage_credentials_without_changing_them() {
let path = std::env::temp_dir().join(format!("codync-cursor-{}.json", uuid::Uuid::new_v4()));
- let token = test_token();
+ let token = test_token("user_cli");
let raw = json!({"accessToken": token, "refreshToken": "leave-this-alone"}).to_string();
std::fs::write(&path, &raw).unwrap();
let saved = read_saved_token(Some(&path), None);
@@ -283,8 +303,19 @@ mod tests {
assert_eq!(after, raw);
}
- fn test_token() -> String {
- let payload = URL_SAFE_NO_PAD.encode(br#"{"sub":"user_cli"}"#);
+ fn test_token(sub: &str) -> String {
+ let payload = URL_SAFE_NO_PAD.encode(json!({ "sub": sub }).to_string());
format!("eyJhbGciOiJub25lIn0.{payload}.sig")
}
+
+ #[test]
+ fn a_failed_dashboard_keeps_a_unified_plan_off_the_legacy_summary() {
+ let unified = json!({"isUnified": true, "usagePercent": 46});
+ let Route::Unified(Some(windows)) = choose(Some(&unified), false) else { panic!("a unified reading") };
+ assert_eq!(windows[0].id, "weekly");
+ assert_eq!(choose(Some(&json!({"isUnified": true})), false), Route::Unified(None));
+ assert_eq!(choose(None, true), Route::Unified(None), "a failed poll keeps the last weekly window");
+ assert_eq!(choose(None, false), Route::Summary, "a legacy or unknown plan still reads its summary");
+ assert_eq!(choose(Some(&json!({"isUnified": false})), true), Route::Summary);
+ }
}
diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdx
index 9af9f5c3..0287dede 100644
--- a/web/content/docs/conversations.mdx
+++ b/web/content/docs/conversations.mdx
@@ -150,7 +150,7 @@ When you send a message from the iPhone, a Live Activity for that bot appears on
## Usage limits
-Codync reads plan limits from the agents installed on your computer. Claude Code uses its usage report and status line. The signed-in Codex CLI reports current account limits without starting a conversation or model turn. oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie are read the same way, from a command, a local database or an IDE file. Cursor has no usage command: Codync uses the sign-in Cursor saved on this computer and asks cursor.com for the summary. Nothing else is sent with an agent's login. To see them:
+Codync reads plan limits from the agents installed on your computer. Claude Code uses its usage report and status line. The signed-in Codex CLI reports current account limits without starting a conversation or model turn. oh-my-pi, Amp, Kiro, Kimi, Antigravity, OpenCode, Mistral Vibe and Junie are read the same way, from a command, a local database or an IDE file. Cursor has no usage command: Codync uses the sign-in saved by the Cursor app or CLI on this computer and asks Cursor's dashboard service for unified-plan usage, or cursor.com for a legacy-plan summary. Nothing else is sent with an agent's login. To see them:
- **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.mdx
index fc838016..7f663da7 100644
--- a/web/content/docs/linux-servers.mdx
+++ b/web/content/docs/linux-servers.mdx
@@ -105,7 +105,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. If the keyring is locked, the host shows its unlock prompt for a minute and then gives the same error; on a server nobody logs in to graphically, unlock the keyring yourself (for example `gnome-keyring-daemon --unlock`) or give it an empty password. 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 agents installed on the server, the same as on a desktop. Cursor asks cursor.com with the sign-in saved on that server.
+- **Usage limits** come from the agents installed on the server, the same as on a desktop. Cursor reads the CLI's saved sign-in (`$XDG_CONFIG_HOME/cursor/auth.json`, normally `~/.config/cursor/auth.json`) or the desktop app's, so a CLI-only login works, then asks Cursor's dashboard service (unified plans) or cursor.com (legacy plans).
## Updates