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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
teams: a rename carries the team's chat along
Lin (kwant bot)c5f02c34cc95
diff --git a/src/db/mod.rs b/src/db/mod.rsindex 748c6cbb..55512c52 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -567,6 +567,10 @@ impl Database {}/// Fails with [`DbError::OtherSpace`] when the lead or a member is another space's kwant.+ ///+ /// A rename carries the team's chat along (`team-<old>` becomes `team-<new>`), in the same+ /// transaction as the team. Fails with [`DbError::Conflict`] when another channel already has+ /// the new name, rather than leaving the team's chat behind under its old one.pub async fn update_team(&self, id: &str, input: &NewTeam) -> Result<Option<Team>, DbError> {let icon = input.icon.as_deref().unwrap_or("users");let members_json = serde_json::to_string(&input.member_kwants)?;@@ -575,7 +579,31 @@ impl Database {};self.check_members(&space, &input.lead_kwant_id, &input.member_kwants).await?;- let res = sqlx::query(+ let mut tx = self.pool.begin().await?;+ let Some((old_name,)): Option<(String,)> = sqlx::query_as("SELECT name FROM teams WHERE id = ?")+ .bind(id)+ .fetch_optional(&mut *tx)+ .await?+ else {+ return Ok(None);+ };+ let new_channel = format!("team-{}", input.name);+ let chat = team_channel_id(&mut *tx, &space, &old_name).await?;+ let taken: Option<(String,)> = sqlx::query_as("SELECT id FROM channels WHERE space_id = ? AND name = ?")+ .bind(space.as_str())+ .bind(&new_channel)+ .fetch_optional(&mut *tx)+ .await?;+ let chat = match (chat, taken) {+ (Some(chat), Some((other,))) if chat != other => {+ return Err(DbError::Conflict(format!(+ "a channel called #{new_channel} already exists; rename or delete it first"+ )));+ }+ (chat, taken) => chat.or(taken.map(|(t,)| t)),+ };++ sqlx::query(r#"UPDATE teamsSET name = ?, description = ?, icon = ?, lead_kwant_id = ?, member_kwants = ?, workspace_path = ?, repo_url = ?@@ -590,23 +618,20 @@ impl Database {.bind(&input.workspace_path).bind(&input.repo_url).bind(id)- .execute(&self.pool)+ .execute(&mut *tx).await?;- if res.rows_affected() == 0 {- return Ok(None);+ if let Some(chat) = chat {+ sqlx::query("UPDATE channels SET name = ?, description = ?, lead_kwant_id = ?, member_kwants = ? WHERE id = ?")+ .bind(&new_channel)+ .bind(&input.description)+ .bind(&input.lead_kwant_id)+ .bind(&members_json)+ .bind(&chat)+ .execute(&mut *tx)+ .await?;}-- // Also update corresponding team channel if it exists- let channel_name = format!("team-{}", input.name);- let _ = sqlx::query("UPDATE channels SET description = ?, lead_kwant_id = ?, member_kwants = ? WHERE name = ? AND space_id = ?")- .bind(&input.description)- .bind(&input.lead_kwant_id)- .bind(&members_json)- .bind(&channel_name)- .bind(space.as_str())- .execute(&self.pool)- .await;+ tx.commit().await?;self.get_team(id).await}@@ -904,3 +929,27 @@ pub(crate) async fn insert_message_on(.fetch_one(&mut *conn).await?)}++/// The id of the chat of the team called `team_name`: the channel `team-<name>`, or else the only+/// channel whose name matches it ignoring (ASCII) case, as left by a rename before renames carried+/// the chat along. `None` when there is neither, or several case-insensitive matches.+pub(crate) async fn team_channel_id<'e, E: sqlx::SqliteExecutor<'e>>(+ ex: E,+ space: &SpaceId,+ team_name: &str,+) -> Result<Option<String>, DbError> {+ let wanted = format!("team-{team_name}");+ let rows: Vec<(String, String)> =+ sqlx::query_as("SELECT id, name FROM channels WHERE space_id = ? AND name = ? COLLATE NOCASE ORDER BY created_at")+ .bind(space.as_str())+ .bind(&wanted)+ .fetch_all(ex)+ .await?;+ if let Some((id, _)) = rows.iter().find(|(_, n)| *n == wanted) {+ return Ok(Some(id.clone()));+ }+ Ok(match rows.as_slice() {+ [(id, _)] => Some(id.clone()),+ _ => None,+ })+}diff --git a/tests/team_channel_test.rs b/tests/team_channel_test.rsnew file mode 100644index 00000000..8fe39fc3--- /dev/null+++ b/tests/team_channel_test.rs@@ -0,0 +1,82 @@+//! A team's chat is the channel `team-<team name>`; these keep the two linked.+use kwnt::db::spaces::SpaceId;+use kwnt::db::{models::*, Database, DbError};+use tempfile::tempdir;++fn team(name: &str, lead: &str, members: &[&str]) -> NewTeam {+ NewTeam {+ name: name.into(),+ description: Some("Hired together".into()),+ icon: None,+ lead_kwant_id: lead.into(),+ member_kwants: members.iter().map(|m| m.to_string()).collect(),+ workspace_path: None,+ repo_url: None,+ }+}++fn said(channel_id: &str, text: &str) -> NewMessage {+ NewMessage {+ channel_id: Some(channel_id.into()),+ direct_kwant_id: None,+ sender_role: "user".into(),+ sender_id: "person".into(),+ text: text.into(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ }+}++async fn channel_named(db: &Database, name: &str) -> Option<Channel> {+ db.list_channels(&SpaceId::default_space()).await.unwrap().into_iter().find(|c| c.name == name)+}++#[tokio::test]+async fn renaming_a_team_renames_its_chat_and_keeps_history() {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let space = SpaceId::default_space();+ let ks = db.list_kwants(&space).await.unwrap();+ let (a, b) = (ks[0].id.as_str(), ks[1].id.as_str());++ let t = db.create_team(&space, &team("Startup", a, &[a])).await.unwrap();+ let chat = channel_named(&db, "team-Startup").await.unwrap();+ db.insert_message(&said(&chat.id, "before the rename")).await.unwrap();++ // Startup -> startup is what Manage Team's save did to a hired team's name.+ db.update_team(&t.id, &team("startup", b, &[a, b])).await.unwrap().unwrap();+ assert!(channel_named(&db, "team-Startup").await.is_none(), "no chat left under the old name");+ let renamed = channel_named(&db, "team-startup").await.expect("the chat follows the team");+ assert_eq!(renamed.id, chat.id, "the same channel, renamed");+ assert_eq!(renamed.lead_kwant_id, b, "members and lead still sync after a rename");+ let history: Vec<String> = db.list_messages(&chat.id, 10).await.unwrap().into_iter().map(|m| m.text).collect();+ assert_eq!(history, vec!["before the rename"]);++ // A later edit, under the new name, still reaches the chat.+ db.update_team(&t.id, &team("Launch crew", a, &[a])).await.unwrap().unwrap();+ assert_eq!(channel_named(&db, "team-Launch crew").await.unwrap().id, chat.id);+}++#[tokio::test]+async fn a_rename_onto_another_channels_name_is_refused_whole() {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let space = SpaceId::default_space();+ let a = db.list_kwants(&space).await.unwrap()[0].id.clone();++ let t = db.create_team(&space, &team("alpha", &a, &[&a])).await.unwrap();+ let other = db+ .create_channel(+ &space,+ &NewChannel { name: "team-beta".into(), description: None, lead_kwant_id: a.clone(), member_kwants: vec![], routing_mode: "auto".into() },+ )+ .await+ .unwrap();++ let err = db.update_team(&t.id, &team("beta", &a, &[&a])).await.unwrap_err();+ assert!(matches!(err, DbError::Conflict(ref m) if m.contains("#team-beta")), "{err}");+ assert_eq!(db.get_team(&t.id).await.unwrap().unwrap().name, "alpha", "the team isn't renamed either");+ assert!(channel_named(&db, "team-alpha").await.is_some());+ assert_eq!(channel_named(&db, "team-beta").await.unwrap().id, other.id, "the other channel is untouched");+}