Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

messages: load history around or before a message (batch2 F)

Lin (kwant bot)79e36dce0be4
diff --git a/src/db/history.rs b/src/db/history.rs
new file mode 100644
index 00000000..99e1c463
--- /dev/null
+++ b/src/db/history.rs
@@ -0,0 +1,127 @@
+//! Chat history beyond the latest page: a window centred on one message (a search hit
+//! older than what's on screen) and the page before a message.
+//!
+//! Order is `(created_at, rowid)`, as in [`Database::list_messages`]; `created_at` has
+//! one-second resolution, so `rowid` breaks ties.
+
+use super::models::Message;
+use super::{Database, DbError};
+
+/// Most messages one history request returns.
+pub const MAX_HISTORY_PAGE: i64 = 200;
+
+/// Messages in a chat (channel, direct chat or thread) with the anchor's position as `a.t, a.r`.
+/// The anchor must be in the same chat, so an id from another chat finds nothing.
+const IN_CHAT_WITH_ANCHOR: &str = r#"
+ WITH a AS (
+ SELECT created_at AS t, rowid AS r FROM messages
+ WHERE id = ?1 AND (channel_id = ?2 OR direct_kwant_id = ?2 OR thread_id = ?2)
+ )
+ SELECT m.*, m.rowid AS _seq FROM messages m, a
+ WHERE (m.channel_id = ?2 OR m.direct_kwant_id = ?2 OR m.thread_id = ?2)
+"#;
+
+impl Database {
+ /// Additive: indexes for loading a channel's or direct chat's messages (threads have
+ /// `messages_by_thread`). An old binary just doesn't use them.
+ pub(super) async fn migrate_history(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE INDEX IF NOT EXISTS messages_by_channel ON messages (channel_id, created_at) WHERE channel_id IS NOT NULL",
+ "CREATE INDEX IF NOT EXISTS messages_by_direct ON messages (direct_kwant_id, created_at) WHERE direct_kwant_id IS NOT NULL",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// Up to `limit` messages around `anchor_id`, oldest first: about half before it, the
+ /// anchor, and the rest after. `None` when the anchor isn't in this chat.
+ pub async fn list_messages_around(
+ &self,
+ chat_id: &str,
+ anchor_id: &str,
+ limit: i64,
+ ) -> Result<Option<Vec<Message>>, DbError> {
+ let limit = limit.clamp(1, MAX_HISTORY_PAGE);
+ let before = limit / 2;
+ // Anchor and newer
+ let mut newer = sqlx::query_as::<_, Message>(&format!(
+ "{IN_CHAT_WITH_ANCHOR} AND (m.created_at, m.rowid) >= (a.t, a.r) ORDER BY m.created_at ASC, m.rowid ASC LIMIT ?3"
+ ))
+ .bind(anchor_id)
+ .bind(chat_id)
+ .bind(limit - before)
+ .fetch_all(&self.pool)
+ .await?;
+ if newer.is_empty() {
+ return Ok(None);
+ }
+ let mut out = self.older_than(chat_id, anchor_id, before).await?;
+ out.append(&mut newer);
+ Ok(Some(out))
+ }
+
+ /// Up to `limit` messages just before `anchor_id`, oldest first. `None` when the anchor
+ /// isn't in this chat.
+ pub async fn list_messages_before(
+ &self,
+ chat_id: &str,
+ anchor_id: &str,
+ limit: i64,
+ ) -> Result<Option<Vec<Message>>, DbError> {
+ let found: Option<(i64,)> = sqlx::query_as(
+ "SELECT 1 FROM messages WHERE id = ?1 AND (channel_id = ?2 OR direct_kwant_id = ?2 OR thread_id = ?2)",
+ )
+ .bind(anchor_id)
+ .bind(chat_id)
+ .fetch_optional(&self.pool)
+ .await?;
+ if found.is_none() {
+ return Ok(None);
+ }
+ Ok(Some(self.older_than(chat_id, anchor_id, limit.clamp(1, MAX_HISTORY_PAGE)).await?))
+ }
+
+ async fn older_than(&self, chat_id: &str, anchor_id: &str, limit: i64) -> Result<Vec<Message>, DbError> {
+ if limit <= 0 {
+ return Ok(Vec::new());
+ }
+ let mut rows = sqlx::query_as::<_, Message>(&format!(
+ "{IN_CHAT_WITH_ANCHOR} AND (m.created_at, m.rowid) < (a.t, a.r) ORDER BY m.created_at DESC, m.rowid DESC LIMIT ?3"
+ ))
+ .bind(anchor_id)
+ .bind(chat_id)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?;
+ rows.reverse();
+ Ok(rows)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Both directions use the per-chat indexes rather than scanning all messages.
+ #[tokio::test]
+ async fn history_queries_use_the_chat_indexes() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ for cmp in [">=", "<"] {
+ let sql = format!(
+ "EXPLAIN QUERY PLAN {IN_CHAT_WITH_ANCHOR} AND (m.created_at, m.rowid) {cmp} (a.t, a.r) ORDER BY m.created_at, m.rowid LIMIT ?3"
+ );
+ let plan: Vec<(i64, i64, i64, String)> =
+ sqlx::query_as(&sql).bind("x").bind("c").bind(10).fetch_all(&db.pool).await.unwrap();
+ let detail: Vec<&str> = plan.iter().map(|p| p.3.as_str()).collect();
+ assert!(
+ !detail.iter().any(|d| d.starts_with("SCAN m") || d.starts_with("SCAN messages")),
+ "full scan in {cmp} plan: {detail:?}"
+ );
+ for idx in ["messages_by_channel", "messages_by_direct", "messages_by_thread"] {
+ assert!(detail.iter().any(|d| d.contains(idx)), "{idx} unused in {cmp} plan: {detail:?}");
+ }
+ }
+ }
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index e3d83a21..8c8c4919 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -2,6 +2,7 @@ pub mod models;
pub mod profiles;
pub mod continuity;
pub mod threads;
+pub mod history;
pub mod attachments;
pub mod questions;
pub mod skills;
@@ -90,6 +91,7 @@ impl Database {
db.migrate_skills().await?;
db.migrate_questions().await?;
db.migrate_attachments().await?;
+ db.migrate_history().await?;
db.seed_defaults().await?;
Ok(db)
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 3c367f4a..7c59e41b 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -194,16 +194,42 @@ pub async fn create_channel(
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
+#[derive(Debug, Deserialize)]
+pub struct MessagesQuery {
+ /// A window centred on this message (e.g. a search hit older than the latest page).
+ pub around: Option<String>,
+ /// The page just before this message.
+ pub before: Option<String>,
+ /// Default 100, at most [`crate::db::history::MAX_HISTORY_PAGE`].
+ pub limit: Option<i64>,
+}
+
+/// The latest 100 messages, or with `around`/`before` an older window. 404 when that
+/// message isn't in this chat.
pub async fn list_messages(
State(state): State<AppState>,
Path(channel_or_kwant_id): Path<String>,
-) -> Result<Json<Vec<Message>>, StatusCode> {
- state
- .db
- .list_messages(&channel_or_kwant_id, 100)
- .await
- .map(Json)
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
+ Query(q): Query<MessagesQuery>,
+) -> Result<Json<Vec<Message>>, (StatusCode, Json<serde_json::Value>)> {
+ let err = |status: StatusCode, m: &str| (status, Json(json!({ "error": m })));
+ let max = crate::db::history::MAX_HISTORY_PAGE;
+ let limit = match q.limit {
+ None => 100,
+ Some(n) if (1..=max).contains(&n) => n,
+ Some(_) => return Err(err(StatusCode::BAD_REQUEST, &format!("limit must be 1–{max}"))),
+ };
+ let db = &state.db;
+ let rows = match (q.around.as_deref(), q.before.as_deref()) {
+ (Some(_), Some(_)) => return Err(err(StatusCode::BAD_REQUEST, "use around or before, not both")),
+ (Some(id), None) => db.list_messages_around(&channel_or_kwant_id, id, limit).await,
+ (None, Some(id)) => db.list_messages_before(&channel_or_kwant_id, id, limit).await,
+ (None, None) => db.list_messages(&channel_or_kwant_id, limit).await.map(Some),
+ };
+ match rows {
+ Ok(Some(rows)) => Ok(Json(rows)),
+ Ok(None) => Err(err(StatusCode::NOT_FOUND, "That message isn't in this chat.")),
+ Err(_) => Err(err(StatusCode::INTERNAL_SERVER_ERROR, "Could not load messages.")),
+ }
}
pub async fn list_teams(State(state): State<AppState>) -> Result<Json<Vec<Team>>, StatusCode> {
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 5de87506..4b1fbbd6 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1107,6 +1107,89 @@ async fn interrupted_runs_are_failed_on_start() {
assert!(runs[0].ended_at.is_some());
}
+// History beyond the latest page (search jumps)
+
+#[tokio::test]
+async fn messages_load_around_and_before_a_message() {
+ let (app, state, _tmp) = setup().await;
+ let kwant = state.db.list_kwants().await.unwrap().remove(0);
+ let channel = |name: &str| NewChannel {
+ name: name.into(),
+ description: None,
+ lead_kwant_id: kwant.id.clone(),
+ member_kwants: vec![kwant.id.clone()],
+ routing_mode: "auto".into(),
+ };
+ let chan = state.db.create_channel(&channel("history")).await.unwrap();
+ let other = state.db.create_channel(&channel("other")).await.unwrap();
+ let mut ids = Vec::new();
+ for i in 0..250 {
+ let m = state.db.insert_message(&msg(Some(&chan.id), None, "user", "me", &format!("m{i}"))).await.unwrap();
+ ids.push(m.id);
+ if i % 50 == 0 {
+ state.db.insert_message(&msg(Some(&other.id), None, "user", "me", "elsewhere")).await.unwrap();
+ }
+ }
+ let foreign = state.db.insert_message(&msg(Some(&other.id), None, "user", "me", "x")).await.unwrap().id;
+ let texts = |v: &Value| v.as_array().unwrap().iter().map(|m| m["text"].as_str().unwrap().to_string()).collect::<Vec<_>>();
+ let range = |a: usize, b: usize| (a..b).map(|i| format!("m{i}")).collect::<Vec<_>>();
+ let base = format!("/api/channels/{}/messages", chan.id);
+
+ // Unchanged without parameters: the latest 100, oldest first
+ let (s, v) = req(&app, "GET", &base, None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(texts(&v), range(150, 250));
+
+ // Centred on m20: 50 before it (only 20 exist), it, and 49 after
+ let (s, v) = req(&app, "GET", &format!("{base}?around={}", ids[20]), None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(texts(&v), range(0, 70));
+ let (_, v) = req(&app, "GET", &format!("{base}?around={}&limit=10", ids[100]), None).await;
+ assert_eq!(texts(&v), range(95, 105));
+ // Near the end, the window just stops at the latest
+ let (_, v) = req(&app, "GET", &format!("{base}?around={}&limit=10", ids[248]), None).await;
+ assert_eq!(texts(&v), range(243, 250));
+
+ // Paging back
+ let (_, v) = req(&app, "GET", &format!("{base}?before={}&limit=30", ids[95]), None).await;
+ assert_eq!(texts(&v), range(65, 95));
+ let (_, v) = req(&app, "GET", &format!("{base}?before={}", ids[0]), None).await;
+ assert_eq!(v, json!([]));
+
+ // Another chat's message, or none, is a 404 that reveals nothing
+ for q in [format!("around={foreign}"), format!("before={foreign}"), "around=nope".into()] {
+ let (s, v) = req(&app, "GET", &format!("{base}?{q}"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{q}");
+ assert!(!v.to_string().contains("elsewhere"));
+ }
+ // Bounded, and one mode at a time
+ for q in ["limit=0", "limit=201", "limit=-1", &format!("around={}&before={}", ids[1], ids[2])] {
+ let (s, _) = req(&app, "GET", &format!("{base}?{q}"), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{q}");
+ }
+ let (_, v) = req(&app, "GET", &format!("{base}?around={}&limit=200", ids[125]), None).await;
+ assert_eq!(texts(&v), range(25, 225));
+
+ // Direct chats work the same way
+ let mut dm = Vec::new();
+ for i in 0..5 {
+ dm.push(state.db.insert_message(&msg(None, Some(&kwant.id), "user", "me", &format!("d{i}"))).await.unwrap().id);
+ }
+ let (_, v) = req(&app, "GET", &format!("/api/channels/{}/messages?around={}&limit=3", kwant.id, dm[2]), None).await;
+ assert_eq!(texts(&v), vec!["d1", "d2", "d3"]);
+
+ // Same auth as the rest of the API
+ let (s, _) = call(
+ &app,
+ "GET",
+ &format!("{base}?around={}", ids[20]),
+ None,
+ &[("host", "kwnt.example.com")],
+ )
+ .await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+}
+
// Notifications
#[tokio::test]