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
Continue in a new chat from here: server (POST /api/messages/:id/continue) (#618)
Oleksandr Ivanchenkodb7b7c8442a2
diff --git a/src/db/threads.rs b/src/db/threads.rsindex 58b2071d..f18573e7 100644--- a/src/db/threads.rs+++ b/src/db/threads.rs@@ -28,6 +28,51 @@ pub struct Thread {pub archived: bool,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,+ /// The chat this one was continued from ("Continue in a new chat from here"): a thread id+ /// or a bot's id (its main chat). `None` for every other thread.+ #[sqlx(default)]+ pub forked_from_context: Option<String>,+ /// The message there it was continued from: the newest one copied.+ #[sqlx(default)]+ pub forked_from_message_id: Option<String>,+ /// How many messages were copied into it (Iris's ask: the "Continued from … · n messages"+ /// line needs n after a reload, not only in the 201). `None` for every other thread.+ #[sqlx(default)]+ pub forked_copied: Option<i64>,+ /// Whether only the newest [`CONTINUE_MAX_MESSAGES`] were copied. `None` for every other thread.+ #[sqlx(default)]+ pub forked_truncated: Option<bool>,+}++/// Most messages "Continue in a new chat from here" copies: the newest ones, up to the pressed one.+pub const CONTINUE_MAX_MESSAGES: usize = 1000;++/// What [`Database::continue_chat`] made.+#[derive(Debug, Clone)]+pub struct Continued {+ pub thread: Thread,+ /// Messages copied into the new thread.+ pub copied: usize,+ /// The chat had more than [`CONTINUE_MAX_MESSAGES`] up to the pressed message, so only the+ /// newest ones were copied.+ pub truncated: bool,+}++/// `<title> (continued)`, at most [`MAX_TITLE_CHARS`]: the source title is cut (not the suffix),+/// and continuing a continued chat doesn't stack a second suffix.+pub fn continued_title(source: &str) -> String {+ const SUFFIX: &str = " (continued)";+ let base = clean_title(source);+ let base = base.strip_suffix(SUFFIX).unwrap_or(&base);+ let room = MAX_TITLE_CHARS - SUFFIX.chars().count();+ let base: String = if base.chars().count() > room {+ let mut b: String = base.chars().take(room - 1).collect();+ b.push('…');+ b+ } else {+ base.to_string()+ };+ format!("{base}{SUFFIX}")}#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]@@ -170,6 +215,19 @@ impl Database {let _ = sqlx::query("ALTER TABLE delegations ADD COLUMN lead_turn_id TEXT;").execute(&self.pool).await;+ // Continue in a new chat from here (0.9.10): where a chat was continued from+ let _ = sqlx::query("ALTER TABLE threads ADD COLUMN forked_from_context TEXT;")+ .execute(&self.pool)+ .await;+ let _ = sqlx::query("ALTER TABLE threads ADD COLUMN forked_from_message_id TEXT;")+ .execute(&self.pool)+ .await;+ let _ = sqlx::query("ALTER TABLE threads ADD COLUMN forked_copied INTEGER;")+ .execute(&self.pool)+ .await;+ let _ = sqlx::query("ALTER TABLE threads ADD COLUMN forked_truncated INTEGER;")+ .execute(&self.pool)+ .await;Ok(())}@@ -194,6 +252,10 @@ impl Database {archived: false,created_at: now,updated_at: now,+ forked_from_context: None,+ forked_from_message_id: None,+ forked_copied: None,+ forked_truncated: None,};sqlx::query("INSERT INTO threads (id, kwant_id, title, kind, team_id, created_by, archived, created_at, updated_at) \@@ -212,6 +274,117 @@ impl Database {Ok(thread)}+ /// "Continue in a new chat from here": a new `chat` thread for `kwant_id`, made by the person,+ /// holding a copy of every message of chat `context_id` up to and including `message_id`, in+ /// one transaction. Copies get new ids and keep their sender, text, reasoning, tool calls,+ /// tokens, meta (file cards by reference) and `created_at`, oldest first, so the order holds;+ /// a reply that quotes a copied message quotes its copy. Stored Smart Results come along.+ /// Reactions, approvals and running turns don't. Past [`CONTINUE_MAX_MESSAGES`] only the+ /// newest are copied (`truncated`). The source chat is only read.+ pub async fn continue_chat(+ &self,+ kwant_id: &str,+ title: &str,+ team_id: Option<&str>,+ context_id: &str,+ message_id: &str,+ ) -> Result<Continued, DbError> {+ let mut tx = self.pool.begin().await?;+ // Newest first, up to and including the pressed message, in the order the chat shows+ // (`list_messages`: created_at, then rowid)+ let mut rows: Vec<(String, Option<String>)> = sqlx::query_as(+ "SELECT m.id, m.reply_to_message_id FROM messages m, \+ (SELECT created_at AS at, rowid AS seq FROM messages WHERE id = ?2) cut \+ WHERE (m.channel_id = ?1 OR m.direct_kwant_id = ?1 OR m.thread_id = ?1) \+ AND (m.created_at < cut.at OR (m.created_at = cut.at AND m.rowid <= cut.seq)) \+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT ?3",+ )+ .bind(context_id)+ .bind(message_id)+ .bind(CONTINUE_MAX_MESSAGES as i64 + 1)+ .fetch_all(&mut *tx)+ .await?;+ let truncated = rows.len() > CONTINUE_MAX_MESSAGES;+ rows.truncate(CONTINUE_MAX_MESSAGES);+ rows.reverse();++ let now = Utc::now();+ let thread = Thread {+ id: Uuid::new_v4().to_string(),+ kwant_id: kwant_id.into(),+ title: clean_title(title),+ kind: "chat".into(),+ team_id: team_id.map(Into::into),+ created_by: "user".into(),+ archived: false,+ created_at: now,+ updated_at: now,+ forked_from_context: Some(context_id.into()),+ forked_from_message_id: Some(message_id.into()),+ forked_copied: Some(rows.len() as i64),+ forked_truncated: Some(truncated),+ };+ sqlx::query(+ "INSERT INTO threads (id, kwant_id, title, kind, team_id, created_by, archived, created_at, updated_at, \+ forked_from_context, forked_from_message_id, forked_copied, forked_truncated) \+ VALUES (?, ?, ?, 'chat', ?, 'user', 0, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&thread.id)+ .bind(&thread.kwant_id)+ .bind(&thread.title)+ .bind(&thread.team_id)+ .bind(now)+ .bind(now)+ .bind(&thread.forked_from_context)+ .bind(&thread.forked_from_message_id)+ .bind(thread.forked_copied)+ .bind(thread.forked_truncated)+ .execute(&mut *tx)+ .await?;++ let new_ids: std::collections::HashMap<&str, String> =+ rows.iter().map(|(id, _)| (id.as_str(), Uuid::new_v4().to_string())).collect();+ for (old, reply_to) in &rows {+ let new = &new_ids[old.as_str()];+ // A quote of a message that wasn't copied keeps pointing at the original+ let reply_to = reply_to.as_deref().map(|r| new_ids.get(r).cloned().unwrap_or_else(|| r.to_string()));+ sqlx::query(+ "INSERT INTO messages (id, channel_id, direct_kwant_id, sender_role, sender_id, text, reasoning_content, \+ tool_calls, tokens_used, created_at, thread_id, meta, reply_to_message_id) \+ SELECT ?, NULL, NULL, sender_role, sender_id, text, reasoning_content, tool_calls, tokens_used, created_at, ?, meta, ? \+ FROM messages WHERE id = ?",+ )+ .bind(new)+ .bind(&thread.id)+ .bind(reply_to)+ .bind(old)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO message_results (message_id, version, payload) SELECT ?, version, payload FROM message_results WHERE message_id = ?",+ )+ .bind(new)+ .bind(old)+ .execute(&mut *tx)+ .await?;+ }+ tx.commit().await?;+ Ok(Continued { thread, copied: rows.len(), truncated })+ }++ /// Whether message `a` comes at or before message `b` in a chat's order (created_at, then+ /// rowid). `false` when either is gone.+ pub async fn message_at_or_before(&self, a: &str, b: &str) -> Result<bool, DbError> {+ Ok(sqlx::query_scalar(+ "SELECT EXISTS (SELECT 1 FROM messages x, messages y WHERE x.id = ? AND y.id = ? \+ AND (x.created_at < y.created_at OR (x.created_at = y.created_at AND x.rowid <= y.rowid)))",+ )+ .bind(a)+ .bind(b)+ .fetch_one(&self.pool)+ .await?)+ }+pub async fn get_thread(&self, id: &str) -> Result<Option<Thread>, DbError> {Ok(sqlx::query_as::<_, Thread>("SELECT * FROM threads WHERE id = ?").bind(id)@@ -271,6 +444,10 @@ impl Database {archived: false,created_at: now,updated_at: now,+ forked_from_context: None,+ forked_from_message_id: None,+ forked_copied: None,+ forked_truncated: None,};sqlx::query("INSERT INTO threads (id, kwant_id, title, kind, team_id, created_by, archived, created_at, updated_at) \@@ -600,4 +777,89 @@ mod tests {assert_eq!(t.chars().count(), MAX_TITLE_CHARS);assert!(t.ends_with('…'));}++ #[test]+ fn continued_titles_keep_the_suffix_and_never_stack_it() {+ assert_eq!(continued_title("Wifi help"), "Wifi help (continued)");+ assert_eq!(continued_title("Wifi help (continued)"), "Wifi help (continued)");+ let t = continued_title(&"x".repeat(300));+ assert_eq!(t.chars().count(), MAX_TITLE_CHARS);+ assert!(t.ends_with("… (continued)"), "{t}");+ }++ async fn say(db: &Database, chat: &str, role: &str, text: &str, reply_to: Option<&str>) -> String {+ let msg = crate::db::models::NewMessage {+ channel_id: None,+ direct_kwant_id: Some(chat.into()),+ sender_role: role.into(),+ sender_id: if role == "user" { "user".into() } else { "Ada".into() },+ text: text.into(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 3,+ };+ let id = db.insert_message(&msg).await.unwrap().id;+ if let Some(r) = reply_to {+ sqlx::query("UPDATE messages SET reply_to_message_id = ? WHERE id = ?").bind(r).bind(&id).execute(&db.pool).await.unwrap();+ }+ id+ }++ #[tokio::test]+ async fn a_continued_chat_copies_up_to_the_cut_with_replies_and_results_but_not_reactions() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let first = say(&db, "k1", "user", "one", None).await;+ let second = say(&db, "k1", "kwant", "two", None).await;+ let cut = say(&db, "k1", "user", "three", Some(&second)).await;+ let quoted_before = say(&db, "k2", "user", "elsewhere", None).await;+ sqlx::query("UPDATE messages SET reply_to_message_id = ? WHERE id = ?").bind("ed_before).bind(&first).execute(&db.pool).await.unwrap();+ say(&db, "k1", "kwant", "four, after the cut", None).await;+ sqlx::query("INSERT INTO message_results (message_id, version, payload) VALUES (?, 1, '{\"blocks\":[]}')")+ .bind(&second)+ .execute(&db.pool)+ .await+ .unwrap();+ db.set_reaction(&second, Some("up")).await.unwrap();++ let c = db.continue_chat("k1", "Ada (continued)", None, "k1", &cut).await.unwrap();+ assert_eq!((c.copied, c.truncated), (3, false));+ assert_eq!(c.thread.kind, "chat");+ assert_eq!(c.thread.created_by, "user");+ assert_eq!(c.thread.forked_from_context.as_deref(), Some("k1"));+ assert_eq!(c.thread.forked_from_message_id.as_deref(), Some(cut.as_str()));+ // Stored, so a reload still shows "· n messages" (Iris)+ let stored = db.get_thread(&c.thread.id).await.unwrap().unwrap();+ assert_eq!((stored.forked_copied, stored.forked_truncated), (Some(c.copied as i64), Some(c.truncated)));+ assert_eq!(db.get_thread(&c.thread.id).await.unwrap().unwrap(), c.thread, "the columns read back");++ let copies = db.list_messages(&c.thread.id, 100).await.unwrap();+ assert_eq!(copies.iter().map(|m| m.text.as_str()).collect::<Vec<_>>(), ["one", "two", "three"]);+ let originals = db.list_messages("k1", 100).await.unwrap();+ for (copy, orig) in copies.iter().zip(&originals) {+ assert_ne!(copy.id, orig.id);+ assert_eq!(copy.thread_id.as_deref(), Some(c.thread.id.as_str()));+ assert!(copy.direct_kwant_id.is_none() && copy.channel_id.is_none());+ assert_eq!((©.sender_role, ©.sender_id, copy.tokens_used, copy.created_at), (&orig.sender_role, &orig.sender_id, orig.tokens_used, orig.created_at));+ }+ // A quote of a copied message quotes its copy; one of a message that wasn't copied stays+ assert_eq!(copies[2].reply_to_message_id.as_deref(), Some(copies[1].id.as_str()));+ assert_eq!(copies[0].reply_to_message_id.as_deref(), Some(quoted_before.as_str()));+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM message_results WHERE message_id = ? AND payload = '{\"blocks\":[]}'")+ .bind(&copies[1].id)+ .fetch_one(&db.pool)+ .await+ .unwrap();+ assert_eq!(n, 1, "stored results come along");+ assert_eq!(db.get_reaction(&copies[1].id).await.unwrap(), None, "reactions don't");+ assert_eq!(db.get_reaction(&second).await.unwrap().as_deref(), Some("up"));+ // The source is untouched+ assert_eq!(originals.len(), 4);+ assert_eq!(originals.iter().filter(|m| m.thread_id.is_some()).count(), 0);++ assert!(db.message_at_or_before(&first, &cut).await.unwrap());+ assert!(db.message_at_or_before(&cut, &cut).await.unwrap());+ assert!(!db.message_at_or_before(&originals[3].id, &cut).await.unwrap());+ assert!(!db.message_at_or_before("gone", &cut).await.unwrap());+ }}diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex f16ddf31..ce191c04 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -802,7 +802,30 @@ pub(crate) async fn visible(state: &AppState, scope: &SelfScope, id: &str) -> Opreturn Some(a);}let origin = task_origin(state, scope).await;- (origin.is_some() && a.context_id == origin).then_some(a)+ if origin.is_some() && a.context_id == origin {+ return Some(a);+ }+ came_along(state, scope, &a).await.then_some(a)+}++/// The chat this turn's thread was continued from ("Continue in a new chat from here") and the+/// message it was continued from.+async fn continued_from(state: &AppState, scope: &SelfScope) -> Option<(String, String)> {+ let thread = scope.origin.as_ref()?.thread_id.as_deref()?;+ let t = state.db.get_thread(thread).await.ok()??;+ Some((t.forked_from_context?, t.forked_from_message_id?))+}++/// A file of the chat this one was continued from, posted with a message that was copied (at or+/// before the one it was continued from): it came along by reference.+async fn came_along(state: &AppState, scope: &SelfScope, a: &Attachment) -> bool {+ let Some((context, cut)) = continued_from(state, scope).await else {+ return false;+ };+ let Some(message) = a.message_id.as_deref().filter(|_| a.context_id.as_deref() == Some(context.as_str())) else {+ return false;+ };+ state.db.message_at_or_before(message, &cut).await.unwrap_or(false)}/// As [`visible`], for a caller that has a chat id and an owning bot but no full turn to check@@ -829,6 +852,18 @@ pub async fn tool_list(state: &AppState, scope: &SelfScope) -> (String, bool) {lines.extend(theirs.iter().map(line));}}+ if let Some((context, _)) = continued_from(state, scope).await {+ let mut theirs = Vec::new();+ for a in state.db.list_attachments_in(&context, 20).await.unwrap_or_default() {+ if came_along(state, scope, &a).await {+ theirs.push(line(&a));+ }+ }+ if !theirs.is_empty() {+ lines.push("Files from the chat this one continues:".into());+ lines.extend(theirs);+ }+ }if lines.is_empty() {return ("No files in this chat.".into(), false);}diff --git a/src/server/continue_chat.rs b/src/server/continue_chat.rsnew file mode 100644index 00000000..c12d6596--- /dev/null+++ b/src/server/continue_chat.rs@@ -0,0 +1,75 @@+//! "Continue in a new chat from here" (0.9.10): `POST /api/messages/:id/continue` starts a new+//! chat with the same bot that already holds every message of the old one up to and including+//! `:id`. The old chat doesn't change. Copied rows are the whole context: no engine resumes a+//! provider session, so the new chat's next turn reads them like any other history.++use super::delegation::{emit_thread, thread_view};+use super::AppState;+use crate::db::threads::continued_title;+use axum::{+ extract::{Path, State},+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde_json::json;++fn error(status: StatusCode, message: &str) -> Response {+ (status, Json(json!({ "error": message }))).into_response()+}++fn internal() -> Response {+ error(StatusCode::INTERNAL_SERVER_ERROR, "couldn't start a new chat")+}++pub const ONLY_ONE_BOT: &str = "Only a chat with one bot can be continued.";++/// `POST /api/messages/:id/continue` (no body), person-only. 201 with the new thread (as+/// `GET /api/threads/:id` shows it) plus `copied` and `truncated`. 404 for an unknown message+/// (or, with `?space=`, one in another space: the row guard), 400 for a team channel, a+/// delegation or anything else that isn't a chat with one bot, 403 for a bot's token.+pub async fn continue_chat(State(state): State<AppState>, Path(id): Path<String>, headers: HeaderMap) -> Response {+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person continues a chat in a new one").await {+ return r;+ }+ let msg = match state.db.get_message(&id).await {+ Ok(Some(m)) => m,+ Ok(None) => return error(StatusCode::NOT_FOUND, "message not found"),+ Err(_) => return internal(),+ };+ let only_one_bot = || error(StatusCode::BAD_REQUEST, ONLY_ONE_BOT);+ let (kwant_id, context_id, title, team_id) = if let Some(thread_id) = &msg.thread_id {+ match state.db.get_thread(thread_id).await {+ Ok(Some(t)) if t.kind == "chat" => (t.kwant_id.clone(), t.id.clone(), continued_title(&t.title), t.team_id.clone()),+ Ok(_) => return only_one_bot(),+ Err(_) => return internal(),+ }+ } else if msg.channel_id.is_some() {+ return only_one_bot();+ } else if let Some(direct) = &msg.direct_kwant_id {+ match state.db.get_kwant(direct).await {+ Ok(Some(k)) => (k.id.clone(), k.id.clone(), continued_title(&k.name), None),+ Ok(None) => return only_one_bot(),+ Err(_) => return internal(),+ }+ } else {+ return only_one_bot();+ };+ match state.db.get_kwant(&kwant_id).await {+ Ok(Some(_)) => {}+ Ok(None) => return error(StatusCode::NOT_FOUND, "bot not found"),+ Err(_) => return internal(),+ }+ let made = match state.db.continue_chat(&kwant_id, &title, team_id.as_deref(), &context_id, &msg.id).await {+ Ok(c) => c,+ Err(e) => {+ tracing::warn!("continue chat: couldn't copy {context_id} up to {}: {e}", msg.id);+ return internal();+ }+ };+ emit_thread(&state, &made.thread);+ let mut view = thread_view(&state, &made.thread).await;+ view["copied"] = made.copied.into();+ view["truncated"] = made.truncated.into();+ (StatusCode::CREATED, Json(view)).into_response()+}diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex da5ad33c..6acb2b1d 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -78,7 +78,7 @@ fn emit_delegation(state: &AppState, d: &Delegation) {});}-fn emit_thread(state: &AppState, t: &Thread) {+pub(super) fn emit_thread(state: &AppState, t: &Thread) {let _ = state.event_sender.send(RuntimeEvent::ThreadUpdated { thread: serde_json::to_value(t).unwrap_or(Value::Null) });}@@ -1605,7 +1605,7 @@ pub struct ThreadsQuery {pub include_archived: Option<String>,}-async fn thread_view(state: &AppState, t: &Thread) -> Value {+pub(super) async fn thread_view(state: &AppState, t: &Thread) -> Value {let mut v = serde_json::to_value(t).unwrap_or(Value::Null);let delegation = state.db.delegation_for_thread(&t.id).await.ok().flatten();let active: Vec<_> = state.turns.active_turns().into_iter().filter(|a| a.thread_id.as_deref() == Some(&t.id)).collect();diff --git a/src/server/dev/fix_it.rs b/src/server/dev/fix_it.rsindex c26a99e3..68f758c6 100644--- a/src/server/dev/fix_it.rs+++ b/src/server/dev/fix_it.rs@@ -656,6 +656,8 @@ fn start_turn(state: &AppState, bot: &Kwant, thread_id: &str, item_id: &str, pro}/// The author bot's Fix-it chat for this PR.+// One short-lived value per press; boxing the thread buys nothing (Thread grew with continue-chat's fork columns)+#[allow(clippy::large_enum_variant)]enum Chat {Open(Thread),/// The person archived it: nothing more goes to this bot for this PR.diff --git a/src/server/mod.rs b/src/server/mod.rsindex eecbfc7e..38d7cc88 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -26,6 +26,7 @@ pub mod bot_budget;pub mod scheduler;pub mod turns;pub mod delegation;+pub mod continue_chat;pub mod keep_going;pub mod parked;pub mod attachments;@@ -518,6 +519,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/questions/:id/answer", post(questions::answer)).route("/api/messages/:message_id/decisions/:index/change", post(decide::change)).route("/api/messages/:id/reaction", put(reactions::put_reaction))+ .route("/api/messages/:id/continue", post(continue_chat::continue_chat)).route("/api/work-ahead/run", post(work_ahead::run_now)).route("/api/ideas", get(idea_jar::list).post(idea_jar::create)).route("/api/ideas/:id", get(idea_jar::get).patch(idea_jar::edit).delete(idea_jar::delete))diff --git a/tests/continue_chat_test.rs b/tests/continue_chat_test.rsnew file mode 100644index 00000000..a611b4d5--- /dev/null+++ b/tests/continue_chat_test.rs@@ -0,0 +1,385 @@+//! "Continue in a new chat from here": `POST /api/messages/:id/continue` (brief:+//! shared/ship-software-safely/autonomy/continue-chat/brief.md). A new chat with the same bot+//! holds a copy of the old one up to and including the pressed message; the old one doesn't+//! change; the new chat's next turn reads the copies; only the person can do it.++#[path = "common/exe.rs"]+mod exe;++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ attachments::NewAttachment,+ models::{MessageExtra, NewChannel, NewMessage},+ spaces::{NewSpace, SpaceId},+ Database,+ },+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime, AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::PathBuf;+use std::sync::OnceLock;+use std::time::Duration;+use tower::ServiceExt;++/// Records each prompt and answers "answer".+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_TEST_PROMPTS/$$-$(date +%s%N)"+echo '{"type":"result","is_error":false,"num_turns":1,"result":"answer"}'+"#;++fn prompts_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 prompts = root.join("prompts");+ std::fs::create_dir_all(&bin).unwrap();+ std::fs::create_dir_all(&prompts).unwrap();+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);+ std::env::set_var("KWNT_TEST_PROMPTS", &prompts);+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ prompts+ })+}++fn prompts_with(marker: &str) -> Vec<String> {+ std::fs::read_dir(prompts_dir())+ .unwrap()+ .filter_map(|e| std::fs::read_to_string(e.unwrap().path()).ok())+ .filter(|p| p.contains(marker))+ .collect()+}++struct Env {+ app: Router,+ state: AppState,+ bot: String,+ other: String,+ /// Bot replies are stored under the bot's name (what the prompt builder matches on)+ bot_name: String,+ _tmp: tempfile::TempDir,+}++async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(t) = bearer {+ req = req.header("authorization", format!("Bearer {t}"));+ }+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn setup() -> Env {+ prompts_dir();+ let tmp = tempfile::tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ db.set_setting("mission_board", "false").await.unwrap();+ db.set_setting("keep_going_turns", "0").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());+ let (_, kwants) = call(&app, "GET", "/api/kwants", None, None).await;+ let mut ids = Vec::new();+ for k in kwants.as_array().unwrap().iter().take(2) {+ let id = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut()+ .unwrap()+ .retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));+ body["preferred_model"] = json!("claude");+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{id}"), None, Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ ids.push(id);+ }+ let bot_name = state.db.get_kwant(&ids[0]).await.unwrap().unwrap().name;+ Env { app, state, bot: ids[0].clone(), other: ids[1].clone(), bot_name, _tmp: tmp }+}++impl Env {+ /// A message in a bot's main chat (`direct`), a thread or a channel.+ async fn say(&self, direct: Option<&str>, thread: Option<&str>, channel: Option<&str>, role: &str, text: &str) -> String {+ let msg = NewMessage {+ channel_id: channel.map(Into::into),+ direct_kwant_id: direct.map(Into::into),+ sender_role: role.into(),+ sender_id: if role == "user" { "user".into() } else { self.bot_name.clone() },+ text: text.into(),+ reasoning_content: Some(format!("why {text}")),+ tool_calls: Some(json!([{"name": "read", "output": text}])),+ tokens_used: 7,+ };+ let extra = MessageExtra { thread_id: thread.map(Into::into), meta: None };+ self.state.db.insert_message_with(&msg, &extra).await.unwrap().id+ }++ async fn texts(&self, context: &str) -> Vec<String> {+ self.state.db.list_messages(context, 2000).await.unwrap().into_iter().map(|m| m.text).collect()+ }++ async fn continue_from(&self, id: &str) -> (StatusCode, Value) {+ call(&self.app, "POST", &format!("/api/messages/{id}/continue"), None, None).await+ }+}++#[tokio::test]+async fn continuing_the_main_chat_copies_up_to_the_pressed_message_and_leaves_it_as_it_was() {+ let e = setup().await;+ let k = e.bot.clone();+ e.say(Some(&k), None, None, "user", "first").await;+ e.say(Some(&k), None, None, "kwant", "second").await;+ let cut = e.say(Some(&k), None, None, "user", "third").await;+ e.say(Some(&k), None, None, "kwant", "fourth, after").await;+ let before = e.state.db.list_messages(&k, 100).await.unwrap();++ let (s, v) = e.continue_from(&cut).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ assert_eq!((v["copied"].as_u64(), v["truncated"].as_bool()), (Some(3), Some(false)));+ assert_eq!(v["kind"], "chat");+ assert_eq!(v["kwant_id"], k.as_str());+ assert_eq!(v["created_by"], "user");+ assert_eq!(v["forked_from_context"], k.as_str());+ assert_eq!(v["forked_from_message_id"], cut.as_str());+ let name = e.state.db.get_kwant(&k).await.unwrap().unwrap().name;+ assert_eq!(v["title"], format!("{name} (continued)"));+ let tid = v["id"].as_str().unwrap().to_string();++ assert_eq!(e.texts(&tid).await, ["first", "second", "third"]);+ let copies = e.state.db.list_messages(&tid, 100).await.unwrap();+ for (c, o) in copies.iter().zip(&before) {+ assert_ne!(c.id, o.id);+ assert_eq!(+ (&c.sender_role, &c.sender_id, &c.reasoning_content, &c.tool_calls, c.tokens_used, c.created_at),+ (&o.sender_role, &o.sender_id, &o.reasoning_content, &o.tool_calls, o.tokens_used, o.created_at)+ );+ }+ // The original chat is unchanged+ let after = e.state.db.list_messages(&k, 100).await.unwrap();+ let ids = |v: &[kwnt::db::models::Message]| v.iter().map(|m| (m.id.clone(), m.text.clone(), m.thread_id.clone())).collect::<Vec<_>>();+ assert_eq!(ids(&after), ids(&before));+ // GET shows the same thread with the two new fields; the bot's thread list has it+ let (s, t) = call(&e.app, "GET", &format!("/api/threads/{tid}"), None, None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(t["forked_from_message_id"], cut.as_str());+ assert_eq!((t["forked_copied"].as_i64(), t["forked_truncated"].as_bool()), (Some(3), Some(false)), "kept for a reload");+ let (_, list) = call(&e.app, "GET", &format!("/api/kwants/{k}/threads"), None, None).await;+ assert!(list.as_array().unwrap().iter().any(|t| t["id"] == tid.as_str()));+ // A plain new thread has neither+ let (_, plain) = call(&e.app, "POST", &format!("/api/kwants/{k}/threads"), None, Some(json!({"title": "x"}))).await;+ for f in ["forked_from_context", "forked_from_message_id", "forked_copied", "forked_truncated"] {+ assert!(plain[f].is_null(), "{f}: {plain}");+ }+}++#[tokio::test]+async fn continuing_a_thread_keeps_its_order_and_the_next_turn_reads_the_copies() {+ let e = setup().await;+ let k = e.bot.clone();+ let t = e.state.db.create_thread(&k, "Wifi help", "chat", None, "user").await.unwrap();+ for i in 0..25 {+ e.say(None, Some(&t.id), None, if i % 2 == 0 { "user" } else { "kwant" }, &format!("OLDMARK{i:02}")).await;+ }+ let cut = e.state.db.list_messages(&t.id, 100).await.unwrap()[22].id.clone();+ let before = e.texts(&t.id).await;++ let (s, v) = e.continue_from(&cut).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ assert_eq!(v["copied"], 23);+ assert_eq!(v["title"], "Wifi help (continued)");+ assert_eq!(v["forked_from_context"], t.id.as_str());+ let tid = v["id"].as_str().unwrap().to_string();+ let want: Vec<String> = (0..23).map(|i| format!("OLDMARK{i:02}")).collect();+ assert_eq!(e.texts(&tid).await, want, "oldest first, up to and including the pressed one");+ assert_eq!(e.texts(&t.id).await, before, "the source thread is unchanged");++ // The new chat's next turn reads the copies as its history (routes.rs loads 20 rows; the CLI+ // prompt shows the newest 10), the bot's copied replies as its own+ let (s, r) = call(&e.app, "POST", "/api/chat/send", None, Some(json!({"thread_id": tid, "prompt": "NEXTTURN go on", "sender_id": "user"}))).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ for _ in 0..300 {+ if e.texts(&tid).await.iter().any(|m| m == "answer") {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ let prompts = prompts_with("NEXTTURN");+ assert_eq!(prompts.len(), 1, "one turn");+ let p = &prompts[0];+ assert!(p.contains("User: OLDMARK22") && p.contains("Assistant: OLDMARK21") && p.contains("OLDMARK13"), "the copies are its history: {p}");+ assert!(!p.contains("another assistant"), "its own copied replies aren't a teammate's: {p}");+ assert!(!p.contains("OLDMARK23") && !p.contains("OLDMARK24"), "nothing after the pressed message");+ assert!(e.texts(&t.id).await.iter().all(|m| m != "answer" && !m.contains("NEXTTURN")), "the old thread got nothing");+}++#[tokio::test]+async fn only_a_chat_with_one_bot_can_be_continued() {+ let e = setup().await;+ let space = SpaceId::default_space();+ let channel = e+ .state+ .db+ .create_channel(+ &space,+ &NewChannel {+ name: "team-room".into(),+ description: None,+ lead_kwant_id: e.bot.clone(),+ member_kwants: vec![e.bot.clone(), e.other.clone()],+ routing_mode: "auto".into(),+ },+ )+ .await+ .unwrap();+ let in_channel = e.say(None, None, Some(&channel.id), "user", "hello team").await;+ let (s, v) = e.continue_from(&in_channel).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ assert_eq!(v["error"], "Only a chat with one bot can be continued.");++ let handoff = e.state.db.create_thread(&e.other, "A task", "delegation", None, &e.bot).await.unwrap();+ let in_handoff = e.say(None, Some(&handoff.id), None, "user", "do it").await;+ let (s, v) = e.continue_from(&in_handoff).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");++ // A context that is no chat at all (a stray direct id)+ let stray = e.say(Some("not-a-bot"), None, None, "user", "?").await;+ assert_eq!(e.continue_from(&stray).await.0, StatusCode::BAD_REQUEST);++ let (s, v) = e.continue_from("no-such-message").await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ assert!(v["error"].is_string(), "{v}");++ for k in [&e.bot, &e.other] {+ let (_, list) = call(&e.app, "GET", &format!("/api/kwants/{k}/threads"), None, None).await;+ assert!(list.as_array().unwrap().iter().all(|t| t["forked_from_context"].is_null()), "nothing was made");+ }+}++#[tokio::test]+async fn bot_tokens_get_403_and_another_space_404() {+ let e = setup().await;+ let msg = e.say(Some(&e.bot), None, None, "user", "hi").await;+ let bot = e.state.db.get_kwant(&e.bot).await.unwrap().unwrap();+ let folder = e._tmp.path().join("ws");+ std::fs::create_dir_all(&folder).unwrap();+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };+ let (_, token) = mcp_runtime::prepare_turn_with_self(&e.state, &bot, None, Some(folder), Some(scope)).await.unwrap();+ let uri = format!("/api/messages/{msg}/continue");+ let (s, v) = call(&e.app, "POST", &uri, Some(&token), None).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");+ let (s, _) = call(&e.app, "POST", &uri, Some("wrong-token"), None).await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ let person = e.state.api_token.reveal().to_string();++ let other = e+ .state+ .db+ .create_space(&NewSpace { name: "Side".into(), icon: "S".into(), color: None, this_machine_enabled: true })+ .await+ .unwrap();+ let (s, _) = call(&e.app, "POST", &format!("{uri}?space={}", other.id), Some(&person), None).await;+ assert_eq!(s, StatusCode::NOT_FOUND, "a message from another space");+ let (_, list) = call(&e.app, "GET", &format!("/api/kwants/{}/threads", e.bot), None, None).await;+ assert!(list.as_array().unwrap().is_empty(), "nothing was made");++ let (s, v) = call(&e.app, "POST", &format!("{uri}?space={}", SpaceId::default_space().as_str()), Some(&person), None).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+}++#[tokio::test]+async fn over_1000_messages_copies_the_newest_1000() {+ let e = setup().await;+ let k = e.bot.clone();+ for i in 0..1003 {+ e.say(Some(&k), None, None, "user", &format!("m{i:04}")).await;+ }+ let cut = e.state.db.list_messages(&k, 2000).await.unwrap()[1001].id.clone();+ let (s, v) = e.continue_from(&cut).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ assert_eq!((v["copied"].as_u64(), v["truncated"].as_bool()), (Some(1000), Some(true)));+ assert_eq!((v["forked_copied"].as_i64(), v["forked_truncated"].as_bool()), (Some(1000), Some(true)));+ let got = e.texts(v["id"].as_str().unwrap()).await;+ assert_eq!(got.len(), 1000);+ assert_eq!((got[0].as_str(), got[999].as_str()), ("m0002", "m1001"));++ // Exactly 1,000 up to the cut is not truncated+ let cut = e.state.db.list_messages(&k, 2000).await.unwrap()[999].id.clone();+ let (_, v) = e.continue_from(&cut).await;+ assert_eq!((v["copied"].as_u64(), v["truncated"].as_bool()), (Some(1000), Some(false)));+}++#[tokio::test]+async fn files_come_along_by_reference_for_the_bot_up_to_the_cut() {+ let e = setup().await;+ let k = e.bot.clone();+ let mut files = Vec::new();+ let mut said = Vec::new();+ for name in ["before.csv", "after.csv"] {+ let a = e+ .state+ .db+ .insert_attachment(&NewAttachment {+ sha256: "0".repeat(64),+ name: name.into(),+ mime: "text/csv".into(),+ size: 4,+ source: "user".into(),+ context_id: Some(k.clone()),+ direct_kwant_id: Some(k.clone()),+ ..Default::default()+ })+ .await+ .unwrap();+ let m = e.say(Some(&k), None, None, "user", &format!("here is {name}")).await;+ e.state.db.link_attachments(std::slice::from_ref(&a.id), &m, &k, None, Some(&k), None).await.unwrap();+ files.push(a);+ said.push(m);+ }+ let (s, v) = e.continue_from(&said[0]).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let tid = v["id"].as_str().unwrap().to_string();+ let bot = e.state.db.get_kwant(&k).await.unwrap().unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(TurnOrigin { thread_id: Some(tid.clone()), ..Default::default() }),+ ..Default::default()+ };+ let (list, err) = kwnt::server::attachments::tool_list(&e.state, &scope).await;+ assert!(!err, "{list}");+ assert!(list.contains("before.csv") && !list.contains("after.csv"), "{list}");+ // A thread that wasn't continued sees neither+ let plain = e.state.db.create_thread(&k, "x", "chat", None, "user").await.unwrap();+ let scope = SelfScope { origin: Some(TurnOrigin { thread_id: Some(plain.id), ..Default::default() }), ..scope };+ let (list, _) = kwnt::server::attachments::tool_list(&e.state, &scope).await;+ assert!(!list.contains("before.csv"), "{list}");+}