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.

Bots work ahead in quiet chats

Lin (kwant bot)b0469345268c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93581ba9..dafa9cc7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
password or sign-in, and when you say you want to pick yourself. App settings has a switch for it.
- **Bots learn how you decide.** Your answers to question cards and your changes to the bots' choices
are kept per space, and bots use them to predict your next pick instead of asking.
+- **Bots work ahead in quiet chats.** When a chat has gone quiet for a couple of hours with open
+ items, its lead bot does the next safe, undoable step on its own (a check, a draft, a summary) and
+ leaves one "While you were away" message with what it did and what it expects you'll want next. It
+ never sends, posts, pays or signs in, stays silent when nothing is worth doing, works each chat at
+ most once until you write again, and is capped per space per day. App settings has a switch for it.
- **Questions say why only you can answer.** A bot's question card now says why it needs you and what
it checked first; a question without a reason goes back to the bot to decide itself.
diff --git a/src/db/mod.rs b/src/db/mod.rs
index bc1bcf0c..3b99f0e0 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -21,6 +21,7 @@ pub mod approval_modes;
pub mod parked;
pub mod waiting;
pub mod decisions;
+pub mod work_ahead;
pub mod api_context;
pub mod usage;
@@ -152,6 +153,7 @@ impl Database {
db.migrate_parked().await?;
db.migrate_waiting().await?;
db.migrate_decisions().await?;
+ db.migrate_work_ahead().await?;
db.migrate_api_context().await?;
db.migrate_usage().await?;
if spaces {
diff --git a/src/db/work_ahead.rs b/src/db/work_ahead.rs
new file mode 100644
index 00000000..cbd1b834
--- /dev/null
+++ b/src/db/work_ahead.rs
@@ -0,0 +1,122 @@
+//! Work-ahead runs: one row per hidden run in a quiet chat (see [`crate::server::work_ahead`]).
+//! The rows give the caps (runs per space per day, one per chat per day) and keep a chat from
+//! being worked on again before the person writes there.
+
+use super::spaces::SpaceId;
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct WorkAheadRun {
+ pub id: String,
+ pub space_id: String,
+ /// The chat: a channel, a thread or a bot's direct chat.
+ pub context_id: String,
+ pub kwant_id: String,
+ /// The day, `YYYY-MM-DD` in UTC.
+ pub day: String,
+ /// "running", "posted", "nothing" or "failed".
+ pub status: String,
+ pub message_id: Option<String>,
+ pub fresh_tokens: i64,
+ pub started_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+}
+
+impl Database {
+ pub(super) async fn migrate_work_ahead(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS work_ahead_runs (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ context_id TEXT NOT NULL,
+ kwant_id TEXT NOT NULL,
+ day TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('running', 'posted', 'nothing', 'failed')),
+ message_id TEXT,
+ fresh_tokens INTEGER NOT NULL DEFAULT 0,
+ started_at TIMESTAMP NOT NULL,
+ finished_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS work_ahead_runs_space_day ON work_ahead_runs (space_id, day)",
+ "CREATE INDEX IF NOT EXISTS work_ahead_runs_context ON work_ahead_runs (context_id, started_at)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ // A restart mid-run leaves nothing running
+ sqlx::query("UPDATE work_ahead_runs SET status = 'failed', finished_at = ? WHERE status = 'running'")
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ pub async fn start_work_ahead_run(&self, space: &SpaceId, context_id: &str, kwant_id: &str, day: &str) -> Result<WorkAheadRun, DbError> {
+ Ok(sqlx::query_as::<_, WorkAheadRun>(
+ "INSERT INTO work_ahead_runs (id, space_id, context_id, kwant_id, day, status, started_at) \
+ VALUES (?, ?, ?, ?, ?, 'running', ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(space.as_str())
+ .bind(context_id)
+ .bind(kwant_id)
+ .bind(day)
+ .bind(Utc::now())
+ .fetch_one(&self.pool)
+ .await?)
+ }
+
+ pub async fn finish_work_ahead_run(&self, id: &str, status: &str, message_id: Option<&str>, fresh_tokens: u64) -> Result<(), DbError> {
+ sqlx::query("UPDATE work_ahead_runs SET status = ?, message_id = ?, fresh_tokens = ?, finished_at = ? WHERE id = ?")
+ .bind(status)
+ .bind(message_id)
+ .bind(fresh_tokens.min(i64::MAX as u64) as i64)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Runs in `space` on `day`, any outcome, and the most fresh tokens one of them used.
+ pub async fn work_ahead_runs_on(&self, space: &SpaceId, day: &str) -> Result<(i64, i64), DbError> {
+ Ok(sqlx::query_as("SELECT COUNT(*), COALESCE(MAX(fresh_tokens), 0) FROM work_ahead_runs WHERE space_id = ? AND day = ?")
+ .bind(space.as_str())
+ .bind(day)
+ .fetch_one(&self.pool)
+ .await?)
+ }
+
+ /// The chat's newest run, if any.
+ pub async fn last_work_ahead_run(&self, context_id: &str) -> Result<Option<WorkAheadRun>, DbError> {
+ Ok(sqlx::query_as::<_, WorkAheadRun>(
+ "SELECT * FROM work_ahead_runs WHERE context_id = ? ORDER BY started_at DESC, rowid DESC LIMIT 1",
+ )
+ .bind(context_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Chats with the newest messages, newest first, at most `limit`: (thread, channel, direct chat).
+ pub async fn recent_chats(&self, limit: i64) -> Result<Vec<(Option<String>, Option<String>, Option<String>)>, DbError> {
+ let rows: Vec<(Option<String>, Option<String>, Option<String>)> = sqlx::query_as(
+ "SELECT thread_id, channel_id, direct_kwant_id FROM messages ORDER BY rowid DESC LIMIT ?",
+ )
+ .bind(limit.saturating_mul(20))
+ .fetch_all(&self.pool)
+ .await?;
+ let mut out: Vec<(Option<String>, Option<String>, Option<String>)> = Vec::new();
+ for r in rows {
+ if !out.contains(&r) {
+ out.push(r);
+ }
+ if out.len() as i64 >= limit {
+ break;
+ }
+ }
+ Ok(out)
+ }
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index ebccd985..dee5e0b8 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -332,6 +332,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "push", ..] => true,
// What the bots wait on the person for: their questions, across every chat
["", "api", "waiting", ..] => true,
+ // Starting work-ahead runs now spends the person's tokens
+ ["", "api", "work-ahead", ..] => true,
// App-wide settings, including where notifications go (`notify_webhook_url`), and the
// sub-routes such as `/computer` (which machine the bots run on) and `/computer/window`:
// bots change the allowed ones through their `settings_update` action, never these routes
@@ -834,6 +836,7 @@ mod tests {
assert!(person_only(&del, "/api/sandbox/t1/passwords/c1"));
assert!(person_only(&get, "/api/passwords/store"));
assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));
+ assert!(person_only(&post, "/api/work-ahead/run"));
assert!(person_only(&post, "/api/passwords/bitwarden/unlock"));
assert!(person_only(&del, "/api/passwords/bitwarden"));
assert!(person_only(&post, "/api/passwords/migrate"));
diff --git a/src/server/mod.rs b/src/server/mod.rs
index be6fe26f..16533b7b 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -42,6 +42,7 @@ pub mod setup_routes;
pub mod push;
pub mod waiting;
pub mod decide;
+pub mod work_ahead;
pub mod app_update_routes;
use crate::broker::PermissionBroker;
@@ -353,6 +354,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/questions/:id", get(questions::get))
.route("/api/questions/:id/answer", post(questions::answer))
.route("/api/messages/:message_id/decisions/:index/change", post(decide::change))
+ .route("/api/work-ahead/run", post(work_ahead::run_now))
.route("/api/questions/:id/cancel", post(questions::cancel))
.route("/api/human-steps", get(human_steps::list))
.route("/api/human-steps/:id", get(human_steps::get))
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 68a2a66b..47af9769 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -650,6 +650,7 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
super::delegation::follow_ups(&state, Utc::now()).await;
super::parked::run_due(&state, Utc::now()).await;
super::waiting::run_due(&state, Utc::now()).await;
+ super::work_ahead::scan(&state, Utc::now(), false).await;
let next = [
state.db.next_routine_due().await.ok().flatten(),
state.db.next_parked_due().await.ok().flatten(),
diff --git a/src/server/work_ahead.rs b/src/server/work_ahead.rs
new file mode 100644
index 00000000..a05b4e06
--- /dev/null
+++ b/src/server/work_ahead.rs
@@ -0,0 +1,310 @@
+//! Work ahead while the person is away: when a chat with recent work has been quiet for
+//! [`QUIET_HOURS`], its lead gets one hidden turn to do the reversible next steps (finish the
+//! checks it left open, write drafts, research, prepare the next deliverable, schedule a
+//! follow-up). It never sends, pays, contacts anyone, deletes or signs in; those are drafted and
+//! offered. A reply of `[NOTHING]` posts nothing. Otherwise one message, "While you were away I …",
+//! lands in the chat with `meta.kind = "work_ahead"` and a `work_ahead` notification.
+//!
+//! Caps: `work_ahead_daily_cap` runs per space per day (default 3), one run per chat per day,
+//! and none again in a chat until the person writes there. A run that uses more than
+//! [`MAX_RUN_TOKENS`] fresh tokens uses up the space's runs for the day. The scheduler looks
+//! every [`SCAN_EVERY`]; `POST /api/work-ahead/run` (person-only) looks now.
+
+use super::continuity::{notify, Notification};
+use super::decide::{work_ahead_cap, work_ahead_enabled};
+use super::routes::{scope_for, turn_once, TurnOpts};
+use super::AppState;
+use crate::db::models::{Kwant, Message};
+use crate::db::spaces::SpaceId;
+use crate::db::work_ahead::WorkAheadRun;
+use crate::drivers::events::RuntimeEvent;
+use axum::{extract::State, response::IntoResponse, response::Response, Json};
+use chrono::{DateTime, Duration, Utc};
+use serde_json::{json, Value};
+use std::sync::atomic::{AtomicI64, Ordering};
+
+/// Hours a chat must be quiet before its lead works ahead.
+pub const QUIET_HOURS: i64 = 2;
+/// A chat whose last message is older than this isn't worked on: the work went cold.
+pub const STALE_HOURS: i64 = 48;
+/// Fresh tokens one run may use; a run over it ends the space's runs for the day.
+pub const MAX_RUN_TOKENS: u64 = 60_000;
+/// The `purpose` of the run's turn in `GET /api/turns` (`turns[]`).
+pub const PURPOSE: &str = "work_ahead";
+/// What a run replies when nothing is worth doing.
+pub const NOTHING: &str = "[NOTHING]";
+/// How often the scheduler looks for quiet chats, in seconds.
+pub const SCAN_EVERY: i64 = 10 * 60;
+/// Chats looked at per scan.
+const CHATS_SCANNED: i64 = 50;
+/// Messages of a chat looked at.
+const RECENT_MESSAGES: i64 = 20;
+/// Longest message a run posts.
+const MAX_MESSAGE_CHARS: usize = 3000;
+
+static LAST_SCAN: AtomicI64 = AtomicI64::new(0);
+static SCANNING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+/// A quiet chat and who works ahead in it.
+#[derive(Debug, Clone)]
+pub struct Candidate {
+ pub context_id: String,
+ pub channel_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub lead: Kwant,
+ pub space: SpaceId,
+ pub quiet_hours: i64,
+}
+
+/// `YYYY-MM-DD` of `now`.
+pub fn day_of(now: DateTime<Utc>) -> String {
+ now.format("%Y-%m-%d").to_string()
+}
+
+/// Whether a chat's recent messages (oldest first) make it worth working ahead in at `now`: the
+/// person wrote there, a bot answered, the last message is between [`QUIET_HOURS`] and
+/// [`STALE_HOURS`] old, and nothing since the person's last message was a work-ahead message.
+pub fn quiet_enough(messages: &[Message], now: DateTime<Utc>) -> Option<i64> {
+ let last = messages.last()?;
+ let at = last.created_at?;
+ let quiet = now - at;
+ if quiet < Duration::hours(QUIET_HOURS) || quiet > Duration::hours(STALE_HOURS) {
+ return None;
+ }
+ let person = messages.iter().rposition(|m| m.sender_role == "user")?;
+ let after = &messages[person + 1..];
+ if !after.iter().any(|m| m.sender_role == "kwant") || after.iter().any(is_work_ahead) {
+ return None;
+ }
+ Some(quiet.num_hours())
+}
+
+fn is_work_ahead(m: &Message) -> bool {
+ m.meta.as_deref().and_then(|s| serde_json::from_str::<Value>(s).ok()).is_some_and(|v| v["kind"] == "work_ahead")
+}
+
+/// The chat's lead: a channel's lead, a thread's or direct chat's bot.
+async fn lead_of(state: &AppState, thread: Option<&str>, channel: Option<&str>, direct: Option<&str>) -> Option<(Kwant, Option<String>, Option<String>)> {
+ if let Some(t) = thread {
+ let thread = state.db.get_thread(t).await.ok().flatten()?;
+ // Delegation threads are bots' work for each other, not the person's chats
+ if thread.kind != "chat" || thread.archived {
+ return None;
+ }
+ let k = state.db.get_kwant(&thread.kwant_id).await.ok().flatten()?;
+ return Some((k, None, Some(t.to_string())));
+ }
+ if let Some(c) = channel {
+ let channel = state.db.get_channel(c).await.ok().flatten()?;
+ let k = state.db.get_kwant(&channel.lead_kwant_id).await.ok().flatten()?;
+ return Some((k, Some(c.to_string()), None));
+ }
+ let k = state.db.get_kwant(direct?).await.ok().flatten()?;
+ Some((k, None, None))
+}
+
+/// Quiet chats at `now` that may get a run, newest first, within each space's daily cap.
+pub async fn candidates(state: &AppState, now: DateTime<Utc>) -> Vec<Candidate> {
+ let day = day_of(now);
+ let cap = work_ahead_cap(state).await as i64;
+ let mut used: std::collections::HashMap<String, i64> = Default::default();
+ let mut out = Vec::new();
+ for (thread, channel, direct) in state.db.recent_chats(CHATS_SCANNED).await.unwrap_or_default() {
+ let Some(context_id) = thread.clone().or_else(|| channel.clone()).or_else(|| direct.clone()) else { continue };
+ if state.turns.has_job(&context_id) {
+ continue;
+ }
+ let messages = state.db.list_messages(&context_id, RECENT_MESSAGES).await.unwrap_or_default();
+ let Some(quiet_hours) = quiet_enough(&messages, now) else { continue };
+ if state.db.last_work_ahead_run(&context_id).await.ok().flatten().is_some_and(|r| r.day == day) {
+ continue;
+ }
+ let Some((lead, channel_id, thread_id)) = lead_of(state, thread.as_deref(), channel.as_deref(), direct.as_deref()).await else {
+ continue;
+ };
+ let space = SpaceId::new(&lead.space_id);
+ if state.db.space_archived(&space).await.unwrap_or(true) {
+ continue;
+ }
+ let n = match used.get(space.as_str()) {
+ Some(n) => *n,
+ None => match state.db.work_ahead_runs_on(&space, &day).await {
+ // A run over the token cap uses up the day
+ Ok((_, most)) if most > MAX_RUN_TOKENS as i64 => i64::MAX,
+ Ok((n, _)) => n,
+ Err(_) => i64::MAX,
+ },
+ };
+ if n >= cap {
+ continue;
+ }
+ used.insert(space.as_str().to_string(), n.saturating_add(1));
+ out.push(Candidate { context_id, channel_id, thread_id, lead, space, quiet_hours });
+ }
+ out
+}
+
+/// The run's prompt.
+pub fn prompt(quiet_hours: i64) -> String {
+ format!(
+ "[Work ahead] The person hasn't been in this chat for about {quiet_hours} h. Nobody asked for this turn; the person \
+ sees only your final reply, and only when you did something useful.\n\
+ Look at the open items in this chat: checks you said weren't done, drafts not written, next steps you promised, \
+ what you wait on. Do the ones that can be undone, now: run the checks, write the drafts, research, prepare the \
+ next deliverable, schedule a follow-up with `follow_up_create`. Decide reversible choices yourself, using \
+ [How the person usually decides] if you have it.\n\
+ Never send, publish, post, pay, buy, delete, sign in or contact anyone for this: draft it and offer it. Don't \
+ @mention teammates and don't ask the person anything.\n\
+ If nothing is worth doing, reply exactly {NOTHING} and nothing else. Otherwise reply in at most 8 short lines: \
+ start with \"While you were away I\", say what you did and where it is, and end with one line \"Next I expect \
+ you'll want …\" that predicts the person's next ask from this chat."
+ )
+}
+
+/// The message a run posts, or `None` for [`NOTHING`] or an empty reply.
+pub fn message_text(reply: &str) -> Option<String> {
+ let t = reply.trim();
+ if t.is_empty() || (t.contains(NOTHING) && t.len() <= NOTHING.len() + 40) {
+ return None;
+ }
+ let t = t.replace(NOTHING, "");
+ let t = t.trim();
+ (!t.is_empty()).then(|| t.chars().take(MAX_MESSAGE_CHARS).collect())
+}
+
+/// Runs one work-ahead turn for `c` under its started `row` and returns the posted message, if any.
+pub async fn run(state: &AppState, c: Candidate, row: WorkAheadRun) -> Option<Message> {
+ let day = row.day.clone();
+ let job = state.turns.start_job([c.context_id.clone()]);
+ let scope = match scope_for(state, &c.lead, c.channel_id.clone(), c.thread_id.clone(), &job, 0).await {
+ Ok(s) => s,
+ Err(_) => {
+ let _ = state.db.finish_work_ahead_run(&row.id, "failed", None, 0).await;
+ return None;
+ }
+ };
+ let mut opts = TurnOpts::default();
+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));
+ let reply = turn_once(&scope, &c.lead, prompt(c.quiet_hours), opts).await;
+ let tokens = state.turns.job_tokens(&job.id);
+ if tokens > MAX_RUN_TOKENS {
+ tracing::warn!(space = %c.space.as_str(), tokens, "a work-ahead run went over its token cap; no more runs in this space today");
+ }
+ let Ok(reply) = reply else {
+ let _ = state.db.finish_work_ahead_run(&row.id, "failed", None, tokens).await;
+ return None;
+ };
+ let Some(text) = message_text(&reply) else {
+ let _ = state.db.finish_work_ahead_run(&row.id, "nothing", None, tokens).await;
+ return None;
+ };
+ let meta = json!({"kind": "work_ahead", "date": day, "run_id": row.id});
+ let saved = scope.save(&scope.message("kwant", &c.lead.name, text), Some(meta)).await;
+ let _ = state.db.finish_work_ahead_run(&row.id, if saved.is_some() { "posted" } else { "failed" }, saved.as_ref().map(|m| m.id.as_str()), tokens).await;
+ let saved = saved?;
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
+ notify(
+ state,
+ Notification {
+ kind: "work_ahead",
+ kwant_id: c.lead.id.clone(),
+ kwant_name: c.lead.name.clone(),
+ channel_id: c.channel_id.clone(),
+ title: format!("{} worked ahead while you were away", c.lead.name),
+ body: "Open the chat to see what's ready.".into(),
+ },
+ )
+ .await;
+ tracing::info!(run_id = %row.id, kwant_id = %c.lead.id, "posted a work-ahead message");
+ Some(saved)
+}
+
+/// Starts a run in every candidate chat at `now` (in the background) and returns them. With
+/// `force` the scan doesn't wait for [`SCAN_EVERY`] since the last one.
+pub async fn scan(state: &AppState, now: DateTime<Utc>, force: bool) -> Vec<Candidate> {
+ if !work_ahead_enabled(state).await {
+ return Vec::new();
+ }
+ let _guard = SCANNING.lock().await;
+ let last = LAST_SCAN.load(Ordering::Relaxed);
+ if !force && now.timestamp() - last < SCAN_EVERY {
+ return Vec::new();
+ }
+ LAST_SCAN.store(now.timestamp(), Ordering::Relaxed);
+ let found = candidates(state, now).await;
+ let mut started = Vec::new();
+ for c in found {
+ // The row is there before the run starts, so the next scan doesn't pick the chat again
+ let Ok(row) = state.db.start_work_ahead_run(&c.space, &c.context_id, &c.lead.id, &day_of(now)).await else { continue };
+ started.push(c.clone());
+ let state = state.clone();
+ tokio::spawn(async move {
+ run(&state, c, row).await;
+ });
+ }
+ started
+}
+
+/// `POST /api/work-ahead/run` (person-only): looks for quiet chats now instead of at the next
+/// scan, still within every cap. Returns the chats where a run started.
+pub async fn run_now(State(state): State<AppState>) -> Response {
+ let started = scan(&state, Utc::now(), true).await;
+ let rows: Vec<Value> = started
+ .iter()
+ .map(|c| json!({"context_id": c.context_id, "kwant_id": c.lead.id, "quiet_hours": c.quiet_hours}))
+ .collect();
+ Json(json!({"enabled": work_ahead_enabled(&state).await, "started": rows})).into_response()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn msg(role: &str, hours_ago: i64, meta: Option<&str>) -> Message {
+ Message {
+ id: uuid::Uuid::new_v4().to_string(),
+ channel_id: Some("c".into()),
+ direct_kwant_id: None,
+ sender_role: role.into(),
+ sender_id: "x".into(),
+ text: "t".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ created_at: Some(Utc::now() - Duration::hours(hours_ago)),
+ thread_id: None,
+ meta: meta.map(str::to_string),
+ }
+ }
+
+ #[test]
+ fn only_a_quiet_chat_with_a_bot_reply_after_the_person_qualifies() {
+ // A minute ahead, so "6 h ago" counts as 6 whole hours
+ let now = Utc::now() + Duration::minutes(1);
+ assert_eq!(quiet_enough(&[msg("user", 7, None), msg("kwant", 6, None)], now), Some(6));
+ assert_eq!(quiet_enough(&[msg("user", 2, None), msg("kwant", 1, None)], now), None, "not quiet yet");
+ assert_eq!(quiet_enough(&[msg("user", 80, None), msg("kwant", 72, None)], now), None, "gone cold");
+ assert_eq!(quiet_enough(&[msg("user", 7, None)], now), None, "no bot answered");
+ assert_eq!(quiet_enough(&[msg("kwant", 7, None)], now), None, "the person never wrote");
+ let wa = r#"{"kind":"work_ahead"}"#;
+ assert_eq!(quiet_enough(&[msg("user", 30, None), msg("kwant", 29, None), msg("kwant", 5, Some(wa))], now), None, "once per person message");
+ assert_eq!(quiet_enough(&[msg("kwant", 30, Some(wa)), msg("user", 7, None), msg("kwant", 6, None)], now), Some(6));
+ }
+
+ #[test]
+ fn nothing_posts_nothing() {
+ assert_eq!(message_text("[NOTHING]"), None);
+ assert_eq!(message_text(" [NOTHING]\n"), None);
+ assert_eq!(message_text("[NOTHING] — all open items need the person."), None);
+ assert_eq!(message_text(""), None);
+ assert_eq!(message_text("While you were away I ran the link check.").as_deref(), Some("While you were away I ran the link check."));
+ }
+
+ #[test]
+ fn the_prompt_forbids_outside_steps_and_asks_for_a_prediction() {
+ let p = prompt(6);
+ for words in ["Never send", "pay", "sign in", NOTHING, "While you were away I", "Next I expect", "about 6 h"] {
+ assert!(p.contains(words), "{words}");
+ }
+ }
+}
diff --git a/tests/work_ahead_test.rs b/tests/work_ahead_test.rs
new file mode 100644
index 00000000..f5ebfee5
--- /dev/null
+++ b/tests/work_ahead_test.rs
@@ -0,0 +1,235 @@
+//! Work ahead: a quiet chat's lead gets one hidden run and posts one "While you were away"
+//! message; `[NOTHING]` posts nothing; the daily cap, the switch, a chat that isn't quiet yet and
+//! a second run before the person writes again all start nothing. A fake claude CLI answers by
+//! keyword. Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrono::{DateTime, Duration as Hours, Utc};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::{Message, NewMessage}, Database},
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use sqlx::sqlite::SqlitePoolOptions;
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// - a work-ahead run in a chat that says QUIETNOTHING: `[NOTHING]`;
+/// - any other work-ahead run: a short report with a prediction;
+/// - anything else: "answer".
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+case "$last" in
+ *"[Work ahead]"*)
+ case "$last" in
+ *QUIETNOTHING*) out='[NOTHING]' ;;
+ *) out='While you were away I ran the pricing page link check: all 14 links work.\nNext I expect you will want the press note draft.' ;;
+ esac ;;
+ *) out="answer" ;;
+esac
+printf '%s\n' "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"$out\",\"usage\":{\"input_tokens\":10,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":90}}"
+"#;
+
+fn fake_cli() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ 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_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,
+ channel: String,
+ ann: String,
+ bob: String,
+ _tmp: tempfile::TempDir,
+}
+
+/// Ann and Bob on the fake claude in one channel; Ann leads.
+async fn setup() -> Env {
+ fake_cli();
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config {
+ data_dir: tmp.path().to_path_buf(),
+ 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(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let bot = |name: &str| {
+ json!({"name": name, "title": format!("{name} the tester"), "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"})
+ };
+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();
+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();
+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": ann, "member_kwants": [bob]}))).await;
+ Env { app, state, channel: c["id"].as_str().unwrap().to_string(), ann, bob, _tmp: tmp }
+}
+
+/// Sets a timestamp the way kwnt writes it (sqlx's encoding), so comparisons line up.
+async fn set_time(state: &AppState, id: &str, t: DateTime<Utc>) {
+ let pool = SqlitePoolOptions::new()
+ .max_connections(1)
+ .connect(&format!("sqlite://{}", state.config.data_dir.join("kwnt.db").display()))
+ .await
+ .unwrap();
+ sqlx::query("UPDATE messages SET created_at = ? WHERE id = ?").bind(t).bind(id).execute(&pool).await.unwrap();
+ pool.close().await;
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+impl Env {
+ /// Puts `(role, sender, text, hours ago)` into `chat` (a channel id, or a bot's direct chat).
+ async fn seed(&self, chat: &str, direct: bool, rows: &[(&str, &str, &str, i64)]) {
+ for (role, sender, text, hours) in rows {
+ let m = NewMessage {
+ channel_id: (!direct).then(|| chat.to_string()),
+ direct_kwant_id: direct.then(|| chat.to_string()),
+ sender_role: role.to_string(),
+ sender_id: sender.to_string(),
+ text: text.to_string(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let saved = self.state.db.insert_message(&m).await.unwrap();
+ set_time(&self.state, &saved.id, Utc::now() - Hours::hours(*hours)).await;
+ }
+ }
+
+ async fn quiet_channel(&self, text: &str) {
+ self.seed(&self.channel, false, &[("user", "user", text, 7), ("kwant", "Ann", "Plan is in place. Open items: link check not run.", 6)]).await;
+ }
+
+ async fn run_now(&self) -> Vec<Value> {
+ ok(&self.app, "POST", "/api/work-ahead/run", None).await["started"].as_array().unwrap().clone()
+ }
+
+ async fn work_ahead_in(&self, chat: &str) -> Vec<Message> {
+ self.state.db.list_messages(chat, 100).await.unwrap().into_iter().filter(|m| meta(m)["kind"] == "work_ahead").collect()
+ }
+
+ /// Waits until no run is going.
+ async fn settle(&self) {
+ for _ in 0..200 {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ let turns = ok(&self.app, "GET", "/api/turns", None).await;
+ if turns["turns"].as_array().is_none_or(|t| t.is_empty()) {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ return;
+ }
+ }
+ panic!("runs never ended");
+ }
+}
+
+#[tokio::test]
+async fn a_quiet_chat_gets_one_run_and_one_message_with_a_prediction() {
+ let env = setup().await;
+ env.quiet_channel("Plan the launch week.").await;
+ let started = env.run_now().await;
+ assert_eq!(started.len(), 1, "{started:?}");
+ assert_eq!(started[0]["kwant_id"], env.ann.as_str(), "the channel's lead works ahead");
+ assert_eq!(started[0]["context_id"], env.channel.as_str());
+ env.settle().await;
+ let posted = env.work_ahead_in(&env.channel).await;
+ assert_eq!(posted.len(), 1);
+ let m = &posted[0];
+ assert_eq!(m.sender_id, "Ann", "kwant messages carry the bot's name");
+ assert!(m.text.starts_with("While you were away I ran the pricing page link check"), "{}", m.text);
+ assert!(m.text.contains("Next I expect"));
+ let meta = meta(m);
+ assert_eq!(meta["date"], Utc::now().format("%Y-%m-%d").to_string());
+ assert!(meta["run_id"].is_string());
+
+ // Not again before the person writes, even on a later scan
+ assert!(env.run_now().await.is_empty());
+ assert_eq!(env.work_ahead_in(&env.channel).await.len(), 1);
+}
+
+#[tokio::test]
+async fn nothing_worth_doing_posts_nothing_and_isnt_retried_today() {
+ let env = setup().await;
+ env.quiet_channel("Plan the launch week. QUIETNOTHING").await;
+ assert_eq!(env.run_now().await.len(), 1);
+ env.settle().await;
+ assert!(env.work_ahead_in(&env.channel).await.is_empty());
+ let all = env.state.db.list_messages(&env.channel, 100).await.unwrap();
+ assert_eq!(all.len(), 2, "only the seeded messages");
+ assert!(env.run_now().await.is_empty(), "one run per chat per day");
+}
+
+#[tokio::test]
+async fn the_daily_cap_the_switch_and_a_chat_that_isnt_quiet_start_nothing() {
+ let env = setup().await;
+ // Not quiet yet: the last message is an hour old
+ env.seed(&env.channel, false, &[("user", "user", "Plan the launch week.", 3), ("kwant", "Ann", "On it.", 1)]).await;
+ assert!(env.run_now().await.is_empty());
+
+ // Two quiet direct chats, a cap of 1: one run
+ env.seed(&env.ann, true, &[("user", "user", "Draft the note.", 8), ("kwant", "Ann", "Outline is ready.", 7)]).await;
+ env.seed(&env.bob, true, &[("user", "user", "Check the links.", 8), ("kwant", "Bob", "Started.", 7)]).await;
+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"work_ahead_daily_cap": 1}))).await;
+ assert!(s.is_success(), "{v}");
+ assert_eq!(env.run_now().await.len(), 1);
+ env.settle().await;
+ assert!(env.run_now().await.is_empty(), "cap reached");
+
+ // Off: nothing, and the route says so
+ let env = setup().await;
+ env.quiet_channel("Plan the launch week.").await;
+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"work_ahead": false}))).await;
+ assert!(s.is_success(), "{v}");
+ let v = ok(&env.app, "POST", "/api/work-ahead/run", None).await;
+ assert_eq!(v, json!({"enabled": false, "started": []}));
+}