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: ask to sign in to an agent when a fallback takes over for it
leepokaiaa5f7fe8cc09
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex d362f403..b605b6d3 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -11,9 +11,9 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o### zh-Hant- Routine 還沒動手就失敗(例如額度用完)時,會在 1、5、15 分鐘後自動再試;已經動過手或超過時間上限的失敗,通知旁有重試按鈕讓你決定- Bot 的記憶頁改成唯讀,想改記憶直接跟 bot 說;Dreams 分頁新增的記憶是綠色、封存的是紅色,旁邊的資訊按鈕說明做夢在做什麼-- Bot 可以設定後備 agent:Claude Code 額度用完、被限流或登出時,下一個 agent(例如 Codex)會在同一個聊天接手,帶著記憶和這一輪做到哪裡;原本的 agent 恢復後自動換回來,也可以按 Switch back。Bot 也能自己設定這份清單,可在設定中關閉+- Bot 可以設定後備 agent:Claude Code 額度用完、被限流或登出時,下一個 agent(例如 Codex)會在同一個聊天接手,帶著記憶和這一輪做到哪裡;原本的 agent 恢復後自動換回來,也可以按 Switch back;如果是被登出,聊天裡會同時出現它的登入卡片,登入後就換回來。Bot 也能自己設定這份清單,可在設定中關閉### en-US- A routine that fails before doing anything (a usage limit, say) tries again on its own after 1, 5 and 15 minutes; one that already acted or hit its time limit gets a retry button on its failure notice, so you decide- A bot's memory is now read-only: to change it, tell the bot. In the Dreams tab, added memories show in green, archived ones in red, and an info button explains what dreaming does-- Fallback agents: when a bot's agent runs out of usage, is rate limited or signed out, the next one (Codex, say) carries on in the same chat, with its memory and where the turn had got to; the bot goes back once its own agent recovers, or when you tap Switch back. A bot can set this list itself, which you can turn off in its settings+- Fallback agents: when a bot's agent runs out of usage, is rate limited or signed out, the next one (Codex, say) carries on in the same chat, with its memory and where the turn had got to; the bot goes back once its own agent recovers, or when you tap Switch back. If it was signed out, its sign-in card shows up in the chat too, and signing in brings it back. A bot can set this list itself, which you can turn off in its settingsdiff --git a/docs/features/agent-fallback.md b/docs/features/agent-fallback.mdindex 22ec54bf..6e20e38f 100644--- a/docs/features/agent-fallback.md+++ b/docs/features/agent-fallback.md@@ -57,7 +57,7 @@ Read from the ACP answer: the JSON-RPC code, the adapter's category (Claude's `d| `usageLimit` | Claude: `rate_limit`/`billing_error` with the Agent SDK's usage-limit text ("You've hit your…"). Codex: `usageLimitExceeded` | Until the reset the agent reported (`usage` windows at 100%); unknown: 1 h || `outOfCredits` | Claude `billing_error`, `account_on_hold` | 6 h || `rateLimited`, `overloaded` | Claude `rate_limit`, `overloaded`, `server_error`; codex-acp `rateLimitExceeded`, `serverOverloaded` | 1, 5, 25, then 60 min for failures in a row |-| `signedOut` | ACP `-32000`, `authentication_failed` | 10 min (the harness shows signed out) |+| `signedOut` | ACP `-32000`, `authentication_failed` | Until it's signed in, looking again after 1 h; an agent Codync can't sign in to (no sign-in card): 10 min. The chat of each bot that moves past it gets the agent's sign-in card (holding no message: the fallback answers it), and signing in there brings the bot back || `notStarting` | `FailureKind::NotSetUp`, `Timeout`, `Exited` | 5 min || `modelMissing` | `model_not_found`, or the agent refusing the step's model (`FailureKind::NoModel`) | None: it's the bot's setup, not the agent's. The bot skips that step until its settings change |@@ -67,6 +67,8 @@ so only its usage limit moves a Codex bot on today.**Rests** (`fallback::rest`, `kv` `rest.<account>`: the agent, or a custom command's own) are the computer's: once onebot finds Claude Code out of usage, every bot skips it until it resets. A rest ends at its time, when any turn on that agent ends normally, or with Switch back.+A signed-out rest also ends when the agent is signed in (`agent_sign_in::agent_signed_in`: the card, Extensions, a turn of it+finishing, a re-check), for each of its accounts; a usage rest stays.Usage windows only time a usage limit's rest; they never skip an agent on their own (extra usage can go past 100%).## Carrying the turn over@@ -88,11 +90,13 @@ turn keeps its number, messages, routine run, room turn or bot request; permissisent and its last note, with "check what's already done before you redo any step". It follows a handoff the userapproved, which waits for the next turn if this one can't start at all.- **Every agent failed** (the turn ran out of agents): the failure notice as before, saying how each agent is ("No agent in this bot's list could- answer: Claude Code reached its usage limit (resets in 2 h); Codex …"). A routine run's 1/5/15-minute retries still+ answer: Claude Code reached its usage limit (resets in 2 h); Codex …"). The turn's messages wait on the sign-in card+ of the first agent it left signed out, and go out again once that agent is signed in. A routine run's 1/5/15-minute retries stillfollow. A bot without fallbacks whose agent ran out of usage, was rate limited or overloaded gets `addFallback` on thenotice.- **Going back.** Each turn starts on the first step that isn't resting, so the bot goes back on its first turn after- the reset, never mid-turn. Switch back (`switchBack`) clears its own agent's rest and moves an idle bot now.+ the reset, never mid-turn; after signing in to a signed-out agent, on its next message. Switch back (`switchBack`)+ clears its own agent's rest and moves an idle bot now.## The bot sets its own@@ -114,7 +118,9 @@ iPhone, Android, desktop and terminal show the same things:and a ⋯ menu (Move up, Move down, Remove); "No fallbacks yet."; a caption; and the "Let the bot change itsfallbacks" switch. The bot's own Agent row says when it resets.- **Chat**: one line where another agent took over ("Claude Code reached its usage limit (resets in 2 h). Codex carried- on.") or the bot's own came back ("Back on Claude Code."); it unfolds to what the agent was told. A failure with+ on.") or the bot's own came back ("Back on Claude Code."); it unfolds to what the agent was told. Moving past a+ signed-out agent also posts its sign-in card (`connectionRequest` kind `agent`), whose Sign in opens the agent's+ sign-in sheet. A failure with`addFallback` offers **Add a fallback**, which opens the Agent card.- **Terminal**: the bot form's Fallbacks field (←→ pick, space adds the next free agent or cycles a fallback's model,`a` changes its agent, `[`/`]` move, `x` removes) and "Bot edits" (whether the bot may change them); Details shows the agent in use and the chain,diff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.mdindex f2d7d99d..a2c06702 100644--- a/docs/features/connector-credentials.md+++ b/docs/features/connector-credentials.md@@ -71,12 +71,15 @@ 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 messagewhen 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+it signed out. When a [fallback agent](agent-fallback.md) takes the turn over, or a bot skips+an agent another bot found signed out, the card comes anyway, holding no message (the fallback+answers it). A bot keeps one such card in each chat; messages that fail later join it. Thecard's Sign in opens the agent's sign-in sheet from Extensions. As soon as a sign-incheck (`agentAuth`, `agentAuthenticate`, `setAgentEnv`, connectorRequestFinish on thecard, a new bot's check, or the re-check at host start and `refreshBackends`) findsthe 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;+every pending card for it completes, its messages go out again and bots that moved on to a+fallback while it was signed out come back on their next message;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. Authorizeddiff --git a/host/src/agent/bot/fallback.rs b/host/src/agent/bot/fallback.rsindex 494716cf..1d0a736d 100644--- a/host/src/agent/bot/fallback.rs+++ b/host/src/agent/bot/fallback.rs@@ -38,6 +38,9 @@ pub(super) struct Relay {tried: Vec<String>,/// Agents (their `rest::account`) that lack their step's model: skipped until the bot's settings change.no_model: Vec<String>,+ /// Agents this turn left signed out, in order, whose sign-in cards are in the chat. When no agent can answer, the+ /// first one's card holds the turn's messages.+ signed_out: Vec<String>,/// The next `start_turn` is this turn again, on the next agent.retrying: bool,/// The agents that failed this turn, in order: why, and what each had done.@@ -91,13 +94,16 @@ impl Actor {if !std::mem::take(&mut self.relay.retrying) {self.relay.tried.clear();self.relay.failed.clear();+ self.relay.signed_out.clear();self.relay.stopped = None;}self.relay.exhausted = false;self.relay.line = None;self.relay.carried = None;self.relay.attempt = Some(Attempt { lane: lane.clone(), entries: entries.to_vec(), text: text.to_owned() });- let target = self.next_step(now_ms()).unwrap_or(0);+ let now = now_ms();+ let target = self.next_step(now).unwrap_or(0);+ self.left_signed_out_before(target, now);let from = self.cfg.clone();if fallback::account(&self.base, target) != rest::account(&from) {self.switch_to(target).await;@@ -105,6 +111,20 @@ impl Actor {}}+ /// A turn (or its retry) starting on step `target`: the agents before it that rest because a bot found them+ /// signed out ask to be signed in here too.+ fn left_signed_out_before(&mut self, target: usize, now: i64) {+ let signed_out = |s: &usize| {+ rest::get(&self.hub.store, &fallback::account(&self.base, *s), now)+ .is_some_and(|r| r.reason == Reason::SignedOut)+ };+ let skipped: Vec<String> =+ (0..target).filter(signed_out).map(|s| fallback::backend(&self.base, s).to_owned()).collect();+ for agent in skipped {+ self.left_signed_out(&agent);+ }+ }+/// `start_turn`, once the session is up (a new one, or the agent's own resumed): sets what the agent should hear/// first, and puts it on the chat line of the move. The main session gets a recap of the chat in a new session or/// a catch-up in its own; a retried turn gets what the agents before did. Not for hidden turns.@@ -251,6 +271,11 @@ impl Actor {let failed = start_error.as_ref().unwrap_or(error);if self.next_step(now).is_none() {self.relay.exhausted = true;+ // No agent answers the turn's messages: they go out again once the first one left signed out is+ // signed in (the last agent's own card holds them only when there is none, `held_for_sign_in`).+ if let Some(first) = self.relay.signed_out.first().filter(|_| !self.turn_entries.is_empty()) {+ self.sign_in_card(first, &self.turn_entries);+ }return match start_error {Some(e) => {self.start_failed(&e);@@ -259,6 +284,9 @@ impl Actor {None => false,};}+ if reason == Reason::SignedOut {+ self.left_signed_out(&agent);+ }self.report_turn(false, Some(failed), "error");crate::analytics::agent_fell_back(&self.hub, &agent, reason);let done = self.so_far();@@ -280,6 +308,22 @@ impl Actor {}}+ /// The turn moves past agent `agent`, signed out: its sign-in card goes in the chat, holding no message (the next+ /// agent answers them, unless none can: `fall_back`). Signing in there brings the bot back (`fallback::signed_in`).+ /// Once per turn.+ fn left_signed_out(&mut self, agent: &str) {+ if crate::agent::backends::harness(agent).is_some() && !self.relay.signed_out.iter().any(|a| a == agent) {+ self.relay.signed_out.push(agent.to_owned());+ self.sign_in_card(agent, &[]);+ }+ }++ /// The messages the sign-in card of the agent this turn ended on holds: none when the card of an agent the turn+ /// left signed out holds them already (`fall_back` ran out of agents), so they go out again once.+ pub(super) fn held_for_sign_in(&self) -> &[String] {+ if self.relay.exhausted && !self.relay.signed_out.is_empty() { &[] } else { &self.turn_entries }+ }+/// A hidden turn (a compaction, a resume) stays on its agent and isn't started again elsewhere.pub(super) fn hidden_turn(&mut self) {self.relay.attempt = None;@@ -335,18 +379,13 @@ impl Actor {/// The agent answered a turn: whatever rest it had is over.pub(super) fn agent_answered(&mut self) {- let account = rest::account(&self.cfg);- if rest::clear(&self.hub.store, &account) {- fallback::tell_bots(&self.hub, &account);- }+ fallback::end_rest(&self.hub, &rest::account(&self.cfg));}/// `switchBack`: the bot's own agent again, now when idle, or for its next turn.pub(super) async fn switch_back(&mut self) {let own = fallback::account(&self.base, 0);- if rest::clear(&self.hub.store, &own) {- fallback::tell_bots(&self.hub, &own);- }+ fallback::end_rest(&self.hub, &own);if self.turn.is_none() && rest::account(&self.cfg) != own {let from = self.cfg.clone();self.idle_relay();diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex f68b6988..d50c4042 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -309,11 +309,17 @@ impl Actor {/// 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;- let Some(h) = crate::agent::backends::harness(backend).filter(|_| crate::agent::acp::needs_sign_in(e)) else {+ 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));- let invited = agent_sign_in::invite(&self.hub, &self.cfg.id, &self.lane, backend, h.name, &self.turn_entries);+ self.sign_in_card(backend, self.held_for_sign_in())+ }++ /// Agent `backend`'s sign-in card in the chat, holding `entries`. Whether it's there.+ pub(super) fn sign_in_card(&self, backend: &str, entries: &[String]) -> bool {+ let Some(h) = crate::agent::backends::harness(backend) else { return false };+ let invited = agent_sign_in::invite(&self.hub, &self.cfg.id, &self.lane, backend, h.name, 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/fallback/mod.rs b/host/src/agent/fallback/mod.rsindex a80561fb..83d5cdd3 100644--- a/host/src/agent/fallback/mod.rs+++ b/host/src/agent/fallback/mod.rs@@ -86,6 +86,21 @@ pub fn tell_bots(hub: &Hub, rested: &str) {}}+/// `account`'s rest is over (it answered, the user asked for it again, it's signed in): bots that use it show it.+pub fn end_rest(hub: &Hub, account: &str) {+ if rest::clear(&hub.store, account) {+ tell_bots(hub, account);+ }+}++/// Agent `backend` is signed in now: its rests for being signed out are over (one for usage stays), so bots that+/// moved on to a fallback come back on their next message.+pub fn signed_in(hub: &Hub, backend: &str) {+ for account in rest::signed_out(&hub.store, backend) {+ end_rest(hub, &account);+ }+}+/// Saved fallbacks are at most `MAX_FALLBACKS`, each a known agent or a custom command, and no agent twice/// (the bot's own included): falling back between one agent's models is that agent's own setting.pub fn check(cfg: &BotConfig) -> Result<()> {diff --git a/host/src/agent/fallback/rest.rs b/host/src/agent/fallback/rest.rsindex 73420dd6..8e57e944 100644--- a/host/src/agent/fallback/rest.rs+++ b/host/src/agent/fallback/rest.rs@@ -15,7 +15,12 @@ const BACKOFF: [i64; 4] = [MINUTE, 5 * MINUTE, 25 * MINUTE, 60 * MINUTE];const UNKNOWN_RESET: i64 = 60 * MINUTE;/// No credits: the user has to add some, so don't look again for a while.const OUT_OF_CREDITS: i64 = 6 * 60 * MINUTE;-const SIGNED_OUT: i64 = 10 * MINUTE;+/// Signed out of an agent Codync signs in to: signing in ends it sooner (`fallback::signed_in`), so look again only+/// now and then (a sign-in outside Codync).+const SIGNED_OUT: i64 = 60 * MINUTE;+/// Signed out of one it can't sign in to (not in `backends::HARNESSES`): only a sign-in outside Codync helps, so look+/// again soon.+const SIGNED_OUT_ELSEWHERE: i64 = 10 * MINUTE;const NOT_STARTING: i64 = 5 * MINUTE;#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]@@ -50,23 +55,33 @@ pub fn account_of(backend: &str, command: Option<&str>) -> String {})}+/// The agent `account` runs.+fn backend_of(account: &str) -> &str {+ account.split_once('#').map_or(account, |(backend, _)| backend)+}++/// `account`'s last rest, over or not.+fn saved(store: &Store, account: &str) -> Option<Rest> {+ serde_json::from_str(&store.kv_get(&key(account))?).ok()+}+/// `account`'s rest at `now`, while it lasts.pub fn get(store: &Store, account: &str, now: i64) -> Option<Rest> {- let rest: Rest = serde_json::from_str(&store.kv_get(&key(account))?).ok()?;- (rest.until > now).then_some(rest)+ saved(store, account).filter(|rest| rest.until > now)}/// Records that `account` couldn't answer for `reason` at `now`. `resets_at`: when its usage limit resets, if it/// said. A model the agent lacks is the bot's setup, not the agent's, so it doesn't rest the agent.pub fn record(store: &Store, account: &str, reason: Reason, now: i64, resets_at: Option<i64>) -> Option<Rest> {- let before: Option<Rest> = store.kv_get(&key(account)).and_then(|v| serde_json::from_str(&v).ok());+ let before = saved(store, account);// An hour after its last rest ended, a failure starts the backoff over.let failures = before.filter(|r| now - r.until < BACKOFF[3]).map_or(0, |r| r.failures) + 1;let wait = match reason {Reason::ModelMissing => return None,Reason::UsageLimit => resets_at.filter(|t| *t > now).map_or(UNKNOWN_RESET, |t| t - now),Reason::OutOfCredits => OUT_OF_CREDITS,- Reason::SignedOut => SIGNED_OUT,+ Reason::SignedOut if crate::agent::backends::harness(backend_of(account)).is_some() => SIGNED_OUT,+ Reason::SignedOut => SIGNED_OUT_ELSEWHERE,Reason::NotStarting => NOT_STARTING,Reason::RateLimited | Reason::Overloaded => BACKOFF[(failures as usize - 1).min(BACKOFF.len() - 1)],};@@ -85,6 +100,18 @@ pub fn reset_time(usage: &Usage, backend: &str, now: i64) -> Option<i64> {provider.windows.iter().filter(|w| w.percent >= 99.5).filter_map(|w| w.resets_at).filter(|t| *t > now).max()}+/// Agent `backend`'s accounts (also ones a command of its own runs) whose last rest was for being signed out.+pub fn signed_out(store: &Store, backend: &str) -> Vec<String> {+ // The prefix also finds agents whose name starts with `backend`'s.+ store+ .kv_prefix(&key(backend))+ .iter()+ .filter_map(|k| k.strip_prefix("rest."))+ .filter(|a| backend_of(a) == backend && saved(store, a).is_some_and(|r| r.reason == Reason::SignedOut))+ .map(str::to_owned)+ .collect()+}+/// The agent answered (or the user asked for it again): its rest and backoff are over. Whether it was resting.pub fn clear(store: &Store, account: &str) -> bool {if store.kv_get(&key(account)).is_none() {@@ -100,6 +127,23 @@ pub fn clear(store: &Store, account: &str) -> bool {mod tests {use super::*;+ #[test]+ fn signing_in_ends_only_a_signed_out_rest() {+ let store = Store::open(std::path::Path::new(":memory:")).expect("a store");+ let wrapped = account_of("claude", Some("claude-wrapper"));+ for account in ["claude", wrapped.as_str(), "claudette"] {+ assert_eq!(record(&store, account, Reason::SignedOut, 0, None).map(|r| r.reason), Some(Reason::SignedOut));+ }+ record(&store, "codex", Reason::UsageLimit, 0, None);+ let mut ended = signed_out(&store, "claude");+ ended.sort();+ assert_eq!(ended, ["claude".to_owned(), wrapped], "a command of its own signs in with the agent");+ assert!(signed_out(&store, "codex").is_empty(), "signing in doesn't give usage back");+ // One Codync can't sign in to looks again sooner.+ assert_eq!(get(&store, "claudette", 0).map(|r| r.until), Some(SIGNED_OUT_ELSEWHERE));+ assert_eq!(record(&store, "claude", Reason::SignedOut, 0, None).map(|r| r.until), Some(SIGNED_OUT));+ }+#[test]fn a_usage_limit_rests_until_its_reset_and_transient_failures_back_off() {let store = Store::open(std::path::Path::new(":memory:")).expect("a store");diff --git a/host/src/market/agent_sign_in.rs b/host/src/market/agent_sign_in.rsindex d357e1fc..d2677580 100644--- a/host/src/market/agent_sign_in.rs+++ b/host/src/market/agent_sign_in.rs@@ -1,5 +1,6 @@//! 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.+//! new bot's agent isn't signed in, or when a turn fails for that reason (also when a fallback agent+//! takes the turn over, then holding no message), 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::{@@ -66,7 +67,7 @@ pub async fn refresh(hub: &Hub) {/// `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.+/// A bot keeps one such card in each chat; 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 };@@ -84,17 +85,21 @@ fn invite_saying(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) {+ // In a room the card's chat is the room's: `botId` says whose it is.+ let mine = |card: &crate::store::Entry| card.bot_id == lane.chat && card.data["connectionRequest"]["botId"] == bot;+ if let Some(card) = hub.store.pending_sign_ins(backend)?.into_iter().find(mine) {let mut data = card.data;let mut ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();+ let held = ids.len();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();+ if ids.len() == held {+ return Ok(());}+ 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(());@@ -126,6 +131,7 @@ pub fn answered(hub: &Hub, backend: &str) {/// 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<()> {+ crate::agent::fallback::signed_in(hub, backend);let _guard = SIGN_IN.locked();for card in hub.store.pending_sign_ins(backend)? {let mut data = card.data.clone();@@ -184,6 +190,21 @@ mod tests {waited.await.unwrap_or_else(|_| panic!("timed out waiting for {what}"));}+ #[tokio::test]+ async fn signing_in_brings_bots_back_from_their_fallbacks() {+ use crate::agent::fallback::{Reason, rest};+ let (hub, dir) = fixture();+ let wrapped = rest::account_of("kiro", Some("kiro-cli acp"));+ rest::record(&hub.store, &wrapped, Reason::SignedOut, now_ms(), None);+ rest::record(&hub.store, "kiro", Reason::UsageLimit, now_ms(), None);+ agent_signed_in(&hub, "kiro").unwrap();+ assert_eq!(rest::get(&hub.store, &wrapped, now_ms()), None, "the agent no longer rests for its sign-in");+ let usage = rest::get(&hub.store, "kiro", now_ms()).map(|r| r.reason);+ assert_eq!(usage, Some(Reason::UsageLimit), "signing in doesn't give usage back");+ hub.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+ }+#[tokio::test]async fn a_new_bot_asks_to_sign_in_only_when_its_agent_is_signed_out() {let (hub, dir) = fixture();diff --git a/host/tests/fallback_e2e.rs b/host/tests/fallback_e2e.rsindex 3c143fda..760e7322 100644--- a/host/tests/fallback_e2e.rs+++ b/host/tests/fallback_e2e.rs@@ -166,3 +166,58 @@ async fn a_bot_without_fallbacks_offers_to_add_one() {assert_eq!(failed["data"]["addFallback"], true);assert!(failed["data"]["text"].as_str().unwrap().contains("You've hit your limit"));}++#[tokio::test]+async fn a_signed_out_agent_hands_the_turn_over_and_asks_to_sign_in() {+ let host = Host::start().await;+ // A harness Codync knows (it gets a sign-in card) that no machine running the tests has installed.+ let bot =+ json!({"name": "Signed", "backend": "kimi", "command": agent("primary"), "connectors": [], "notify": false});+ let bot = host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned();+ let fallbacks = json!([{"backend": "codex", "command": agent("standin")}]);+ host.call("updateBot", json!({"id": bot, "fallbacks": fallbacks})).await;+ let folder = host.home.join("bots").join(&bot).join("workspace");+ std::fs::write(folder.join("primary.signedout"), "").unwrap();++ host.reply(&bot, "Fix the build").await;+ let reply = wait_for(&host, &bot, "reply", |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ assert_eq!(reply["data"]["text"], "standin answered");+ let card = wait_for(&host, &bot, "sign-in card", |e| e["data"]["connectionRequest"]["kind"] == "agent").await;+ let request = &card["data"]["connectionRequest"];+ assert_eq!((request["backend"].as_str(), request["status"].as_str()), (Some("kimi"), Some("pending")));+ assert_eq!(request["entryIds"], json!([]), "the fallback answered: nothing waits for the sign-in");+ let line = wait_for(&host, &bot, "switch line", |e| e["data"]["agentSwitch"].is_object()).await;+ assert_eq!(line["data"]["text"], "Kimi Code is signed out. Codex carried on.");+ assert_eq!(bot_value(&host, &bot).await["resting"][0]["reason"], "signedOut");++ // Another bot on the same agent skips it while it rests, and asks to sign in too.+ let second = json!({"name": "Second", "backend": "kimi", "command": agent("primary"), "connectors": [],+ "notify": false, "fallbacks": fallbacks});+ let second = host.call("createBot", second).await["bot"]["id"].as_str().unwrap().to_owned();+ host.reply(&second, "Fix the tests").await;+ let line = wait_for(&host, &second, "switch line", |e| e["data"]["agentSwitch"].is_object()).await;+ assert_eq!(line["data"]["text"], "Kimi Code is signed out. Codex carried on.");+ let card = wait_for(&host, &second, "sign-in card", |e| e["data"]["connectionRequest"]["kind"] == "agent").await;+ assert_eq!(card["data"]["connectionRequest"]["backend"], "kimi");++ // One that starts on an agent before it skips it when that agent fails, and asks to sign in too.+ let chain = json!([{"backend": "kimi", "command": agent("primary")}, fallbacks[0]]);+ let third = json!({"name": "Third", "backend": "custom", "command": agent("limited"), "connectors": [],+ "notify": false, "fallbacks": chain});+ let third = host.call("createBot", third).await["bot"]["id"].as_str().unwrap().to_owned();+ std::fs::write(host.home.join("bots").join(&third).join("workspace").join("limited.limit"), "").unwrap();+ host.reply(&third, "Fix the docs").await;+ let card = wait_for(&host, &third, "sign-in card", |e| e["data"]["connectionRequest"]["kind"] == "agent").await;+ assert_eq!(card["data"]["connectionRequest"]["backend"], "kimi");++ // A turn of the agent elsewhere means it's signed in (with a command of its own, too): the bot goes back.+ let solo =+ json!({"name": "Solo", "backend": "kimi", "command": agent("helper"), "connectors": [], "notify": false});+ let solo = host.call("createBot", solo).await["bot"]["id"].as_str().unwrap().to_owned();+ host.reply(&solo, "Hello").await;+ wait_for(&host, &bot, "the card to complete", |e| e["data"]["connectionRequest"]["status"] == "ready").await;+ std::fs::remove_file(folder.join("primary.signedout")).unwrap();+ host.reply(&bot, "Thanks").await;+ wait_for(&host, &bot, "back line", |e| e["data"]["text"] == "Back on Kimi Code.").await;+ assert!(last_prompt(&host, &bot, "primary").contains("Thanks"));+}diff --git a/host/tests/fixtures/relay_agent.py b/host/tests/fixtures/relay_agent.pyindex ce577327..48a3fa4a 100644--- a/host/tests/fixtures/relay_agent.py+++ b/host/tests/fixtures/relay_agent.py@@ -1,7 +1,7 @@"""ACP agent for the fallback chain test, run as `relay_agent.py <name>`. While `<name>.limit` exists in its folder,every prompt edits a file and then fails the way Claude's adapter reports a usage limit; otherwise it answers-"<name> answered". Sessions load (`<name>-s<n>`) unless `<name>.noload` exists; every request goes to `<name>.jsonl` in-its folder."""+"<name> answered". While `<name>.signedout` exists, every prompt fails asking to sign in (ACP's -32000). Sessions load+(`<name>-s<n>`) unless `<name>.noload` exists; every request goes to `<name>.jsonl` in its folder."""import jsonimport os@@ -43,7 +43,9 @@ for line in sys.stdin:send({"id": message["id"], "result": {}})elif method == "session/prompt":sid = params["sessionId"]- if os.path.exists(f"{NAME}.limit"):+ if os.path.exists(f"{NAME}.signedout"):+ send({"id": message["id"], "error": {"code": -32000, "message": "Authentication required"}})+ elif os.path.exists(f"{NAME}.limit"):tool = {"toolCallId": "t1", "title": "Edit a.txt", "kind": "edit", "status": "completed"}update(sid, {"sessionUpdate": "tool_call", **tool})update(sid, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Edited a.txt"}})