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.

Channels: Laya routes every new channel; people can create and regroup them

Lin (kwant bot)79ec2539e258
diff --git a/src/db/mod.rs b/src/db/mod.rs
index b7b6213d..df40397f 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -367,6 +367,23 @@ impl Database {
.ok_or_else(|| DbError::Sqlx(sqlx::Error::RowNotFound))
}
+ /// Sets who is in a channel and how it routes. `members` must already hold the lead.
+ /// `Ok(false)` when there is no such channel.
+ pub async fn set_channel_routing(&self, id: &str, lead: &str, members: &[String], routing_mode: &str) -> Result<bool, DbError> {
+ let Some(channel) = self.get_channel(id).await? else {
+ return Ok(false);
+ };
+ self.check_members(&SpaceId::new(channel.space_id), lead, members).await?;
+ let done = sqlx::query("UPDATE channels SET lead_kwant_id = ?, member_kwants = ?, routing_mode = ? WHERE id = ?")
+ .bind(lead)
+ .bind(serde_json::to_string(members)?)
+ .bind(routing_mode)
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
pub async fn list_channels(&self, space: &SpaceId) -> Result<Vec<Channel>, DbError> {
let rows = sqlx::query_as::<_, Channel>("SELECT * FROM channels WHERE space_id = ? ORDER BY created_at ASC")
.bind(space.as_str())
diff --git a/src/db/models.rs b/src/db/models.rs
index 8e2b1bf4..e15d3bed 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -70,12 +70,37 @@ pub struct Channel {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewChannel {
pub name: String,
+ #[serde(default)]
pub description: Option<String>,
+ /// `""` from the API: the first member leads.
+ #[serde(default)]
pub lead_kwant_id: String,
+ #[serde(default)]
pub member_kwants: Vec<String>,
+ /// One of [`ROUTING_MODES`]; the API defaults it to `auto`.
+ #[serde(default = "default_routing_mode")]
pub routing_mode: String,
}
+/// `auto`: Laya picks who answers each message (once the channel has two or more bots).
+/// `lead`: the lead answers everything.
+pub const ROUTING_MODES: [&str; 2] = ["auto", "lead"];
+
+pub fn default_routing_mode() -> String {
+ "auto".into()
+}
+
+/// The lead first, then the other members, each once.
+pub fn members_with_lead(lead: &str, members: &[String]) -> Vec<String> {
+ let mut out = vec![lead.to_string()];
+ for m in members {
+ if !out.contains(m) {
+ out.push(m.clone());
+ }
+ }
+ out
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Message {
pub id: String,
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
index 4b7d6c73..6d6a667d 100644
--- a/src/server/bot_actions.rs
+++ b/src/server/bot_actions.rs
@@ -237,7 +237,8 @@ pub fn tools() -> Vec<Value> {
json!({"name": "channel_list", "description": "The channels in your space.", "inputSchema": {"type": "object", "properties": {}}}),
json!({
"name": "channel_create",
- "description": "Create a channel in your space. Members are bots of your space; you lead it unless `lead` says otherwise.",
+ "description": "Create a channel in your space. Members are bots of your space; you lead it unless `lead` says otherwise. \
+ With two or more bots in it, Laya picks who answers each message; with only the lead, the lead answers everything.",
"inputSchema": {
"type": "object",
"properties": {
@@ -251,11 +252,16 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "channel_update",
- "description": "Set a channel's pinned instructions, which every bot there follows; \"\" clears them.",
+ "description": "Change a channel: its pinned instructions, which every bot there follows (\"\" clears them), and/or its \
+ members (the full new list; the lead stays in). Not for #general or a team's chat.",
"inputSchema": {
"type": "object",
- "properties": {"channel": {"type": "string", "description": "Its id or name"}, "instructions": {"type": "string"}},
- "required": ["channel", "instructions"],
+ "properties": {
+ "channel": {"type": "string", "description": "Its id or name"},
+ "instructions": {"type": "string"},
+ "members": {"type": "array", "items": {"type": "string"}, "description": "Bots' ids or names"},
+ },
+ "required": ["channel"],
},
}),
json!({
@@ -1461,7 +1467,13 @@ impl Ctx<'_> {
};
let id = created["id"].as_str().unwrap_or("").to_string();
let after = json!({"channel_id": id, "name": created["name"], "lead_kwant_id": lead.id, "member_kwants": created["member_kwants"]});
- let reply = format!("Created #{} [{id}], led by {}.", created["name"].as_str().unwrap_or(name), lead.name);
+ let mut reply = format!("Created #{} [{id}], led by {}.", created["name"].as_str().unwrap_or(name), lead.name);
+ if created["member_kwants"].as_str().and_then(|m| serde_json::from_str::<Vec<String>>(m).ok()).map_or(0, |m| m.len()) < 2 {
+ reply.push_str(&format!(
+ " Only {} is in it, so Laya has no one to choose between: add members with channel_update for Laya to pick who answers.",
+ lead.name
+ ));
+ }
self.applied("channel_create", "channel", Some(id), format!("created channel #{name}"), None, after, reply).await
}
@@ -1473,17 +1485,56 @@ impl Ctx<'_> {
Ok(c) => c,
Err(e) => return e,
};
- let Some(text) = args["instructions"].as_str() else {
- return fail("instructions is required (\"\" clears them)");
+ let text = args["instructions"].as_str();
+ let mut members = None;
+ if let Some(list) = args["members"].as_array() {
+ let mut ids = vec![channel.lead_kwant_id.clone()];
+ for m in list {
+ match self.bot(m.as_str()).await {
+ Ok(k) if !ids.contains(&k.id) => ids.push(k.id),
+ Ok(_) => {}
+ Err(e) => return e,
+ }
+ }
+ members = Some(ids);
+ }
+ let members_given = members.is_some();
+ if text.is_none() && !members_given {
+ return fail("give instructions (\"\" clears them) and/or members");
+ }
+ // Only what this call changes, so Undo puts back just that
+ let snapshot = |instructions: Option<String>, members: String| {
+ let mut v = json!({"channel_id": channel.id, "name": channel.name});
+ if text.is_some() {
+ v["instructions"] = json!(instructions);
+ }
+ if members_given {
+ v["member_kwants"] = json!(members);
+ }
+ v
+ };
+ let before = snapshot(self.db().channel_instructions(&channel.id).await.ok().flatten(), channel.member_kwants.clone());
+ let payload = super::continuity::ChannelPatch {
+ instructions: text.map(str::to_string),
+ member_kwants: members.clone(),
+ ..Default::default()
};
- let before = json!({"channel_id": channel.id, "name": channel.name, "instructions": self.db().channel_instructions(&channel.id).await.ok().flatten()});
- let payload = super::continuity::InstructionsPayload { instructions: Some(text.to_string()) };
if let Err(e) = read(super::continuity::patch_channel(State(self.state.clone()), Path(channel.id.clone()), Json(payload)).await).await {
return fail(format!("The channel was not changed: {e}"));
}
- let after = json!({"channel_id": channel.id, "name": channel.name, "instructions": self.db().channel_instructions(&channel.id).await.ok().flatten()});
- let verb = if text.trim().is_empty() { "cleared" } else { "set" };
- let summary = format!("{verb} the instructions of #{}", channel.name);
+ let now = self.db().get_channel(&channel.id).await.ok().flatten();
+ let after = snapshot(
+ self.db().channel_instructions(&channel.id).await.ok().flatten(),
+ now.map(|c| c.member_kwants).unwrap_or_default(),
+ );
+ let mut parts = vec![];
+ if let Some(t) = text {
+ parts.push(format!("{} the instructions", if t.trim().is_empty() { "cleared" } else { "set" }));
+ }
+ if let Some(m) = &members {
+ parts.push(format!("set the members ({} bots)", m.len()));
+ }
+ let summary = format!("{} of #{}", parts.join(" and "), channel.name);
self.applied("channel_update", "channel", Some(channel.id), summary.clone(), Some(before), after, format!("{}.", capitalize(&summary)))
.await
}
@@ -1809,11 +1860,23 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
},
"channel_update" => {
- let text = before["instructions"].as_str().unwrap_or("").to_string();
- match state.db.set_channel_instructions(&target, &text).await {
- Ok(true) => {}
- Ok(false) => return Err(error(StatusCode::CONFLICT, "the channel no longer exists")),
- Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ if before.get("instructions").is_some() {
+ let text = before["instructions"].as_str().unwrap_or("").to_string();
+ match state.db.set_channel_instructions(&target, &text).await {
+ Ok(true) => {}
+ Ok(false) => return Err(error(StatusCode::CONFLICT, "the channel no longer exists")),
+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ }
+ }
+ if let Some(members) = before["member_kwants"].as_str().and_then(|m| serde_json::from_str::<Vec<String>>(m).ok()) {
+ let channel = match state.db.get_channel(&target).await {
+ Ok(Some(c)) => c,
+ Ok(None) => return Err(error(StatusCode::CONFLICT, "the channel no longer exists")),
+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ };
+ if let Err(e) = state.db.set_channel_routing(&target, &channel.lead_kwant_id, &members, &channel.routing_mode).await {
+ return Err(error(StatusCode::CONFLICT, format!("the members can't be put back: {e}")));
+ }
}
}
_ => return Err(error(StatusCode::CONFLICT, "this change can't be undone")),
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index ae29aa25..98f61648 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -865,16 +865,66 @@ pub async fn get_channel(State(state): State<AppState>, Path(id): Path<String>)
}
}
-/// `PATCH /api/channels/:id {instructions}`; `""` clears.
-pub async fn patch_channel(
- State(state): State<AppState>,
- Path(id): Path<String>,
- Json(p): Json<InstructionsPayload>,
-) -> Response {
+/// `PATCH /api/channels/:id`: any of these; the rest stay as they are.
+#[derive(Debug, Default, Deserialize)]
+pub struct ChannelPatch {
+ /// `""` clears.
+ pub instructions: Option<String>,
+ /// Replaces the members; the lead always stays one.
+ pub member_kwants: Option<Vec<String>>,
+ pub lead_kwant_id: Option<String>,
+ /// `auto` (Laya picks) or `lead`.
+ pub routing_mode: Option<String>,
+}
+
+/// `PATCH /api/channels/:id {instructions?, member_kwants?, lead_kwant_id?, routing_mode?}`.
+/// #general always has every bot and a team's chat follows the team, so neither takes members.
+pub async fn patch_channel(State(state): State<AppState>, Path(id): Path<String>, Json(p): Json<ChannelPatch>) -> Response {
if let Some(text) = &p.instructions {
if let Err(r) = check_instructions(text) {
return r;
}
+ }
+ if p.member_kwants.is_some() || p.lead_kwant_id.is_some() || p.routing_mode.is_some() {
+ let channel = match state.db.get_channel(&id).await {
+ Ok(Some(c)) => c,
+ Ok(None) => return StatusCode::NOT_FOUND.into_response(),
+ Err(_) => return internal(),
+ };
+ let mode = p.routing_mode.clone().unwrap_or_else(|| channel.routing_mode.clone());
+ if !crate::db::models::ROUTING_MODES.contains(&mode.as_str()) {
+ return error(StatusCode::BAD_REQUEST, "routing_mode must be \"auto\" or \"lead\"");
+ }
+ let regroups = p.member_kwants.is_some() || p.lead_kwant_id.is_some();
+ if regroups && channel.name == "general" {
+ return error(StatusCode::BAD_REQUEST, "#general always includes every bot in the space");
+ }
+ if regroups {
+ let space = crate::db::spaces::SpaceId::new(channel.space_id.clone());
+ let teams = match state.db.list_teams(&space).await {
+ Ok(t) => t,
+ Err(_) => return internal(),
+ };
+ for team in teams {
+ if state.db.team_channel(&space, &team.name).await.ok().flatten().as_deref() == Some(channel.id.as_str()) {
+ return error(
+ StatusCode::BAD_REQUEST,
+ format!("#{} is team {}'s chat: change the team's members instead", channel.name, team.name),
+ );
+ }
+ }
+ }
+ let lead = p.lead_kwant_id.clone().unwrap_or_else(|| channel.lead_kwant_id.clone());
+ let current: Vec<String> = serde_json::from_str(&channel.member_kwants).unwrap_or_default();
+ let members = crate::db::models::members_with_lead(&lead, p.member_kwants.as_deref().unwrap_or(&current));
+ match state.db.set_channel_routing(&id, &lead, &members, &mode).await {
+ Ok(true) => {}
+ Ok(false) => return StatusCode::NOT_FOUND.into_response(),
+ Err(crate::db::DbError::OtherSpace(m)) => return error(StatusCode::BAD_REQUEST, m),
+ Err(_) => return internal(),
+ }
+ }
+ if let Some(text) = &p.instructions {
match state.db.set_channel_instructions(&id, text).await {
Ok(true) => {}
Ok(false) => return StatusCode::NOT_FOUND.into_response(),
diff --git a/src/server/routes.rs b/src/server/routes.rs
index fa0860dc..ee80c071 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -383,6 +383,17 @@ pub async fn create_channel(
if payload.name.is_empty() {
return Err(api_error(StatusCode::BAD_REQUEST, "a channel needs a name"));
}
+ if !crate::db::models::ROUTING_MODES.contains(&payload.routing_mode.as_str()) {
+ return Err(api_error(StatusCode::BAD_REQUEST, "routing_mode must be \"auto\" or \"lead\""));
+ }
+ if payload.lead_kwant_id.is_empty() {
+ match payload.member_kwants.first() {
+ Some(first) => payload.lead_kwant_id = first.clone(),
+ None => return Err(api_error(StatusCode::BAD_REQUEST, "a channel needs at least one bot")),
+ }
+ }
+ // The lead is always one of the bots Laya picks from
+ payload.member_kwants = crate::db::models::members_with_lead(&payload.lead_kwant_id, &payload.member_kwants);
let clash = format!("a channel called #{} already exists in this space", payload.name);
let channels = state.db.list_channels(&space).await.map_err(|e| db_error(&e, ""))?;
if channels.iter().any(|c| c.name.eq_ignore_ascii_case(&payload.name)) {
@@ -2635,7 +2646,8 @@ async fn send_chat_inner(
} else {
let member_ids: Vec<String> =
serde_json::from_str(&channel.member_kwants).unwrap_or_default();
- member_ids
+ // Channels made before the lead was always a member still count the lead
+ crate::db::models::members_with_lead(&channel.lead_kwant_id, &member_ids)
.iter()
.filter_map(|mid| all_kwants.iter().find(|k| &k.id == mid).cloned())
.collect()
diff --git a/tests/bot_actions_test.rs b/tests/bot_actions_test.rs
index 64eda95e..27a56a95 100644
--- a/tests/bot_actions_test.rs
+++ b/tests/bot_actions_test.rs
@@ -534,3 +534,36 @@ async fn switching_bots_tools_off_is_refused_directly() {
}
assert!(actions(&e).await.is_empty());
}
+
+#[tokio::test]
+async fn a_bot_adds_members_to_its_channel_so_laya_routes_it_and_the_person_can_undo() {
+ let e = setup().await;
+ let token = turn(&e, "t-members").await;
+ let space = SpaceId::default_space();
+ let chan = |name: &'static str| {
+ let db = e.state.db.clone();
+ let space = space.clone();
+ async move { db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == name).unwrap() }
+ };
+ let ids = |c: &kwnt::db::models::Channel| serde_json::from_str::<Vec<String>>(&c.member_kwants).unwrap();
+
+ let text = ok(&e, &token, "channel_create", json!({"name": "solo"})).await;
+ assert!(text.contains("add members with channel_update"), "a one-bot channel says Laya has no one to pick: {text}");
+ ok(&e, &token, "channel_update", json!({"channel": "solo", "instructions": "Be brief."})).await;
+
+ let text = ok(&e, &token, "channel_update", json!({"channel": "solo", "members": [e.other.name]})).await;
+ assert!(text.contains("Set the members (2 bots)"), "{text}");
+ assert_eq!(ids(&chan("solo").await), vec![e.bot.id.clone(), e.other.id.clone()], "the lead stays in");
+
+ // Not for #general, which always has every bot
+ refused(&e, &token, "channel_update", json!({"channel": "general", "members": [e.other.name]})).await;
+ refused(&e, &token, "channel_update", json!({"channel": "solo"})).await;
+
+ // Undo puts the members back and leaves the instructions alone
+ let update = last_action(&e).await;
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", update["id"].as_str().unwrap()), Some(e.state.api_token.reveal()), None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ let solo = chan("solo").await;
+ assert_eq!(ids(&solo), vec![e.bot.id.clone()]);
+ assert_eq!(e.state.db.channel_instructions(&solo.id).await.unwrap().as_deref(), Some("Be brief."));
+}
diff --git a/tests/channel_routing_test.rs b/tests/channel_routing_test.rs
new file mode 100644
index 00000000..4370d053
--- /dev/null
+++ b/tests/channel_routing_test.rs
@@ -0,0 +1,192 @@
+//! A channel made by the person (`POST /api/channels`) or by a bot routes through Laya like the
+//! rest: `routing_mode` defaults to `auto`, the lead is always one of the bots Laya picks from, and
+//! a channel that starts with one bot gets Laya once `PATCH /api/channels/:id` adds members.
+//! A fake claude CLI answers turns. Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::NewChannel, spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+ RuntimeEvent,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+echo '{"type":"result","is_error":false,"num_turns":1,"result":"answer ok"}'
+"#;
+
+fn fake_cli() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))
+}
+
+async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (s, v) = call(app, method, uri, body).await;
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+async fn setup() -> (Router, AppState, tempfile::TempDir) {
+ fake_cli();
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+fn bot(name: &str) -> Value {
+ json!({"name": name, "title": format!("{name} the tester"), "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "api", "preferred_model": "claude"})
+}
+
+fn members(c: &Value) -> Vec<String> {
+ serde_json::from_str(c["member_kwants"].as_str().unwrap()).unwrap()
+}
+
+/// Sends a message to the channel; `Some(candidates)` when Laya routed it, `None` when it went
+/// straight to the lead.
+async fn routed(app: &Router, state: &AppState, channel: &str) -> Option<usize> {
+ let mut events = state.event_sender.subscribe();
+ ok(app, "POST", "/api/chat/send", Some(json!({"channel_id": channel, "prompt": "Who takes this?", "sender_id": "user"}))).await;
+ // Waits for the turn to end, so the next message doesn't queue behind it
+ tokio::time::timeout(Duration::from_secs(20), async {
+ let mut candidates = None;
+ loop {
+ match events.recv().await.map(|e| e.unscoped().clone()) {
+ Ok(RuntimeEvent::RoutingDecided { candidate_count, .. }) => candidates = candidate_count,
+ Ok(RuntimeEvent::TurnEnded { .. }) => return candidates,
+ Err(e) => panic!("events: {e}"),
+ _ => {}
+ }
+ }
+ })
+ .await
+ .expect("the message was handled")
+}
+
+#[tokio::test]
+async fn the_person_makes_a_channel_with_just_a_name_and_bots_and_laya_routes_it() {
+ let (app, state, _tmp) = setup().await;
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+
+ // No lead, no routing_mode: the first bot leads and Laya picks
+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "member_kwants": [ann, bob]}))).await;
+ assert_eq!(c["routing_mode"], "auto");
+ assert_eq!(c["lead_kwant_id"], ann.as_str());
+ assert_eq!(members(&c), vec![ann.clone(), bob.clone()]);
+ assert_eq!(routed(&app, &state, c["id"].as_str().unwrap()).await, Some(2));
+
+ // A lead plus one other member: the lead is a member too, so Laya has two to choose from
+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "ops", "lead_kwant_id": ann, "member_kwants": [bob], "routing_mode": "auto"}))).await;
+ assert_eq!(members(&c), vec![ann.clone(), bob.clone()], "the lead joins its own channel");
+ assert_eq!(routed(&app, &state, c["id"].as_str().unwrap()).await, Some(2));
+
+ // Refused: an unknown routing mode (it used to be stored, silently turning Laya off) and no bots
+ let (s, v) = call(&app, "POST", "/api/channels", Some(json!({"name": "x", "member_kwants": [ann], "routing_mode": "whatever"}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+ let (s, v) = call(&app, "POST", "/api/channels", Some(json!({"name": "y"}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+ assert!(state.db.list_channels(&SpaceId::default_space()).await.unwrap().iter().all(|c| c.name != "x" && c.name != "y"));
+}
+
+#[tokio::test]
+async fn an_older_channel_whose_lead_isnt_listed_still_counts_the_lead() {
+ let (app, state, _tmp) = setup().await;
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+ // As the API used to store it: lead Ann, members [Bob]
+ let old = NewChannel { name: "legacy".into(), description: None, lead_kwant_id: ann, member_kwants: vec![bob], routing_mode: "auto".into() };
+ let c = state.db.create_channel(&SpaceId::default_space(), &old).await.unwrap();
+ assert_eq!(routed(&app, &state, &c.id).await, Some(2));
+}
+
+#[tokio::test]
+async fn a_one_bot_channel_gets_laya_once_members_are_added() {
+ let (app, state, _tmp) = setup().await;
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+
+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "solo", "member_kwants": [ann]}))).await;
+ let id = c["id"].as_str().unwrap().to_string();
+ assert_eq!(routed(&app, &state, &id).await, None, "one bot: the lead answers, no routing");
+
+ let c = ok(&app, "PATCH", &format!("/api/channels/{id}"), Some(json!({"member_kwants": [bob]}))).await;
+ assert_eq!(members(&c), vec![ann.clone(), bob.clone()], "the lead stays in");
+ assert_eq!(c["routing_mode"], "auto");
+ assert_eq!(routed(&app, &state, &id).await, Some(2));
+
+ // `lead` turns Laya off, `auto` back on; instructions in the same call are kept
+ let c = ok(&app, "PATCH", &format!("/api/channels/{id}"), Some(json!({"routing_mode": "lead", "instructions": "Be brief."}))).await;
+ assert_eq!(c["routing_mode"], "lead");
+ assert_eq!(c["instructions"], "Be brief.");
+ assert_eq!(routed(&app, &state, &id).await, None);
+ ok(&app, "PATCH", &format!("/api/channels/{id}"), Some(json!({"routing_mode": "auto"}))).await;
+
+ // Refused without changing anything
+ let space = SpaceId::default_space();
+ let general = state.db.general_channel(&space).await.unwrap().unwrap();
+ let team = ok(&app, "POST", "/api/teams", Some(json!({"name": "core", "lead_kwant_id": ann, "member_kwants": [ann, bob]}))).await;
+ let team_chat = state.db.team_channel(&space, team["name"].as_str().unwrap()).await.unwrap().expect("the team's chat");
+ for (target, body) in [
+ (id.clone(), json!({"routing_mode": "sometimes"})),
+ (id.clone(), json!({"member_kwants": ["no-such-bot"]})),
+ (general.id.clone(), json!({"member_kwants": [ann]})),
+ (team_chat.clone(), json!({"member_kwants": [ann]})),
+ ] {
+ let (s, v) = call(&app, "PATCH", &format!("/api/channels/{target}"), Some(body.clone())).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{body}: {v}");
+ }
+ let c = state.db.get_channel(&id).await.unwrap().unwrap();
+ assert_eq!((c.routing_mode.as_str(), serde_json::from_str::<Vec<String>>(&c.member_kwants).unwrap()), ("auto", vec![ann, bob]));
+ let (s, _) = call(&app, "PATCH", "/api/channels/nope", Some(json!({"routing_mode": "auto"}))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}