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: fix QA failures (SSE leak, team-name escape, ?space= on item routes, archive gaps)
Lin (kwant bot)6a641244d534
diff --git a/Cargo.lock b/Cargo.lockindex 6eef3018..95b5f130 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1157,7 +1157,9 @@ dependencies = ["clap","dirs","futures",+ "libc","mime_guess",+ "percent-encoding","reqwest","rust-embed","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 737311cc..e5bbba7a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -40,6 +40,10 @@ sha2 = "0.10"base64 = "0.22"url = "2"tz-rs = "0.7"+percent-encoding = "2"++[target.'cfg(unix)'.dependencies]+libc = "0.2"[dev-dependencies]tempfile = "3"diff --git a/src/db/continuity.rs b/src/db/continuity.rsindex 336f9564..99997453 100644--- a/src/db/continuity.rs+++ b/src/db/continuity.rs@@ -517,10 +517,12 @@ impl Database {Ok(res.rows_affected())}- /// Enabled routines due at `now`, in every space: each one runs in its own space.+ /// Enabled routines due by `now`, in every space that isn't archived; each runs in its own+ /// space. An archived space's routines never run, even one switched back on by hand.pub async fn due_routines(&self, now: DateTime<Utc>) -> Result<Vec<RoutineRow>, DbError> {Ok(sqlx::query_as::<_, RoutineRow>(&format!(- "{ROUTINE_SELECT} WHERE r.enabled = 1 AND r.next_run_at IS NOT NULL AND r.next_run_at <= ? ORDER BY r.next_run_at"+ "{ROUTINE_SELECT} WHERE r.enabled = 1 AND r.next_run_at IS NOT NULL AND r.next_run_at <= ? \+ AND r.space_id NOT IN (SELECT id FROM spaces WHERE archived_at IS NOT NULL) ORDER BY r.next_run_at")).bind(now).fetch_all(&self.pool)@@ -530,7 +532,8 @@ impl Database {/// Earliest upcoming run of any enabled routine, so the scheduler can sleep until then.pub async fn next_routine_due(&self) -> Result<Option<DateTime<Utc>>, DbError> {let row: Option<(Option<DateTime<Utc>>,)> = sqlx::query_as(- "SELECT MIN(next_run_at) FROM routines WHERE enabled = 1 AND next_run_at IS NOT NULL",+ "SELECT MIN(next_run_at) FROM routines WHERE enabled = 1 AND next_run_at IS NOT NULL \+ AND space_id NOT IN (SELECT id FROM spaces WHERE archived_at IS NOT NULL)",).fetch_optional(&self.pool).await?;diff --git a/src/db/spaces.rs b/src/db/spaces.rsindex 625ee8f1..8b6fd4ba 100644--- a/src/db/spaces.rs+++ b/src/db/spaces.rs@@ -512,6 +512,41 @@ impl Database {self.space_of("SELECT space_id FROM mcp_servers WHERE id = ?", id).await}+ pub async fn space_of_routine(&self, id: &str) -> Result<Option<SpaceId>, DbError> {+ self.space_of("SELECT space_id FROM routines WHERE id = ?", id).await+ }++ pub async fn space_of_skill(&self, id: &str) -> Result<Option<SpaceId>, DbError> {+ self.space_of("SELECT space_id FROM skills WHERE id = ?", id).await+ }++ /// A question lives in the space of the kwant that asked it.+ pub async fn space_of_question(&self, id: &str) -> Result<Option<SpaceId>, DbError> {+ self.space_of("SELECT k.space_id FROM questions q JOIN kwants k ON k.id = q.kwant_id WHERE q.id = ?", id)+ .await+ }++ pub async fn space_of_thread(&self, id: &str) -> Result<Option<SpaceId>, DbError> {+ self.space_of("SELECT k.space_id FROM threads t JOIN kwants k ON k.id = t.kwant_id WHERE t.id = ?", id)+ .await+ }++ /// A delegation lives in its lead's space (its specialist is always in the same one).+ pub async fn space_of_delegation(&self, id: &str) -> Result<Option<SpaceId>, DbError> {+ self.space_of("SELECT k.space_id FROM delegations d JOIN kwants k ON k.id = d.lead_kwant_id WHERE d.id = ?", id)+ .await+ }++ pub async fn space_of_approval(&self, id: &str) -> Result<Option<SpaceId>, DbError> {+ self.space_of("SELECT k.space_id FROM approvals a JOIN kwants k ON k.id = a.kwant_id WHERE a.id = ?", id)+ .await+ }++ /// Whether `space` exists and is archived.+ pub async fn space_archived(&self, space: &SpaceId) -> Result<bool, DbError> {+ Ok(self.get_space(space).await?.is_some_and(|s| s.archived_at.is_some()))+ }+/// The space of whatever an event or chat id names: a channel, a kwant (its direct chat),/// a thread (its kwant's space) or a team.pub async fn space_of_context(&self, id: &str) -> Result<Option<SpaceId>, DbError> {diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 62d6c3b6..765e2432 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -7,6 +7,43 @@ use tokio::io::AsyncReadExt;use tokio::process::Command;use tokio::sync::mpsc;+/// Kills a CLI's whole process group if its turn is dropped (cancelled, or its space archived)+/// before the CLI exits. `kill_on_drop` only reaches the CLI itself; the tools, shells and MCP+/// servers it started would live on. Declare it after the child, so it drops first, while the+/// child is still unreaped and its group id can't be reused. Disarmed once the CLI has exited,+/// so anything a finished turn deliberately left running is kept.+pub(crate) struct ProcessGroup(Option<u32>);++impl ProcessGroup {+ pub(crate) fn of(child: &tokio::process::Child) -> Self {+ Self(child.id())+ }++ pub(crate) fn disarm(&mut self) {+ self.0 = None;+ }+}++impl Drop for ProcessGroup {+ fn drop(&mut self) {+ #[cfg(unix)]+ if let Some(pid) = self.0.and_then(|p| i32::try_from(p).ok()).filter(|p| *p > 0) {+ // SAFETY: kill(2) with a negative pid signals that process group; no memory involved+ unsafe {+ libc::kill(-pid, libc::SIGKILL);+ }+ }+ }+}++/// Starts the CLI as the leader of its own process group, for [`ProcessGroup`].+fn own_process_group(cmd: &mut Command) {+ #[cfg(unix)]+ cmd.process_group(0);+ #[cfg(not(unix))]+ let _ = cmd;+}+static CLI_BINARY_CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, Option<String>>>> =std::sync::OnceLock::new();@@ -355,8 +392,10 @@ impl CliDriver {.stderr(Stdio::piped());// A cancelled turn aborts this task; the CLI must not outlive itcmd.kill_on_drop(true);+ own_process_group(&mut cmd);let mut child = cmd.spawn()?;+ let mut group = ProcessGroup::of(&child);let stdout_pipe = child.stdout.take();let stderr_pipe = child.stderr.take();let read_stdout = async {@@ -405,6 +444,7 @@ impl CliDriver {};let (mut run, stderr) = tokio::join!(read_stdout, read_stderr);run.exit_code = child.wait().await.ok().and_then(|s| s.code());+ group.disarm();drop(home);run.stderr = stderr;Ok(run)@@ -866,9 +906,11 @@ impl Driver for CliDriver {});// A cancelled turn aborts this task; the CLI must not outlive itcmd.kill_on_drop(true);+ own_process_group(&mut cmd);match cmd.spawn() {Ok(mut child) => {+ let mut group = ProcessGroup::of(&child);let stdout_pipe = child.stdout.take();let stderr_pipe = child.stderr.take();let read_stdout = async {@@ -885,6 +927,7 @@ impl Driver for CliDriver {};let (stdout, stderr) = tokio::join!(read_stdout, read_stderr);let exit = child.wait().await.ok();+ group.disarm();let mut tokens = None;let output_str = if let Some(ref out_file) = codex_out_file {diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex c919f7d1..9cd0bde9 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -136,6 +136,9 @@ pub enum RuntimeEvent {#[serde(rename = "discussion_completed", alias = "DiscussionCompleted")]DiscussionCompleted {total_turns: usize,+ /// The channel or team the discussion ran in, so the event reaches only its space.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ context_id: Option<String>,},#[serde(rename = "browser_navigated", alias = "BrowserNavigated")]BrowserNavigated {diff --git a/src/server/mod.rs b/src/server/mod.rsindex b708c2c9..eaa5dc49 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -221,6 +221,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/away/seen", post(away::seen)).route("/api/events", get(sse::sse_handler)).fallback(crate::embedded::static_handler)+ .layer(axum::middleware::from_fn_with_state(state.clone(), spaces::row_guard)).layer(axum::middleware::from_fn_with_state(state.clone(), auth::guard)).with_state(state)}diff --git a/src/server/routes.rs b/src/server/routes.rsindex f773e5fc..45e292d4 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -306,7 +306,7 @@ pub async fn create_team(Scope(space): Scope,Json(payload): Json<NewTeam>,) -> Result<Json<Team>, axum::response::Response> {- check_workspace(&state, &space, None, &payload.name, payload.workspace_path.as_deref()).await?;+ check_workspace(&state, &space, None, &payload).await?;state.db.create_team(&space, &payload)@@ -351,7 +351,7 @@ pub async fn update_team(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?;+ check_workspace(&state, &space, Some(&id), &payload.team).await?;match state.db.update_team(&id, &payload.team).await {Ok(Some(mut team)) => {if let Some(text) = &payload.instructions {@@ -394,6 +394,7 @@ pub struct CancelPayload {/// given), or everything with no body. A direct chat's Stop leaves that agent's threads running.pub async fn cancel_chat(State(state): State<AppState>,+ Scope(space): Scope,body: axum::body::Bytes,) -> Result<Json<serde_json::Value>, StatusCode> {let key = if !body.is_empty() {@@ -403,7 +404,11 @@ pub async fn cancel_chat(} else {None};- let cancelled = state.turns.cancel(key.as_deref());+ // Without an id, "stop all" stops only the request's space (Default when no ?space=)+ let cancelled = match &key {+ Some(k) => state.turns.cancel(Some(k)),+ None => super::spaces::stop_turns(&state, &space).await,+ };if let Some(thread_id) = &key {super::delegation::cancel_thread_delegation(&state, thread_id).await;}@@ -701,7 +706,7 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(let context_id = scope.context_id(&replies[0].0);let total = |queue_len: usize, done: usize| (1 + done + queue_len).min(1 + MAX_HANDOFFS);let _ = events.send(RuntimeEvent::DiscussionStarted {- team_id: context_id,+ team_id: context_id.clone(),team_name: scope.team_keys.as_ref().map(|(_, n)| n.clone()).unwrap_or_default(),total_turns: total(queue.len(), 0),speakers: queue.iter().map(|(k, _, _)| k.id.clone()).collect(),@@ -739,7 +744,7 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(}}- let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: done + 1 });+ let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: done + 1, context_id: Some(context_id.clone()) });}/// Runs a moderated team discussion: the lead opens (or pauses to ask the user), teammates react to@@ -859,7 +864,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, userun_kwant_turn(scope, &lead, prompt, opts).await;}- let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: turn });+ let _ = events.send(RuntimeEvent::DiscussionCompleted { total_turns: turn, context_id: Some(team.id.clone()) });}/// Per-turn tweaks for turns that kwnt drives itself (team discussions).diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex 195f3bb7..ff64c15d 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -400,6 +400,9 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<Stringif kwant.space_id != routine.space_id {return Err("the routine's agent is in another space, so it was not run".into());}+ if state.db.space_archived(&crate::db::spaces::SpaceId::new(&routine.space_id)).await.unwrap_or(true) {+ return Err("the routine's space is archived, so it was not run".into());+ }if let Some(c) = &routine.channel_id {let channel = state.dbdiff --git a/src/server/skills.rs b/src/server/skills.rsindex 6bfef4ed..6826544e 100644--- a/src/server/skills.rs+++ b/src/server/skills.rs@@ -330,10 +330,24 @@ 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>, scope: Scope, Json(p): Json<SkillPayload>) -> Response {+pub async fn create(+ State(state): State<AppState>,+ scope: Scope,+ uri: axum::http::Uri,+ Json(p): Json<SkillPayload>,+) -> Response {if let Err(r) = check_owner(&state, &p.kwant_id).await {return r;}+ // With an explicit ?space=, the owner must be in it (as for routines); without, the skill+ // follows its owner+ if let (true, Some(Some(owner))) = (super::spaces::space_param(uri.query()).is_some(), &p.kwant_id) {+ match state.db.space_of_kwant(owner).await {+ Ok(Some(of)) if of == scope.0 => {}+ Ok(_) => return error(StatusCode::BAD_REQUEST, "that agent is in another space"),+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+ }let text = match clean_skill_text(p.name.as_deref().unwrap_or(""),p.description.as_deref().unwrap_or(""),@@ -344,6 +358,9 @@ pub async fn create(State(state): State<AppState>, scope: Scope, Json(p): Json<S};let kwant_id = p.kwant_id.flatten();let space = skill_space(&state, kwant_id.as_deref(), scope).await;+ if let Err(r) = super::spaces::ensure_active(&state, &space).await {+ return r;+ }match state.db.create_user_skill(&space, kwant_id.as_deref(), text).await {Ok(s) => {changed(&state, &s);@@ -425,7 +442,7 @@ pub async fn remove(State(state): State<AppState>, Path(id): Path<String>) -> Rematch state.db.delete_skill(&id).await {Ok(true) => {let _ = state.event_sender.send(RuntimeEvent::SkillUpdated {- skill: json!({"id": skill.id, "kwant_id": skill.kwant_id, "deleted": true}),+ skill: json!({"id": skill.id, "kwant_id": skill.kwant_id, "space_id": skill.space_id, "deleted": true}),});StatusCode::NO_CONTENT.into_response()}diff --git a/src/server/spaces.rs b/src/server/spaces.rsindex 9b08b398..78363242 100644--- a/src/server/spaces.rs+++ b/src/server/spaces.rs@@ -2,8 +2,9 @@//! [`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.+//! 409: a request never falls back to Default. Item endpoints (`/api/kwants/:id`, …) take+//! their space from the row; [`row_guard`] refuses one whose explicit `?space=` names another+//! space (404) and any change to a row of an archived space (409).#![allow(clippy::result_large_err)]use super::AppState;@@ -82,6 +83,96 @@ pub async fn ensure_active(state: &AppState, space: &SpaceId) -> Result<(), Resp}}+/// The kinds of row an item route names, by the path segments before its id.+const ITEM_ROUTES: &[(&[&str], RowKind)] = &[+ (&["kwants"], RowKind::Kwant),+ (&["channels"], RowKind::Channel),+ (&["teams"], RowKind::Team),+ (&["sandbox"], RowKind::Team),+ (&["routines"], RowKind::Routine),+ (&["skills"], RowKind::Skill),+ (&["mcp", "servers"], RowKind::McpServer),+ (&["profiles"], RowKind::Profile),+ (&["questions"], RowKind::Question),+ (&["threads"], RowKind::Thread),+ (&["delegations"], RowKind::Delegation),+ (&["approvals"], RowKind::Approval),+];++#[derive(Debug, Clone, Copy, PartialEq)]+pub enum RowKind {+ Kwant,+ Channel,+ Team,+ Routine,+ Skill,+ McpServer,+ Profile,+ Question,+ Thread,+ Delegation,+ Approval,+}++/// The kind and id of the row an `/api/...` path names, if it is an item route.+pub fn item_route(path: &str) -> Option<(RowKind, String)> {+ let segs: Vec<&str> = path.strip_prefix("/api/")?.split('/').collect();+ ITEM_ROUTES.iter().find_map(|(prefix, kind)| {+ let id = segs.get(prefix.len()).filter(|id| !id.is_empty())?;+ (segs[..prefix.len()] == **prefix)+ .then(|| (*kind, percent_encoding::percent_decode_str(id).decode_utf8_lossy().into_owned()))+ })+}++async fn space_of_row(state: &AppState, kind: RowKind, id: &str) -> Result<Option<SpaceId>, DbError> {+ let db = &state.db;+ match kind {+ RowKind::Kwant => db.space_of_kwant(id).await,+ RowKind::Channel => db.space_of_channel(id).await,+ RowKind::Team => db.space_of_team(id).await,+ RowKind::Routine => db.space_of_routine(id).await,+ RowKind::Skill => db.space_of_skill(id).await,+ RowKind::McpServer => db.space_of_mcp_server(id).await,+ RowKind::Profile => db.space_of_profile(id).await,+ RowKind::Question => db.space_of_question(id).await,+ RowKind::Thread => db.space_of_thread(id).await,+ RowKind::Delegation => db.space_of_delegation(id).await,+ RowKind::Approval => db.space_of_approval(id).await,+ }+}++/// Middleware for every item route (see [`ITEM_ROUTES`]). A request with an explicit `?space=`+/// whose row lives in another space gets a 404, so a screen still showing the old space after a+/// switch can't read or change the wrong one; without `?space=` the row decides, as before. Any+/// change (not GET/HEAD) to a row of an archived space is a 409. Unknown rows pass through to the+/// handler, which answers as it always did.+pub async fn row_guard(+ State(state): State<AppState>,+ req: axum::extract::Request,+ next: axum::middleware::Next,+) -> Response {+ let Some((kind, id)) = item_route(req.uri().path()) else {+ return next.run(req).await;+ };+ let row_space = match space_of_row(&state, kind, &id).await {+ Ok(Some(space)) => space,+ Ok(None) => return next.run(req).await,+ Err(_) => return internal(),+ };+ if let Some(want) = space_param(req.uri().query()) {+ if want.trim() != row_space.as_str() {+ return error(StatusCode::NOT_FOUND, "that isn't in this space");+ }+ }+ let read = matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD);+ if !read {+ if let Err(r) = ensure_active(&state, &row_space).await {+ return r;+ }+ }+ next.run(req).await+}+fn archived() -> Response {error(StatusCode::CONFLICT, "this space is archived; restore it first")}@@ -306,7 +397,7 @@ pub async fn update(State(state): State<AppState>, Path(id): Path<String>, Json(}/// 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 {+pub 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));@@ -372,24 +463,52 @@ pub fn normalize(path: &std::path::Path) -> PathBuf {out}+/// Whether one folder is, holds or sits in the other. Compared without case, since macOS's+/// default file system ignores it; on Linux that refuses a few folders that only differ in case.fn overlaps(a: &std::path::Path, b: &std::path::Path) -> bool {- a.starts_with(b) || b.starts_with(a)+ let fold = |p: &std::path::Path| PathBuf::from(p.to_string_lossy().to_lowercase());+ let (a, b) = (fold(a), fold(b));+ 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'.+/// Why `name` can't name a team: its folder (when it has no `workspace_path`) is made from the+/// name, so a separator, `..` or a leading dot could put it anywhere.+pub fn bad_team_name(name: &str) -> Option<&'static str> {+ let name = name.trim();+ if name.contains(['/', '\\', '\0']) {+ Some("a team name can't contain / or \\")+ } else if name.contains("..") || name.starts_with('.') {+ Some("a team name can't start with a dot or contain ..")+ } else {+ None+ }+}++/// 400 when a team's folder 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'. The folder is the one the+/// team will really use, from its `workspace_path` or else its name and repo. A new or renamed+/// team also needs a name that is safe as a folder name.pub async fn check_workspace(state: &AppState,space: &SpaceId,team_id: Option<&str>,- name: &str,- workspace_path: Option<&str>,+ team: &crate::db::models::NewTeam,) -> Result<(), Response> {- if workspace_path.is_none_or(|p| p.trim().is_empty()) {- return Ok(());+ let renamed = match team_id {+ None => true,+ Some(id) => match state.db.get_team(id).await {+ Ok(Some(old)) => old.name != team.name,+ Ok(None) => true,+ Err(_) => return Err(internal()),+ },+ };+ if renamed {+ if let Some(why) = bad_team_name(&team.name) {+ return Err(error(StatusCode::BAD_REQUEST, why));+ }}let data_dir = normalize(&state.config.data_dir);- let mine = team_folder(&data_dir, space, name, workspace_path, None);+ let mine = team_folder(&data_dir, space, &team.name, team.workspace_path.as_deref(), team.repo_url.as_deref());let Ok(spaces) = state.db.list_spaces().await else {return Err(internal());};diff --git a/src/server/sse.rs b/src/server/sse.rsindex 9ba81033..60ca6eb3 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -15,35 +15,119 @@ use super::AppState;use crate::db::Database;use crate::drivers::events::RuntimeEvent;-/// Fields that name the chat, agent or team an event belongs to, most specific first.-const SPACE_KEYS: [&str; 5] = ["context_id", "channel_id", "thread_id", "kwant_id", "team_id"];+/// Event types that belong to no space and so reach every scoped stream when their `space_id`+/// is null. Empty today: every event names a kwant, chat, team, routine, skill or approval. An+/// event that can't be placed in a space and isn't listed here never reaches a scoped stream.+pub const GLOBAL_EVENTS: &[&str] = &[];-/// The event's wire JSON with the `space_id` it belongs to, or `null` for global events-/// (accounts, models, …). `cache` maps ids already looked up to their space for one connection.+/// Something an event names that decides its space.+#[derive(Debug, Clone, PartialEq)]+pub enum Owner {+ /// The space itself, carried by the event.+ Space(String),+ /// A channel, kwant (its direct chat), thread or team id.+ Context(String),+ Routine(String),+ Skill(String),+ Approval(String),+}++fn str_field(v: &Value, key: &str) -> Option<String> {+ v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string)+}++fn contexts<'a>(ids: impl IntoIterator<Item = &'a Option<String>>) -> Vec<Owner> {+ ids.into_iter().flatten().filter(|s| !s.is_empty()).cloned().map(Owner::Context).collect()+}++fn fields(v: &Value, keys: &[&str], to: fn(String) -> Owner) -> Vec<Owner> {+ keys.iter().filter_map(|k| str_field(v, k)).map(to).collect()+}++/// What decides `event`'s space, most specific first. Every variant is listed with no catch-all,+/// so a new event has to say here how it is placed. An empty list means the event can't be+/// placed: it reaches scoped streams only if its type is in [`GLOBAL_EVENTS`].+pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {+ use RuntimeEvent as E;+ match event {+ E::Scoped { tag, .. } => contexts([&Some(tag.context_id.clone()), &Some(tag.kwant_id.clone())]),+ // Only ever sent inside a turn (`Scoped`); bare, they belong nowhere+ E::TextDelta(_) | E::ThinkingDelta(_) | E::ToolCallPending { .. } | E::ToolCallCompleted { .. } => Vec::new(),+ E::ApprovalRequired { id, .. } | E::ApprovalWithdrawn { id } => vec![Owner::Approval(id.clone())],+ E::TurnComplete { kwant_id, .. } => contexts([kwant_id]),+ E::TurnStarted { kwant_id, context_id, thread_id, .. }+ | E::TurnEnded { kwant_id, context_id, thread_id, .. }+ | E::TurnQueued { kwant_id, context_id, thread_id, .. } => {+ contexts([context_id, thread_id, &Some(kwant_id.clone())])+ }+ E::ThreadUpdated { thread } => fields(thread, &["kwant_id", "id"], Owner::Context),+ E::DelegationUpdated { delegation } => fields(+ delegation,+ &["lead_kwant_id", "specialist_kwant_id", "thread_id", "origin_channel_id"],+ Owner::Context,+ ),+ E::MessageAdded { message } => {+ fields(message, &["channel_id", "direct_kwant_id", "thread_id"], Owner::Context)+ }+ E::SkillUpdated { skill } => {+ let mut out = fields(skill, &["space_id"], Owner::Space);+ out.extend(fields(skill, &["kwant_id"], Owner::Context));+ out.extend(fields(skill, &["id"], Owner::Skill));+ out+ }+ E::QuestionUpdated { question } => fields(+ question,+ &["kwant_id", "channel_id", "direct_kwant_id", "thread_id"],+ Owner::Context,+ ),+ E::ProfileSwitched { kwant_id, .. } | E::MemoryChanged { kwant_id } => contexts([&Some(kwant_id.clone())]),+ E::DiscussionStarted { team_id, .. }+ | E::BrowserNavigated { team_id, .. }+ | E::BrowserScreenshot { team_id, .. }+ | E::SandboxStatusChanged { team_id, .. } => contexts([&Some(team_id.clone())]),+ E::DiscussionTurnStarted { speaker_id, .. } => contexts([&Some(speaker_id.clone())]),+ E::DiscussionCompleted { context_id, .. } | E::RoutingStarted { context_id, .. } => contexts([context_id]),+ E::RoutingDecided { context_id, kwant_id, .. } => contexts([context_id, &Some(kwant_id.clone())]),+ E::Error { kwant_id, .. } => contexts([kwant_id]),+ E::RoutineRun { routine_id, .. } => vec![Owner::Routine(routine_id.clone())],+ E::Notify { space_id, kwant_id, channel_id, .. } => {+ let mut out: Vec<Owner> = space_id.iter().cloned().map(Owner::Space).collect();+ out.extend(contexts([channel_id, &Some(kwant_id.clone())]));+ out+ }+ }+}++async fn resolve(db: &Database, owner: &Owner) -> Option<String> {+ let found = match owner {+ Owner::Space(s) => return Some(s.clone()),+ Owner::Context(id) => db.space_of_context(id).await,+ Owner::Routine(id) => db.space_of_routine(id).await,+ Owner::Skill(id) => db.space_of_skill(id).await,+ Owner::Approval(id) => db.space_of_approval(id).await,+ };+ found.ok().flatten().map(|s| s.as_str().to_string())+}++/// The event's wire JSON with the `space_id` it belongs to, or `null` when it can't be placed.+/// `cache` maps owners already looked up to their space for one connection.pub async fn wire_event(db: &Database, cache: &mut HashMap<String, Option<String>>, event: &RuntimeEvent) -> Value {let mut v = event.to_wire();let Value::Object(map) = &mut v else {return v;};- // Turn tags sit at the top; an event's own ids are in its `data`- let ids: Vec<String> = SPACE_KEYS- .iter()- .flat_map(|key| [map.get(*key), map.get("data").and_then(|d| d.get(*key))])- .flatten()- .filter_map(|v| v.as_str().filter(|s| !s.is_empty()).map(str::to_string))- .collect();let mut space = None;- for id in &ids {- let id = id.as_str();- if !cache.contains_key(id) {+ for owner in owners(event) {+ let key = format!("{owner:?}");+ if !cache.contains_key(&key) {// A long-lived connection sees ids come and go; start over rather than grow foreverif cache.len() >= 10_000 {cache.clear();}- let found = db.space_of_context(id).await.ok().flatten().map(|s| s.as_str().to_string());- cache.insert(id.to_string(), found);+ let found = resolve(db, &owner).await;+ cache.insert(key.clone(), found);}- if let Some(s) = cache.get(id).cloned().flatten() {+ if let Some(s) = cache.get(&key).cloned().flatten() {space = Some(s);break;}@@ -53,8 +137,8 @@ pub async fn wire_event(db: &Database, cache: &mut HashMap<String, Option<String}/// `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.+/// that space's events and the [`GLOBAL_EVENTS`]; an event that can't be placed is dropped. 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,@@ -81,9 +165,173 @@ pub async fn sse_handler(State(state): State<AppState>, uri: Uri) -> Response {}/// Whether a wire event goes to a connection scoped to `space` (every event when unscoped).+/// Fails closed: on a scoped stream an event with no space passes only if it is global.pub fn in_space(wire: &Value, space: Option<&str>) -> bool {match (space, wire.get("space_id").and_then(Value::as_str)) {- (None, _) | (_, None) => true,+ (None, _) => true,(Some(want), Some(got)) => want == got,+ (Some(_), None) => wire.get("type").and_then(Value::as_str).is_some_and(|t| GLOBAL_EVENTS.contains(&t)),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::drivers::events::{RoutingCandidate, TurnTag};+ use serde_json::json;++ /// One of every event, each naming kwant `k`, chat `c`, team `t`, routine `r`, skill `s` or+ /// approval `a` wherever it can name something. The match has no catch-all, so a new event+ /// fails to compile here until it gets a sample, and then the test below places it.+ fn samples() -> Vec<RuntimeEvent> {+ use RuntimeEvent as E;+ let s = |x: &str| x.to_string();+ let all = vec![+ E::TextDelta(s("x")),+ E::ThinkingDelta(s("x")),+ E::ToolCallPending { id: s("x"), name: s("x"), args: json!({}) },+ E::ToolCallCompleted { id: s("x"), result: json!({}) },+ E::ApprovalRequired { id: s("a"), tool_name: s("x"), details: json!({}) },+ E::ApprovalWithdrawn { id: s("a") },+ E::TurnComplete { tokens: 1, duration_ms: 1, kwant_id: Some(s("k")), profile_id: None },+ E::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: None, thread_id: None },+ E::TurnEnded { kwant_id: s("k"), context_id: None, outcome: s("completed"), turn_id: None, thread_id: None },+ E::TurnQueued { turn_id: s("x"), kwant_id: s("k"), context_id: None, thread_id: None, position: 1, reason: s("x") },+ E::ThreadUpdated { thread: json!({"id": "th", "kwant_id": "k"}) },+ E::DelegationUpdated { delegation: json!({"id": "d", "lead_kwant_id": "k", "thread_id": "th"}) },+ E::MessageAdded { message: json!({"id": "m", "channel_id": "c"}) },+ E::SkillUpdated { skill: json!({"id": "s", "kwant_id": null, "deleted": true}) },+ E::QuestionUpdated { question: json!({"id": "q", "kwant_id": "k"}) },+ E::Scoped {+ tag: TurnTag { turn_id: s("x"), kwant_id: s("k"), context_id: s("c"), thread_id: None },+ event: Box::new(E::TextDelta(s("x"))),+ },+ E::ProfileSwitched {+ kwant_id: s("k"),+ from_profile_id: s("x"),+ from_name: s("x"),+ to_profile_id: s("x"),+ to_name: s("x"),+ class: s("quota"),+ retry_at: None,+ },+ E::DiscussionStarted { team_id: s("t"), team_name: s("x"), total_turns: 1, speakers: vec![], plan: vec![], kind: s("x") },+ E::DiscussionTurnStarted {+ speaker_id: s("k"),+ speaker_name: s("x"),+ turn_index: 0,+ total_turns: 1,+ prompt: s("x"),+ asked_by: None,+ phase: None,+ },+ E::DiscussionCompleted { total_turns: 1, context_id: Some(s("t")) },+ E::BrowserNavigated { team_id: s("t"), url: s("x"), title: s("x"), status_code: 200 },+ E::BrowserScreenshot { team_id: s("t"), url: s("x"), image_base64: s("x"), timestamp: s("x") },+ E::SandboxStatusChanged { team_id: s("t"), container_name: s("x"), is_running: true },+ E::RoutingStarted {+ context_id: Some(s("c")),+ candidates: vec![RoutingCandidate { id: s("k"), name: s("x"), title: s("x") }],+ },+ E::RoutingDecided {+ context_id: Some(s("c")),+ kwant_id: s("k"),+ kwant_name: s("x"),+ kwant_title: s("x"),+ reason: s("x"),+ mode: s("direct"),+ candidate_count: None,+ fallback: false,+ matched_terms: vec![],+ },+ E::Error { code: s("x"), message: s("x"), kwant_id: Some(s("k")) },+ E::MemoryChanged { kwant_id: s("k") },+ E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok") },+ E::Notify {+ kind: s("x"),+ kwant_id: s("k"),+ kwant_name: s("x"),+ channel_id: None,+ title: s("x"),+ body: s("x"),+ space_id: Some(s("spc_x")),+ space_name: None,+ },+ ];+ for e in &all {+ match e {+ E::TextDelta(_)+ | E::ThinkingDelta(_)+ | E::ToolCallPending { .. }+ | E::ToolCallCompleted { .. }+ | E::ApprovalRequired { .. }+ | E::ApprovalWithdrawn { .. }+ | E::TurnComplete { .. }+ | E::TurnStarted { .. }+ | E::TurnEnded { .. }+ | E::TurnQueued { .. }+ | E::ThreadUpdated { .. }+ | E::DelegationUpdated { .. }+ | E::MessageAdded { .. }+ | E::SkillUpdated { .. }+ | E::QuestionUpdated { .. }+ | E::Scoped { .. }+ | E::ProfileSwitched { .. }+ | E::DiscussionStarted { .. }+ | E::DiscussionTurnStarted { .. }+ | E::DiscussionCompleted { .. }+ | E::BrowserNavigated { .. }+ | E::BrowserScreenshot { .. }+ | E::SandboxStatusChanged { .. }+ | E::RoutingStarted { .. }+ | E::RoutingDecided { .. }+ | E::Error { .. }+ | E::MemoryChanged { .. }+ | E::RoutineRun { .. }+ | E::Notify { .. } => {}+ }+ }+ all+ }++ fn wire_type(e: &RuntimeEvent) -> String {+ e.to_wire()["type"].as_str().unwrap_or_default().to_string()+ }++ #[test]+ fn every_event_is_placed_in_a_space_or_is_global() {+ // Only ever sent inside a turn; bare, they are dropped from scoped streams on purpose+ let turn_only = ["TextDelta", "ThinkingDelta", "ToolCallPending", "ToolCallCompleted"];+ for e in samples() {+ let t = wire_type(&e);+ if turn_only.contains(&t.as_str()) && !matches!(e, RuntimeEvent::Scoped { .. }) {+ assert!(owners(&e).is_empty(), "{t}");+ continue;+ }+ assert!(+ !owners(&e).is_empty() || GLOBAL_EVENTS.contains(&t.as_str()),+ "{t} names nothing to find its space by and isn't global, so scoped streams drop it"+ );+ }+ }++ #[test]+ fn nested_ids_place_records() {+ let msg = RuntimeEvent::MessageAdded { message: json!({"channel_id": null, "direct_kwant_id": "k1"}) };+ assert_eq!(owners(&msg), vec![Owner::Context("k1".into())]);+ let del = RuntimeEvent::DelegationUpdated { delegation: json!({"lead_kwant_id": "k2"}) };+ assert_eq!(owners(&del)[0], Owner::Context("k2".into()));+ let skill = RuntimeEvent::SkillUpdated { skill: json!({"id": "s1", "space_id": "spc_b", "kwant_id": null}) };+ assert_eq!(owners(&skill)[0], Owner::Space("spc_b".into()));+ }++ #[test]+ fn a_scoped_stream_drops_events_with_no_space() {+ let placed = json!({"type": "message_added", "space_id": "spc_a"});+ let unplaced = json!({"type": "message_added", "space_id": null});+ assert!(in_space(&placed, Some("spc_a")));+ assert!(!in_space(&placed, Some("spc_b")));+ assert!(!in_space(&unplaced, Some("spc_a")), "fails closed");+ assert!(in_space(&unplaced, None), "the unscoped stream still gets everything");}}diff --git a/tests/spaces_api_test.rs b/tests/spaces_api_test.rsindex 3f846b60..68c01c3d 100644--- a/tests/spaces_api_test.rs+++ b/tests/spaces_api_test.rs@@ -303,7 +303,7 @@ async fn two_spaces_end_to_end_through_the_api() {StatusCode::NOT_FOUND);- // SSE ?space=B: B's events and global ones only+ // SSE ?space=B: only B's eventslet resp = app.clone().oneshot(Request::builder().uri(format!("/api/events?space={b}")).body(Body::empty()).unwrap())@@ -318,9 +318,13 @@ async fn two_spaces_end_to_end_through_the_api() {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}");+ // Fail closed: an event with no space never reaches a scoped streamsend(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");+ send(RuntimeEvent::DiscussionCompleted { total_turns: 1, context_id: None });+ send(RuntimeEvent::MemoryChanged { kwant_id: bea_id.clone() });+ let next = next_event(&mut stream).await;+ assert_eq!(next["space_id"], b.as_str(), "a space-less event leaked: {next}");+ assert_eq!(next["data"]["kwant_id"], bea_id.as_str(), "{next}");// The spaces list shows both, Default firstlet list = ok(app, "GET", "/api/spaces", None).await;diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rsindex f3aa8dcc..82944194 100644--- a/tests/spaces_isolation_test.rs+++ b/tests/spaces_isolation_test.rs@@ -626,7 +626,7 @@ async fn sse_events_carry_the_space_they_belong_to() {assert_eq!(next_event(&mut stream).await["space_id"], env.a.as_str());send(RuntimeEvent::RoutingStarted { context_id: Some(general_b), candidates: Vec::new() });assert_eq!(next_event(&mut stream).await["space_id"], env.b.as_str());- send(RuntimeEvent::DiscussionCompleted { total_turns: 1 });+ send(RuntimeEvent::DiscussionCompleted { total_turns: 1, context_id: None });assert_eq!(next_event(&mut stream).await["space_id"], Value::Null, "an event with no chat is global");}diff --git a/tests/spaces_s2_fixes_test.rs b/tests/spaces_s2_fixes_test.rsnew file mode 100644index 00000000..d4721010--- /dev/null+++ b/tests/spaces_s2_fixes_test.rs@@ -0,0 +1,590 @@+//! Spaces S2 QA fixes: the `?space=` SSE stream with real events from both spaces, team names that+//! try to leave their space's folder, an explicit `?space=` on item routes that must match the row,+//! skill owners and chat cancel scoped to the space, and the archive gaps (question answers, the+//! scheduler, writes on archived rows, and a live CLI child killed with its whole process group).+//! A fake claude CLI on PATH answers turns; `SLEEPY:<tag>` in the prompt makes it start a `sleep`+//! child, write both pids under `KWNT_S2_PIDS`, and wait. 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::{questions::QuestionPlace, Database},+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::collections::BTreeSet;+use std::path::{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+for a; do last="$a"; done+printf '%s' "$last" > "$KWNT_S2_PIDS/inv-$$"+tag=$(printf '%s' "$last" | sed -n 's/.*SLEEPY:\([A-Za-z0-9_]*\).*/\1/p' | tail -n 1)+if [ -n "$tag" ]; then+ echo $$ > "$KWNT_S2_PIDS/$tag.cli"+ sleep 60 &+ echo $! > "$KWNT_S2_PIDS/$tag.child"+ wait+fi+echo '{"type":"result","is_error":false,"num_turns":1,"result":"answer ok"}'+"#;++fn pids_dir() -> &'static PathBuf {+ static DIR: OnceLock<PathBuf> = OnceLock::new();+ DIR.get_or_init(|| {+ let root = tempfile::tempdir().unwrap().keep();+ let bin = root.join("bin");+ let pids = root.join("pids");+ std::fs::create_dir_all(&bin).unwrap();+ std::fs::create_dir_all(&pids).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("KWNT_S2_PIDS", &pids);+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ pids+ })+}++/// How many CLI turns so far had `marker` in their prompt.+fn invocations_with(marker: &str) -> usize {+ std::fs::read_dir(pids_dir())+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| e.file_name().to_string_lossy().starts_with("inv-"))+ .filter_map(|e| std::fs::read_to_string(e.path()).ok())+ .filter(|p| p.contains(marker))+ .count()+}++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 {+ pids_dir();+ 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 }+}++impl Env {+ async fn new_space(&self, name: &str) -> String {+ let (s, v) = call(&self.app, "POST", "/api/spaces", Some(json!({"name": name, "this_machine_enabled": true}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ v["id"].as_str().unwrap().to_string()+ }++ async fn bot(&self, space: &str, name: &str) -> String {+ let v = ok(&self.app, "POST", &format!("/api/kwants?space={space}"), Some(bot(name))).await;+ v["id"].as_str().unwrap().to_string()+ }++ async fn general(&self, space: &str) -> String {+ let v = ok(&self.app, "GET", &format!("/api/spaces/{space}"), None).await;+ v["general_channel_id"].as_str().expect("#general").to_string()+ }++ async fn question(&self, kwant: &str) -> String {+ let place = QuestionPlace {+ kwant_id: kwant.into(),+ channel_id: None,+ direct_kwant_id: Some(kwant.into()),+ thread_id: None,+ turn_id: None,+ };+ let q = self.state.db.create_question(&place, "Which one?", &["left".into(), "right".into()]).await.unwrap();+ q.id+ }++ async fn idle(&self) {+ let mut quiet = 0;+ for _ in 0..300 {+ quiet = if self.state.turns.active_turns().is_empty() { quiet + 1 } else { 0 };+ if quiet >= 10 {+ return;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("turns never finished: {:?}", self.state.turns.active_turns());+ }+}++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, workspace_path: Option<&str>) -> Value {+ json!({"name": name, "lead_kwant_id": lead, "member_kwants": [lead], "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,+ })+}++fn skill(name: &str, kwant_id: Option<&str>) -> Value {+ json!({"name": name, "description": "Notes", "body": "Steps.", "kwant_id": kwant_id})+}++fn mcp(name: &str) -> Value {+ json!({"name": name, "transport": "http", "url": "https://example.com/mcp"})+}++fn profile(name: &str) -> Value {+ json!({"engine": "claude", "name": name, "kind": "api_key"})+}++/// Collects every event of an SSE stream in the background until `stop` is dropped or sent.+async fn record(app: &Router, uri: String) -> (tokio::task::JoinHandle<Vec<Value>>, tokio::sync::oneshot::Sender<()>) {+ let app = app.clone();+ let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();+ let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel::<()>();+ let handle = tokio::spawn(async move {+ let resp = app.oneshot(Request::builder().uri(&uri).body(Body::empty()).unwrap()).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK, "{uri}");+ let _ = ready_tx.send(());+ let mut stream = resp.into_body().into_data_stream();+ let mut events = Vec::new();+ let mut buf = String::new();+ loop {+ let chunk = tokio::select! {+ _ = &mut stop_rx => break,+ c = stream.next() => match c {+ Some(Ok(c)) => c,+ _ => break,+ },+ };+ buf.push_str(&String::from_utf8_lossy(&chunk));+ while let Some(end) = buf.find("\n\n") {+ let frame: String = buf.drain(..end + 2).collect();+ for line in frame.lines() {+ if let Some(data) = line.strip_prefix("data:") {+ if let Ok(v) = serde_json::from_str::<Value>(data.trim()) {+ events.push(v);+ }+ }+ }+ }+ }+ events+ });+ // The subscription is made when the response is built+ let _ = ready_rx.await;+ (handle, stop_tx)+}++/// Is the process gone (or only a zombie waiting for its parent)?+fn gone(pid: &str) -> bool {+ match std::fs::read_to_string(format!("/proc/{}/stat", pid.trim())) {+ Err(_) => true,+ Ok(stat) => stat.rsplit(')').next().map(|r| r.trim_start().starts_with('Z')).unwrap_or(true),+ }+}++async fn wait_file(path: &Path) -> String {+ for _ in 0..200 {+ if let Ok(s) = std::fs::read_to_string(path) {+ if !s.trim().is_empty() {+ return s.trim().to_string();+ }+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("{} never appeared", path.display());+}++async fn wait_gone(pid: &str, what: &str) {+ for _ in 0..100 {+ if gone(pid) {+ return;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("{what} (pid {pid}) is still running");+}++/// Starts a direct turn for `kwant` that sleeps in the fake CLI; returns (cli pid, child pid).+async fn sleepy_turn(env: &Env, kwant: &str, tag: &str) -> (String, String) {+ ok(+ &env.app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kwant, "prompt": format!("Work slowly SLEEPY:{tag}"), "sender_id": "user"})),+ )+ .await;+ let dir = pids_dir();+ (wait_file(&dir.join(format!("{tag}.cli"))).await, wait_file(&dir.join(format!("{tag}.child"))).await)+}++#[tokio::test]+async fn scoped_event_streams_see_only_their_own_space_for_real_activity() {+ let env = setup().await;+ let app = &env.app;+ let a = "spc_default".to_string();+ let b = env.new_space("Side").await;+ let remy = env.bot(&a, "Remy").await;+ let rae = env.bot(&a, "Rae").await;+ let bea = env.bot(&b, "Bea").await;+ let cy = env.bot(&b, "Cy").await;++ let (in_a, stop_a) = record(app, format!("/api/events?space={a}")).await;+ let (in_b, stop_b) = record(app, format!("/api/events?space={b}")).await;+ let (all, stop_all) = record(app, "/api/events".into()).await;++ for (space, lead, specialist, name) in [(&a, &remy, &rae, "Remy"), (&b, &bea, &cy, "Bea")] {+ let general = env.general(space).await;+ // A #general message+ ok(+ app,+ "POST",+ "/api/chat/send",+ Some(json!({"channel_id": general, "prompt": format!("{name}, how is it going?"), "sender_id": "user"})),+ )+ .await;+ // A thread+ ok(app, "POST", &format!("/api/kwants/{lead}/threads"), Some(json!({"title": "A side thread"}))).await;+ // A delegation+ let (s, v) = call(+ app,+ "POST",+ "/api/delegations",+ Some(json!({"lead_kwant_id": lead, "specialist_kwant_id": specialist, "task": "Check it", "kwant_id": lead, "continue_lead": false})),+ )+ .await;+ assert_eq!(s, StatusCode::ACCEPTED, "{v}");+ // A routine run+ let r = ok(app, "POST", &format!("/api/routines?space={space}"), Some(routine(lead, "digest", false))).await;+ ok(app, "POST", &format!("/api/routines/{}/run", r["id"].as_str().unwrap()), None).await;+ // A question answer+ let q = env.question(lead).await;+ ok(app, "POST", &format!("/api/questions/{q}/answer"), Some(json!({"choice": 0}))).await;+ }+ env.idle().await;+ tokio::time::sleep(Duration::from_millis(500)).await;+ for stop in [stop_a, stop_b, stop_all] {+ let _ = stop.send(());+ }++ let (in_a, in_b, all) = (in_a.await.unwrap(), in_b.await.unwrap(), all.await.unwrap());+ let kinds = |events: &[Value]| events.iter().filter_map(|e| e["type"].as_str().map(String::from)).collect::<BTreeSet<_>>();+ for (space, events) in [(&a, &in_a), (&b, &in_b)] {+ for e in events {+ assert_eq!(e["space_id"].as_str(), Some(space.as_str()), "the {space} stream got another space's event: {e}");+ }+ let seen = kinds(events);+ for want in ["message_added", "thread_updated", "delegation_updated", "routine_run", "question_updated"] {+ assert!(seen.contains(want), "the {space} stream never saw its own {want}: {seen:?}");+ }+ }+ // The unscoped stream is unchanged: it sees both spaces+ let spaces: BTreeSet<_> = all.iter().filter_map(|e| e["space_id"].as_str()).collect();+ assert!(spaces.contains(a.as_str()) && spaces.contains(b.as_str()), "{spaces:?}");+}++#[tokio::test]+async fn team_names_can_not_leave_the_space_folder_and_collisions_ignore_case() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let remy = env.bot("spc_default", "Remy").await;+ let bea = env.bot(&b, "Bea").await;++ let escapes = [+ ("spc_default", remy.as_str(), format!("../spaces/{b}/pwnD")),+ (b.as_str(), bea.as_str(), "../../../workspaces/pwnB".to_string()),+ ];+ for (space, lead, name) in &escapes {+ let (s, v) = call(app, "POST", &format!("/api/teams?space={space}"), Some(team(name, lead, None))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{name}: {v}");+ }+ assert!(!env.data.join("spaces").join(&b).join("pwnD").exists());+ assert!(!env.data.join("workspaces").join("pwnB").exists());+ for name in ["a/b", "a\\b", "..", "x..y", ".hidden", "nul\0x"] {+ let (s, v) = call(app, "POST", "/api/teams", Some(team(name, &remy, None))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{name:?}: {v}");+ }++ // Renaming onto an escape is refused too+ let t = ok(app, "POST", &format!("/api/teams?space={b}"), Some(team("beta", &bea, None))).await;+ let tid = t["id"].as_str().unwrap();+ let mut renamed = team("../../../workspaces/pwnB", &bea, None);+ renamed["id"] = t["id"].clone();+ let (s, v) = call(app, "PUT", &format!("/api/teams/{tid}"), Some(renamed)).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");++ // An outside folder taken in one space is taken in any letter case+ let shared = env._tmp.path().join("Shared-Repo");+ ok(app, "POST", "/api/teams", Some(team("alpha", &remy, Some(&shared.display().to_string())))).await;+ let lower = env._tmp.path().join("shared-repo").join("sub").display().to_string();+ let (s, v) = call(app, "POST", &format!("/api/teams?space={b}"), Some(team("beta2", &bea, Some(&lower)))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+}++#[tokio::test]+async fn an_explicit_space_on_an_item_route_must_be_the_rows_space() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ env.bot(&b, "Bea").await;+ let remy = env.bot("spc_default", "Remy").await;+ let general = env.general("spc_default").await;+ let team_id = ok(app, "POST", "/api/teams", Some(team("alpha", &remy, None))).await["id"].as_str().unwrap().to_string();+ let routine_id = ok(app, "POST", "/api/routines", Some(routine(&remy, "digest", false))).await["id"].as_str().unwrap().to_string();+ let skill_id = ok(app, "POST", "/api/skills", Some(skill("alpha-notes", None))).await["id"].as_str().unwrap().to_string();+ let mcp_id = ok(app, "POST", "/api/mcp/servers", Some(mcp("alpha_mcp"))).await["id"].as_str().unwrap().to_string();+ let profile_id = ok(app, "POST", "/api/profiles", Some(profile("Alpha key"))).await["id"].as_str().unwrap().to_string();+ let thread_id = ok(app, "POST", &format!("/api/kwants/{remy}/threads"), Some(json!({"title": "t"}))).await["id"]+ .as_str()+ .unwrap()+ .to_string();+ let question_id = env.question(&remy).await;++ let reads = [+ format!("/api/channels/{general}"),+ format!("/api/channels/{general}/messages"),+ format!("/api/kwants/{remy}/memories"),+ format!("/api/kwants/{remy}/threads"),+ format!("/api/kwants/{remy}/mcp-servers"),+ format!("/api/teams/{team_id}"),+ format!("/api/routines/{routine_id}"),+ format!("/api/routines/{routine_id}/runs"),+ format!("/api/skills/{skill_id}"),+ format!("/api/mcp/servers/{mcp_id}"),+ format!("/api/threads/{thread_id}"),+ format!("/api/questions/{question_id}"),+ ];+ let writes = [+ ("PUT", format!("/api/kwants/{remy}"), bot("Remy")),+ ("PATCH", format!("/api/profiles/{profile_id}"), json!({"name": "Renamed"})),+ ("PATCH", format!("/api/skills/{skill_id}"), json!({"description": "Changed"})),+ ("POST", format!("/api/questions/{question_id}/answer"), json!({"choice": 0})),+ ];+ for path in &reads {+ let (s, v) = call(app, "GET", &format!("{path}?space={b}"), None).await;+ assert_eq!(s, StatusCode::NOT_FOUND, "GET {path}?space={b}: {v}");+ ok(app, "GET", &format!("{path}?space=spc_default"), None).await;+ ok(app, "GET", path, None).await;+ }+ for (method, path, body) in &writes {+ let (s, v) = call(app, method, &format!("{path}?space={b}"), Some(body.clone())).await;+ assert_eq!(s, StatusCode::NOT_FOUND, "{method} {path}?space={b}: {v}");+ }+ // Nothing was changed by the refused writes+ let q = ok(app, "GET", &format!("/api/questions/{question_id}"), None).await;+ assert_eq!(q["status"].as_str().or(q["question"]["status"].as_str()), Some("open"), "{q}");+ let p = env.state.db.list_profiles(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();+ assert!(p.iter().all(|p| p.name != "Renamed"));+ // An unknown id under ?space= is still the handler's own 404+ assert_eq!(call(app, "GET", &format!("/api/teams/nope?space={b}"), None).await.0, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn a_skill_owner_must_be_in_the_requested_space() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let remy = env.bot("spc_default", "Remy").await;+ let bea = env.bot(&b, "Bea").await;+ let (s, v) = call(app, "POST", &format!("/api/skills?space={b}"), Some(skill("stray", Some(&remy)))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ let made = ok(app, "POST", &format!("/api/skills?space={b}"), Some(skill("own", Some(&bea)))).await;+ assert_eq!(made["space_id"], b.as_str(), "{made}");+ // Without ?space= the owner still picks the space+ ok(app, "POST", "/api/skills", Some(skill("by-owner", Some(&bea)))).await;+}++#[tokio::test]+async fn cancel_without_ids_stops_only_the_requests_space() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let remy = env.bot("spc_default", "Remy").await;+ let bea = env.bot(&b, "Bea").await;+ let (a_cli, a_child) = sleepy_turn(&env, &remy, "cancelA").await;+ let (b_cli, b_child) = sleepy_turn(&env, &bea, "cancelB").await;++ ok(app, "POST", &format!("/api/chat/cancel?space={b}"), Some(json!({}))).await;+ wait_gone(&b_cli, "B's CLI").await;+ wait_gone(&b_child, "B's CLI child").await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(!gone(&a_cli), "Default's turn was stopped by B's cancel");+ assert!(env.state.turns.active_turns().iter().any(|t| t.kwant_id == remy));++ // No ?space= means Default+ ok(app, "POST", "/api/chat/cancel", Some(json!({}))).await;+ wait_gone(&a_cli, "Default's CLI").await;+ wait_gone(&a_child, "Default's CLI child").await;+}++#[tokio::test]+async fn answering_a_question_in_an_archived_space_is_refused_and_starts_no_turn() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let bea = env.bot(&b, "Bea").await;+ let q = env.question(&bea).await;+ ok(app, "PATCH", &format!("/api/spaces/{b}"), Some(json!({"archived": true}))).await;+ let (s, v) = call(app, "POST", &format!("/api/questions/{q}/answer"), Some(json!({"text": "ANSWER_IN_ARCHIVE"}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert_eq!(invocations_with("ANSWER_IN_ARCHIVE"), 0, "a turn was started");+ assert!(env.state.turns.active_turns().is_empty());+ let after = env.state.db.get_question(&q).await.unwrap().unwrap();+ assert_eq!(after.status, "open");+}++#[tokio::test]+async fn the_scheduler_skips_enabled_routines_of_an_archived_space() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let bea = env.bot(&b, "Bea").await;+ let r = ok(app, "POST", &format!("/api/routines?space={b}"), Some(routine(&bea, "digest", true))).await;+ let rid = r["id"].as_str().unwrap();+ ok(app, "PATCH", &format!("/api/spaces/{b}"), Some(json!({"archived": true}))).await;+ // Turned back on behind the archive's back, and due+ let now = chrono::Utc::now();+ env.state.db.set_routine_schedule_state(rid, Some(now - chrono::Duration::minutes(5)), true, None).await.unwrap();+ assert_eq!(kwnt::server::scheduler::tick(&env.state, now).await, 0);+ assert!(env.state.db.list_routine_runs(rid, 10).await.unwrap().is_empty());+ // Run now is refused as well+ assert_eq!(call(app, "POST", &format!("/api/routines/{rid}/run"), None).await.0, StatusCode::CONFLICT);+}++#[tokio::test]+async fn writes_on_an_archived_spaces_rows_are_refused() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let q = format!("?space={b}");+ let bea = env.bot(&b, "Bea").await;+ let team_id = ok(app, "POST", &format!("/api/teams{q}"), Some(team("beta", &bea, None))).await["id"].as_str().unwrap().to_string();+ let routine_id = ok(app, "POST", &format!("/api/routines{q}"), Some(routine(&bea, "digest", false))).await["id"].as_str().unwrap().to_string();+ let skill_id = ok(app, "POST", &format!("/api/skills{q}"), Some(skill("beta-notes", None))).await["id"].as_str().unwrap().to_string();+ let mcp_id = ok(app, "POST", &format!("/api/mcp/servers{q}"), Some(mcp("beta_mcp"))).await["id"].as_str().unwrap().to_string();+ let profile_id = ok(app, "POST", &format!("/api/profiles{q}"), Some(profile("Beta key"))).await["id"].as_str().unwrap().to_string();+ ok(app, "PATCH", &format!("/api/spaces/{b}"), Some(json!({"archived": true}))).await;++ let mut renamed_team = team("beta", &bea, None);+ renamed_team["id"] = json!(team_id);+ let writes = [+ ("PUT", format!("/api/kwants/{bea}"), Some(bot("Bea"))),+ ("POST", format!("/api/kwants/{bea}/memories"), Some(json!({"text": "remember"}))),+ ("PUT", format!("/api/teams/{team_id}"), Some(renamed_team)),+ ("DELETE", format!("/api/teams/{team_id}"), None),+ ("PATCH", format!("/api/routines/{routine_id}"), Some(json!({"name": "renamed"}))),+ ("PATCH", format!("/api/skills/{skill_id}"), Some(json!({"description": "Changed"}))),+ ("DELETE", format!("/api/skills/{skill_id}"), None),+ ("PUT", format!("/api/mcp/servers/{mcp_id}"), Some(mcp("beta_mcp"))),+ ("PATCH", format!("/api/profiles/{profile_id}"), Some(json!({"name": "Renamed"}))),+ ("POST", "/api/skills".to_string(), Some(skill("late", Some(&bea)))),+ ];+ for (method, path, body) in writes {+ let (s, v) = call(app, method, &path, body).await;+ assert_eq!(s, StatusCode::CONFLICT, "{method} {path}: {v}");+ }+ // Reads still work, and nothing changed+ ok(app, "GET", &format!("/api/teams/{team_id}"), None).await;+ ok(app, "GET", &format!("/api/skills/{skill_id}"), None).await;+ assert_eq!(env.state.db.get_routine(&routine_id).await.unwrap().unwrap().name, "digest");+}++#[cfg(unix)]+#[tokio::test]+async fn archiving_kills_a_running_cli_and_its_children_and_posts_nothing() {+ let env = setup().await;+ let app = &env.app;+ let b = env.new_space("Side").await;+ let bea = env.bot(&b, "Bea").await;+ let (cli, child) = sleepy_turn(&env, &bea, "archive").await;+ assert!(!gone(&cli) && !gone(&child));++ ok(app, "PATCH", &format!("/api/spaces/{b}"), Some(json!({"archived": true}))).await;+ wait_gone(&cli, "the CLI").await;+ wait_gone(&child, "the CLI's sleeping child").await;+ tokio::time::sleep(Duration::from_millis(500)).await;+ let posted: Vec<_> = env+ .state+ .db+ .list_messages(&bea, 50)+ .await+ .unwrap()+ .into_iter()+ .filter(|m| m.sender_role == "kwant")+ .map(|m| m.text)+ .collect();+ assert!(posted.iter().all(|t| !t.contains("answer ok")), "{posted:?}");+ assert!(env.state.turns.active_turns().is_empty());+}