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(host): ask for the agent sign-in before the first message
leepokaiad36a247a852
diff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.mdindex ca752604..f2d7d99d 100644--- a/docs/features/connector-credentials.md+++ b/docs/features/connector-credentials.md@@ -65,14 +65,19 @@ correct credentials and retry. Current clients offer no way to cancel a request(it stays until it's done); `cancel: true` remains for older clients, and acancelled request rejects submissions.-The host posts one more kind itself, `agent`: when a bot's own agent (Claude Code…)-refuses a turn because it needs signing in, the chat gets a card naming the agent-(`backend`) and the user messages it couldn't answer (`entryIds`) instead of an-error. A bot keeps one such card; messages that fail later join it. The card's-Sign in opens the agent's sign-in sheet from Extensions. As soon as a sign-in check-(`agentAuth`, `agentAuthenticate`, `setAgentEnv`, or connectorRequestFinish on the-card) finds the agent signed in, every pending card for it completes and its-messages go out again; a card older than 24 hours only completes.+The host posts one more kind itself, `agent` (`market/agent_sign_in.rs`): when a bot's+own agent (Claude Code…) refuses a turn because it needs signing in, the chat gets a+card naming the agent (`backend`) and the user messages it couldn't answer+(`entryIds`) instead of an error. Only agents Codync knows by name get the card;+others show the agent's error. A new bot gets the card before its first message+when the agent's sign-in check, run in the background as the bot is created, finds+it signed out. A bot keeps one such card; messages that fail later join it. The+card's Sign in opens the agent's sign-in sheet from Extensions. As soon as a sign-in+check (`agentAuth`, `agentAuthenticate`, `setAgentEnv`, connectorRequestFinish on the+card, a new bot's check, or the re-check at host start and `refreshBackends`) finds+the agent signed in, or a turn of the agent finishes (signed in outside Codync),+every pending card for it completes and its messages go out again;+a message older than 24 hours isn't sent again. The card itself doesn't expire.MCP connection requests and runtime secret retrieval are loopback-only. AuthorizedControl devices may submit or cancel requests. No endpoint exposes a genericdiff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 8d264d8d..78b77f15 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -4,7 +4,7 @@ use super::{Actor, CANCEL_GRACE, Cmd, Done, NoticeStyle, Queued, RESUME_PROMPT,use crate::agent::own_memory;use crate::chat::memory;use crate::hub::BotStatus;-use crate::market::requests;+use crate::market::agent_sign_in;use crate::store::{Lane, now_ms};use anyhow::{Result, anyhow};use serde_json::json;@@ -300,8 +300,7 @@ impl Actor {return false;};crate::agent::backends::set_signed_in(backend, Some(false));- let invited =- requests::invite_agent_sign_in(&self.hub, &self.cfg.id, &self.lane, backend, h.name, &self.turn_entries);+ let invited = agent_sign_in::invite(&self.hub, &self.cfg.id, &self.lane, backend, h.name, &self.turn_entries);invited.inspect_err(|error| tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't ask to sign in"),diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 304dc135..d1b2d8cc 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -292,6 +292,7 @@ impl Actor {(_, "max_tokens") => self.notice("The agent hit its output limit.", NoticeStyle::Info),(_, "max_turn_requests") => self.notice("The agent hit its step limit for this turn.", NoticeStyle::Info),(_, "refusal") => self.notice("The agent declined to continue.", NoticeStyle::Info),+ (Ok(_), "end_turn") if !stopped => crate::market::agent_sign_in::answered(&self.hub, &self.cfg.backend),_ => {}}let failure = done.as_ref().err().filter(|_| !self.stop_requested);diff --git a/host/src/api/host.rs b/host/src/api/host.rsindex e990a03f..a1157e24 100644--- a/host/src/api/host.rs+++ b/host/src/api/host.rs@@ -79,7 +79,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value}"refreshBackends" => {tokio::task::spawn_blocking(backends::hydrate_path).await?;- backends::refresh_sign_in().await;+ crate::market::agent_sign_in::refresh(hub).await;json!({"backends": backends::list()})}"usage" => {@@ -115,7 +115,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value};// Chats that asked the user to sign in get their messages answered now.if status["signedIn"] == true {- crate::market::requests::agent_signed_in(hub, backend)?;+ crate::market::agent_sign_in::agent_signed_in(hub, backend)?;}status}diff --git a/host/src/background.rs b/host/src/background.rsindex 45695faf..0d7a1206 100644--- a/host/src/background.rs+++ b/host/src/background.rs@@ -1,12 +1,6 @@//! Background services started alongside the host API.-use crate::{- agent::{backends, registry},- hub::Hub,- market,- remote::relay,- screen, update, usage, voice,-};+use crate::{agent::registry, hub::Hub, market, remote::relay, screen, update, usage, voice};use std::sync::Arc;pub fn start(hub: &Arc<Hub>) {@@ -14,7 +8,10 @@ pub fn start(hub: &Arc<Hub>) {tokio::spawn(market::refresh_first_page());tokio::spawn(market::automatic_loop(hub.clone()));tokio::spawn(voice::refresh_loop(hub.clone()));- tokio::spawn(backends::refresh_sign_in());+ tokio::spawn({+ let hub = hub.clone();+ async move { market::agent_sign_in::refresh(&hub).await }+ });tokio::spawn(usage::poll(hub.clone()));tokio::spawn(update::automatic_loop(hub.clone()));tokio::spawn(screen::serve_helpers(hub.screen.clone()));diff --git a/host/src/hub.rs b/host/src/hub.rsindex d95b9172..78da28f7 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -212,6 +212,7 @@ impl Hub {}if !cfg.is_group() {self.spawn_bot(cfg.clone());+ crate::market::agent_sign_in::ask_before_first_message(self, &cfg);}self.emit_bot(&cfg.id);Ok(self.bot_value(&cfg.id).unwrap_or(Value::Null))diff --git a/host/src/market/agent_sign_in.rs b/host/src/market/agent_sign_in.rsnew file mode 100644index 00000000..d357e1fc--- /dev/null+++ b/host/src/market/agent_sign_in.rs@@ -0,0 +1,284 @@+//! The card that asks the user to sign in to a bot's own agent (Claude Code…): posted when a+//! new bot's agent isn't signed in, or when a turn fails for that reason, and completed once it is.+//! Only agents Codync knows by name (`backends::HARNESSES`) get one; others show the agent's error.+use super::requests::{MAX_AGE, RequestKind, RequestStatus};+use crate::{+ LockExt,+ agent::{backends, bot::Cmd},+ hub::Hub,+ store::{BotConfig, EntryKind, Lane, now_ms},+};+use anyhow::{Result, anyhow};+use serde_json::{Value, json};+use std::sync::Arc;++/// Agent sign-in cards change from bot actors and API calls alike (no `.await` while held).+static SIGN_IN: std::sync::Mutex<()> = std::sync::Mutex::new(());++// The card's title names the agent.+const BEFORE_FIRST: &str = "Needs you to sign in before your first message.";+const NEEDED: &str = "Needs you to sign in.";+const HOLDING: &str = "Needs you to sign in. Your message goes out again once you're signed in.";++/// A new bot whose agent isn't signed in shows its sign-in card right away, so the user signs in+/// before writing instead of after the first message fails. The agent's own check runs in the+/// background.+pub fn ask_before_first_message(hub: &Arc<Hub>, cfg: &BotConfig) {+ let Some(h) = backends::harness(&cfg.backend) else { return };+ if backends::signed_in(&cfg.backend) == Some(true) {+ return;+ }+ let (hub, bot, backend) = (hub.clone(), cfg.id.clone(), cfg.backend.clone());+ tokio::spawn(async move {+ let asked = match check(&hub, &backend).await {+ Ok(Some(false)) => invite_saying(&hub, &bot, &Lane::main(&bot), &backend, h.name, &[], BEFORE_FIRST),+ // Other chats waiting on this agent go on.+ Ok(Some(true)) => agent_signed_in(&hub, &backend),+ Ok(None) => Ok(()),+ Err(error) => {+ tracing::info!(bot, backend, error = format!("{error:#}"), "sign-in check failed");+ Ok(())+ }+ };+ if let Err(error) = asked {+ tracing::warn!(bot, error = format!("{error:#}"), "couldn't ask to sign in");+ }+ });+}++/// What the agent's own check says about its sign-in (`None`: can't tell).+#[cfg(not(test))]+async fn check(hub: &Hub, backend: &str) -> Result<Option<bool>> {+ Ok(crate::agent::auth::check(&hub.store, backend).await?["signedIn"].as_bool())+}+#[cfg(test)]+use tests::check;++/// Re-checks every installed agent's sign-in; chats waiting on one that's signed in now go on.+pub async fn refresh(hub: &Hub) {+ backends::refresh_sign_in().await;+ for h in backends::HARNESSES.iter().filter(|h| backends::signed_in(h.id) == Some(true)) {+ if let Err(error) = agent_signed_in(hub, h.id) {+ tracing::warn!(backend = h.id, error = format!("{error:#}"), "couldn't complete the sign-in cards");+ }+ }+}++/// `bot`'s turn failed because agent `backend` (`name`) needs signing in: a card in `lane` asks+/// the user to, and `entries` (the user messages it couldn't answer) go out again once they have.+/// A bot keeps one such card; messages that fail later join it.+pub fn invite(hub: &Hub, bot: &str, lane: &Lane, backend: &str, name: &str, entries: &[String]) -> Result<()> {+ // A routine's, a room's or another bot's turn has no message of the user's to send again.+ let text = if entries.is_empty() { NEEDED } else { HOLDING };+ invite_saying(hub, bot, lane, backend, name, entries, text)+}++/// The card, saying `text` when it's new.+fn invite_saying(+ hub: &Hub,+ bot: &str,+ lane: &Lane,+ backend: &str,+ name: &str,+ entries: &[String],+ text: &str,+) -> Result<()> {+ let _guard = SIGN_IN.locked();+ if let Some(card) = hub.store.pending_sign_ins(backend)?.into_iter().find(|card| card.bot_id == bot) {+ let mut data = card.data;+ let mut ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();+ for id in entries {+ if !ids.iter().any(|v| v == id.as_str()) {+ ids.push(json!(id));+ }+ }+ if !ids.is_empty() {+ data["text"] = HOLDING.into();+ }+ data["connectionRequest"]["entryIds"] = Value::Array(ids);+ hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not update the sign-in request"))?;+ return Ok(());+ }+ let request = json!({"kind": RequestKind::Agent, "status": RequestStatus::Pending, "title": name, "botId": bot,+ "backend": backend, "entryIds": entries});+ hub.add_entry(+ lane,+ EntryKind::Notice,+ hub.store.max_turn(bot),+ &json!({"text": text, "connectionRequest": request}),+ )+ .ok_or_else(|| anyhow!("Could not save the sign-in request"))?;+ Ok(())+}++/// 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) {+ return;+ }+ backends::set_signed_in(backend, Some(true));+ if let Err(error) = agent_signed_in(hub, backend) {+ tracing::warn!(backend, error = format!("{error:#}"), "couldn't complete the sign-in cards");+ }+}++/// Agent `backend` is signed in now: its sign-in cards complete, and the messages they hold go+/// out again (a message older than a day doesn't).+pub fn agent_signed_in(hub: &Hub, backend: &str) -> Result<()> {+ let _guard = SIGN_IN.locked();+ for card in hub.store.pending_sign_ins(backend)? {+ let mut data = card.data.clone();+ data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;+ hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not complete the sign-in request"))?;+ let Some(bot) = hub.store.bot(&card.bot_id)?.filter(|b| !b.deleted) else { continue };+ let ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();+ let held = ids.iter().filter_map(Value::as_str).filter_map(|id| hub.store.entry(id));+ for mut entry in held.filter(|entry| now_ms() - entry.created_at <= MAX_AGE) {+ let prompt = crate::chat::prompt::of_entry(hub, &bot.config, &entry.data);+ entry.data["status"] = "queued".into();+ hub.set_entry(&entry.id, &entry.data);+ let lane = Lane::main(&entry.bot_id);+ hub.send_cmd(&card.bot_id, Cmd::Send { lane, entry_id: entry.id, text: prompt })?;+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::super::requests::tests::fixture;+ use super::*;+ use std::time::Duration;++ /// Sign-in checks the tests answer themselves (no real agent starts): `(backend, signed in)`.+ static CHECKS: std::sync::Mutex<Vec<(&str, bool)>> = std::sync::Mutex::new(Vec::new());++ #[allow(clippy::unused_async)] // the real check's signature+ pub(super) async fn check(_: &Hub, backend: &str) -> Result<Option<bool>> {+ Ok(CHECKS.locked().iter().find(|(b, _)| *b == backend).map(|(_, ok)| *ok))+ }++ fn cards(hub: &Hub, backend: &str, bot: &str) -> Vec<crate::store::Entry> {+ hub.store.pending_sign_ins(backend).unwrap().into_iter().filter(|c| c.bot_id == bot).collect()+ }++ fn create(hub: &Arc<Hub>, backend: &str) -> String {+ let cfg =+ json!({"id": "", "name": backend, "backend": backend, "cwd": std::env::temp_dir(), "command": "true"});+ let made = hub.create_bot(serde_json::from_value(cfg).unwrap()).unwrap();+ made["id"].as_str().unwrap().to_owned()+ }++ /// A message of the user's in `lane`, as sent.+ fn message(hub: &Hub, lane: &Lane, text: &str) -> String {+ hub.add_entry(lane, EntryKind::User, 1, &json!({"text": text, "status": "sent"})).unwrap().id+ }++ async fn until(what: &str, done: impl Fn() -> bool) {+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ while !done() {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ });+ waited.await.unwrap_or_else(|_| panic!("timed out waiting for {what}"));+ }++ #[tokio::test]+ async fn a_new_bot_asks_to_sign_in_only_when_its_agent_is_signed_out() {+ let (hub, dir) = fixture();+ // Harness ids no other test uses: sign-in state is per process.+ CHECKS.locked().extend([("kimi", false), ("qoder", false)]);+ backends::set_signed_in("qoder", Some(true));+ let known = create(&hub, "qoder");+ let unknown = create(&hub, "fixture-unknown");+ let signed_out = create(&hub, "kimi");+ until("the card", || !cards(&hub, "kimi", &signed_out).is_empty()).await;+ let card = &cards(&hub, "kimi", &signed_out)[0];+ assert_eq!(card.data["text"], BEFORE_FIRST);+ assert_eq!(card.data["connectionRequest"]["title"], "Kimi Code");+ assert!(cards(&hub, "qoder", &known).is_empty(), "a signed-in agent asks nothing");+ assert!(cards(&hub, "fixture-unknown", &unknown).is_empty(), "nor one Codync doesn't know");+ hub.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn the_first_card_holds_the_messages_that_fail_later() {+ let (hub, dir) = fixture();+ let lane = Lane::main("bot");+ invite_saying(&hub, "bot", &lane, "fixture-first", "Fixture", &[], BEFORE_FIRST).unwrap();+ let sent = message(&hub, &lane, "hi");+ invite(&hub, "bot", &lane, "fixture-first", "Fixture", std::slice::from_ref(&sent)).unwrap();+ let cards = cards(&hub, "fixture-first", "bot");+ assert_eq!(cards.len(), 1, "the failed message joins the first card");+ assert_eq!(cards[0].data["connectionRequest"]["entryIds"], json!([sent]));+ assert_eq!(cards[0].data["text"], HOLDING);+ invite(&hub, "other", &Lane::main("other"), "fixture-first", "Fixture", &[]).unwrap();+ let routine = &hub.store.pending_sign_ins("fixture-first").unwrap()[1];+ assert_eq!(routine.data["text"], NEEDED, "a turn without the user's message promises none");+ hub.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn signing_in_completes_the_card_and_sends_its_messages_again() {+ let (hub, dir) = fixture();+ let lane = Lane::main("bot");+ let (first, second) = (message(&hub, &lane, "alpha-7"), message(&hub, &lane, "bravo-9"));+ invite(&hub, "bot", &lane, "fixture", "Fixture", std::slice::from_ref(&first)).unwrap();+ invite(&hub, "bot", &lane, "fixture", "Fixture", &[second.clone(), first.clone()]).unwrap();+ let cards = hub.store.pending_sign_ins("fixture").unwrap();+ assert_eq!(cards.len(), 1, "a bot keeps one sign-in card");+ assert_eq!(cards[0].data["connectionRequest"]["entryIds"], json!([first, second]));+ agent_signed_in(&hub, "fixture").unwrap();+ assert_eq!(hub.store.entry(&cards[0].id).unwrap().data["connectionRequest"]["status"], "ready");+ let prompts = dir.join("prompts.jsonl");+ let sent = || std::fs::read_to_string(&prompts).is_ok_and(|p| p.contains("alpha-7") && p.contains("bravo-9"));+ until("both messages to go out again", sent).await;+ hub.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn only_messages_younger_than_a_day_go_out_again_whatever_the_cards_age() {+ let (hub, dir) = fixture();+ let lane = Lane::main("bot");+ invite_saying(&hub, "bot", &lane, "fixture-old", "Fixture", &[], BEFORE_FIRST).unwrap();+ let card = cards(&hub, "fixture-old", "bot")[0].id.clone();+ let day_ago = now_ms() - MAX_AGE - 1;+ hub.store.backdate_entry(&card, day_ago);+ let (stale, fresh) = (message(&hub, &lane, "stale"), message(&hub, &lane, "fresh"));+ hub.store.backdate_entry(&stale, day_ago);+ invite(&hub, "bot", &lane, "fixture-old", "Fixture", &[stale.clone(), fresh.clone()]).unwrap();+ agent_signed_in(&hub, "fixture-old").unwrap();+ assert_eq!(hub.store.entry(&fresh).unwrap().data["status"], "queued", "a day-old card still sends");+ assert_eq!(hub.store.entry(&stale).unwrap().data["status"], "sent", "a day-old message doesn't");+ hub.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+ }++ #[tokio::test]+ async fn a_finished_turn_completes_the_card_of_an_agent_signed_in_elsewhere() {+ let (hub, dir) = fixture();+ let lane = Lane::main("bot");+ invite(&hub, "bot", &lane, "fixture-known", "Fixture", &[]).unwrap();+ answered(&hub, "fixture-known");+ assert_eq!(cards(&hub, "fixture-known", "bot").len(), 1, "an agent Codync doesn't know has none");+ // A bot of its own on a fixture agent that answers, under a harness id no other test uses.+ let agent = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ let cfg = json!({"id": "", "name": "elsewhere", "backend": "junie", "cwd": dir,+ "command": crate::shell::python(&agent)});+ let bot = hub.create_bot(serde_json::from_value(cfg).unwrap()).unwrap()["id"].as_str().unwrap().to_owned();+ // After a host restart nothing says signed out any more.+ backends::set_signed_in("junie", None);+ let lane = Lane::main(&bot);+ invite(&hub, &bot, &lane, "junie", "Junie", &[]).unwrap();+ let hi = message(&hub, &lane, "hi");+ hub.send_cmd(&bot, Cmd::Send { lane, entry_id: hi, text: "hi".into() }).unwrap();+ until("the answered turn to complete the card", || cards(&hub, "junie", &bot).is_empty()).await;+ assert_eq!(backends::signed_in("junie"), Some(true));+ hub.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+ }+}diff --git a/host/src/market/mod.rs b/host/src/market/mod.rsindex b0edf132..d6f7bde0 100644--- a/host/src/market/mod.rs+++ b/host/src/market/mod.rs@@ -16,6 +16,7 @@//! they're reduced to a safe slug first. Secret values (API keys, tokens) stay//! on this computer; listings only say which keys are set.+pub mod agent_sign_in;pub mod composio;pub mod logins;pub mod oauth;diff --git a/host/src/market/requests.rs b/host/src/market/requests.rsindex 3f21e90e..52f238eb 100644--- a/host/src/market/requests.rs+++ b/host/src/market/requests.rs@@ -2,7 +2,6 @@//! tools receive status, never credential values.use super::connectors;use crate::{- LockExt,agent::bot::Cmd,hub::Hub,store::{Entry, EntryKind, Lane, now_ms},@@ -15,7 +14,7 @@ use std::sync::Arc;pub const INSTRUCTIONS: &str = "Connect external services with search_connectors, list_connectors and request_connection. To update an installed connector's key use request_secret. To sign in to a website or app on the screen, check list_logins, ask with request_login if it's missing, then type it with the computer tool type_login. Requests appear as secure cards in the user's conversation. Never ask for passwords or keys in ordinary chat or tool arguments. After requesting, finish your turn and wait; Codync resumes you after the user completes setup.";#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]-enum RequestKind {+pub(super) enum RequestKind {Connection,Secret,App,@@ -26,7 +25,7 @@ enum RequestKind {#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]-enum RequestStatus {+pub(super) enum RequestStatus {Pending,Ready,Cancelled,@@ -36,72 +35,8 @@ fn has_status(request: &Value, status: RequestStatus) -> bool {serde_json::from_value::<RequestStatus>(request["status"].clone()).ok() == Some(status)}-const MAX_AGE: i64 = 24 * 60 * 60 * 1000;+pub(super) const MAX_AGE: i64 = 24 * 60 * 60 * 1000;static MUTATION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());-/// Agent sign-in cards change from bot actors and API calls alike (no `.await` while held).-static SIGN_IN: std::sync::Mutex<()> = std::sync::Mutex::new(());--/// `bot`'s turn failed because agent `backend` (`name`) needs signing in: a card in `lane`-/// asks the user to, and `entries` (the user messages it couldn't answer) go out again once-/// they have. A bot keeps one such card; messages that fail later join it.-pub fn invite_agent_sign_in(- hub: &Hub,- bot: &str,- lane: &Lane,- backend: &str,- name: &str,- entries: &[String],-) -> Result<()> {- let _guard = SIGN_IN.locked();- if let Some(card) = hub.store.pending_sign_ins(backend)?.into_iter().find(|card| card.bot_id == bot) {- let mut data = card.data;- let mut ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();- for id in entries {- if !ids.iter().any(|v| v == id.as_str()) {- ids.push(json!(id));- }- }- data["connectionRequest"]["entryIds"] = Value::Array(ids);- hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not update the sign-in request"))?;- return Ok(());- }- let request = json!({"kind": RequestKind::Agent, "status": RequestStatus::Pending, "title": name, "botId": bot,- "backend": backend, "entryIds": entries});- // The card's title names the agent.- let text = "Needs you to sign in. Your message goes out again once you're signed in.";- hub.add_entry(- lane,- EntryKind::Notice,- hub.store.max_turn(bot),- &json!({"text": text, "connectionRequest": request}),- )- .ok_or_else(|| anyhow!("Could not save the sign-in request"))?;- Ok(())-}--/// Agent `backend` is signed in now: its sign-in cards complete, and the messages they hold go-/// out again (a card older than a day only completes).-pub fn agent_signed_in(hub: &Hub, backend: &str) -> Result<()> {- let _guard = SIGN_IN.locked();- for card in hub.store.pending_sign_ins(backend)? {- let mut data = card.data.clone();- data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;- hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not complete the sign-in request"))?;- let Some(bot) = hub.store.bot(&card.bot_id)?.filter(|b| !b.deleted) else { continue };- if now_ms() - card.created_at > MAX_AGE {- continue;- }- let ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();- for mut entry in ids.iter().filter_map(Value::as_str).filter_map(|id| hub.store.entry(id)) {- let prompt = crate::chat::prompt::of_entry(hub, &bot.config, &entry.data);- entry.data["status"] = "queued".into();- hub.set_entry(&entry.id, &entry.data);- let lane = Lane::main(&entry.bot_id);- hub.send_cmd(&card.bot_id, Cmd::Send { lane, entry_id: entry.id, text: prompt })?;- }- }- Ok(())-}pub fn tools() -> Value {json!([@@ -212,7 +147,9 @@ fn pending(hub: &Hub, id: &str, cancelling: bool) -> Result<Entry> {if !has_status(&e.data["connectionRequest"], RequestStatus::Pending) {bail!("This request is already completed or cancelled");}- if !cancelling && now_ms() - e.created_at > MAX_AGE {+ // An agent sign-in card doesn't expire; each message it holds does (`agent_sign_in`).+ let agent = serde_json::from_value(e.data["connectionRequest"]["kind"].clone()).ok() == Some(RequestKind::Agent);+ if !cancelling && !agent && now_ms() - e.created_at > MAX_AGE {bail!("This request expired. Ask the bot for a new request.");}let bot = text(&e.data["connectionRequest"], "botId")?;@@ -241,7 +178,7 @@ pub async fn finish(hub: &Arc<Hub>, args: &Value) -> Result<Value> {if crate::agent::auth::check(&hub.store, backend).await?["signedIn"] != true {bail!("{} isn't signed in yet.", request["title"].as_str().unwrap_or("The agent"));}- agent_signed_in(hub, backend)?;+ super::agent_sign_in::agent_signed_in(hub, backend)?;return Ok(json!({"entry": hub.store.entry(id)}));}if kind == RequestKind::Login {@@ -326,12 +263,12 @@ fn complete(hub: &Arc<Hub>, e: &Entry, id: &str, note: String) -> Result<Value>}#[cfg(test)]-mod tests {+pub(super) mod tests {use super::*;use crate::store::{BotConfig, Store};use std::path::{Path, PathBuf};- fn fixture() -> (Arc<Hub>, PathBuf) {+ pub(in crate::market) fn fixture() -> (Arc<Hub>, PathBuf) {let dir = std::env::temp_dir().join(format!("codync-credentials-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&dir).unwrap();let store = Store::open(Path::new(":memory:")).unwrap();@@ -414,31 +351,6 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}- #[tokio::test]- async fn signing_in_completes_the_card_and_sends_its_messages_again() {- let (hub, dir) = fixture();- let lane = Lane::main("bot");- let user =- |text: &str| hub.add_entry(&lane, EntryKind::User, 1, &json!({"text":text,"status":"sent"})).unwrap().id;- let (first, second) = (user("alpha-7"), user("bravo-9"));- invite_agent_sign_in(&hub, "bot", &lane, "fixture", "Fixture", std::slice::from_ref(&first)).unwrap();- invite_agent_sign_in(&hub, "bot", &lane, "fixture", "Fixture", &[second.clone(), first.clone()]).unwrap();- let cards = hub.store.pending_sign_ins("fixture").unwrap();- assert_eq!(cards.len(), 1, "a bot keeps one sign-in card");- assert_eq!(cards[0].data["connectionRequest"]["entryIds"], json!([first, second]));- agent_signed_in(&hub, "fixture").unwrap();- assert_eq!(hub.store.entry(&cards[0].id).unwrap().data["connectionRequest"]["status"], "ready");- let prompts = dir.join("prompts.jsonl");- let sent = tokio::time::timeout(std::time::Duration::from_secs(20), async {- while !std::fs::read_to_string(&prompts).is_ok_and(|p| p.contains("alpha-7") && p.contains("bravo-9")) {- tokio::time::sleep(std::time::Duration::from_millis(50)).await;- }- });- sent.await.expect("both messages go out again");- hub.shutdown().await;- let _ = std::fs::remove_dir_all(dir);- }-#[tokio::test]async fn cancellation_rejects_later_secret_submission() {let (hub, dir) = fixture();diff --git a/host/src/store/entries.rs b/host/src/store/entries.rsindex 2622a59a..6c6cb891 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -90,6 +90,13 @@ impl Store {Ok(c.query_row(&format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"), [id], row_entry).optional()?)}+ /// Moves an entry back in time, for tests of what happens to old entries.+ #[cfg(test)]+ pub fn backdate_entry(&self, id: &str, created_at: i64) {+ let c = self.db.locked();+ c.execute("UPDATE entries SET created_at = ?2 WHERE id = ?1", params![id, created_at]).expect("backdate");+ }+pub fn entry(&self, id: &str) -> Option<Entry> {let c = self.db.locked();let row = c.query_row(&format!("SELECT {ENTRY_COLS} FROM entries WHERE id = ?1"), [id], row_entry);