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
fix(host): finish WorkBuddy sign-in after the browser
forwardxue7d6077ccfba
diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rsindex 7d1ce582..d61fc067 100644--- a/host/src/agent/auth.rs+++ b/host/src/agent/auth.rs@@ -119,6 +119,7 @@ pub async fn check(store: &Store, backend: &str) -> Result<Value> {if status.signed_in.is_none() && !backends::session_proves_sign_in(backend) {status.signed_in = backends::signed_in(backend);}+ status.signed_in = backends::apply_prompt_refusal(backend, status.signed_in);backends::set_signed_in(backend, status.signed_in);CHECKED.locked().insert(backend.to_owned(), status.clone());let mut v = serde_json::to_value(&status)?;diff --git a/host/src/agent/auth/agent.rs b/host/src/agent/auth/agent.rsindex c2c6aceb..af022cf5 100644--- a/host/src/agent/auth/agent.rs+++ b/host/src/agent/auth/agent.rs@@ -92,6 +92,12 @@ fn stderr_reason(stderr_tail: &str) -> Option<String> {/// Lets the agent sign itself in (it usually opens a browser on this computer).pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result<Value> {+ // A saved session makes WorkBuddy log out first, and that logout cancels the login.+ if backend == "workbuddy" {+ tokio::task::spawn_blocking(|| backends::move_saved_session_aside("workbuddy"))+ .await+ .context("couldn't prepare WorkBuddy sign-in")?;+ }let (acp, mut inbox, _, _) = start(store, backend).await?;let res = tokio::time::timeout(Duration::from_secs(10 * 60), sign_in(&acp, &mut inbox, method)).await;acp.kill().await;@@ -101,13 +107,11 @@ pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result<}Err(_) => bail!("Sign-in didn't finish within 10 minutes."),}- let mut status = check(store, backend).await?;- // Completing `authenticate` is the proof for an agent whose session doesn't check the login.- if !backends::session_proves_sign_in(backend) {- backends::set_signed_in(backend, Some(true));- status["signedIn"] = true.into();- }- Ok(status)+ // The browser flow finished. Ask the account again; a prompt refusal no longer overrides it.+ // Completing `authenticate` is not itself proof: WorkBuddy still answers the next prompt+ // with "Authentication required" when the account isn't usable.+ backends::clear_prompt_refused(backend);+ check(store, backend).await}/// The agent's answer to `authenticate`. A headless CLI that only posts its sign-in page (`WorkBuddy`'s) gets itdiff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rsindex 36cf2350..d823c186 100644--- a/host/src/agent/backends.rs+++ b/host/src/agent/backends.rs@@ -20,8 +20,11 @@ mod sign_in;mod workbuddy;pub use catalog::HARNESSES;pub use search_path::{hydrate_path, on_path, which};-pub use sign_in::{SignInCheck, cli_signed_in, refresh_sign_in, set_signed_in, signed_in};-pub use workbuddy::{apply_process_env, session_proves_sign_in};+pub use sign_in::{+ SignInCheck, apply_prompt_refusal, clear_prompt_refused, cli_signed_in, note_prompt_refused, refresh_sign_in,+ set_signed_in, signed_in,+};+pub use workbuddy::{apply_process_env, move_saved_session_aside, session_proves_sign_in};pub struct Harness {pub id: &'static str,diff --git a/host/src/agent/backends/sign_in.rs b/host/src/agent/backends/sign_in.rsindex 78601001..9a466e44 100644--- a/host/src/agent/backends/sign_in.rs+++ b/host/src/agent/backends/sign_in.rs@@ -37,6 +37,27 @@ pub fn signed_in(id: &str) -> Option<bool> {SIGNED_IN.locked().iter().find(|(h, _)| h == id).map(|(_, ok)| *ok)}+/// A prompt was refused because the agent asked for auth. `WorkBuddy` can still report an+/// account after that, which is not proof the next prompt will be accepted.+static PROMPT_REFUSED: Mutex<Vec<String>> = Mutex::new(Vec::new());++/// The latest prompt for `id` was refused for auth. Stands until a prompt succeeds or the user signs in again.+pub fn note_prompt_refused(id: &str) {+ let mut refused = PROMPT_REFUSED.locked();+ if !refused.iter().any(|known| known == id) {+ refused.push(id.to_owned());+ }+}++pub fn clear_prompt_refused(id: &str) {+ PROMPT_REFUSED.locked().retain(|known| known != id);+}++/// An account check that says signed in loses to a prompt that was just refused for auth.+pub fn apply_prompt_refusal(id: &str, probe: Option<bool>) -> Option<bool> {+ if probe == Some(true) && PROMPT_REFUSED.locked().iter().any(|known| known == id) { Some(false) } else { probe }+}+/// Records what a check found (`None`: can't tell).pub fn set_signed_in(id: &str, state: Option<bool>) {let mut map = SIGNED_IN.locked();@@ -77,3 +98,21 @@ pub async fn cli_signed_in(h: &Harness, env: &[(String, String)]) -> Option<boolErr(_) => None,}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_refused_prompt_outranks_an_account_that_still_looks_signed_in() {+ let id = "workbuddy-refusal-test";+ clear_prompt_refused(id);+ assert_eq!(apply_prompt_refusal(id, Some(true)), Some(true));+ note_prompt_refused(id);+ assert_eq!(apply_prompt_refusal(id, Some(true)), Some(false), "an account object is not a working login");+ assert_eq!(apply_prompt_refusal(id, Some(false)), Some(false));+ assert_eq!(apply_prompt_refusal(id, None), None);+ clear_prompt_refused(id);+ assert_eq!(apply_prompt_refusal(id, Some(true)), Some(true));+ }+}diff --git a/host/src/agent/backends/workbuddy.rs b/host/src/agent/backends/workbuddy.rsindex 04c0a167..b90359d5 100644--- a/host/src/agent/backends/workbuddy.rs+++ b/host/src/agent/backends/workbuddy.rs@@ -15,6 +15,8 @@ const CLI_DIR_OTHER: &str = "resources/app.asar.unpacked/cli/bin";/// The desktop app ships only `codebuddy-lite-wb.mjs`. `--acp` alone loads the/// headless bundle, which is not in the app, so the process exits immediately.const PROCESS_ENV: &[(&str, &str)] = &[("CODEBUDDY_FORCE_LITE_WB_BUNDLE", "1")];+/// The product id in `cli/product.json` when that file can't be read. It is the auth file's name.+const FALLBACK_AUTH_ID: &str = "workbuddy-desktop";/// A new session proves the agent is signed in. `WorkBuddy` opens one with no token and only fails/// the first prompt, so its session does not.@@ -32,6 +34,18 @@ pub(super) fn runs_on_node(id: &str) -> bool {id == "workbuddy"}+/// `WorkBuddy`'s sign-in logs out when a saved session is already there, and that logout cancels the+/// login it starts next: the auth-file watcher aborts the token poll, then the call waits forever+/// while the browser can already say the login succeeded. Moving the saved session aside first+/// leaves the new process nothing to log out of.+pub fn move_saved_session_aside(id: &str) {+ if id != "workbuddy" {+ return;+ }+ let Some(path) = saved_session_file() else { return };+ retire_file(&path);+}+/// Environment the harness needs in addition to saved sign-in keys. A saved key wins.pub fn apply_process_env(id: &str, env: &mut Vec<(String, String)>) {if id != "workbuddy" {@@ -75,6 +89,68 @@ fn find_in(roots: &[PathBuf]) -> Option<PathBuf> {.find(|p| is_executable(p))}+/// `{home}/Library/Application Support/CodeBuddyExtension/Data/Public/auth/{id}.info` on macOS.+/// The CLI reads this path from the product id (`workbuddy-desktop` for the mainland app).+fn saved_session_file() -> Option<PathBuf> {+ let home = dirs::home_dir()?;+ let id = product_auth_id().unwrap_or_else(|| FALLBACK_AUTH_ID.to_owned());+ saved_session_path(&home, &id)+}++fn saved_session_path(home: &Path, id: &str) -> Option<PathBuf> {+ if !safe_auth_id(id) {+ return None;+ }+ let base = if cfg!(target_os = "macos") {+ home.join("Library").join("Application Support")+ } else if cfg!(windows) {+ home.join("AppData").join("Local")+ } else {+ home.join(".local").join("share")+ };+ Some(base.join("CodeBuddyExtension").join("Data").join("Public").join("auth").join(format!("{id}.info")))+}++fn safe_auth_id(id: &str) -> bool {+ !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+}++fn product_auth_id() -> Option<String> {+ let bin = find()?;+ let product = bin.parent()?.parent()?.join("product.json");+ let text = std::fs::read_to_string(product).ok()?;+ auth_id_from_product(&text)+}++fn auth_id_from_product(text: &str) -> Option<String> {+ let value: serde_json::Value = serde_json::from_str(text).ok()?;+ let id = value.get("authentication")?.get("id")?.as_str()?;+ safe_auth_id(id).then(|| id.to_owned())+}++/// Rename the live auth file. The CLI loads only `{id}.info`, so a `.retired` name is invisible to it.+fn retire_file(path: &Path) {+ if !path.is_file() {+ return;+ }+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("session.info");+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("system time is after the unix epoch")+ .as_millis();+ let backup = path.with_file_name(format!("{name}.{}.{stamp}.retired", std::process::id()));+ match std::fs::rename(path, &backup) {+ Ok(()) => tracing::info!(path = %path.display(), "moved WorkBuddy's saved session aside before sign-in"),+ Err(error) => {+ tracing::warn!(+ path = %path.display(),+ error = format!("{error:#}"),+ "couldn't move WorkBuddy's saved session aside"+ );+ }+ }+}+fn install_roots() -> Vec<PathBuf> {let mut roots = Vec::new();if cfg!(target_os = "macos") {@@ -124,4 +200,56 @@ mod tests {assert!(!is_cli("/opt/homebrew/bin/codebuddy"));assert!(!is_cli("/Applications/Other.app/Contents/Resources/app.asar.unpacked/cli/bin/codebuddy"));}++ #[test]+ fn the_saved_session_sits_where_the_cli_reads_it() {+ let home = if cfg!(windows) { PathBuf::from(r"C:\Users\example") } else { PathBuf::from("/Users/example") };+ let path = saved_session_path(&home, "workbuddy-desktop").unwrap();+ let base = if cfg!(target_os = "macos") {+ home.join("Library").join("Application Support")+ } else if cfg!(windows) {+ home.join("AppData").join("Local")+ } else {+ home.join(".local").join("share")+ };+ let expected =+ base.join("CodeBuddyExtension").join("Data").join("Public").join("auth").join("workbuddy-desktop.info");+ assert_eq!(path, expected);+ assert!(saved_session_path(&home, "../workbuddy").is_none());+ assert!(saved_session_path(&home, "").is_none());+ }++ #[test]+ fn the_product_auth_id_names_the_session_file() {+ assert_eq!(+ auth_id_from_product(r#"{"authentication":{"id":"workbuddy-desktop"}}"#).as_deref(),+ Some("workbuddy-desktop")+ );+ assert!(auth_id_from_product(r#"{"authentication":{"id":"../x"}}"#).is_none());+ assert!(auth_id_from_product("not json").is_none());+ }++ #[test]+ fn moving_the_saved_session_aside_leaves_the_name_the_cli_loads_empty() {+ let dir = std::env::temp_dir().join(format!("codync-wb-auth-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("workbuddy-desktop.info");+ std::fs::write(&path, "token").unwrap();+ retire_file(&path);+ assert!(!path.exists(), "the cli loads only this exact name");+ let left: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|entry| entry.unwrap().file_name()).collect();+ assert_eq!(left.len(), 1);+ let name = left[0].to_string_lossy();+ assert!(name.starts_with("workbuddy-desktop.info."), "{name}");+ assert!(name.ends_with(".retired"), "{name}");+ assert_eq!(std::fs::read_to_string(dir.join(&left[0])).unwrap(), "token");+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn a_missing_saved_session_is_left_alone() {+ let path = std::env::temp_dir().join(format!("codync-wb-missing-{}", uuid::Uuid::new_v4()));+ retire_file(&path);+ assert!(!path.exists());+ }}diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex b0ec5a91..642ff36c 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -337,13 +337,20 @@ impl Actor {/// When `e` asks for signing in: marks the harness signed out and puts a sign-in card in the/// chat, which sends this turn's messages again once the user has signed in. Whether it did.- pub(super) fn invite_sign_in(&self, e: &anyhow::Error) -> bool {- let backend = &self.cfg.backend;- if crate::agent::backends::harness(backend).is_none() || !crate::agent::acp::needs_sign_in(e) {+ pub(super) fn invite_sign_in(&mut self, e: &anyhow::Error) -> bool {+ let backend = self.cfg.backend.clone();+ if crate::agent::backends::harness(&backend).is_none() || !crate::agent::acp::needs_sign_in(e) {return false;}- crate::agent::backends::set_signed_in(backend, Some(false));- self.sign_in_card(backend, self.held_for_sign_in())+ let held = self.held_for_sign_in().to_vec();+ crate::agent::backends::set_signed_in(&backend, Some(false));+ // The account object can still be there. It must not count as signed in until a prompt works,+ // or the user signs in again. WorkBuddy's current process was opened before that, so drop it.+ crate::agent::backends::note_prompt_refused(&backend);+ if !crate::agent::backends::session_proves_sign_in(&backend) {+ self.restart_after_turn = true;+ }+ self.sign_in_card(&backend, &held)}/// Agent `backend`'s sign-in card in the chat, holding `entries`. Whether it's there.diff --git a/host/src/market/agent_sign_in.rs b/host/src/market/agent_sign_in.rsindex d2677580..88aedcc3 100644--- a/host/src/market/agent_sign_in.rs+++ b/host/src/market/agent_sign_in.rs@@ -119,7 +119,12 @@ fn invite_saying(/// A turn of agent `backend` just finished, so it's signed in whatever Codync last found (the/// user signed in outside Codync, or since the host started): its cards complete.pub fn answered(hub: &Hub, backend: &str) {- if backends::harness(backend).is_none() || backends::signed_in(backend) == Some(true) {+ if backends::harness(backend).is_none() {+ return;+ }+ // A prompt got through, so an earlier auth refusal is over.+ backends::clear_prompt_refused(backend);+ if backends::signed_in(backend) == Some(true) {return;}backends::set_signed_in(backend, Some(true));