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: deleting a team archives its chat; a new team gets a fresh one
Lin (kwant bot)c7d1e3721fff
diff --git a/src/db/mod.rs b/src/db/mod.rsindex 8166c49d..ee2e1c1a 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -498,13 +498,28 @@ impl Database {}// Teams CRUD- /// Fails with [`DbError::OtherSpace`] when the lead or a member is another space's kwant.+ /// Fails with [`DbError::OtherSpace`] when the lead or a member is another space's kwant, and+ /// with [`DbError::Conflict`] when the space has a team of that name ignoring case.+ ///+ /// The team always gets a fresh, empty chat `team-<name>`. A channel already answering to that+ /// name (ignoring case) belongs to no team, since team names are unique ignoring case: it was+ /// left by a team deleted before deletes archived the chat. It is archived first (see+ /// [`archive_team_chat`]) so the new team never inherits its history.pub async fn create_team(&self, space: &SpaceId, input: &NewTeam) -> Result<Team, DbError> {let id = Uuid::new_v4().to_string();let icon = input.icon.as_deref().unwrap_or("users");let members_json = serde_json::to_string(&input.member_kwants)?;self.check_members(space, &input.lead_kwant_id, &input.member_kwants).await?;+ let mut tx = self.pool.begin().await?;+ let (clash,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM teams WHERE space_id = ? AND name = ? COLLATE NOCASE")+ .bind(space.as_str())+ .bind(&input.name)+ .fetch_one(&mut *tx)+ .await?;+ if clash > 0 {+ return Err(DbError::Conflict(format!("a team called {} already exists in this space", input.name)));+ }sqlx::query(r#"INSERT INTO teams (id, name, description, icon, lead_kwant_id, member_kwants, workspace_path, repo_url, space_id)@@ -520,22 +535,30 @@ impl Database {.bind(&input.workspace_path).bind(&input.repo_url).bind(space.as_str())- .execute(&self.pool)+ .execute(&mut *tx).await?;- // Auto-create a team channel team-{name} if it doesn't already existlet channel_name = format!("team-{}", input.name);- let channels = self.list_channels(space).await?;- if !channels.iter().any(|c| c.name == channel_name) {- let chan = NewChannel {- name: channel_name,- description: input.description.clone(),- lead_kwant_id: input.lead_kwant_id.clone(),- member_kwants: input.member_kwants.clone(),- routing_mode: "auto".into(),- };- self.create_channel(space, &chan).await?;+ let leftovers: Vec<(String, String)> =+ sqlx::query_as("SELECT id, name FROM channels WHERE space_id = ? AND name = ? COLLATE NOCASE")+ .bind(space.as_str())+ .bind(&channel_name)+ .fetch_all(&mut *tx)+ .await?;+ for (chat, name) in leftovers {+ let archived = archive_team_chat(&mut tx, space, &chat, &name).await?;+ tracing::info!(from = %name, to = %archived, "archived a deleted team's chat before reusing its name");}+ sqlx::query("INSERT INTO channels (id, name, description, lead_kwant_id, member_kwants, routing_mode, space_id) VALUES (?, ?, ?, ?, ?, 'auto', ?)")+ .bind(Uuid::new_v4().to_string())+ .bind(&channel_name)+ .bind(&input.description)+ .bind(&input.lead_kwant_id)+ .bind(&members_json)+ .bind(space.as_str())+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;self.get_team(&id).await?@@ -642,11 +665,28 @@ impl Database {team_channel_id(&self.pool, space, team_name).await}+ /// Deletes the team and keeps its chat, history and all, as an ordinary channel renamed to+ /// `archived-team-<name>` (see [`archive_team_chat`]), in the same transaction.pub async fn delete_team(&self, id: &str) -> Result<bool, DbError> {+ let mut tx = self.pool.begin().await?;+ let Some((space, name)): Option<(String, String)> = sqlx::query_as("SELECT space_id, name FROM teams WHERE id = ?")+ .bind(id)+ .fetch_optional(&mut *tx)+ .await?+ else {+ return Ok(false);+ };+ let space = SpaceId::new(space);+ if let Some(chat) = team_channel_id(&mut *tx, &space, &name).await? {+ let (chat_name,): (String,) =+ sqlx::query_as("SELECT name FROM channels WHERE id = ?").bind(&chat).fetch_one(&mut *tx).await?;+ archive_team_chat(&mut tx, &space, &chat, &chat_name).await?;+ }let res = sqlx::query("DELETE FROM teams WHERE id = ?").bind(id)- .execute(&self.pool)+ .execute(&mut *tx).await?;+ tx.commit().await?;Ok(res.rows_affected() > 0)}@@ -975,6 +1015,32 @@ pub(crate) async fn insert_message_on(.await?)}+/// Renames chat `chat`, now called `chat_name` (`team-<name>`), to `archived-team-<name>`, or+/// `archived-team-<name>-2`, `-3`… when that is taken (ignoring case). No team answers to an+/// `archived-` name, so it becomes an ordinary channel; its messages, lead and members stay.+/// Returns the new name.+async fn archive_team_chat(+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,+ space: &SpaceId,+ chat: &str,+ chat_name: &str,+) -> Result<String, DbError> {+ let base = format!("archived-{chat_name}");+ for n in 1..1000 {+ let candidate = if n == 1 { base.clone() } else { format!("{base}-{n}") };+ let (taken,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM channels WHERE space_id = ? AND name = ? COLLATE NOCASE")+ .bind(space.as_str())+ .bind(&candidate)+ .fetch_one(&mut **tx)+ .await?;+ if taken == 0 {+ sqlx::query("UPDATE channels SET name = ? WHERE id = ?").bind(&candidate).bind(chat).execute(&mut **tx).await?;+ return Ok(candidate);+ }+ }+ Err(DbError::Conflict(format!("too many archived chats called #{base}")))+}+/// 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.diff --git a/tests/team_channel_test.rs b/tests/team_channel_test.rsindex dc9434cb..28caa76d 100644--- a/tests/team_channel_test.rs+++ b/tests/team_channel_test.rs@@ -160,3 +160,79 @@ async fn lookups_find_a_chat_that_differs_only_in_case() {assert!(members.contains(&b), "a new member joins the team's chat too");assert_eq!(db.team_channel(&space, "nobody").await.unwrap(), None);}++#[tokio::test]+async fn deleting_a_team_archives_its_chat_with_history() {+ 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 first = 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, "first team's plan")).await.unwrap();+ assert!(db.delete_team(&first.id).await.unwrap());++ assert!(channel_named(&db, "team-Startup").await.is_none(), "no #team-* left behind");+ let archived = channel_named(&db, "archived-team-Startup").await.expect("the chat is archived");+ assert_eq!(archived.id, chat.id, "the same channel, renamed");+ let history: Vec<String> = db.list_messages(&chat.id, 10).await.unwrap().into_iter().map(|m| m.text).collect();+ assert_eq!(history, vec!["first team's plan"]);++ // A second team of that name, deleted too, doesn't clobber the first archive.+ let second = db.create_team(&space, &team("Startup", &a, &[&a])).await.unwrap();+ let second_chat = channel_named(&db, "team-Startup").await.unwrap();+ assert_ne!(second_chat.id, chat.id);+ db.delete_team(&second.id).await.unwrap();+ assert_eq!(channel_named(&db, "archived-team-Startup").await.unwrap().id, chat.id);+ assert_eq!(channel_named(&db, "archived-team-Startup-2").await.unwrap().id, second_chat.id);+ assert!(!db.delete_team(&second.id).await.unwrap(), "a second delete finds nothing");+}++#[tokio::test]+async fn a_new_team_never_inherits_an_old_chat() {+ 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();++ // Delete, then the same name in another case: a fresh, empty chat.+ let old = db.create_team(&space, &team("Startup", &a, &[&a])).await.unwrap();+ let old_chat = channel_named(&db, "team-Startup").await.unwrap();+ db.insert_message(&said(&old_chat.id, "old team's secret")).await.unwrap();+ db.delete_team(&old.id).await.unwrap();+ let new = db.create_team(&space, &team("startup", &a, &[&a])).await.unwrap();+ let new_chat = db.team_channel(&space, &new.name).await.unwrap().expect("the new team has a chat");+ assert_ne!(new_chat, old_chat.id);+ assert!(db.list_messages(&new_chat, 10).await.unwrap().is_empty(), "the new chat starts empty");+ assert_eq!(channel_named(&db, "archived-team-Startup").await.unwrap().id, old_chat.id, "the archive is untouched");++ // A chat left by a delete before deletes archived (a bare `team-x` channel) is archived when+ // a team of that name is made, in any case, rather than handed to it.+ let make = |name: &str| NewChannel {+ name: name.into(),+ description: None,+ lead_kwant_id: a.clone(),+ member_kwants: vec![],+ routing_mode: "auto".into(),+ };+ let orphan = db.create_channel(&space, &make("team-Growth")).await.unwrap();+ db.insert_message(&said(&orphan.id, "left behind")).await.unwrap();+ let growth = db.create_team(&space, &team("growth", &a, &[&a])).await.unwrap();+ let growth_chat = db.team_channel(&space, &growth.name).await.unwrap().unwrap();+ assert_ne!(growth_chat, orphan.id);+ assert!(db.list_messages(&growth_chat, 10).await.unwrap().is_empty());+ assert_eq!(channel_named(&db, "archived-team-Growth").await.unwrap().id, orphan.id);+ assert_eq!(db.list_messages(&orphan.id, 10).await.unwrap().len(), 1, "the orphan keeps its history");++ // Team names stay unique ignoring case, so a live team's chat is never taken this way.+ let err = db.create_team(&space, &team("GROWTH", &a, &[&a])).await.unwrap_err();+ assert!(matches!(err, DbError::Conflict(_)), "{err}");+ assert_eq!(db.team_channel(&space, "growth").await.unwrap().unwrap(), growth_chat);++ // The startup repair leaves archives alone.+ drop(db);+ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(channel_named(&db, "archived-team-Startup").await.unwrap().id, old_chat.id);+ assert_eq!(db.team_channel(&space, "startup").await.unwrap().unwrap(), new_chat);+}