Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.9.8: no Concierge until an AI account can answer it (#579)

Oleksandr Ivanchenkoefaa1181e2f7
diff --git a/src/server/concierge.rs b/src/server/concierge.rs
index d7eae7fc..27f1911b 100644
--- a/src/server/concierge.rs
+++ b/src/server/concierge.rs
@@ -1,6 +1,7 @@
//! The Concierge: a generalist bot that answers in #general when no specialist fits the message.
//!
-//! It is made on the first message nothing fits (with a card the person can undo), never counts
+//! It is made on the first message nothing fits once an AI account could answer it (with a card
+//! the person can undo; before any account is connected nothing is made), never counts
//! against the daily cap on bots made without a card, and is never picked by role scoring. Its id
//! is kept in the `concierge:<space>` setting: set and present is the Concierge; set but gone means
//! the person removed it, so #general goes back to the lead and it is never made again unasked.
@@ -61,8 +62,9 @@ pub async fn id(app: &AppState, space: &SpaceId, all_kwants: &[Kwant]) -> Option
}
/// The Concierge for a #general message nothing fits: the existing one, else a new one made now
-/// with a card in `channel_id` the person can undo. `None` when the person removed it (or it
-/// couldn't be made): the message stays with today's pick.
+/// with a card in `channel_id` the person can undo. `None` when the person removed it, when no
+/// AI account could answer it yet (see [`can_answer`]), or when it couldn't be made: the message
+/// stays with today's pick.
pub async fn for_no_match(app: &AppState, space: &SpaceId, channel_id: &str, all_kwants: &[Kwant]) -> Option<Kwant> {
let _making = MAKING.lock().await;
let fresh = app.db.list_kwants(space).await.unwrap_or_else(|_| all_kwants.to_vec());
@@ -71,6 +73,13 @@ pub async fn for_no_match(app: &AppState, space: &SpaceId, channel_id: &str, all
State::Removed => return None,
State::None => {}
}
+ // Nothing made while no AI account could answer it: on a fresh install the first message
+ // would otherwise show a change to undo and then a reply that no account can run bots.
+ // The setting stays unset, so the first unmatched message after one is connected makes it.
+ if !can_answer(app, space).await {
+ tracing::info!(space = %space.as_str(), "no AI account can answer yet; the Concierge waits until one is connected");
+ return None;
+ }
// A bot the person already named Concierge is adopted rather than doubled
if let Some(k) = fresh.iter().find(|k| k.name.trim().eq_ignore_ascii_case(NAME)) {
let _ = app.db.set_setting(&key(space), &k.id).await;
@@ -119,6 +128,28 @@ pub async fn for_no_match(app: &AppState, space: &SpaceId, channel_id: &str, all
app.db.get_kwant(&id).await.ok().flatten()
}
+/// Whether a turn in `space` could run now, so a new Concierge could answer: an AI account
+/// that is ready or only out of usage for now (it answers after the reset, as today), or a
+/// model this machine runs without an account (its own CLI login, an API key in Settings,
+/// Ollama). The second half is the same check a turn makes before it says no account can run
+/// bots (`run_kwant_turn_inner`), so the Concierge waits exactly while its reply would be that.
+async fn can_answer(app: &AppState, space: &SpaceId) -> bool {
+ let accounts = super::profile_turn::call_accounts(app, space).await;
+ if connected(&accounts) {
+ return true;
+ }
+ let profile_engines = super::profile_turn::profile_engines(app, space).await;
+ let host_off = super::profile_turn::host_off(app, space).await;
+ !crate::drivers::detect_available_models(&app.db, &app.engines, &profile_engines, &host_off)
+ .await
+ .is_empty()
+}
+
+/// An account is connected when one is ready, or one is signed in but out of usage for now.
+fn connected(accounts: &super::profile_turn::CallAccounts) -> bool {
+ !accounts.ready.is_empty() || accounts.limited.is_some()
+}
+
/// Similar requests the Concierge must have had (this one included) within [`SIMILAR_WINDOW_DAYS`]
/// before it suggests a specialist.
pub const SIMILAR_FOR_HIRE: usize = 3;
@@ -176,6 +207,21 @@ pub fn hire_note(ids: &[&str]) -> String {
)
}
+#[cfg(test)]
+mod account_tests {
+ use super::*;
+ use crate::server::profile_turn::CallAccounts;
+
+ /// No account at all isn't connected; one only out of usage is (the Concierge is made then,
+ /// as before, and answers after the reset).
+ #[test]
+ fn an_account_out_of_usage_counts_as_connected() {
+ assert!(!connected(&CallAccounts::default()));
+ let limited = CallAccounts { ready: Vec::new(), limited: Some(("Work".into(), chrono::Utc::now() + chrono::Duration::hours(2))) };
+ assert!(connected(&limited));
+ }
+}
+
#[cfg(test)]
mod hire_tests {
use super::*;
diff --git a/tests/concierge_test.rs b/tests/concierge_test.rs
index af1d2a81..f9c309b2 100644
--- a/tests/concierge_test.rs
+++ b/tests/concierge_test.rs
@@ -18,6 +18,8 @@ use kwnt::{
spaces::SpaceId,
Database,
},
+ drivers::engines::EngineId,
+ profiles::classify::{FailClass, ProviderFailure},
router::LayaRouter,
server::{
continuity::{SelfScope, TurnOrigin},
@@ -208,6 +210,99 @@ async fn other_channels_lean_to_their_own_members() {
assert!(concierges(&state).await.is_empty());
}
+/// Turns every engine off but `keep`, as on a fresh install where nothing is signed in.
+fn engines_off_except(state: &AppState, keep: &[EngineId]) {
+ state.engines.set_disabled(EngineId::ALL.into_iter().filter(|e| !keep.contains(e)).collect());
+}
+
+/// The `concierge:<space>` setting: unset until the Concierge is made (or adopted).
+async fn concierge_setting(state: &AppState) -> Option<String> {
+ state.db.get_setting(&format!("concierge:{}", SpaceId::default_space().as_str())).await.unwrap()
+}
+
+/// How many "added Concierge" cards the space has.
+async fn concierge_cards(app: &Router) -> usize {
+ let actions = ok(app, "GET", "/api/bot-actions", None).await;
+ let list = actions.as_array().cloned().or_else(|| actions["actions"].as_array().cloned()).unwrap_or_default();
+ list.iter().filter(|a| a["action"] == "concierge_create").count()
+}
+
+/// Sends `prompt` and waits for its turn to end, whatever it said.
+async fn send_and_wait(app: &Router, state: &AppState, channel: &str, prompt: &str) {
+ let mut events = state.event_sender.subscribe();
+ ok(app, "POST", "/api/chat/send", Some(json!({"channel_id": channel, "prompt": prompt, "sender_id": "user"}))).await;
+ tokio::time::timeout(Duration::from_secs(20), async {
+ loop {
+ if let Ok(RuntimeEvent::TurnEnded { .. }) = events.recv().await.map(|e| e.unscoped().clone()) {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("the turn ended");
+}
+
+/// Mira's audit #6: on a fresh install the first message made the Concierge ("Concierge changed
+/// something… Undo") and its reply then said no account can run bots. With no AI account nothing
+/// is made, no card, the setting stays unset, and today's pick shows the one setup card; the
+/// first unmatched message after an account is connected makes the Concierge once, with its card.
+#[tokio::test]
+async fn no_concierge_until_an_ai_account_can_answer() {
+ let (app, state, _tmp) = setup().await;
+ let script = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter & Hook Specialist",
+ "You write short TikTok video scripts and scroll-stopping hooks for book content."))).await["id"].as_str().unwrap().to_string();
+ let atlas = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "You audit sites for crawl errors, sitemaps and page speed."))).await["id"].as_str().unwrap().to_string();
+ only(&app, &state, &[&script, &atlas]).await;
+ let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;
+
+ // No AI account: nothing is made, nothing to undo, and the setting stays unset
+ engines_off_except(&state, &[]);
+ send_and_wait(&app, &state, &general, "Best place to eat corn dogs in Munich tomorrow?").await;
+ assert!(concierges(&state).await.is_empty(), "no Concierge before an account can answer");
+ assert_eq!(concierge_cards(&app).await, 0, "no concierge_create card");
+ assert_eq!(concierge_setting(&state).await, None, "the setting stays unset");
+ // What the person sees: the setup card from today's pick (meta kind setup_needed), not a raw error
+ let msgs = state.db.list_messages(&general, 50).await.unwrap();
+ let reply = msgs.iter().rev().find(|m| m.sender_role == "kwant").expect("a reply");
+ let meta: Value = reply.meta.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or(Value::Null);
+ assert_eq!((meta["kind"].as_str(), meta["reason"].as_str()), (Some("setup_needed"), Some("no_account")), "{meta}");
+ assert!(reply.text.contains(kwnt::drivers::engines::NO_ENGINE_MESSAGE), "{}", reply.text);
+ assert!(["Scriptwriter", "Atlas"].contains(&reply.sender_id.as_str()), "today's pick answers, not a Concierge: {reply:?}");
+
+ // An account is connected: the next unmatched message makes the Concierge once, with its card
+ engines_off_except(&state, &EngineId::ALL);
+ let (to, basis) = routed_to(&app, &state, &general, "Best place to eat corn dogs in Munich tomorrow?").await;
+ let made = concierges(&state).await;
+ assert_eq!(made.len(), 1);
+ assert_eq!((to.as_str(), basis.as_deref()), (made[0].as_str(), Some("concierge")));
+ assert_eq!(concierge_cards(&app).await, 1);
+ assert_eq!(concierge_setting(&state).await.as_deref(), Some(made[0].as_str()));
+ let (to, _) = routed_to(&app, &state, &general, "Any good everyday questions to ask at a dinner party?").await;
+ assert_eq!(to, made[0]);
+ assert_eq!((concierges(&state).await.len(), concierge_cards(&app).await), (1, 1), "made once");
+}
+
+/// An account that is only out of usage counts as connected: the Concierge is made as before
+/// (its turn then waits for the reset like any other).
+#[tokio::test]
+async fn an_account_out_of_usage_still_gets_the_concierge() {
+ let (app, state, _tmp) = setup().await;
+ let script = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter", "Scripts and hooks for book content."))).await["id"].as_str().unwrap().to_string();
+ let atlas = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "Crawl errors, sitemaps and page speed."))).await["id"].as_str().unwrap().to_string();
+ only(&app, &state, &[&script, &atlas]).await;
+ let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;
+
+ engines_off_except(&state, &[EngineId::Claude]);
+ let until = chrono::Utc::now() + chrono::Duration::hours(3);
+ state.db.record_profile_failure("prf_system_claude", "quota", Some(until)).await.unwrap();
+ state.engines.record_failure(EngineId::Claude, &ProviderFailure { class: FailClass::Quota, retry_at: Some(until), detail: String::new() });
+ send_and_wait(&app, &state, &general, "Best place to eat corn dogs in Munich tomorrow?").await;
+ let made = concierges(&state).await;
+ assert_eq!(made.len(), 1, "an account out of usage is still connected");
+ assert_eq!(concierge_cards(&app).await, 1);
+ assert_eq!(concierge_setting(&state).await.as_deref(), Some(made[0].as_str()));
+}
+
async fn call_as(app: &Router, uri: &str, token: &str, body: Value) -> (StatusCode, Value) {
let req = Request::builder()
.method("POST")