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
Spaces S2: spaces usable through the API
Lin (kwant bot)f2b6038d8379
diff --git a/src/db/away.rs b/src/db/away.rsindex 1a576ad5..4355b41f 100644--- a/src/db/away.rs+++ b/src/db/away.rs@@ -2,6 +2,7 @@//! stuck, read from the tables that already record it (questions, approvals, delegations and//! routine runs). Read-only apart from the user's last-seen marker.+use super::spaces::SpaceId;use super::{Database, DbError};use chrono::{DateTime, Utc};use sqlx::FromRow;@@ -33,7 +34,8 @@ const OPEN_QUESTIONS: &str = "SELECT 'question' AS kind, q.id, q.kwant_id, k.name AS kwant_name, q.question AS title, q.status,NULL AS body, q.created_at AS at, q.thread_id, q.channel_id, q.direct_kwant_id, q.choicesFROM questions q LEFT JOIN kwants k ON k.id = q.kwant_id- WHERE q.status = 'open'";+ WHERE q.status = 'open'+ AND COALESCE(k.space_id, 'spc_default') = ?3";/// `?1` = since. Completed delegations report the specialist's result message.const DELEGATIONS_ENDED: &str = "@@ -43,7 +45,8 @@ const DELEGATIONS_ENDED: &str = "FROM delegations dLEFT JOIN kwants k ON k.id = d.specialist_kwant_idLEFT JOIN messages m ON m.id = d.result_message_id- WHERE d.ended_at > ?1";+ WHERE d.ended_at > ?1+ AND COALESCE(k.space_id, 'spc_default') = ?3";/// `?1` = started before. Still running past the threshold.const DELEGATIONS_STUCK: &str = "@@ -51,7 +54,8 @@ const DELEGATIONS_STUCK: &str = "'stuck' AS status, NULL AS body, d.started_at AS at, d.thread_id,NULL AS channel_id, NULL AS direct_kwant_id, NULL AS choicesFROM delegations d LEFT JOIN kwants k ON k.id = d.specialist_kwant_id- WHERE d.status = 'running' AND d.started_at < ?1";+ WHERE d.status = 'running' AND d.started_at < ?1+ AND COALESCE(k.space_id, 'spc_default') = ?3";/// `?1` = since. A routine posts in its channel, or the kwant's direct chat when it has none.const ROUTINE_RUNS_ENDED: &str = "@@ -63,7 +67,8 @@ const ROUTINE_RUNS_ENDED: &str = "JOIN routines rt ON rt.id = r.routine_idLEFT JOIN kwants k ON k.id = rt.kwant_idLEFT JOIN messages m ON m.id = r.message_id- WHERE r.ended_at > ?1";+ WHERE r.ended_at > ?1+ AND COALESCE(k.space_id, 'spc_default') = ?3";const FINISHED_DELEGATIONS: &str = "d.status = 'completed'";const FAILED_DELEGATIONS: &str = "d.status IN ('failed', 'interrupted')";@@ -84,16 +89,21 @@ impl Database {Ok(())}- /// Open questions, newest first.- pub async fn away_open_questions(&self, limit: i64) -> Result<Vec<AwayRow>, DbError> {- Ok(sqlx::query_as(&format!("{OPEN_QUESTIONS} ORDER BY q.created_at DESC, q.rowid DESC LIMIT ?1"))+ /// The space's open questions, newest first.+ pub async fn away_open_questions(&self, space: &SpaceId, limit: i64) -> Result<Vec<AwayRow>, DbError> {+ Ok(sqlx::query_as(&format!("{OPEN_QUESTIONS} ORDER BY q.created_at DESC, q.rowid DESC LIMIT ?2"))+ .bind(Utc::now()).bind(limit)+ .bind(space.as_str()).fetch_all(&self.pool).await?)}- pub async fn away_count_open_questions(&self) -> Result<i64, DbError> {- Ok(sqlx::query_scalar("SELECT COUNT(*) FROM questions WHERE status = 'open'")+ pub async fn away_count_open_questions(&self, space: &SpaceId) -> Result<i64, DbError> {+ Ok(sqlx::query_scalar(&format!("SELECT COUNT(*) FROM ({OPEN_QUESTIONS})"))+ .bind(Utc::now())+ .bind(0)+ .bind(space.as_str()).fetch_one(&self.pool).await?)}@@ -119,10 +129,11 @@ impl Database {Ok(q.fetch_all(&self.pool).await?)}- /// Completed delegations and successful routine runs that ended after `since`, newest first.- pub async fn away_finished(&self, since: DateTime<Utc>, limit: i64) -> Result<Vec<AwayRow>, DbError> {- let mut rows = self.ended(DELEGATIONS_ENDED, FINISHED_DELEGATIONS, "d", since, limit).await?;- rows.extend(self.ended(ROUTINE_RUNS_ENDED, FINISHED_RUNS, "r", since, limit).await?);+ /// The space's completed delegations and successful routine runs that ended after `since`,+ /// newest first.+ pub async fn away_finished(&self, space: &SpaceId, since: DateTime<Utc>, limit: i64) -> Result<Vec<AwayRow>, DbError> {+ let mut rows = self.ended(DELEGATIONS_ENDED, FINISHED_DELEGATIONS, "d", space, since, limit).await?;+ rows.extend(self.ended(ROUTINE_RUNS_ENDED, FINISHED_RUNS, "r", space, since, limit).await?);Ok(newest(rows, limit))}@@ -130,16 +141,18 @@ impl Database {/// delegations still running that started before `stuck_before`, newest first.pub async fn away_failed(&self,+ space: &SpaceId,since: DateTime<Utc>,stuck_before: DateTime<Utc>,limit: i64,) -> Result<Vec<AwayRow>, DbError> {- let mut rows = self.ended(DELEGATIONS_ENDED, FAILED_DELEGATIONS, "d", since, limit).await?;- rows.extend(self.ended(ROUTINE_RUNS_ENDED, FAILED_RUNS, "r", since, limit).await?);+ let mut rows = self.ended(DELEGATIONS_ENDED, FAILED_DELEGATIONS, "d", space, since, limit).await?;+ rows.extend(self.ended(ROUTINE_RUNS_ENDED, FAILED_RUNS, "r", space, since, limit).await?);rows.extend(sqlx::query_as::<_, AwayRow>(&format!("{DELEGATIONS_STUCK} ORDER BY d.started_at DESC, d.rowid DESC LIMIT ?2")).bind(stuck_before).bind(limit)+ .bind(space.as_str()).fetch_all(&self.pool).await?,);@@ -147,18 +160,26 @@ impl Database {}/// Uncapped (finished, failed) counts for the same filters.- pub async fn away_counts(&self, since: DateTime<Utc>, stuck_before: DateTime<Utc>) -> Result<(i64, i64), DbError> {- let finished = self.count(DELEGATIONS_ENDED, FINISHED_DELEGATIONS, since).await?- + self.count(ROUTINE_RUNS_ENDED, FINISHED_RUNS, since).await?;- let failed = self.count(DELEGATIONS_ENDED, FAILED_DELEGATIONS, since).await?- + self.count(ROUTINE_RUNS_ENDED, FAILED_RUNS, since).await?- + self.count(DELEGATIONS_STUCK, "1", stuck_before).await?;+ pub async fn away_counts(+ &self,+ space: &SpaceId,+ since: DateTime<Utc>,+ stuck_before: DateTime<Utc>,+ ) -> Result<(i64, i64), DbError> {+ let finished = self.count(DELEGATIONS_ENDED, FINISHED_DELEGATIONS, space, since).await?+ + self.count(ROUTINE_RUNS_ENDED, FINISHED_RUNS, space, since).await?;+ let failed = self.count(DELEGATIONS_ENDED, FAILED_DELEGATIONS, space, since).await?+ + self.count(ROUTINE_RUNS_ENDED, FAILED_RUNS, space, since).await?+ + self.count(DELEGATIONS_STUCK, "1", space, stuck_before).await?;Ok((finished, failed))}- async fn count(&self, sql: &str, cond: &str, t: DateTime<Utc>) -> Result<i64, DbError> {+ async fn count(&self, sql: &str, cond: &str, space: &SpaceId, t: DateTime<Utc>) -> Result<i64, DbError> {+ // ?2 is the listing limit: unused here, but the slots are numbered up to ?3Ok(sqlx::query_scalar(&format!("SELECT COUNT(*) FROM ({sql} AND {cond})")).bind(t)+ .bind(0)+ .bind(space.as_str()).fetch_one(&self.pool).await?)}@@ -168,6 +189,7 @@ impl Database {sql: &str,cond: &str,alias: &str,+ space: &SpaceId,since: DateTime<Utc>,limit: i64,) -> Result<Vec<AwayRow>, DbError> {@@ -176,6 +198,7 @@ impl Database {)).bind(since).bind(limit)+ .bind(space.as_str()).fetch_all(&self.pool).await?)}@@ -196,6 +219,7 @@ mod tests {let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&format!("EXPLAIN QUERY PLAN {sql}")).bind(Utc::now()).bind(50)+ .bind("spc_default").fetch_all(&db.pool).await.unwrap();diff --git a/src/db/mod.rs b/src/db/mod.rsindex 60db3e52..3f795666 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -122,6 +122,7 @@ impl Database {db.require_spaces_schema(&migration).await?;db.ensure_one_general().await?;db.seed_defaults().await?;+ db.migrate_space_archive().await?;}Ok(db)diff --git a/src/db/questions.rs b/src/db/questions.rsindex ff479ddb..169f815f 100644--- a/src/db/questions.rs+++ b/src/db/questions.rs@@ -190,15 +190,23 @@ impl Database {}/// Questions, newest first: by status and/or chat (channel, thread or direct-chat kwant id).- pub async fn list_questions(&self, status: Option<&str>, context_id: Option<&str>) -> Result<Vec<Question>, DbError> {+ /// Newest first, at most 100; `space` keeps the questions of that space's kwants (all when `None`).+ pub async fn list_questions(+ &self,+ status: Option<&str>,+ context_id: Option<&str>,+ space: Option<&super::spaces::SpaceId>,+ ) -> Result<Vec<Question>, DbError> {Ok(sqlx::query_as::<_, Question>("SELECT * FROM questionsWHERE (?1 IS NULL OR status = ?1)AND (?2 IS NULL OR channel_id = ?2 OR thread_id = ?2 OR direct_kwant_id = ?2)+ AND (?3 IS NULL OR COALESCE((SELECT k.space_id FROM kwants k WHERE k.id = questions.kwant_id), 'spc_default') = ?3)ORDER BY created_at DESC LIMIT 100",).bind(status).bind(context_id)+ .bind(space.map(|s| s.as_str())).fetch_all(&self.pool).await?)}diff --git a/src/db/spaces.rs b/src/db/spaces.rsindex 0dae8fff..625ee8f1 100644--- a/src/db/spaces.rs+++ b/src/db/spaces.rs@@ -536,4 +536,103 @@ impl Database {}Ok(true)}++ /// Renames or restyles a space, or moves it in the list. `None` keeps a field.+ pub async fn update_space(&self, id: &SpaceId, input: &SpaceUpdate) -> Result<Option<Space>, DbError> {+ let res = sqlx::query(+ "UPDATE spaces SET name = COALESCE(?, name), icon = COALESCE(?, icon), \+ color = CASE WHEN ? THEN ? ELSE color END, sort = COALESCE(?, sort) WHERE id = ?",+ )+ .bind(input.name.as_deref().map(str::trim))+ .bind(&input.icon)+ .bind(input.color.is_some())+ .bind(input.color.clone().flatten())+ .bind(input.sort)+ .bind(id.as_str())+ .execute(&self.pool)+ .await?;+ if res.rows_affected() == 0 {+ return Ok(None);+ }+ self.get_space(id).await+ }++ /// Archives a space: its enabled routines are switched off and marked, so a restore brings+ /// back only those. The Default space can't be archived. Returns how many were paused.+ pub async fn archive_space(&self, id: &SpaceId) -> Result<u64, DbError> {+ if id.is_default() {+ return Err(DbError::Conflict("the Default space can't be archived".into()));+ }+ let mut tx = self.pool.begin().await?;+ let paused = sqlx::query(+ "UPDATE routines SET enabled = 0, paused_by_archive = 1 WHERE space_id = ? AND enabled = 1",+ )+ .bind(id.as_str())+ .execute(&mut *tx)+ .await?+ .rows_affected();+ sqlx::query("UPDATE spaces SET archived_at = COALESCE(archived_at, ?) WHERE id = ?")+ .bind(chrono::Utc::now())+ .bind(id.as_str())+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(paused)+ }++ /// Restores an archived space and switches back on the routines its archive paused. Their+ /// next runs are left for the caller to recompute. Returns how many came back.+ pub async fn restore_space(&self, id: &SpaceId) -> Result<u64, DbError> {+ let mut tx = self.pool.begin().await?;+ let resumed = sqlx::query(+ "UPDATE routines SET enabled = 1, paused_by_archive = 0, next_run_at = NULL \+ WHERE space_id = ? AND paused_by_archive = 1",+ )+ .bind(id.as_str())+ .execute(&mut *tx)+ .await?+ .rows_affected();+ sqlx::query("UPDATE spaces SET archived_at = NULL WHERE id = ?")+ .bind(id.as_str())+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(resumed)+ }++ /// Bots in the space and routines its archive paused.+ pub async fn space_counts(&self, id: &SpaceId) -> Result<(i64, i64), DbError> {+ let (bots,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM kwants WHERE space_id = ?")+ .bind(id.as_str())+ .fetch_one(&self.pool)+ .await?;+ let (paused,): (i64,) =+ sqlx::query_as("SELECT COUNT(*) FROM routines WHERE space_id = ? AND paused_by_archive = 1")+ .bind(id.as_str())+ .fetch_one(&self.pool)+ .await?;+ Ok((bots, paused))+ }++ /// Adds `routines.paused_by_archive` if missing. Additive, so an older binary still runs.+ pub(super) async fn migrate_space_archive(&self) -> Result<(), DbError> {+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info('routines')")+ .fetch_all(&self.pool)+ .await?;+ if !cols.iter().any(|(c,)| c == "paused_by_archive") {+ sqlx::query("ALTER TABLE routines ADD COLUMN paused_by_archive INTEGER NOT NULL DEFAULT 0")+ .execute(&self.pool)+ .await?;+ }+ Ok(())+ }+}++/// A `PATCH /api/spaces/:id` body without the archive switch. `color: Some(None)` clears it.+#[derive(Debug, Default, Clone)]+pub struct SpaceUpdate {+ pub name: Option<String>,+ pub icon: Option<String>,+ pub color: Option<Option<String>>,+ pub sort: Option<i64>,}diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex 869eb42c..c919f7d1 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -171,6 +171,15 @@ pub enum RuntimeEvent {reason: String,/// "direct" for a single responder, "discuss" for a multi-turn team discussion.mode: String,+ /// How many agents were considered.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ candidate_count: Option<usize>,+ /// True when Laya was unreachable and keyword matching picked instead.+ #[serde(default)]+ fallback: bool,+ /// Prompt words that matched the picked agent (keyword fallback only).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ matched_terms: Vec<String>,},Error {code: String,@@ -198,6 +207,11 @@ pub enum RuntimeEvent {channel_id: Option<String>,title: String,body: String,+ /// The space the kwant lives in, so the UI can label and filter the notification.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ space_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ space_name: Option<String>,},}diff --git a/src/router/mod.rs b/src/router/mod.rsindex cacd14cb..4896d9e5 100644--- a/src/router/mod.rs+++ b/src/router/mod.rs@@ -8,8 +8,8 @@ pub use fallback::heuristic_fallback;pub use laya::LayaRouter;pub use tags::{handoff_targets, parse_mentions, parse_mentions_with_lookup, TagMention};pub use team::{- heuristic_pick_kwant, heuristic_team_decision, parse_laya_kwant_choice, parse_laya_team_answers,- TeamDecision,+ heuristic_pick_kwant, heuristic_team_decision, matched_terms, parse_laya_kwant_choice,+ parse_laya_team_answers, ChannelRoute, TeamDecision,};use serde::{Deserialize, Serialize};use thiserror::Error;diff --git a/src/router/team.rs b/src/router/team.rsindex b1d4134d..ee45e124 100644--- a/src/router/team.rs+++ b/src/router/team.rs@@ -109,16 +109,33 @@ impl LayaRouter {lead_kwant_id: &str,members: &[Kwant],) -> (String, String) {+ let route = self.route_channel_query_detailed(prompt, channel_name, lead_kwant_id, members).await;+ (route.kwant_id, route.reason)+ }++ /// [`Self::route_channel_query`] plus how the pick was made, for the UI's "why this agent".+ pub async fn route_channel_query_detailed(+ &self,+ prompt: &str,+ channel_name: &str,+ lead_kwant_id: &str,+ members: &[Kwant],+ ) -> ChannelRoute {match self.query_laya_for_kwant(prompt, channel_name, members).await {- Ok(choice) => choice,+ Ok((kwant_id, reason)) => ChannelRoute { kwant_id, reason, fallback: false, matched_terms: Vec::new() },Err(e) => {if self.status().is_up() {tracing::warn!(error = %e, url = %self.base_url, "Laya channel routing failed, using keyword fallback");}- let (kwant, reason) = heuristic_pick_kwant(prompt, lead_kwant_id, members)- .map(|(k, r)| (k.id.clone(), r))- .unwrap_or_else(|| (lead_kwant_id.to_string(), "Routed to channel lead".into()));- (kwant, format!("{reason}. {}", self.offline_note()))+ let (kwant_id, reason, matched_terms) = heuristic_pick_kwant(prompt, lead_kwant_id, members)+ .map(|(k, r)| (k.id.clone(), r, matched_terms(prompt, k)))+ .unwrap_or_else(|| (lead_kwant_id.to_string(), "Routed to channel lead".into(), Vec::new()));+ ChannelRoute {+ kwant_id,+ reason: format!("{reason}. {}", self.offline_note()),+ fallback: true,+ matched_terms,+ }}}}@@ -445,7 +462,27 @@ const STOP_WORDS: &[&str] = &["any", "not", "but", "out", "use", "using", "does", "did", "its", "it's", "some", "need", "want",];+/// A channel routing pick and how it was made.+#[derive(Debug, Clone, PartialEq)]+pub struct ChannelRoute {+ pub kwant_id: String,+ pub reason: String,+ /// True when Laya was unreachable and keyword matching picked instead.+ pub fallback: bool,+ /// Prompt words found in the picked agent's name, title or persona (keyword fallback only).+ pub matched_terms: Vec<String>,+}+fn calculate_kwant_relevance(prompt: &str, kwant: &Kwant) -> usize {+ relevance(prompt, kwant).0+}++/// The prompt words that matched `kwant`, in prompt order, without repeats.+pub fn matched_terms(prompt: &str, kwant: &Kwant) -> Vec<String> {+ relevance(prompt, kwant).1+}++fn relevance(prompt: &str, kwant: &Kwant) -> (usize, Vec<String>) {let lower_prompt = prompt.to_lowercase();let words: Vec<&str> = lower_prompt.split(|c: char| !c.is_alphanumeric() && c != '-')@@ -464,7 +501,9 @@ fn calculate_kwant_relevance(prompt: &str, kwant: &Kwant) -> usize {};let mut score = 0;+ let mut terms: Vec<String> = Vec::new();for w in words {+ let before = score;if matches(&name_lower, w) {score += 3;}@@ -474,8 +513,11 @@ fn calculate_kwant_relevance(prompt: &str, kwant: &Kwant) -> usize {if matches(&prompt_lower, w) {score += 1;}+ if score > before && !terms.iter().any(|t| t == w) {+ terms.push(w.to_string());+ }}- score+ (score, terms)}fn generate_discussion_plan(speakers: &[String], members: &[Kwant]) -> Vec<String> {diff --git a/src/server/away.rs b/src/server/away.rsindex e289472f..1976546b 100644--- a/src/server/away.rs+++ b/src/server/away.rs@@ -5,8 +5,10 @@//! Summaries are one line of at most [`SUMMARY_CHARS`] with anything key-like masked: results//! and errors can carry provider text.+use super::spaces::Scope;use super::AppState;use crate::db::away::{AwayRow, LAST_SEEN_KEY};+use crate::db::spaces::SpaceId;use crate::profiles::classify::{mask_credentials, redact_detail};use axum::{extract::{Query, State},@@ -174,19 +176,45 @@ fn item(row: AwayRow) -> Value {v}-async fn last_seen(state: &AppState) -> Result<Option<DateTime<Utc>>, crate::db::DbError> {+/// The space's last-seen marker. Default keeps the marker from before spaces.+fn seen_key(space: &SpaceId) -> String {+ match space.is_default() {+ true => LAST_SEEN_KEY.to_string(),+ false => format!("{LAST_SEEN_KEY}:{space}"),+ }+}++async fn last_seen(state: &AppState, space: &SpaceId) -> Result<Option<DateTime<Utc>>, crate::db::DbError> {Ok(state.db- .get_setting(LAST_SEEN_KEY)+ .get_setting(&seen_key(space)).await?.and_then(|s| DateTime::parse_from_rfc3339(&s).ok()).map(|t| t.with_timezone(&Utc)))}-/// Approvals the broker still waits on, each linked to the chat its turn runs in.-async fn waiting_approvals(state: &AppState) -> Result<Vec<AwayRow>, crate::db::DbError> {+/// The space's unread badge: what waits on the user plus what finished or failed since they+/// last looked, as `unseen.total` of `GET /api/away?space=` counts it.+pub async fn unread_total(state: &AppState, space: &SpaceId) -> Result<i64, crate::db::DbError> {+ let now = Utc::now();+ let since = last_seen(state, space).await?.unwrap_or(now - Duration::days(DEFAULT_LOOKBACK_DAYS));+ let waiting = state.db.away_count_open_questions(space).await? + waiting_approvals(state, space).await?.len() as i64;+ let (finished, failed) = state.db.away_counts(space, since, now - Duration::minutes(STUCK_AFTER_MINUTES)).await?;+ Ok(waiting + finished + failed)+}++/// The space's approvals the broker still waits on, each linked to the chat its turn runs in.+async fn waiting_approvals(state: &AppState, space: &SpaceId) -> Result<Vec<AwayRow>, crate::db::DbError> {let live = state.broker.pending_ids().await;let mut rows = state.db.away_pending_approvals(&live).await?;+ let mut mine = Vec::with_capacity(rows.len());+ for row in rows.drain(..) {+ let of = state.db.space_of_kwant(&row.kwant_id).await?.unwrap_or_else(SpaceId::default_space);+ if &of == space {+ mine.push(row);+ }+ }+ let mut rows = mine;let turns = state.turns.active_turns();// turn_id isn't in the row; look it up by ticketfor row in &mut rows {@@ -211,9 +239,9 @@ pub struct AwayQuery {/// `GET /api/away?since=<RFC 3339>`: `since` defaults to the last-seen marker, else 7 days ago./// Waiting items and stuck delegations are listed whatever `since` is: they still need you.-pub async fn get(State(state): State<AppState>, Query(q): Query<AwayQuery>) -> Response {+pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<AwayQuery>) -> Response {let now = Utc::now();- let Ok(seen) = last_seen(&state).await else {+ let Ok(seen) = last_seen(&state, &space).await else {return internal();};let default_since = seen.unwrap_or(now - Duration::days(DEFAULT_LOOKBACK_DAYS));@@ -227,16 +255,16 @@ pub async fn get(State(state): State<AppState>, Query(q): Query<AwayQuery>) -> Rlet stuck_before = now - Duration::minutes(STUCK_AFTER_MINUTES);let result = async {- let mut waiting = state.db.away_open_questions(MAX_ITEMS).await?;- let approvals = waiting_approvals(&state).await?;- let waiting_count = state.db.away_count_open_questions().await? + approvals.len() as i64;+ let mut waiting = state.db.away_open_questions(&space, MAX_ITEMS).await?;+ let approvals = waiting_approvals(&state, &space).await?;+ let waiting_count = state.db.away_count_open_questions(&space).await? + approvals.len() as i64;waiting.extend(approvals);waiting.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| b.id.cmp(&a.id)));waiting.truncate(MAX_ITEMS as usize);- let finished = state.db.away_finished(since, MAX_ITEMS).await?;- let failed = state.db.away_failed(since, stuck_before, MAX_ITEMS).await?;+ let finished = state.db.away_finished(&space, since, MAX_ITEMS).await?;+ let failed = state.db.away_failed(&space, since, stuck_before, MAX_ITEMS).await?;// The badge counts from the marker, whatever this page asked for- let (unseen_finished, unseen_failed) = state.db.away_counts(default_since, stuck_before).await?;+ let (unseen_finished, unseen_failed) = state.db.away_counts(&space, default_since, stuck_before).await?;Ok::<_, crate::db::DbError>((waiting, finished, failed, waiting_count, unseen_finished, unseen_failed))}.await;@@ -261,10 +289,10 @@ pub async fn get(State(state): State<AppState>, Query(q): Query<AwayQuery>) -> R.into_response()}-/// `POST /api/away/seen`: the user has looked; returns the stored marker.-pub async fn seen(State(state): State<AppState>) -> Response {+/// `POST /api/away/seen?space=`: the user has looked at that space; returns the stored marker.+pub async fn seen(State(state): State<AppState>, Scope(space): Scope) -> Response {let now = Utc::now();- if state.db.set_setting(LAST_SEEN_KEY, &rfc3339(now)).await.is_err() {+ if state.db.set_setting(&seen_key(&space), &rfc3339(now)).await.is_err() {return internal();}Json(json!({ "last_seen": rfc3339(now) })).into_response()diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex f3a27cf1..56ab834e 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -571,9 +571,13 @@ pub struct SearchQuery {pub limit: Option<i64>,}-/// `GET /api/search?q=&channel_id=&kwant_id=&limit=`, in the channel's or kwant's space, else-/// the Default space.-pub async fn search(State(state): State<AppState>, Query(q): Query<SearchQuery>) -> Response {+/// `GET /api/search?q=&channel_id=&kwant_id=&limit=&space=`, in the channel's or kwant's space,+/// else the `?space=` one (Default when there is none).+pub async fn search(+ State(state): State<AppState>,+ super::spaces::Scope(scope): super::spaces::Scope,+ Query(q): Query<SearchQuery>,+) -> Response {let text = q.q.unwrap_or_default();if store::fts_query(&text).is_none() {return error(StatusCode::BAD_REQUEST, "q needs at least one word");@@ -584,7 +588,7 @@ pub async fn search(State(state): State<AppState>, Query(q): Query<SearchQuery>)(None, None) => Ok(None),};let space = match space {- Ok(s) => s.unwrap_or_else(super::routes::request_space),+ Ok(s) => s.unwrap_or(scope),Err(_) => return internal(),};let filter = SearchFilter {@@ -839,7 +843,16 @@ pub async fn notify(state: &AppState, n: Notification) {return;}let body = clip(&n.body, NOTIFY_BODY_CHARS);- let title = clip(&n.title, 120);+ let space = notify_space(state, &n.kwant_id).await;+ // With more than one space the phone can't tell "Laya finished" apart, so name the space+ let title = match &space {+ Some((_, name, true)) => clip(&format!("{name} · {}", n.title), 120),+ _ => clip(&n.title, 120),+ };+ let (space_id, space_name) = match space {+ Some((id, name, _)) => (Some(id), Some(name)),+ None => (None, None),+ };let _ = state.event_sender.send(RuntimeEvent::Notify {kind: n.kind.into(),kwant_id: n.kwant_id,@@ -847,6 +860,8 @@ pub async fn notify(state: &AppState, n: Notification) {channel_id: n.channel_id,title: title.clone(),body: body.clone(),+ space_id,+ space_name,});let Some(url) = state.db@@ -861,6 +876,19 @@ pub async fn notify(state: &AppState, n: Notification) {tokio::spawn(post_webhook(url, title, body));}+/// The kwant's space: id, name and whether other active spaces exist.+async fn notify_space(state: &AppState, kwant_id: &str) -> Option<(String, String, bool)> {+ let id = state.db.space_of_kwant(kwant_id).await.ok().flatten()?;+ let space = state.db.get_space(&id).await.ok().flatten()?;+ let several = state+ .db+ .list_spaces()+ .await+ .map(|s| s.iter().filter(|s| s.archived_at.is_none()).count() > 1)+ .unwrap_or(false);+ Some((space.id.as_str().to_string(), space.name, several))+}+pub async fn post_webhook(url: String, title: String, body: String) {if check_webhook_url(&url).is_err() {return tracing::warn!(url = %loggable_url(&url), "notify webhook is not an https URL; skipped");diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex 1e7bf849..50c0c954 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -440,9 +440,17 @@ pub async fn interrupt_open(state: &AppState) {// Routes-pub async fn list_turns(State(state): State<AppState>) -> Response {+/// `GET /api/turns?space=`: the turns running for that space's kwants. The limits are app-wide.+pub async fn list_turns(State(state): State<AppState>, super::spaces::Scope(space): super::spaces::Scope) -> Response {let (per_agent, global) = state.turns.limiter.limits();- Json(json!({ "turns": state.turns.active_turns(), "max_turns_per_agent": per_agent, "max_turns_global": global })).into_response()+ let mut turns = Vec::new();+ for t in state.turns.active_turns() {+ let of = state.db.space_of_kwant(&t.kwant_id).await.ok().flatten().unwrap_or_else(crate::db::spaces::SpaceId::default_space);+ if of == space {+ turns.push(t);+ }+ }+ Json(json!({ "turns": turns, "max_turns_per_agent": per_agent, "max_turns_global": global })).into_response()}#[derive(Deserialize)]diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rsindex 5e87cead..f71b6140 100644--- a/src/server/engine_routes.rs+++ b/src/server/engine_routes.rs@@ -2,7 +2,9 @@//! engine can run, why not, the models it offers, and turning one off or on.use super::profile_turn::{self, with_accounts};+use super::spaces::Scope;use super::AppState;+use crate::db::spaces::SpaceId;use crate::drivers::engines::{parse_disabled, EngineId, EngineReport, ProbeEnv, DISABLED_SETTING};use axum::{extract::{Path, State},@@ -18,24 +20,24 @@ pub struct EnginesResponse {/// The cached checks; never waits on one. Engines not checked yet show as "checking". Stale/// profile sign-in checks run in the background for the next call.-pub async fn list(State(state): State<AppState>) -> Json<EnginesResponse> {- let engines = with_accounts(&state, &super::routes::request_space(), state.engines.snapshot()).await;+pub async fn list(State(state): State<AppState>, Scope(space): Scope) -> Json<EnginesResponse> {+ let engines = with_accounts(&state, &space, state.engines.snapshot()).await;let bg = state.clone();tokio::spawn(async move { profile_turn::refresh_sign_ins(&bg).await });Json(EnginesResponse { engines })}/// Checks every engine again and answers once done (each check is capped at 10s).-pub async fn recheck(State(state): State<AppState>) -> Json<EnginesResponse> {- Json(EnginesResponse { engines: recheck_all(&state).await })+pub async fn recheck(State(state): State<AppState>, Scope(space): Scope) -> Json<EnginesResponse> {+ Json(EnginesResponse { engines: recheck_all(&state, &space).await })}-/// Every engine and every profile's sign-in, checked again.-pub async fn recheck_all(state: &AppState) -> Vec<EngineReport> {+/// Every engine and every profile's sign-in, checked again; `ready` and `uses` for `space`.+pub async fn recheck_all(state: &AppState, space: &SpaceId) -> Vec<EngineReport> {load_disabled(state).await;let env = probe_env(state).await;let (engines, ()) = tokio::join!(state.engines.recheck(&env), profile_turn::refresh_sign_ins(state));- with_accounts(state, &super::routes::request_space(), engines).await+ with_accounts(state, space, engines).await}/// What the checks run with: Settings and the env, and Claude's sign-in config dir.@@ -61,6 +63,7 @@ static SWITCH: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());/// once). Answers with every engine, as `GET /api/engines` does.pub async fn set_enabled(State(state): State<AppState>,+ Scope(space): Scope,Path(id): Path<String>,Json(body): Json<SetEnabled>,) -> Result<Json<EnginesResponse>, StatusCode> {@@ -81,13 +84,13 @@ pub async fn set_enabled(let env = probe_env(&state).await;state.engines.recheck_one(id, &env).await;}- Ok(Json(EnginesResponse { engines: with_accounts(&state, &super::routes::request_space(), state.engines.snapshot()).await }))+ Ok(Json(EnginesResponse { engines: with_accounts(&state, &space, state.engines.snapshot()).await }))}/// Checks every engine in the background, so the first turns after startup see real status.pub fn spawn_startup_check(state: AppState) {tokio::spawn(async move {- let engines = recheck_all(&state).await;+ let engines = recheck_all(&state, &SpaceId::default_space()).await;let ready: Vec<_> = engines.iter().filter(|e| e.status == crate::drivers::engines::EngineStatus::Ready)diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rsindex 0905fd01..1a2e303e 100644--- a/src/server/mcp_routes.rs+++ b/src/server/mcp_routes.rs@@ -1,6 +1,8 @@//! MCP server registry and per-kwant assignment endpoints. Contract: docs/mcp-api.md.+use super::spaces::Scope;use super::{mcp_oauth::{self, TokenUse}, AppState};+use crate::db::spaces::SpaceId;use crate::db::{models::McpServer, DbError};use crate::mcp::{self, McpClient, McpError, McpServerInput, McpServerView};use axum::{@@ -30,8 +32,8 @@ fn db_err(e: DbError) -> ApiError {}/// Which kwants have each server off. A read failure shows no opt-outs rather than failing the list.-async fn opt_outs(state: &AppState) -> std::collections::HashMap<String, Vec<String>> {- state.db.list_mcp_kwant_opt_outs(&super::routes::request_space()).await.unwrap_or_else(|e| {+async fn opt_outs(state: &AppState, space: &SpaceId) -> std::collections::HashMap<String, Vec<String>> {+ state.db.list_mcp_kwant_opt_outs(space).await.unwrap_or_else(|e| {tracing::warn!(error = %e, "could not read MCP kwant opt-outs");Default::default()})@@ -41,14 +43,15 @@ async fn opt_outs(state: &AppState) -> std::collections::HashMap<String, Vec<Strasync fn view(state: &AppState, server: &McpServer) -> McpServerView {let mut view = McpServerView::from(server);view.oauth = mcp_oauth::statuses(state).await.remove(&server.id).unwrap_or_default();- view.disabled_for_kwants = opt_outs(state).await.remove(&server.id).unwrap_or_default();+ let space = state.db.space_of_mcp_server(&server.id).await.ok().flatten().unwrap_or_else(SpaceId::default_space);+ view.disabled_for_kwants = opt_outs(state, &space).await.remove(&server.id).unwrap_or_default();view}-pub async fn list_servers(State(state): State<AppState>) -> ApiResult<Vec<McpServerView>> {- let servers = state.db.list_mcp_servers(&super::routes::request_space()).await.map_err(db_err)?;+pub async fn list_servers(State(state): State<AppState>, Scope(space): Scope) -> ApiResult<Vec<McpServerView>> {+ let servers = state.db.list_mcp_servers(&space).await.map_err(db_err)?;let mut statuses = mcp_oauth::statuses(&state).await;- let mut opt_outs = opt_outs(&state).await;+ let mut opt_outs = opt_outs(&state, &space).await;Ok(Json(servers.iter()@@ -68,9 +71,13 @@ pub async fn get_server(State(state): State<AppState>, Path(id): Path<String>) -}}-pub async fn create_server(State(state): State<AppState>, Json(input): Json<McpServerInput>) -> ApiResult<McpServerView> {+pub async fn create_server(+ State(state): State<AppState>,+ Scope(space): Scope,+ Json(input): Json<McpServerInput>,+) -> ApiResult<McpServerView> {let server = mcp::build_server(input, None).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;- let created = state.db.create_mcp_server(&super::routes::request_space(), &server).await.map_err(db_err)?;+ let created = state.db.create_mcp_server(&space, &server).await.map_err(db_err)?;Ok(Json(McpServerView::from(&created)))}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 35de7655..b708c2c9 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -17,6 +17,7 @@ pub mod delegation;pub mod attachments;pub mod questions;pub mod skills;+pub mod spaces;pub mod away;pub mod computer;@@ -118,6 +119,8 @@ pub fn create_router(state: AppState) -> Router {Router::new().route("/api/health", get(routes::health)).route("/api/auth/status", get(auth::status))+ .route("/api/spaces", get(spaces::list).post(spaces::create))+ .route("/api/spaces/:id", get(spaces::get).patch(spaces::update)).route("/api/auth/session", post(auth::create_session).delete(auth::delete_session)).route("/api/profiles", get(profile_routes::list).post(profile_routes::create)).route("/api/profiles/:id", axum::routing::patch(profile_routes::update).delete(profile_routes::remove))diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rsindex 185a1fe7..ea0fe8e9 100644--- a/src/server/profile_routes.rs+++ b/src/server/profile_routes.rs@@ -1,6 +1,7 @@//! `/api/profiles`: LLM accounts per engine. API keys are write-only: no response ever carries//! one, only `has_key`.+use super::spaces::Scope;use super::AppState;use crate::db::models::{LlmProfile, LlmProfilePatch, NewLlmProfile};use crate::db::spaces::SpaceId;@@ -137,8 +138,8 @@ async fn load(state: &AppState, id: &str) -> Result<LlmProfile, Response> {}/// `GET /api/profiles`-pub async fn list(State(state): State<AppState>) -> Response {- match state.db.list_profiles(&super::routes::request_space()).await {+pub async fn list(State(state): State<AppState>, Scope(space): Scope) -> Response {+ match state.db.list_profiles(&space).await {Ok(profiles) => Json(views(&state, profiles).await).into_response(),Err(e) => db_err(e),}@@ -158,7 +159,7 @@ pub struct CreateBody {}/// `POST /api/profiles`-pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>) -> Response {+pub async fn create(State(state): State<AppState>, Scope(space): Scope, Json(body): Json<CreateBody>) -> Response {let Some(engine) = Engine::parse(&body.engine) else {return err(StatusCode::BAD_REQUEST,@@ -184,7 +185,6 @@ pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>)("cli_home", None) => None,_ => return err(StatusCode::BAD_REQUEST, "kind must be cli_home or api_key"),};- let space = super::routes::request_space();let all = match state.db.list_profiles(&space).await {Ok(a) => a,Err(e) => return db_err(e),diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex 9164e14c..fd3bfc5f 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -220,6 +220,54 @@ pub async fn with_accounts(state: &AppState, space: &SpaceId, mut reports: Vec<Ereports}+/// How many of `space`'s enabled accounts could take a turn now: This machine when its+/// engine's own login is ready and the engine is on, any other account when it is signed in+/// and its engine is on.+pub async fn ready_accounts(state: &AppState, space: &SpaceId) -> usize {+ let Some((profiles, avail)) = accounts(state, space).await else {+ return 0;+ };+ let reports = state.engines.snapshot();+ let host_ready = |family: Engine| {+ let (cli, _) = EngineId::of_family(family);+ reports.iter().any(|r| r.id == cli && r.enabled && r.status == EngineStatus::Ready)+ };+ let now = chrono::Utc::now();+ profiles+ .iter()+ .filter(|p| p.enabled)+ .filter(|p| match (p.kind.as_str(), Engine::parse(&p.engine)) {+ ("system", Some(family)) => host_ready(family),+ ("system", None) => false,+ _ => avail.admits(p, now, SignInBar::SignedIn) && profile_engine_on(state, p),+ })+ .count()+}++/// The account a bot's next turn would run on, for its card: the first account failover would+/// try, else This machine when the engine's own login may be used there. `blocked` when This+/// machine is off in the space and no account of its own can take the turn. Bots on "auto" or+/// on a model without accounts (Ollama) have none.+pub async fn runs_on(state: &AppState, kwant: &crate::db::models::Kwant) -> serde_json::Value {+ let model = kwant.preferred_model.as_str();+ let engine = Engine::parse(model).or_else(|| Engine::from_model(model));+ let Some(engine) = engine else {+ return serde_json::json!({ "auto": model == "auto", "engine": null, "account": null, "profile_id": null, "blocked": false });+ };+ if let Some(p) = plan(state, Some(engine), &kwant.id).await.into_iter().next() {+ return serde_json::json!({ "auto": false, "engine": engine.as_str(), "account": p.name, "profile_id": p.id, "blocked": false });+ }+ let space = SpaceId::new(&kwant.space_id);+ let blocked = host_off(state, &space).await.contains(&engine);+ serde_json::json!({+ "auto": false,+ "engine": engine.as_str(),+ "account": if blocked { None } else { Some("This machine") },+ "profile_id": null,+ "blocked": blocked,+ })+}+static REFRESHING: AtomicBool = AtomicBool::new(false);/// Runs the stale profile sign-in checks so `ready` is current; one run at a time, othersdiff --git a/src/server/questions.rs b/src/server/questions.rsindex cab6b690..1937990d 100644--- a/src/server/questions.rs+++ b/src/server/questions.rs@@ -254,15 +254,20 @@ fn error(status: StatusCode, message: impl Into<String>) -> Response {(status, Json(json!({ "error": message.into() }))).into_response()}-/// `GET /api/questions?status=&context_id=`: newest first (to show open cards after a reload).-pub async fn list(State(state): State<AppState>, Query(q): Query<ListQuery>) -> Response {+/// `GET /api/questions?status=&context_id=&space=`: the space's questions, newest first (to show open cards after a reload).+pub async fn list(+ State(state): State<AppState>,+ super::spaces::Scope(space): super::spaces::Scope,+ Query(q): Query<ListQuery>,+) -> Response {let status = q.status.filter(|s| !s.is_empty());if let Some(s) = &status {if !QUESTION_STATUSES.contains(&s.as_str()) {return error(StatusCode::BAD_REQUEST, "unknown status");}}- match state.db.list_questions(status.as_deref(), q.context_id.as_deref().filter(|c| !c.is_empty())).await {+ let context = q.context_id.as_deref().filter(|c| !c.is_empty());+ match state.db.list_questions(status.as_deref(), context, Some(&space)).await {Ok(list) => Json(list).into_response(),Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),}@@ -354,7 +359,7 @@ async fn resume(state: &AppState, q: &Question, answer: &str) {/// After a turn was stopped: its questions that are still open are cancelled, so a late answer/// doesn't restart work the user stopped. One indexed query, only for stopped turns.pub async fn cancel_for_turn(state: &AppState, turn_id: &str) {- let open = state.db.list_questions(Some("open"), None).await.unwrap_or_default();+ let open = state.db.list_questions(Some("open"), None, None).await.unwrap_or_default();for q in open.iter().filter(|q| q.turn_id.as_deref() == Some(turn_id)) {if let Some(tx) = state.questions.take(&q.id) {drop(tx);diff --git a/src/server/routes.rs b/src/server/routes.rsindex b4618dc7..f773e5fc 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1,4 +1,5 @@use super::discussion;+use super::spaces::{check_workspace, Scope};use super::AppState;use crate::broker::ApprovalDecision;use crate::db::models::*;@@ -50,20 +51,24 @@ pub(crate) fn db_status(e: &DbError) -> StatusCode {}}-/// The space of a request that doesn't name one: Default, until `?space=` arrives (S2).-pub(crate) fn request_space() -> SpaceId {- SpaceId::default_space()-}-+/// The space's kwants, each with `runs_on`: the account its next turn would use.pub async fn list_kwants(State(state): State<AppState>,-) -> Result<Json<Vec<KwantView>>, StatusCode> {- state+ Scope(space): Scope,+) -> Result<Json<Vec<serde_json::Value>>, StatusCode> {+ let views = state.db- .kwant_views(&request_space())+ .kwant_views(&space).await- .map(Json)- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ let mut out = Vec::with_capacity(views.len());+ for v in views {+ let runs_on = super::profile_turn::runs_on(&state, &v.kwant).await;+ let mut item = serde_json::to_value(&v).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ item["runs_on"] = runs_on;+ out.push(item);+ }+ Ok(Json(out))}/// Trims the name and rejects names that can't be @mentioned or clash with another kwant in the@@ -171,9 +176,9 @@ async fn kwant_view_json(state: &AppState, id: &str) -> Result<Json<KwantView>,pub async fn create_kwant(State(state): State<AppState>,+ Scope(space): Scope,Json(mut payload): Json<CreateKwantRequest>,) -> Result<Json<KwantView>, StatusCode> {- let space = request_space();validate_kwant_name(&state, &space, &mut payload.base.name, None).await?;check_binding(&state, &space, &payload.binding, &payload.base.preferred_model).await?;let kwant = state@@ -182,9 +187,28 @@ pub async fn create_kwant(.await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;save_binding(&state, &kwant.id, &payload.binding).await?;+ ensure_general(&state, &space, &kwant.id).await;kwant_view_json(&state, &kwant.id).await}+/// A new space starts empty, and a channel needs a lead, so its #general (routed by Laya)+/// appears with its first bot. Default's comes from the seed.+async fn ensure_general(state: &AppState, space: &SpaceId, lead: &str) {+ if space.is_default() || !matches!(state.db.general_channel(space).await, Ok(None)) {+ return;+ }+ let general = NewChannel {+ name: "general".into(),+ description: Some("Everyone in this space. Laya picks who answers.".into()),+ lead_kwant_id: lead.to_string(),+ member_kwants: vec![lead.to_string()],+ routing_mode: "auto".into(),+ };+ if let Err(e) = state.db.create_channel(space, &general).await {+ tracing::warn!(error = %e, space = %space, "could not create the space's #general");+ }+}+pub async fn update_kwant(State(state): State<AppState>,Path(id): Path<String>,@@ -207,10 +231,10 @@ pub async fn update_kwant(kwant_view_json(&state, &id).await}-pub async fn list_channels(State(state): State<AppState>) -> Result<Json<Vec<Channel>>, StatusCode> {+pub async fn list_channels(State(state): State<AppState>, Scope(space): Scope) -> Result<Json<Vec<Channel>>, StatusCode> {state.db- .list_channels(&request_space())+ .list_channels(&space).await.map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)@@ -218,11 +242,12 @@ pub async fn list_channels(State(state): State<AppState>) -> Result<Json<Vec<Chapub async fn create_channel(State(state): State<AppState>,+ Scope(space): Scope,Json(payload): Json<NewChannel>,) -> Result<Json<Channel>, StatusCode> {state.db- .create_channel(&request_space(), &payload)+ .create_channel(&space, &payload).await.map(Json).map_err(|e| db_status(&e))@@ -266,25 +291,28 @@ pub async fn list_messages(}}-pub async fn list_teams(State(state): State<AppState>) -> Result<Json<Vec<Team>>, StatusCode> {+pub async fn list_teams(State(state): State<AppState>, Scope(space): Scope) -> Result<Json<Vec<Team>>, StatusCode> {state.db- .list_teams(&request_space())+ .list_teams(&space).await.map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)}+#[allow(clippy::result_large_err)]pub async fn create_team(State(state): State<AppState>,+ Scope(space): Scope,Json(payload): Json<NewTeam>,-) -> Result<Json<Team>, StatusCode> {+) -> Result<Json<Team>, axum::response::Response> {+ check_workspace(&state, &space, None, &payload.name, payload.workspace_path.as_deref()).await?;state.db- .create_team(&request_space(), &payload)+ .create_team(&space, &payload).await.map(Json)- .map_err(|e| db_status(&e))+ .map_err(|e| db_status(&e).into_response())}pub async fn get_team(@@ -306,26 +334,38 @@ pub struct UpdateTeamPayload {pub instructions: Option<String>,}+#[allow(clippy::result_large_err)]pub async fn update_team(State(state): State<AppState>,Path(id): Path<String>,Json(payload): Json<UpdateTeamPayload>,-) -> Result<Json<Team>, StatusCode> {+) -> Result<Json<Team>, axum::response::Response> {+ let status = |s: StatusCode| s.into_response();if let Some(text) = &payload.instructions {if super::continuity::check_instructions(text).is_err() {- return Err(StatusCode::BAD_REQUEST);+ return Err(status(StatusCode::BAD_REQUEST));}}+ let space = match state.db.space_of_team(&id).await {+ Ok(Some(space)) => space,+ Ok(None) => return Err(status(StatusCode::NOT_FOUND)),+ Err(_) => return Err(status(StatusCode::INTERNAL_SERVER_ERROR)),+ };+ check_workspace(&state, &space, Some(&id), &payload.team.name, payload.team.workspace_path.as_deref()).await?;match state.db.update_team(&id, &payload.team).await {Ok(Some(mut team)) => {if let Some(text) = &payload.instructions {- state.db.set_team_instructions(&id, text).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ state+ .db+ .set_team_instructions(&id, text)+ .await+ .map_err(|_| status(StatusCode::INTERNAL_SERVER_ERROR))?;team.instructions = Some(text.trim().to_string()).filter(|t| !t.is_empty());}Ok(Json(team))}- Ok(None) => Err(StatusCode::NOT_FOUND),- Err(e) => Err(db_status(&e)),+ Ok(None) => Err(status(StatusCode::NOT_FOUND)),+ Err(e) => Err(status(db_status(&e))),}}@@ -573,6 +613,7 @@ fn execute_single_turn(team_context: Option<crate::drivers::TeamContext>,workspace_dir: Option<std::path::PathBuf>,teammates: Vec<Kwant>,+ routing: Option<serde_json::Value>,) {let scope = TurnScope {channel_id: payload.channel_id.clone(),@@ -592,7 +633,8 @@ fn execute_single_turn(tokio::spawn(async move {// Ends the job (its cancel keys) when the turn and its handoffs are donelet _job = job;- if let Some(reply) = run_kwant_turn(&scope, &target_kwant, prompt.clone(), TurnOpts::default()).await {+ let opts = TurnOpts { routing, ..TurnOpts::default() };+ if let Some(reply) = run_kwant_turn(&scope, &target_kwant, prompt.clone(), opts).await {run_handoffs(&scope, std::slice::from_ref(&target_kwant.id), &[(target_kwant.clone(), reply)], &prompt).await;}});@@ -760,6 +802,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use// Only the opening turn may navigate the bot browser for a URL in the user's messagenav_prompt: Some(if opening { user_prompt.to_string() } else { String::new() }),discussion: Some(opening.then(|| discussion::question_label(&kwant.name, &team.name))),+ routing: None,};let Some(raw) = run_kwant_turn(scope, &kwant, prompt, opts).await else {if scope.cancel_token.is_cancelled() {@@ -811,6 +854,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, uselabel: Some(discussion::summary_label(&team.name, &contributors)),nav_prompt: Some(String::new()),discussion: None,+ routing: None,};run_kwant_turn(scope, &lead, prompt, opts).await;}@@ -828,6 +872,8 @@ pub(super) struct TurnOpts {/// Discussion reply handling: `[PASS]` replies aren't saved; `Some(label)` lets an `[ASK_USER]`/// reply be saved as a question for the user under that label.discussion: Option<Option<String>>,+ /// How this reply's agent was picked, saved as the reply's `meta.routing`.+ routing: Option<serde_json::Value>,}/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it.@@ -959,11 +1005,13 @@ impl TurnEvents {struct RanOn {engine: crate::drivers::engines::EngineId,profile_id: Option<String>,+ /// The account's name, or "This machine" for the host's own CLI.+ account: Option<String>,choice: Option<crate::drivers::engines::ModelChoice>,}impl RanOn {- /// `{engine, engine_name, family, model, model_label, tier, picked_by, effort, profile_id}`;+ /// `{engine, engine_name, family, model, model_label, tier, picked_by, effort, profile_id, account}`;/// `driver_model` is what the driver itself chose when nothing was picked for it.fn to_json(&self, driver_model: Option<&str>, picked_by: &str, effort: &str) -> serde_json::Value {let family = self.engine.family().map_or("ollama", |f| f.as_str());@@ -982,6 +1030,7 @@ impl RanOn {"picked_by": picked_by,"effort": effort,"profile_id": self.profile_id,+ "account": self.account,})}}@@ -1327,6 +1376,7 @@ async fn run_kwant_turn_inner(ran_on = runs_on.map(|e| RanOn {engine: e,profile_id: profile.as_ref().map(|p| p.id.clone()),+ account: super::profile_turn::account_name(profile.as_ref(), e),choice: if unlisted_api { None } else { choice.clone() },});let (driver_tx, mut driver_rx) = mpsc::channel(32);@@ -1525,9 +1575,12 @@ async fn run_kwant_turn_inner((false, true) => "pinned_engine",(false, false) => "laya",};- let meta = ran_on+ let mut meta = ran_on.as_ref().map(|r| serde_json::json!({ "ran_on": r.to_json(output.model.as_deref(), pick, &effort_level) }));+ if let Some(routing) = &opts.routing {+ meta.get_or_insert_with(|| serde_json::json!({}))["routing"] = routing.clone();+ }scope.save(&asst_msg, meta).await;}return Ok(output.text);@@ -1559,7 +1612,7 @@ async fn chat_space(state: &AppState, payload: &SendChatPayload) -> Result<Spacereturn Ok(space);}}- Ok(request_space())+ Ok(SpaceId::default_space())}pub async fn send_chat(@@ -1572,6 +1625,9 @@ pub async fn send_chat(}// Everything this message can reach (mentions, teams, Laya's candidates) is in its spacelet space = chat_space(&state, &payload).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ if super::spaces::ensure_active(&state, &space).await.is_err() {+ return Err(StatusCode::CONFLICT);+ }let all_kwants = state.db.list_kwants(&space)@@ -1779,6 +1835,9 @@ pub async fn send_chat(.unwrap_or(&members[0]).clone();+ // The team router doesn't say which path it took; Laya being down means keywords did+ let fallback = !state.router.status().is_up();+ let routing = routing_meta(&target_kwant, &reason, members.len(), fallback, &[]);let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {context_id: routing_context_id,kwant_id: target_kwant.id.clone(),@@ -1786,6 +1845,9 @@ pub async fn send_chat(kwant_title: target_kwant.title.clone(),reason: reason.clone(),mode: "direct".into(),+ candidate_count: Some(members.len()),+ fallback,+ matched_terms: Vec::new(),});let _ = state.event_sender.send(RuntimeEvent::ThinkingDelta(format!(@@ -1802,6 +1864,7 @@ pub async fn send_chat(active_team_context,workspace_dir.clone(),members.clone(),+ Some(routing),);Ok(Json(json!({@@ -1830,6 +1893,9 @@ pub async fn send_chat(turns, lead.name),mode: "discuss".into(),+ candidate_count: Some(members.len()),+ fallback: !state.router.status().is_up(),+ matched_terms: Vec::new(),});}@@ -1878,6 +1944,7 @@ pub async fn send_chat(}} else {// Target single Kwant+ let mut routing = None;let target_kwant = if let Some(kname) = kwant_mention {all_kwants.iter()@@ -1913,19 +1980,23 @@ pub async fn send_chat(context_id: context_id.clone(),candidates: routing_candidates(&members),});- let (chosen_id, reason) = state+ let route = state.router- .route_channel_query(&payload.prompt, &channel.name, &channel.lead_kwant_id, &members)+ .route_channel_query_detailed(&payload.prompt, &channel.name, &channel.lead_kwant_id, &members).await;- let chosen = members.iter().find(|k| k.id == chosen_id).cloned().or(lead);+ let chosen = members.iter().find(|k| k.id == route.kwant_id).cloned().or(lead);if let Some(ref k) = chosen {+ routing = Some(routing_meta(k, &route.reason, members.len(), route.fallback, &route.matched_terms));let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {context_id,kwant_id: k.id.clone(),kwant_name: k.name.clone(),kwant_title: k.title.clone(),- reason,+ reason: route.reason,mode: "direct".into(),+ candidate_count: Some(members.len()),+ fallback: route.fallback,+ matched_terms: route.matched_terms,});}chosen@@ -1950,6 +2021,7 @@ pub async fn send_chat(active_team_context,workspace_dir,chat_teammates,+ routing,);Ok(Json(json!({@@ -1960,6 +2032,18 @@ pub async fn send_chat(}}+/// A reply's `meta.routing`: who Laya picked for a channel or team message and why.+fn routing_meta(kwant: &Kwant, reason: &str, candidates: usize, fallback: bool, terms: &[String]) -> serde_json::Value {+ json!({+ "kwant_id": kwant.id,+ "kwant_name": kwant.name,+ "reason": reason,+ "candidate_count": candidates,+ "fallback": fallback,+ "matched_terms": terms,+ })+}+/// `/api/chat/send` into a thread: the thread's agent answers there, with only that thread's history.async fn send_to_thread(state: AppState,@@ -1972,6 +2056,9 @@ async fn send_to_thread(return Err(StatusCode::CONFLICT);}let kwant = state.db.get_kwant(&thread.kwant_id).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.ok_or(StatusCode::NOT_FOUND)?;+ if super::spaces::ensure_active(&state, &SpaceId::new(&kwant.space_id)).await.is_err() {+ return Err(StatusCode::CONFLICT);+ }let depth = match state.db.delegation_for_thread(&thread.id).await.ok().flatten() {Some(d) => d.depth,None => 0,@@ -2186,7 +2273,7 @@ pub async fn save_settings(if engines_changed {let state = state.clone();tokio::spawn(async move {- super::engine_routes::recheck_all(&state).await;+ super::engine_routes::recheck_all(&state, &SpaceId::default_space()).await;});}if payload.max_turns_per_agent.is_some() || payload.max_turns_global.is_some() {@@ -2429,7 +2516,7 @@ pub async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> O} else if let Ok(Some(kwant)) = state.db.get_kwant(target_id).await {let safe_kname = kwant.name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-");Some((format!("bot-{}", safe_kname), workspaces(&kwant.space_id).join(format!("bot-{}", safe_kname))))- } else if let Ok(Some(team)) = state.db.get_team_by_name(&request_space(), target_id).await {+ } else if let Ok(Some(team)) = state.db.get_team_by_name(&SpaceId::default_space(), target_id).await {Some(team_folder(team))} else {Nonediff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex 54fe1f58..195f3bb7 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -6,6 +6,7 @@#![allow(clippy::result_large_err)]use super::continuity::{notify, Notification};+use super::spaces::Scope;use super::AppState;use crate::db::continuity::{NewRoutine, RoutineRow, RoutineRun};use crate::drivers::events::RuntimeEvent;@@ -110,7 +111,8 @@ async fn build(.or_else(|| existing.map(|e| e.kwant_id.clone())).ok_or_else(|| bad("kwant_id is required"))?;match state.db.get_kwant(&kwant_id).await {- Ok(Some(_)) => {}+ // Nothing new is scheduled in an archived space+ Ok(Some(k)) => super::spaces::ensure_active(state, &crate::db::spaces::SpaceId::new(&k.space_id)).await?,Ok(None) => return Err(bad("unknown kwant_id")),Err(_) => return Err(internal()),}@@ -171,8 +173,8 @@ async fn build(})}-pub async fn list(State(state): State<AppState>) -> Response {- match state.db.list_routines(&super::routes::request_space()).await {+pub async fn list(State(state): State<AppState>, Scope(space): Scope) -> Response {+ match state.db.list_routines(&space).await {Ok(list) => {Json(list.into_iter().map(RoutineView::from).collect::<Vec<_>>()).into_response()}@@ -188,11 +190,24 @@ pub async fn get(State(state): State<AppState>, Path(id): Path<String>) -> Respo}}-pub async fn create(State(state): State<AppState>, Json(p): Json<RoutinePayload>) -> Response {+/// `POST /api/routines`: the routine lives in its agent's space. An explicit `?space=` must+/// name that space; without one the agent decides, as before spaces had a picker.+pub async fn create(+ State(state): State<AppState>,+ Scope(space): Scope,+ uri: axum::http::Uri,+ Json(p): Json<RoutinePayload>,+) -> Response {let input = match build(&state, p, None).await {Ok(i) => i,Err(r) => return r,};+ let explicit = super::spaces::space_param(uri.query()).is_some();+ match state.db.space_of_kwant(&input.kwant_id).await {+ Ok(Some(of)) if of == space || !explicit => {}+ Ok(_) => return error(StatusCode::BAD_REQUEST, "the agent is in another space"),+ Err(_) => return internal(),+ }match state.db.create_routine(&input).await {Ok(r) => {state.scheduler_wake.notify_one();@@ -270,6 +285,9 @@ pub async fn run_now(State(state): State<AppState>, Path(id): Path<String>) -> ROk(None) => return StatusCode::NOT_FOUND.into_response(),Err(_) => return internal(),};+ if let Err(r) = super::spaces::ensure_active(&state, &crate::db::spaces::SpaceId::new(&routine.space_id)).await {+ return r;+ }match start_run(&state, routine, "manual").await {Some(run) => (StatusCode::ACCEPTED, Json(run)).into_response(),None => internal(),diff --git a/src/server/skills.rs b/src/server/skills.rsindex d0329456..6bfef4ed 100644--- a/src/server/skills.rs+++ b/src/server/skills.rs@@ -7,6 +7,7 @@#![allow(clippy::result_large_err)]use super::continuity::{notify, Notification, SelfScope};+use super::spaces::Scope;use super::AppState;use crate::db::skills::{clean_skill_text, Skill, SkillEdit, SkillError, SKILL_STATUSES};use crate::drivers::events::RuntimeEvent;@@ -221,14 +222,15 @@ fn unified(lines: &[DiffLine]) -> String {// Routes-/// The space a skill request is about: the kwant's, or the request's when it names none.-async fn skill_space(state: &AppState, kwant_id: Option<&str>) -> crate::db::spaces::SpaceId {+/// The space a skill request is about: the kwant's, or the request's (`?space=`) when it names+/// none.+async fn skill_space(state: &AppState, kwant_id: Option<&str>, scope: Scope) -> crate::db::spaces::SpaceId {match kwant_id {Some(id) => match state.db.space_of_kwant(id).await {Ok(Some(space)) => space,- _ => super::routes::request_space(),+ _ => scope.0,},- None => super::routes::request_space(),+ None => scope.0,}}@@ -239,7 +241,7 @@ pub struct SkillsQuery {}/// `GET /api/skills?kwant_id=&status=`: newest first; `kwant_id` includes the shared skills.-pub async fn list(State(state): State<AppState>, Query(q): Query<SkillsQuery>) -> Response {+pub async fn list(State(state): State<AppState>, scope: Scope, Query(q): Query<SkillsQuery>) -> Response {let status = q.status.filter(|s| !s.is_empty());if let Some(s) = &status {if !SKILL_STATUSES.contains(&s.as_str()) {@@ -247,7 +249,7 @@ pub async fn list(State(state): State<AppState>, Query(q): Query<SkillsQuery>) -}}let kwant_id = q.kwant_id.as_deref().filter(|s| !s.is_empty());- let space = skill_space(&state, kwant_id).await;+ let space = skill_space(&state, kwant_id, scope).await;match state.db.list_skills(&space, kwant_id, status.as_deref()).await {Ok(list) => Json(list).into_response(),Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),@@ -328,7 +330,7 @@ impl SkillPayload {}/// `POST /api/skills {name, description, body, kwant_id?}`: a skill the user wrote, enabled at once.-pub async fn create(State(state): State<AppState>, Json(p): Json<SkillPayload>) -> Response {+pub async fn create(State(state): State<AppState>, scope: Scope, Json(p): Json<SkillPayload>) -> Response {if let Err(r) = check_owner(&state, &p.kwant_id).await {return r;}@@ -341,7 +343,7 @@ pub async fn create(State(state): State<AppState>, Json(p): Json<SkillPayload>)Err(e) => return skill_error(e),};let kwant_id = p.kwant_id.flatten();- let space = skill_space(&state, kwant_id.as_deref()).await;+ let space = skill_space(&state, kwant_id.as_deref(), scope).await;match state.db.create_user_skill(&space, kwant_id.as_deref(), text).await {Ok(s) => {changed(&state, &s);diff --git a/src/server/spaces.rs b/src/server/spaces.rsnew file mode 100644index 00000000..9b08b398--- /dev/null+++ b/src/server/spaces.rs@@ -0,0 +1,452 @@+//! Spaces through the API (S2): `GET/POST /api/spaces`, `GET/PATCH /api/spaces/:id`, and the+//! [`Scope`] extractor every collection endpoint takes its space from (`?space=<id>`).+//!+//! A missing `?space=` means the Default space. An unknown id is a 404 and an archived one a+//! 409: a request never falls back to Default. Item endpoints (`/api/kwants/:id`, …) keep taking+//! their space from the row.+#![allow(clippy::result_large_err)]++use super::AppState;+use crate::db::spaces::{NewSpace, Space, SpaceId, SpaceUpdate};+use crate::db::DbError;+use axum::{+ async_trait,+ extract::{FromRequestParts, Path, Query, State},+ http::{request::Parts, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde::{Deserialize, Deserializer};+use serde_json::{json, Value};+use std::path::PathBuf;++const MAX_NAME_CHARS: usize = 60;+const MAX_ICON_CHARS: usize = 16;++fn error(status: StatusCode, message: impl Into<String>) -> Response {+ (status, Json(json!({ "error": message.into() }))).into_response()+}++fn internal() -> Response {+ StatusCode::INTERNAL_SERVER_ERROR.into_response()+}++/// The space a collection request works in, from `?space=<id>`; Default when there is none.+#[derive(Debug, Clone)]+pub struct Scope(pub SpaceId);++#[async_trait]+impl FromRequestParts<AppState> for Scope {+ type Rejection = Response;++ async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Response> {+ match space_param(parts.uri.query()) {+ None => Ok(Scope(SpaceId::default_space())),+ Some(id) => active_space(state, &id).await.map(Scope),+ }+ }+}++/// The `space` value of a raw query string. Parsed on its own so handlers' own query structs+/// don't have to know about it.+pub fn space_param(query: Option<&str>) -> Option<String> {+ url::form_urlencoded::parse(query.unwrap_or("").as_bytes())+ .find(|(k, _)| k == "space")+ .map(|(_, v)| v.into_owned())+}++/// The space `id` names, if it exists and isn't archived: 404 for an unknown (or empty) id, 409+/// for an archived one.+pub async fn active_space(state: &AppState, id: &str) -> Result<SpaceId, Response> {+ let id = id.trim();+ if id.is_empty() {+ return Err(error(StatusCode::NOT_FOUND, "no such space"));+ }+ match state.db.get_space(&SpaceId::new(id)).await {+ Ok(Some(s)) if s.archived_at.is_some() => Err(archived()),+ Ok(Some(s)) => Ok(SpaceId::new(s.id)),+ Ok(None) => Err(error(StatusCode::NOT_FOUND, "no such space")),+ Err(_) => Err(internal()),+ }+}++/// 409 when `space` is archived: nothing new starts there until it is restored.+pub async fn ensure_active(state: &AppState, space: &SpaceId) -> Result<(), Response> {+ if space.is_default() {+ return Ok(());+ }+ match state.db.get_space(space).await {+ Ok(Some(s)) if s.archived_at.is_some() => Err(archived()),+ Ok(_) => Ok(()),+ Err(_) => Err(internal()),+ }+}++fn archived() -> Response {+ error(StatusCode::CONFLICT, "this space is archived; restore it first")+}++/// One space as the API shows it, with what the space switcher needs.+pub async fn view(state: &AppState, s: Space) -> Result<Value, DbError> {+ let id = SpaceId::new(&s.id);+ let (bots, paused) = state.db.space_counts(&id).await?;+ let ready = super::profile_turn::ready_accounts(state, &id).await;+ let unread = super::away::unread_total(state, &id).await?;+ let general = state.db.general_channel(&id).await?.map(|c| c.id);+ Ok(json!({+ "id": s.id,+ "name": s.name,+ "icon": s.icon,+ "color": s.color,+ "sort": s.sort,+ "is_default": id.is_default(),+ "archived_at": s.archived_at,+ "created_at": s.created_at,+ "general_channel_id": general,+ "counts": { "bots": bots, "ready_accounts": ready, "unread": unread },+ "paused_routines": paused,+ }))+}++#[derive(Debug, Deserialize)]+pub struct ListQuery {+ pub archived: Option<String>,+ /// Ignored here: listing spaces isn't scoped to one.+ #[allow(dead_code)]+ pub space: Option<String>,+}++/// `GET /api/spaces`: active spaces in their order; `?archived=1` lists the archived ones.+pub async fn list(State(state): State<AppState>, Query(q): Query<ListQuery>) -> Response {+ let archived = matches!(q.archived.as_deref(), Some("1" | "true"));+ let Ok(spaces) = state.db.list_spaces().await else {+ return internal();+ };+ let mut out = Vec::new();+ for s in spaces.into_iter().filter(|s| s.archived_at.is_some() == archived) {+ match view(&state, s).await {+ Ok(v) => out.push(v),+ Err(_) => return internal(),+ }+ }+ Json(out).into_response()+}++/// `GET /api/spaces/:id`, archived or not.+pub async fn get(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ match state.db.get_space(&SpaceId::new(id)).await {+ Ok(Some(s)) => respond(&state, s, StatusCode::OK).await,+ Ok(None) => error(StatusCode::NOT_FOUND, "no such space"),+ Err(_) => internal(),+ }+}++async fn respond(state: &AppState, s: Space, status: StatusCode) -> Response {+ match view(state, s).await {+ Ok(v) => (status, Json(v)).into_response(),+ Err(_) => internal(),+ }+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct CreateBody {+ pub name: String,+ pub icon: Option<String>,+ pub color: Option<String>,+ /// This machine's switch in the new space, for every engine. Default on.+ pub this_machine_enabled: Option<bool>,+}++fn check_name(name: &str) -> Result<String, Response> {+ let name = name.trim();+ if name.is_empty() {+ return Err(error(StatusCode::BAD_REQUEST, "a space needs a name"));+ }+ if name.chars().count() > MAX_NAME_CHARS {+ return Err(error(StatusCode::BAD_REQUEST, format!("a space name is at most {MAX_NAME_CHARS} characters")));+ }+ Ok(name.to_string())+}++fn check_icon(icon: &str) -> Result<String, Response> {+ let icon = icon.trim();+ if icon.is_empty() || icon.chars().count() > MAX_ICON_CHARS {+ return Err(error(StatusCode::BAD_REQUEST, format!("an icon is 1 to {MAX_ICON_CHARS} characters")));+ }+ Ok(icon.to_string())+}++/// 409 when another space already has `name` (names are unique ignoring ASCII case).+async fn name_free(state: &AppState, name: &str, except: Option<&str>) -> Result<(), Response> {+ let Ok(spaces) = state.db.list_spaces().await else {+ return Err(internal());+ };+ if spaces.iter().any(|s| Some(s.id.as_str()) != except && s.name.eq_ignore_ascii_case(name)) {+ return Err(error(StatusCode::CONFLICT, "another space already has that name"));+ }+ Ok(())+}++fn unique_violation(e: &DbError) -> bool {+ matches!(e, DbError::Sqlx(sqlx::Error::Database(d)) if d.is_unique_violation())+}++/// `POST /api/spaces`: a new, empty space with its own This machine accounts and work folder.+/// Its #general appears with its first bot (a channel needs a lead).+pub async fn create(State(state): State<AppState>, Json(body): Json<CreateBody>) -> Response {+ let name = match check_name(&body.name) {+ Ok(n) => n,+ Err(r) => return r,+ };+ let icon = match body.icon.as_deref().map(check_icon).transpose() {+ Ok(i) => i.unwrap_or_else(|| "box".into()),+ Err(r) => return r,+ };+ if let Err(r) = name_free(&state, &name, None).await {+ return r;+ }+ let input = NewSpace {+ name,+ icon,+ color: body.color.map(|c| c.trim().to_string()).filter(|c| !c.is_empty()),+ this_machine_enabled: body.this_machine_enabled.unwrap_or(true),+ };+ let space = match state.db.create_space(&input).await {+ Ok(s) => s,+ Err(e) if unique_violation(&e) => return error(StatusCode::CONFLICT, "another space already has that name"),+ Err(_) => return internal(),+ };+ let dir = crate::db::spaces::space_data_dir(&state.config.data_dir, &SpaceId::new(&space.id));+ if let Err(e) = std::fs::create_dir_all(&dir) {+ // Team folders are also made on first use, so the space still works+ tracing::warn!(error = %e, space = %space.id, "could not create the space's work folder");+ }+ tracing::info!(space = %space.id, "space created");+ respond(&state, space, StatusCode::CREATED).await+}++/// `Some(None)` for an explicit null, so a PATCH can clear a field.+fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<Option<T>>, D::Error> {+ Option::<T>::deserialize(d).map(Some)+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct PatchBody {+ pub name: Option<String>,+ pub icon: Option<String>,+ #[serde(default, deserialize_with = "present")]+ pub color: Option<Option<String>>,+ pub sort: Option<i64>,+ /// `true` archives, `false` restores.+ pub archived: Option<bool>,+}++/// `PATCH /api/spaces/:id`: rename, restyle, reorder, archive or restore. Archiving pauses the+/// space's routines and stops its running turns; restoring brings back only the routines the+/// archive paused. The Default space can be renamed but not archived (409). No hard delete.+pub async fn update(State(state): State<AppState>, Path(id): Path<String>, Json(body): Json<PatchBody>) -> Response {+ let id = SpaceId::new(id);+ let current = match state.db.get_space(&id).await {+ Ok(Some(s)) => s,+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such space"),+ Err(_) => return internal(),+ };+ let name = match body.name.as_deref().map(check_name).transpose() {+ Ok(n) => n,+ Err(r) => return r,+ };+ let icon = match body.icon.as_deref().map(check_icon).transpose() {+ Ok(i) => i,+ Err(r) => return r,+ };+ if body.archived == Some(true) && id.is_default() {+ return error(StatusCode::CONFLICT, "the Default space can't be archived");+ }+ if let Some(n) = &name {+ if let Err(r) = name_free(&state, n, Some(id.as_str())).await {+ return r;+ }+ }+ let change = SpaceUpdate {+ name,+ icon,+ color: body.color.map(|c| c.map(|c| c.trim().to_string()).filter(|c| !c.is_empty())),+ sort: body.sort,+ };+ match state.db.update_space(&id, &change).await {+ Ok(_) => {}+ Err(e) if unique_violation(&e) => return error(StatusCode::CONFLICT, "another space already has that name"),+ Err(_) => return internal(),+ }+ match (body.archived, current.archived_at.is_some()) {+ (Some(true), false) => {+ let paused = match state.db.archive_space(&id).await {+ Ok(n) => n,+ Err(e @ DbError::Conflict(_)) => return error(StatusCode::CONFLICT, e.to_string()),+ Err(_) => return internal(),+ };+ let stopped = stop_turns(&state, &id).await;+ state.scheduler_wake.notify_one();+ tracing::info!(space = %id, paused, stopped, "space archived");+ }+ (Some(false), true) => {+ let resumed = match state.db.restore_space(&id).await {+ Ok(n) => n,+ Err(_) => return internal(),+ };+ super::scheduler::reschedule_all(&state, chrono::Utc::now()).await;+ state.scheduler_wake.notify_one();+ tracing::info!(space = %id, resumed, "space restored");+ }+ _ => {}+ }+ get(State(state), Path(id.as_str().to_string())).await+}++/// Cancels every running turn of the space's bots, channels and teams. Returns how many jobs.+async fn stop_turns(state: &AppState, space: &SpaceId) -> usize {+ let mut keys: Vec<String> = Vec::new();+ keys.extend(state.db.list_kwants(space).await.unwrap_or_default().into_iter().map(|k| k.id));+ keys.extend(state.db.list_channels(space).await.unwrap_or_default().into_iter().map(|c| c.id));+ keys.extend(state.db.list_teams(space).await.unwrap_or_default().into_iter().map(|t| t.id));+ keys.iter().map(|k| state.turns.cancel(Some(k.as_str()))).sum()+}++/// Where a space's own files live, for the overlap check: Default's work folders in the data dir+/// (the data dir itself also holds every other space), another space's whole folder.+fn work_roots(data_dir: &std::path::Path, space: &SpaceId) -> Vec<PathBuf> {+ if space.is_default() {+ vec![data_dir.join("workspace"), data_dir.join("workspaces")]+ } else {+ vec![crate::db::spaces::space_data_dir(data_dir, space)]+ }+}++/// A team's folder as `resolve_or_prepare_workspace` would pick it, made absolute.+fn team_folder(data_dir: &std::path::Path, space: &SpaceId, name: &str, path: Option<&str>, repo: Option<&str>) -> PathBuf {+ let base = crate::db::spaces::space_data_dir(data_dir, space);+ let raw = match path.map(str::trim).filter(|p| !p.is_empty()) {+ Some(p) => match (p.strip_prefix("~/"), std::env::var("HOME")) {+ (Some(rest), Ok(home)) => PathBuf::from(home).join(rest),+ _ => PathBuf::from(p),+ },+ None if repo.is_some_and(|r| !r.trim().is_empty()) => base.join("workspaces").join(name),+ None => base.join("workspace"),+ };+ normalize(&raw)+}++/// Absolute, with `.` and `..` resolved and symlinks followed as far as the path exists.+pub fn normalize(path: &std::path::Path) -> PathBuf {+ use std::path::Component;+ let abs = match path.is_absolute() {+ true => path.to_path_buf(),+ false => std::env::current_dir().unwrap_or_default().join(path),+ };+ let mut clean = PathBuf::new();+ for c in abs.components() {+ match c {+ Component::CurDir => {}+ Component::ParentDir => {+ clean.pop();+ }+ other => clean.push(other),+ }+ }+ // Follow symlinks in the part that exists, then add back the rest+ let mut existing = clean.clone();+ let mut rest = Vec::new();+ while !existing.exists() {+ match (existing.file_name().map(|n| n.to_os_string()), existing.parent()) {+ (Some(name), Some(parent)) => {+ rest.push(name);+ existing = parent.to_path_buf();+ }+ _ => return clean,+ }+ }+ let mut out = std::fs::canonicalize(&existing).unwrap_or(existing);+ out.extend(rest.into_iter().rev());+ out+}++fn overlaps(a: &std::path::Path, b: &std::path::Path) -> bool {+ a.starts_with(b) || b.starts_with(a)+}++/// 400 when a team's own `workspace_path` would share files with another space: the same+/// folder as, or one inside or around, another space's work folder or one of its teams'.+pub async fn check_workspace(+ state: &AppState,+ space: &SpaceId,+ team_id: Option<&str>,+ name: &str,+ workspace_path: Option<&str>,+) -> Result<(), Response> {+ if workspace_path.is_none_or(|p| p.trim().is_empty()) {+ return Ok(());+ }+ let data_dir = normalize(&state.config.data_dir);+ let mine = team_folder(&data_dir, space, name, workspace_path, None);+ let Ok(spaces) = state.db.list_spaces().await else {+ return Err(internal());+ };+ for other in spaces.iter().map(|s| SpaceId::new(&s.id)).filter(|s| s != space) {+ if work_roots(&data_dir, &other).iter().any(|root| overlaps(&mine, &normalize(root))) {+ return Err(collision(&other, &spaces, "its work folder"));+ }+ let Ok(teams) = state.db.list_teams(&other).await else {+ return Err(internal());+ };+ for t in teams.iter().filter(|t| Some(t.id.as_str()) != team_id) {+ let theirs = team_folder(&data_dir, &other, &t.name, t.workspace_path.as_deref(), t.repo_url.as_deref());+ if overlaps(&mine, &theirs) {+ return Err(collision(&other, &spaces, &format!("team {}", t.name)));+ }+ }+ }+ Ok(())+}++fn collision(other: &SpaceId, spaces: &[Space], what: &str) -> Response {+ let name = spaces.iter().find(|s| s.id == other.as_str()).map(|s| s.name.as_str()).unwrap_or("another space");+ error(+ StatusCode::BAD_REQUEST,+ format!("that folder overlaps {what} in the space \"{name}\"; spaces never share a folder"),+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_space_parameter_is_read_from_the_raw_query() {+ assert_eq!(space_param(None), None);+ assert_eq!(space_param(Some("q=x")), None);+ assert_eq!(space_param(Some("q=x&space=spc_1")).as_deref(), Some("spc_1"));+ assert_eq!(space_param(Some("space=a%20b")).as_deref(), Some("a b"));+ assert_eq!(space_param(Some("space=")).as_deref(), Some(""));+ }++ #[test]+ fn folders_overlap_when_one_holds_the_other() {+ let tmp = tempfile::tempdir().unwrap();+ let a = normalize(&tmp.path().join("x/../a"));+ assert_eq!(a, normalize(&tmp.path().join("a")));+ assert!(overlaps(&a, &a.join("b")));+ assert!(overlaps(&a.join("b"), &a));+ assert!(!overlaps(&a, &normalize(&tmp.path().join("ab"))));+ }++ #[test]+ fn a_patch_tells_a_null_colour_from_a_missing_one() {+ let p: PatchBody = serde_json::from_str(r#"{"color":null}"#).unwrap();+ assert_eq!(p.color, Some(None));+ let p: PatchBody = serde_json::from_str(r#"{}"#).unwrap();+ assert_eq!(p.color, None);+ assert!(serde_json::from_str::<PatchBody>(r#"{"archive":true}"#).is_err());+ }+}diff --git a/src/server/sse.rs b/src/server/sse.rsindex c7ef2130..9ba81033 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -1,8 +1,9 @@use axum::{extract::State,+ http::Uri,response::sse::{Event, KeepAlive, Sse},+ response::{IntoResponse, Response},};-use futures::stream::Stream;use futures::StreamExt;use serde_json::Value;use std::collections::HashMap;@@ -51,9 +52,17 @@ pub async fn wire_event(db: &Database, cache: &mut HashMap<String, Option<Stringv}-pub async fn sse_handler(- State(state): State<AppState>,-) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {+/// `GET /api/events`: every event, each tagged with its `space_id`. With `?space=<id>`, only+/// that space's events and the global ones (`space_id` null); an unknown space is a 404 and an+/// archived one a 409, as for the collections.+pub async fn sse_handler(State(state): State<AppState>, uri: Uri) -> Response {+ let only = match super::spaces::space_param(uri.query()) {+ None => None,+ Some(id) => match super::spaces::active_space(&state, &id).await {+ Ok(space) => Some(space.as_str().to_string()),+ Err(r) => return r,+ },+ };let rx = state.event_sender.subscribe();let cache = Arc::new(Mutex::new(HashMap::new()));let stream = BroadcastStream::new(rx)@@ -61,11 +70,20 @@ pub async fn sse_handler(.then(move |event| {let db = state.db.clone();let cache = cache.clone();- async move {- let wire = wire_event(&db, &mut *cache.lock().await, &event).await;- Ok(Event::default().data(wire.to_string()))- }+ async move { wire_event(&db, &mut *cache.lock().await, &event).await }+ })+ .filter_map(move |wire| {+ let keep = in_space(&wire, only.as_deref());+ async move { keep.then(|| Ok::<_, Infallible>(Event::default().data(wire.to_string()))) }});- Sse::new(stream).keep_alive(KeepAlive::default())+ Sse::new(stream).keep_alive(KeepAlive::default()).into_response()+}++/// Whether a wire event goes to a connection scoped to `space` (every event when unscoped).+pub fn in_space(wire: &Value, space: Option<&str>) -> bool {+ match (space, wire.get("space_id").and_then(Value::as_str)) {+ (None, _) | (_, None) => true,+ (Some(want), Some(got)) => want == got,+ }}diff --git a/tests/spaces_api_test.rs b/tests/spaces_api_test.rsnew file mode 100644index 00000000..3f846b60--- /dev/null+++ b/tests/spaces_api_test.rs@@ -0,0 +1,510 @@+//! Spaces S2: spaces through the API. A second space is made with `POST /api/spaces`, filled+//! through `?space=`, and every collection is checked to show only its own space; archive and+//! restore, the Default archive refusal and team folder collisions are covered too. A fake claude+//! CLI on PATH answers turns, so no real engine is ever called. Its own test binary: it changes PATH.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use futures::StreamExt;+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{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 resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))+ .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+}++struct Env {+ app: Router,+ state: AppState,+ data: PathBuf,+ _tmp: tempfile::TempDir,+}++async fn setup() -> Env {+ fake_cli();+ let tmp = tempfile::tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ 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(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());+ Env { app, state, data, _tmp: 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 team(name: &str, lead: &str, members: &[&str], workspace_path: Option<&str>) -> Value {+ json!({"name": name, "lead_kwant_id": lead, "member_kwants": members, "workspace_path": workspace_path})+}++fn routine(kwant_id: &str, name: &str, enabled: bool) -> Value {+ json!({+ "kwant_id": kwant_id,+ "name": name,+ "instructions": "Summarise yesterday.",+ "schedule": {"type": "interval", "every_minutes": 60},+ "enabled": enabled,+ })+}++impl Env {+ async fn new_space(&self, name: &str, this_machine: bool) -> String {+ let (s, v) = call(+ &self.app,+ "POST",+ "/api/spaces",+ Some(json!({"name": name, "icon": "🧪", "this_machine_enabled": this_machine})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ v["id"].as_str().unwrap().to_string()+ }++ async fn space(&self, id: &str) -> Value {+ ok(&self.app, "GET", &format!("/api/spaces/{id}"), None).await+ }+}++async fn next_event<S, E>(stream: &mut S) -> Value+where+ S: futures::Stream<Item = Result<axum::body::Bytes, E>> + Unpin,+ E: std::fmt::Debug,+{+ let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next()).await.expect("an event").unwrap().unwrap();+ let text = String::from_utf8_lossy(&chunk).to_string();+ let data = text.lines().find_map(|l| l.strip_prefix("data:")).expect("a data line").trim().to_string();+ serde_json::from_str(&data).unwrap()+}++#[tokio::test]+async fn two_spaces_end_to_end_through_the_api() {+ let env = setup().await;+ let app = &env.app;++ // Space A (Default), filled without ?space=+ let remy = ok(app, "POST", "/api/kwants", Some(bot("Remy"))).await;+ let remy_id = remy["id"].as_str().unwrap().to_string();+ ok(app, "POST", "/api/teams", Some(team("alpha", &remy_id, &[&remy_id], None))).await;+ ok(app, "POST", "/api/routines", Some(routine(&remy_id, "alpha-digest", true))).await;+ ok(+ app,+ "POST",+ "/api/skills",+ Some(json!({"name": "alpha-notes", "description": "Alpha notes", "body": "Steps.", "kwant_id": remy_id})),+ )+ .await;+ ok(+ app,+ "POST",+ "/api/mcp/servers",+ Some(json!({"name": "alpha_mcp", "transport": "http", "url": "https://a.example.com/mcp"})),+ )+ .await;+ ok(app, "POST", "/api/profiles", Some(json!({"engine": "claude", "name": "Alpha key", "kind": "api_key"}))).await;++ // Space B through the API: seeded, empty, with its own folder+ let b = env.new_space("Side project", false).await;+ let view = env.space(&b).await;+ assert_eq!(view["name"], "Side project");+ assert_eq!(view["is_default"], false);+ assert_eq!(view["archived_at"], Value::Null);+ assert_eq!(view["counts"]["bots"], 0);+ assert_eq!(view["paused_routines"], 0);+ assert_eq!(view["general_channel_id"], Value::Null, "#general comes with the first bot");+ assert!(env.data.join("spaces").join(&b).is_dir(), "B has a work folder");+ let profiles = env.state.db.list_profiles(&SpaceId::new(&b)).await.unwrap();+ let system: Vec<_> = profiles.iter().filter(|p| p.kind == "system").collect();+ assert!(!system.is_empty() && system.iter().all(|p| !p.enabled), "this_machine_enabled: false is kept");++ let q = format!("?space={b}");+ let bea = ok(app, "POST", &format!("/api/kwants{q}"), Some(bot("Bea"))).await;+ let bea_id = bea["id"].as_str().unwrap().to_string();+ assert_eq!(bea["space_id"], b.as_str());+ let cy = ok(app, "POST", &format!("/api/kwants{q}"), Some(bot("Cy"))).await;+ let cy_id = cy["id"].as_str().unwrap().to_string();+ let view = env.space(&b).await;+ assert_eq!(view["counts"]["bots"], 2);+ let general_b = view["general_channel_id"].as_str().expect("#general after the first bot").to_string();++ // B's bots run nowhere yet: This machine is off in B and B has no account+ let kwants_b = ok(app, "GET", &format!("/api/kwants{q}"), None).await;+ let runs_on = &kwants_b.as_array().unwrap()[0]["runs_on"];+ assert_eq!(runs_on["blocked"], true, "{runs_on}");+ // A's bot runs on This machine+ let kwants_a = ok(app, "GET", "/api/kwants", None).await;+ let remy_row = kwants_a.as_array().unwrap().iter().find(|k| k["id"] == remy_id.as_str()).unwrap().clone();+ assert_eq!(remy_row["runs_on"]["account"], "This machine", "{remy_row}");++ ok(app, "POST", &format!("/api/teams{q}"), Some(team("beta", &bea_id, &[&bea_id, &cy_id], None))).await;+ ok(app, "POST", &format!("/api/routines{q}"), Some(routine(&bea_id, "beta-digest", true))).await;+ ok(+ app,+ "POST",+ &format!("/api/skills{q}"),+ Some(json!({"name": "beta-notes", "description": "Beta notes", "body": "Steps."})),+ )+ .await;+ ok(+ app,+ "POST",+ &format!("/api/mcp/servers{q}"),+ Some(json!({"name": "beta_mcp", "transport": "http", "url": "https://b.example.com/mcp"})),+ )+ .await;+ ok(+ app,+ "POST",+ &format!("/api/profiles{q}"),+ Some(json!({"engine": "claude", "name": "Beta key", "kind": "api_key"})),+ )+ .await;+ // A routine for A's bot can't be made in B+ let (s, v) = call(app, "POST", &format!("/api/routines{q}"), Some(routine(&remy_id, "stray", true))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");++ // Every collection under ?space= shows only its own space+ let a_marks = [remy_id.as_str(), "alpha", "alpha_mcp", "Alpha key"];+ let b_marks = [bea_id.as_str(), "beta", "beta_mcp", "Beta key"];+ let collections = [+ ("/api/kwants", Some(0)),+ ("/api/channels", None),+ ("/api/teams", Some(1)),+ ("/api/routines", Some(1)),+ ("/api/skills", Some(1)),+ ("/api/mcp/servers", Some(2)),+ ("/api/profiles", Some(3)),+ ("/api/engines", None),+ ("/api/turns", None),+ ("/api/questions", None),+ ("/api/away", None),+ ];+ for (path, own) in collections {+ let in_b = ok(app, "GET", &format!("{path}{q}"), None).await.to_string();+ let in_a = ok(app, "GET", path, None).await.to_string();+ for m in a_marks {+ assert!(!in_b.contains(m), "{path}?space=B shows A's {m}: {in_b}");+ }+ for m in b_marks {+ assert!(!in_a.contains(m), "{path} in Default shows B's {m}: {in_a}");+ }+ if let Some(i) = own {+ assert!(in_b.contains(b_marks[i]), "{path}?space=B misses {}: {in_b}", b_marks[i]);+ assert!(in_a.contains(a_marks[i]), "{path} misses {}: {in_a}", a_marks[i]);+ }+ }+ let channels_b = ok(app, "GET", &format!("/api/channels{q}"), None).await;+ let names: Vec<&str> = channels_b.as_array().unwrap().iter().filter_map(|c| c["name"].as_str()).collect();+ assert_eq!(names, ["general", "team-beta"], "B has only its own channels");+ assert_eq!(channels_b[0]["id"], general_b.as_str());++ // Search: B's message isn't found from A, and A's isn't found from B+ env.state.db.insert_message(&kwnt::db::models::NewMessage {+ channel_id: Some(general_b.clone()),+ direct_kwant_id: None,+ sender_role: "user".into(),+ sender_id: "user".into(),+ text: "zebracorn launch plan".into(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 1,+ })+ .await+ .unwrap();+ let found_b = ok(app, "GET", &format!("/api/search?q=zebracorn&space={b}"), None).await.to_string();+ let found_a = ok(app, "GET", "/api/search?q=zebracorn", None).await.to_string();+ assert!(found_b.contains("zebracorn"), "{found_b}");+ assert!(!found_a.contains("zebracorn"), "{found_a}");++ // Unknown and empty space ids are refused, never Default+ for bad in ["/api/kwants?space=spc_nope", "/api/kwants?space=", "/api/events?space=spc_nope"] {+ assert_eq!(call(app, "GET", bad, None).await.0, StatusCode::NOT_FOUND, "{bad}");+ }+ assert_eq!(+ call(app, "POST", "/api/kwants?space=spc_nope", Some(bot("Zed"))).await.0,+ StatusCode::NOT_FOUND+ );++ // SSE ?space=B: B's events and global ones only+ let resp = app+ .clone()+ .oneshot(Request::builder().uri(format!("/api/events?space={b}")).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let mut stream = resp.into_body().into_data_stream();+ let send = |e: RuntimeEvent| {+ let _ = env.state.event_sender.send(e);+ };+ send(RuntimeEvent::MemoryChanged { kwant_id: remy_id.clone() });+ send(RuntimeEvent::MemoryChanged { kwant_id: bea_id.clone() });+ let first = next_event(&mut stream).await;+ assert_eq!(first["space_id"], b.as_str(), "A's event was filtered out: {first}");+ send(RuntimeEvent::MemoryChanged { kwant_id: remy_id.clone() });+ send(RuntimeEvent::DiscussionCompleted { total_turns: 1 });+ assert_eq!(next_event(&mut stream).await["space_id"], Value::Null, "global events pass");++ // The spaces list shows both, Default first+ let list = ok(app, "GET", "/api/spaces", None).await;+ let ids: Vec<&str> = list.as_array().unwrap().iter().filter_map(|s| s["id"].as_str()).collect();+ assert_eq!(ids, ["spc_default", b.as_str()]);+ assert_eq!(list[0]["is_default"], true);+}++#[tokio::test]+async fn archive_pauses_routines_and_restore_brings_back_only_the_active_ones() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Archive me", true).await;+ let q = format!("?space={b}");+ let bea = ok(app, "POST", &format!("/api/kwants{q}"), Some(bot("Bea"))).await;+ let bea_id = bea["id"].as_str().unwrap();+ let on = ok(app, "POST", &format!("/api/routines{q}"), Some(routine(bea_id, "on", true))).await;+ let off = ok(app, "POST", &format!("/api/routines{q}"), Some(routine(bea_id, "off", false))).await;+ let enabled = |id: &str| {+ let id = id.to_string();+ let db = env.state.db.clone();+ async move { db.get_routine(&id).await.unwrap().unwrap().enabled }+ };++ let archived = ok(app, "PATCH", &format!("/api/spaces/{b}"), Some(json!({"archived": true}))).await;+ assert!(archived["archived_at"].is_string(), "{archived}");+ assert_eq!(archived["paused_routines"], 1);+ assert!(!enabled(on["id"].as_str().unwrap()).await);+ assert!(!enabled(off["id"].as_str().unwrap()).await);++ // Archived: gone from the list, in ?archived=1, and refused under ?space=+ let active = ok(app, "GET", "/api/spaces", None).await.to_string();+ assert!(!active.contains(&b), "{active}");+ let gone = ok(app, "GET", "/api/spaces?archived=1", None).await;+ assert_eq!(gone.as_array().unwrap().len(), 1);+ assert_eq!(gone[0]["id"], b.as_str());+ for (m, path, body) in [+ ("GET", format!("/api/kwants{q}"), None),+ ("POST", format!("/api/kwants{q}"), Some(bot("Late"))),+ ("GET", format!("/api/events{q}"), None),+ ("POST", format!("/api/routines/{}/run", on["id"].as_str().unwrap()), None),+ ("POST", "/api/chat/send".to_string(), Some(json!({"kwant_id": bea_id, "prompt": "hi", "sender_id": "user"}))),+ ] {+ assert_eq!(call(app, m, &path, body).await.0, StatusCode::CONFLICT, "{m} {path}");+ }+ // An item endpoint still reads it+ ok(app, "GET", &format!("/api/spaces/{b}"), None).await;++ let restored = ok(app, "PATCH", &format!("/api/spaces/{b}"), Some(json!({"archived": false}))).await;+ assert_eq!(restored["archived_at"], Value::Null);+ assert_eq!(restored["paused_routines"], 0);+ assert!(enabled(on["id"].as_str().unwrap()).await, "the active routine came back");+ assert!(!enabled(off["id"].as_str().unwrap()).await, "the paused-before routine stays off");+ ok(app, "GET", &format!("/api/kwants{q}"), None).await;+}++#[tokio::test]+async fn default_can_be_renamed_but_not_archived_and_names_stay_unique() {+ let env = setup().await;+ let app = &env.app;+ let (s, v) = call(app, "PATCH", "/api/spaces/spc_default", Some(json!({"archived": true}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ let renamed = ok(+ app,+ "PATCH",+ "/api/spaces/spc_default",+ Some(json!({"name": "Home", "icon": "🏠", "color": "#ff8800", "sort": 0})),+ )+ .await;+ assert_eq!((renamed["name"].as_str(), renamed["color"].as_str()), (Some("Home"), Some("#ff8800")));+ let cleared = ok(app, "PATCH", "/api/spaces/spc_default", Some(json!({"color": null}))).await;+ assert_eq!(cleared["color"], Value::Null);+ assert_eq!(cleared["name"], "Home", "fields left out stay");++ env.new_space("Work", true).await;+ assert_eq!(+ call(app, "POST", "/api/spaces", Some(json!({"name": "work"}))).await.0,+ StatusCode::CONFLICT+ );+ for bad in [json!({"name": ""}), json!({"name": "x", "bogus": 1}), json!({"name": "a".repeat(61)})] {+ let (s, _) = call(app, "POST", "/api/spaces", Some(bad.clone())).await;+ assert!(s.is_client_error() && s != StatusCode::CONFLICT, "{bad}: {s}");+ }+ assert_eq!(call(app, "PATCH", "/api/spaces/spc_nope", Some(json!({"name": "x"}))).await.0, StatusCode::NOT_FOUND);+ assert_eq!(call(app, "GET", "/api/spaces/spc_nope", None).await.0, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn a_team_folder_can_not_overlap_another_spaces_folders() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side", true).await;+ let q = format!("?space={b}");+ let remy = ok(app, "POST", "/api/kwants", Some(bot("Remy"))).await;+ let remy_id = remy["id"].as_str().unwrap();+ let bea = ok(app, "POST", &format!("/api/kwants{q}"), Some(bot("Bea"))).await;+ let bea_id = bea["id"].as_str().unwrap();+ let b_dir = env.data.join("spaces").join(&b);+ let shared = env._tmp.path().join("shared-repo");++ // A team in A inside B's work folder, and one in B inside A's+ let into_b = b_dir.join("repo").display().to_string();+ let (s, v) = call(app, "POST", "/api/teams", Some(team("a1", remy_id, &[remy_id], Some(&into_b)))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ assert!(v["error"].as_str().unwrap().contains("Side"), "{v}");+ let into_a = env.data.join("workspace").display().to_string();+ let (s, v) = call(app, "POST", &format!("/api/teams{q}"), Some(team("b1", bea_id, &[bea_id], Some(&into_a)))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ // A parent of B's folder overlaps too+ let parent = env.data.join("spaces").display().to_string();+ let (s, _) = call(app, "POST", "/api/teams", Some(team("a2", remy_id, &[remy_id], Some(&parent)))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);++ // Inside its own space's folder is fine+ ok(app, "POST", &format!("/api/teams{q}"), Some(team("b2", bea_id, &[bea_id], Some(&into_b)))).await;++ // An outside folder taken by A's team can't be used by B's, nor by `..` tricks+ let a_team = ok(app, "POST", "/api/teams", Some(team("a3", remy_id, &[remy_id], Some(&shared.display().to_string())))).await;+ let sneaky = shared.join("x").join("..").join("sub").display().to_string();+ let (s, v) = call(app, "POST", &format!("/api/teams{q}"), Some(team("b3", bea_id, &[bea_id], Some(&sneaky)))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ // Same space may share (S1 behaviour unchanged)+ ok(app, "POST", "/api/teams", Some(team("a4", remy_id, &[remy_id], Some(&sneaky)))).await;++ // Moving a team onto another space's folder is refused as well+ let b_team = ok(app, "POST", &format!("/api/teams{q}"), Some(team("b4", bea_id, &[bea_id], None))).await;+ let mut moved = team("b4", bea_id, &[bea_id], Some(&shared.display().to_string()));+ moved["id"] = b_team["id"].clone();+ let (s, v) = call(app, "PUT", &format!("/api/teams/{}", b_team["id"].as_str().unwrap()), Some(moved)).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ let _ = a_team;+}++#[tokio::test]+async fn a_general_reply_carries_routing_and_account_and_notifications_name_the_space() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side", true).await;+ let q = format!("?space={b}");+ let bea = ok(app, "POST", &format!("/api/kwants{q}"), Some(bot("Bea"))).await;+ ok(app, "POST", &format!("/api/kwants{q}"), Some(bot("Cy"))).await;+ let general_b = env.space(&b).await["general_channel_id"].as_str().unwrap().to_string();+ let mut events = env.state.event_sender.subscribe();+ let notifier = kwnt::server::continuity::spawn_notifier(env.state.clone());++ ok(+ app,+ "POST",+ "/api/chat/send",+ Some(json!({"channel_id": general_b, "prompt": "Bea, how is the tester work?", "sender_id": "user"})),+ )+ .await;++ let (decided, notify) = tokio::time::timeout(Duration::from_secs(20), async {+ let (mut decided, mut notify) = (None, None);+ while decided.is_none() || notify.is_none() {+ match events.recv().await.map(|e| e.unscoped().clone()) {+ Ok(e @ RuntimeEvent::RoutingDecided { .. }) => decided = Some(e),+ Ok(e @ RuntimeEvent::Notify { .. }) => notify = Some(e),+ _ => {}+ }+ }+ (decided.unwrap(), notify.unwrap())+ })+ .await+ .expect("a routing decision and a notification");+ let RuntimeEvent::RoutingDecided { kwant_id, candidate_count, fallback, matched_terms, .. } = decided else {+ unreachable!()+ };+ assert_eq!(kwant_id, bea["id"].as_str().unwrap(), "keywords pick Bea by name");+ assert_eq!(candidate_count, Some(2));+ assert!(fallback, "Laya is offline in tests");+ assert!(matched_terms.iter().any(|t| t == "bea"), "{matched_terms:?}");+ let RuntimeEvent::Notify { space_id, space_name, title, .. } = notify else { unreachable!() };+ assert_eq!(space_id.as_deref(), Some(b.as_str()));+ assert_eq!(space_name.as_deref(), Some("Side"));+ assert!(title.starts_with("Side · "), "two spaces, so the title names it: {title}");++ let msgs = env.state.db.list_messages(&general_b, 50).await.unwrap();+ let reply = msgs.iter().find(|m| m.sender_role == "kwant").expect("Bea's reply");+ let meta: Value = serde_json::from_str(reply.meta.as_deref().expect("reply meta")).unwrap();+ assert_eq!(meta["routing"]["kwant_id"], bea["id"]);+ assert_eq!(meta["routing"]["candidate_count"], 2);+ assert_eq!(meta["routing"]["fallback"], true);+ assert_eq!(meta["ran_on"]["account"], "This machine", "{meta}");+ notifier.abort();+}diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rsindex b4b0cd81..71d2dc82 100644--- a/tests/spaces_migration_test.rs+++ b/tests/spaces_migration_test.rs@@ -71,7 +71,7 @@ async fn snapshot(pool: &SqlitePool) -> BTreeMap<String, Vec<String>> {.unwrap();let mut out = BTreeMap::new();for (table,) in tables {- let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info(?) WHERE name != 'space_id' ORDER BY cid")+ let cols: Vec<(String,)> = sqlx::query_as("SELECT name FROM pragma_table_info(?) WHERE name NOT IN ('space_id', 'paused_by_archive') ORDER BY cid").bind(&table).fetch_all(pool).await