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.

Watch claude CLI turns for stalls; stop flagging slow API replies

Lin (kwant bot)6f8503ed241c
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 824dbde3..3ecbcea3 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -563,10 +563,6 @@ impl ApiDriver {
#[async_trait]
impl Driver for ApiDriver {
- fn streams_progress(&self) -> bool {
- true
- }
-
async fn stream_turn(
&self,
input: TurnInput,
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index fbf0a189..991647df 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -663,7 +663,145 @@ async fn empty_grok_reply(
(msg, 0)
}
-/// What `claude -p --output-format json` reports.
+/// Longest single line of claude's `stream-json` output that is read; the rest of a longer line is
+/// skipped (it still counts as progress).
+const CLAUDE_LINE_MAX: usize = 16 * 1024 * 1024;
+/// Longest non-JSON output kept as the reply of a claude that doesn't print `stream-json`.
+const CLAUDE_PLAIN_MAX: usize = 8 * 1024 * 1024;
+/// Longest tool input shown on a claude tool call's `ToolCallPending`.
+const CLAUDE_SHOWN_ARGS_MAX: usize = 2000;
+/// At most one `Progress` per this long, however fast claude prints.
+const CLAUDE_PROGRESS_EVERY: Duration = Duration::from_secs(1);
+
+/// What `claude -p --output-format stream-json` prints, one JSON object per line, turned into
+/// events as it arrives: each tool call claude starts and finishes, and `Progress` for anything
+/// else, so the turn's stall watchdog sees a claude that is still working and pauses while a tool
+/// (or its approval card) runs. Keeps the final `result` line for [`ClaudeResult::parse`].
+#[derive(Default)]
+struct ClaudeStream {
+ /// Tool calls started and not yet finished, by `tool_use` id.
+ running: std::collections::HashSet<String>,
+ /// Tool calls already reported, so a repeated message isn't reported twice.
+ seen: std::collections::HashSet<String>,
+ result_line: Option<String>,
+ /// Output that isn't JSON (an older claude without `stream-json`).
+ plain: String,
+ last_progress: Option<Instant>,
+}
+
+impl ClaudeStream {
+ fn line(&mut self, line: &str, now: Instant) -> Vec<RuntimeEvent> {
+ let line = line.trim();
+ if line.is_empty() {
+ return Vec::new();
+ }
+ let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
+ if self.plain.len() < CLAUDE_PLAIN_MAX {
+ self.plain.push_str(line);
+ self.plain.push('\n');
+ }
+ return self.progress(now);
+ };
+ let mut events = Vec::new();
+ let blocks = v["message"]["content"].as_array().map(Vec::as_slice).unwrap_or_default();
+ match v["type"].as_str() {
+ Some("result") => self.result_line = Some(line.to_string()),
+ Some("assistant") => {
+ for b in blocks.iter().filter(|b| b["type"] == "tool_use") {
+ let Some(id) = b["id"].as_str().filter(|id| self.seen.insert(id.to_string())) else {
+ continue;
+ };
+ self.running.insert(id.to_string());
+ let args = match b["input"].to_string() {
+ shown if shown.len() > CLAUDE_SHOWN_ARGS_MAX => {
+ serde_json::Value::String(crate::mcp::truncate_text(&shown, CLAUDE_SHOWN_ARGS_MAX))
+ }
+ _ => b["input"].clone(),
+ };
+ let name = b["name"].as_str().unwrap_or("tool").to_string();
+ events.push(RuntimeEvent::ToolCallPending { id: id.to_string(), name, args });
+ }
+ }
+ Some("user") => {
+ for b in blocks.iter().filter(|b| b["type"] == "tool_result") {
+ let Some(id) = b["tool_use_id"].as_str().filter(|id| self.running.remove(*id)) else {
+ continue;
+ };
+ let status = if b["is_error"] == true { "error" } else { "ok" };
+ events.push(RuntimeEvent::ToolCallCompleted { id: id.to_string(), result: serde_json::json!({ "status": status }) });
+ }
+ }
+ _ => {}
+ }
+ if events.is_empty() {
+ return self.progress(now);
+ }
+ self.last_progress = Some(now);
+ events
+ }
+
+ fn progress(&mut self, now: Instant) -> Vec<RuntimeEvent> {
+ if self.last_progress.is_some_and(|at| now.duration_since(at) < CLAUDE_PROGRESS_EVERY) {
+ return Vec::new();
+ }
+ self.last_progress = Some(now);
+ vec![RuntimeEvent::Progress]
+ }
+
+ /// What [`ClaudeResult::parse`] reads: the result line, or the plain text when there was none.
+ fn into_stdout(self) -> String {
+ self.result_line.unwrap_or(self.plain)
+ }
+}
+
+/// Reads claude's `stream-json` stdout to the end, sending its events as they arrive.
+async fn read_claude_stream<R: tokio::io::AsyncRead + Unpin>(mut pipe: R, event_tx: &mpsc::Sender<RuntimeEvent>) -> String {
+ let mut stream = ClaudeStream::default();
+ let mut line: Vec<u8> = Vec::new();
+ // The rest of a line longer than CLAUDE_LINE_MAX is being skipped
+ let mut skipping = false;
+ let mut buffer = [0u8; 8192];
+ loop {
+ let n = match pipe.read(&mut buffer).await {
+ Ok(0) | Err(_) => break,
+ Ok(n) => n,
+ };
+ let mut chunk = &buffer[..n];
+ while !chunk.is_empty() {
+ let (part, ended) = match chunk.iter().position(|b| *b == b'\n') {
+ Some(i) => (&chunk[..i], true),
+ None => (chunk, false),
+ };
+ chunk = if ended { &chunk[part.len() + 1..] } else { &[] };
+ if !skipping {
+ line.extend_from_slice(part);
+ if line.len() > CLAUDE_LINE_MAX {
+ line.clear();
+ skipping = true;
+ }
+ }
+ let events = if ended {
+ let events = if skipping { stream.progress(Instant::now()) } else { stream.line(&String::from_utf8_lossy(&line), Instant::now()) };
+ line.clear();
+ skipping = false;
+ events
+ } else {
+ Vec::new()
+ };
+ for event in events {
+ let _ = event_tx.send(event).await;
+ }
+ }
+ }
+ if !skipping {
+ for event in stream.line(&String::from_utf8_lossy(&line), Instant::now()) {
+ let _ = event_tx.send(event).await;
+ }
+ }
+ stream.into_stdout()
+}
+
+/// What `claude -p --output-format stream-json` reports on its final `result` line.
#[derive(Debug, Default, serde::Deserialize)]
struct ClaudeResult {
#[serde(default)]
@@ -707,6 +845,13 @@ impl ClaudeResult {
#[async_trait]
impl Driver for CliDriver {
+ /// claude prints `stream-json` as it works (see [`ClaudeStream`]). codex runs with `-o` and
+ /// prints nothing until it ends, and grok's stream has no event for a tool run ending, so a
+ /// silent grok can't be told apart from one running a long tool: neither is watched.
+ fn streams_progress(&self) -> bool {
+ self.cli_binary.is_some() && !matches!(self.tool_kind.as_str(), "codex" | "grok")
+ }
+
async fn stream_turn(
&self,
input: TurnInput,
@@ -959,8 +1104,9 @@ impl Driver for CliDriver {
String::new()
};
cmd.arg("--append-system-prompt").arg(format!("{system_prompt}{tools_block}"));
- // One JSON result: tells a usage limit or sign-out apart from a reply
- cmd.arg("--output-format").arg("json");
+ // JSON lines as claude works, ending in one result that tells a usage limit or
+ // sign-out apart from a reply; partial messages keep a long answer from looking stalled
+ cmd.arg("--output-format").arg("stream-json").arg("--verbose").arg("--include-partial-messages");
cmd.arg("-p").arg(&effective_prompt);
}
}
@@ -994,7 +1140,7 @@ impl Driver for CliDriver {
let stderr_pipe = child.stderr.take();
let read_stdout = async {
match stdout_pipe {
- Some(stdout) => read_tail(stdout, 8 * 1024 * 1024).await,
+ Some(stdout) => read_claude_stream(stdout, &event_tx).await,
None => String::new(),
}
};
@@ -1097,6 +1243,84 @@ mod tests {
use super::*;
use crate::db::models::{Kwant, Message};
+ fn kinds(events: &[RuntimeEvent]) -> Vec<String> {
+ events
+ .iter()
+ .map(|e| match e {
+ RuntimeEvent::ToolCallPending { id, name, .. } => format!("start {id} {name}"),
+ RuntimeEvent::ToolCallCompleted { id, result } => format!("end {id} {}", result["status"].as_str().unwrap_or("")),
+ RuntimeEvent::Progress => "progress".into(),
+ other => format!("{other:?}"),
+ })
+ .collect()
+ }
+
+ #[test]
+ fn claude_stream_reports_tool_runs_and_keeps_the_result() {
+ let t0 = Instant::now();
+ let mut s = ClaudeStream::default();
+ assert_eq!(kinds(&s.line(r#"{"type":"system","subtype":"init"}"#, t0)), ["progress"]);
+ let call = r#"{"type":"assistant","message":{"content":[{"type":"text","text":"ok"},{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"sleep 600"}}]}}"#;
+ assert_eq!(kinds(&s.line(call, t0)), ["start tu_1 Bash"]);
+ // The same message again (claude repeats content across partial and whole messages)
+ assert!(kinds(&s.line(call, t0 + Duration::from_secs(5))).iter().all(|k| k == "progress"));
+ let done = r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tu_1","is_error":true,"content":"denied"}]}}"#;
+ assert_eq!(kinds(&s.line(done, t0)), ["end tu_1 error"]);
+ // A result for a call never started, or one already finished, is not reported
+ assert!(!kinds(&s.line(done, t0 + Duration::from_secs(9))).iter().any(|k| k.starts_with("end")));
+ let result = r#"{"type":"result","is_error":false,"num_turns":2,"result":"all done","usage":{"input_tokens":3,"output_tokens":4}}"#;
+ s.line(result, t0);
+ let parsed = ClaudeResult::parse(&s.into_stdout()).unwrap();
+ assert_eq!(parsed.result, "all done");
+ assert_eq!(parsed.tokens(), Some(7));
+ }
+
+ #[test]
+ fn claude_stream_progress_is_sent_at_most_once_a_second() {
+ let t0 = Instant::now();
+ let mut s = ClaudeStream::default();
+ let delta = r#"{"type":"stream_event","event":{"type":"content_block_delta"}}"#;
+ assert_eq!(s.line(delta, t0).len(), 1);
+ assert!(s.line(delta, t0 + Duration::from_millis(300)).is_empty());
+ assert!(s.line(delta, t0 + Duration::from_millis(900)).is_empty());
+ assert_eq!(s.line(delta, t0 + Duration::from_millis(1100)).len(), 1);
+ }
+
+ #[test]
+ fn claude_stream_shows_long_tool_input_truncated_and_keeps_plain_output() {
+ let mut s = ClaudeStream::default();
+ let big = "x".repeat(10_000);
+ let call = serde_json::json!({"type":"assistant","message":{"content":[{"type":"tool_use","id":"w","name":"Write","input":{"content": big}}]}});
+ let events = s.line(&call.to_string(), Instant::now());
+ let RuntimeEvent::ToolCallPending { args, .. } = &events[0] else { panic!("{events:?}") };
+ assert!(args.as_str().is_some_and(|a| a.len() < 2100 && a.ends_with("[truncated]")), "{args}");
+
+ // An older claude that prints plain text: the text is the reply
+ let mut old = ClaudeStream::default();
+ old.line("hello", Instant::now());
+ old.line("world", Instant::now());
+ assert_eq!(old.into_stdout(), "hello\nworld\n");
+ }
+
+ #[tokio::test]
+ async fn claude_stream_reader_splits_lines_across_reads_and_skips_huge_ones() {
+ let (tx, mut rx) = mpsc::channel(64);
+ let mut input = Vec::new();
+ input.extend_from_slice(br#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"a","name":"Read","input":{}}]}}"#);
+ input.push(b'\n');
+ input.extend(std::iter::repeat_n(b'y', CLAUDE_LINE_MAX + 10));
+ input.push(b'\n');
+ input.extend_from_slice(br#"{"type":"result","result":"fine"}"#);
+ let out = read_claude_stream(&input[..], &tx).await;
+ drop(tx);
+ assert_eq!(ClaudeResult::parse(&out).unwrap().result, "fine");
+ let mut got = Vec::new();
+ while let Some(e) = rx.recv().await {
+ got.push(e);
+ }
+ assert_eq!(kinds(&got)[0], "start a Read");
+ }
+
#[test]
fn grok_may_fetch_pages_and_edit_only_inside_the_folder() {
assert_eq!(grok_builtin_rules(None), ["--allow", "WebFetch"]);
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index ec54f02e..33c9b33f 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -15,6 +15,9 @@ pub enum RuntimeEvent {
id: String,
result: Value,
},
+ /// A driver is still working: it printed something that isn't reply text or a tool call.
+ /// Only feeds the turn's stall watchdog; it is never broadcast.
+ Progress,
ApprovalRequired {
id: String,
tool_name: String,
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 970449d8..92b1d7bd 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -412,9 +412,11 @@ pub trait Driver: Send + Sync {
event_tx: mpsc::Sender<RuntimeEvent>,
) -> Result<TurnOutput, DriverError>;
- /// Whether this driver streams its reply as it goes and brackets tool runs with
- /// `ToolCallPending`/`ToolCallCompleted`, so a long silence means it is stuck. Drivers that
- /// only report at the end (one-shot CLIs) say false and are never stopped for silence.
+ /// Whether this driver reports progress as it goes (output, or `Progress`) and brackets tool
+ /// runs with `ToolCallPending`/`ToolCallCompleted`, so a long silence means it is stuck.
+ /// Drivers that can be silent while healthy say false and are never stopped for silence: CLIs
+ /// that only report at the end, and the API driver, whose model calls aren't streamed (a slow
+ /// reply would look stalled) and are bounded by their own HTTP timeout instead.
fn streams_progress(&self) -> bool {
false
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 900452ab..336c1908 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1613,6 +1613,8 @@ async fn run_kwant_turn_inner(
let mut cancelled = false;
let mut driver_result = None;
let mut gave_up: Option<String> = None;
+ // Saved with the gave-up reply, so a client can offer Retry without reading its wording
+ let mut gave_up_meta: Option<serde_json::Value> = None;
let mut ran_on: Option<RanOn> = None;
if attempts.is_empty() {
let text = format!(
@@ -1742,6 +1744,8 @@ async fn run_kwant_turn_inner(
Some(RuntimeEvent::TurnComplete { tokens, duration_ms, .. }) => {
held_complete = Some((tokens, duration_ms));
}
+ // Only resets the stall clock (above)
+ Some(RuntimeEvent::Progress) => {}
Some(event) => {
let visible = match &event {
RuntimeEvent::TextDelta(t) => !t.trim().is_empty(),
@@ -1774,6 +1778,13 @@ async fn run_kwant_turn_inner(
profile_id: profile.as_ref().map(|p| p.id.clone()),
});
gave_up = Some(text);
+ gave_up_meta = Some(json!({
+ "kind": "turn_stalled",
+ "stalled": true,
+ "kwant_id": target_kwant.id,
+ "kwant_name": target_kwant.name,
+ "stall_secs": secs,
+ }));
break;
}
let result = driver_task.await;
@@ -1881,7 +1892,7 @@ async fn run_kwant_turn_inner(
reasoning_content: with_notices(opts.label.clone()),
..scope.message("kwant", &target_kwant.name, text.clone())
};
- scope.save(&msg, None).await;
+ scope.save(&msg, gave_up_meta).await;
return Err(text);
} else if let Some(Ok(Ok(output))) = driver_result {
// Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VM
diff --git a/src/server/sse.rs b/src/server/sse.rs
index c8ebaa1c..c3015ae5 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -53,6 +53,8 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
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(),
+ // Never broadcast: the turn's stall watchdog takes it
+ E::Progress => 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, .. }
@@ -201,6 +203,7 @@ mod tests {
E::ThinkingDelta(s("x")),
E::ToolCallPending { id: s("x"), name: s("x"), args: json!({}) },
E::ToolCallCompleted { id: s("x"), result: json!({}) },
+ E::Progress,
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 },
@@ -278,6 +281,7 @@ mod tests {
| E::ThinkingDelta(_)
| E::ToolCallPending { .. }
| E::ToolCallCompleted { .. }
+ | E::Progress
| E::ApprovalRequired { .. }
| E::ApprovalWithdrawn { .. }
| E::TurnComplete { .. }
@@ -318,7 +322,7 @@ mod tests {
#[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"];
+ let turn_only = ["TextDelta", "ThinkingDelta", "ToolCallPending", "ToolCallCompleted", "Progress"];
for e in samples() {
let t = wire_type(&e);
if turn_only.contains(&t.as_str()) && !matches!(e, RuntimeEvent::Scoped { .. }) {
diff --git a/tests/turn_recovery_test.rs b/tests/turn_recovery_test.rs
index be6e4dad..3f623d9e 100644
--- a/tests/turn_recovery_test.rs
+++ b/tests/turn_recovery_test.rs
@@ -1,5 +1,6 @@
-//! Replies that can't finish: a model that goes silent is stopped by the stall watchdog with a
-//! visible reason, and replies cut short by a restart are marked interrupted on the next start.
+//! Replies that can't finish: a claude that goes silent is stopped by the stall watchdog with a
+//! visible reason (but not while a tool runs, and never an API reply that is just slow), and
+//! replies cut short by a restart are marked interrupted on the next start.
use axum::{
body::{to_bytes, Body},
@@ -17,9 +18,49 @@ use kwnt::{
tools::ToolRunner,
};
use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
use std::time::Duration;
use tower::ServiceExt;
+/// A claude CLI that prints `stream-json` like the real one; what it does depends on a word in
+/// the prompt.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+echo '{"type":"system","subtype":"init"}'
+case "$*" in
+ *GO_SILENT*) exec sleep 3600 ;;
+ *LONG_TOOL*)
+ echo '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"sleep 5"}}]}}'
+ sleep 5
+ echo '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tu_1","content":"done"}]}}'
+ echo '{"type":"result","is_error":false,"num_turns":2,"result":"finished after the tool"}' ;;
+ *KEEP_TALKING*)
+ for i in 1 2 3 4 5; do echo '{"type":"stream_event","event":{"type":"content_block_delta"}}'; sleep 1; done
+ echo '{"type":"result","is_error":false,"num_turns":1,"result":"finished talking"}' ;;
+ *) echo '{"type":"result","is_error":false,"num_turns":1,"result":"answer ok"}' ;;
+esac
+"#;
+
+fn fake_claude() {
+ static DONE: OnceLock<PathBuf> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let bin = tempfile::tempdir().unwrap().keep().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ bin
+ });
+}
+
async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
let resp = app
.clone()
@@ -38,15 +79,18 @@ async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (St
(s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))
}
-/// An OpenAI-compatible server that lists one model and then never answers a chat request.
-async fn hanging_server() -> String {
+/// An OpenAI-compatible server that answers every chat request, but only after `after`.
+async fn slow_server(after: Duration) -> String {
let app = Router::new()
.route("/v1/models", get(|| async { Json(json!({"object": "list", "data": [{"id": "gpt-4.1"}]})) }))
.route(
"/v1/chat/completions",
- post(|| async {
- tokio::time::sleep(Duration::from_secs(3600)).await;
- Json(json!({}))
+ post(move || async move {
+ tokio::time::sleep(after).await;
+ Json(json!({
+ "choices": [{"message": {"role": "assistant", "content": "slow but fine"}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8},
+ }))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -62,6 +106,7 @@ struct Env {
}
async fn setup() -> Env {
+ fake_claude();
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
@@ -119,13 +164,33 @@ impl Env {
v["id"].as_str().unwrap().to_string()
}
+ /// A bot on this machine's claude CLI (the fake one on PATH).
+ async fn claude_bot(&self) -> String {
+ let (s, v) = call(
+ &self.app,
+ "POST",
+ "/api/kwants",
+ Some(json!({
+ "name": "Clio", "title": "Tester", "persona_prompt": "Test persona",
+ "avatar_sprite": "s", "driver_type": "api", "preferred_model": "claude",
+ })),
+ )
+ .await;
+ assert!(s.is_success(), "{s} {v}");
+ v["id"].as_str().unwrap().to_string()
+ }
+
async fn turn(&self, kwant_id: &str, within: Duration) -> Vec<RuntimeEvent> {
+ self.turn_with(kwant_id, "hi", within).await
+ }
+
+ async fn turn_with(&self, kwant_id: &str, prompt: &str, within: Duration) -> Vec<RuntimeEvent> {
let mut rx = self.state.event_sender.subscribe();
let (s, v) = call(
&self.app,
"POST",
"/api/chat/send",
- Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"})),
+ Some(json!({"kwant_id": kwant_id, "prompt": prompt, "sender_id": "user"})),
)
.await;
assert_eq!(s, StatusCode::OK, "{v}");
@@ -145,46 +210,96 @@ impl Env {
}
}
+fn shown(events: &[RuntimeEvent]) -> String {
+ events
+ .iter()
+ .filter_map(|e| match e {
+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),
+ _ => None,
+ })
+ .collect()
+}
+
#[tokio::test]
-async fn a_silent_model_is_stopped_with_a_visible_reason() {
+async fn a_silent_claude_is_stopped_with_a_visible_reason() {
let env = setup().await;
env.state.db.set_setting(routes::STALL_SETTING, "2").await.unwrap();
- let root = hanging_server().await;
- let kid = env.api_bot(&root).await;
+ let kid = env.claude_bot().await;
let started = std::time::Instant::now();
- let events = env.turn(&kid, Duration::from_secs(30)).await;
+ let events = env.turn_with(&kid, "please GO_SILENT now", Duration::from_secs(30)).await;
let waited = started.elapsed();
assert!(waited >= Duration::from_secs(2), "stopped before the limit: {waited:?}");
assert!(waited < Duration::from_secs(15), "the watchdog should stop it soon after 2 s: {waited:?}");
- let shown: String = events
- .iter()
- .filter_map(|e| match e {
- RuntimeEvent::TextDelta(t) => Some(t.as_str()),
- _ => None,
- })
- .collect();
- assert!(shown.contains("sent nothing for 2 s"), "{shown}");
+ assert!(shown(&events).contains("sent nothing for 2 s"), "{}", shown(&events));
- // The reason is kept in the chat, and the bot isn't left marked as replying
- let saved = env.state.db.list_messages(&kid, 10).await.unwrap();
- assert!(saved.iter().any(|m| m.text.contains("sent nothing for 2 s")), "{saved:?}");
+ // The reason is kept in the chat, tagged for a Retry button, and the bot isn't left marked as replying
+ let (s, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;
+ assert_eq!(s, StatusCode::OK, "{msgs}");
+ let stopped = msgs
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|m| m["text"].as_str().is_some_and(|t| t.contains("sent nothing for 2 s")))
+ .unwrap_or_else(|| panic!("{msgs}"));
+ let meta: Value = serde_json::from_str(stopped["meta"].as_str().unwrap()).unwrap();
+ assert_eq!(meta["kind"], "turn_stalled");
+ assert_eq!(meta["stalled"], true);
+ assert_eq!(meta["kwant_id"], kid.as_str());
+ assert_eq!(meta["stall_secs"], 2);
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(env.state.db.take_running_turns().await.unwrap().is_empty(), "the running row is cleared");
}
+#[tokio::test]
+async fn the_watchdog_waits_while_a_tool_runs() {
+ let env = setup().await;
+ env.state.db.set_setting(routes::STALL_SETTING, "2").await.unwrap();
+ let kid = env.claude_bot().await;
+ // The tool runs 5 s with no output, far past the 2 s limit
+ let events = env.turn_with(&kid, "run a LONG_TOOL please", Duration::from_secs(30)).await;
+ let text = shown(&events);
+ assert!(text.contains("finished after the tool"), "{text}");
+ assert!(!text.contains("sent nothing"), "{text}");
+ assert!(events.iter().any(|e| matches!(e, RuntimeEvent::ToolCallPending { id, .. } if id == "tu_1")), "{events:?}");
+ assert!(events.iter().any(|e| matches!(e, RuntimeEvent::ToolCallCompleted { id, .. } if id == "tu_1")), "{events:?}");
+ assert!(!events.iter().any(|e| matches!(e, RuntimeEvent::Progress)), "progress is never broadcast");
+}
+
+#[tokio::test]
+async fn a_claude_still_writing_is_not_stopped() {
+ let env = setup().await;
+ env.state.db.set_setting(routes::STALL_SETTING, "2").await.unwrap();
+ let kid = env.claude_bot().await;
+ // 5 s in all, but never silent for 2 s
+ let events = env.turn_with(&kid, "KEEP_TALKING for a while", Duration::from_secs(30)).await;
+ assert!(shown(&events).contains("finished talking"), "{}", shown(&events));
+}
+
+#[tokio::test]
+async fn a_slow_api_reply_is_not_stopped_as_a_stall() {
+ // The API driver's model calls aren't streamed, so a slow healthy reply is silent throughout
+ let env = setup().await;
+ env.state.db.set_setting(routes::STALL_SETTING, "1").await.unwrap();
+ let root = slow_server(Duration::from_secs(3)).await;
+ let kid = env.api_bot(&root).await;
+ let events = env.turn(&kid, Duration::from_secs(30)).await;
+ let text = shown(&events);
+ assert!(text.contains("slow but fine"), "{text}");
+ assert!(!text.contains("sent nothing"), "{text}");
+}
+
#[tokio::test]
async fn the_stall_limit_comes_from_settings_and_zero_turns_it_off() {
let env = setup().await;
env.state.db.set_setting(routes::STALL_SETTING, "0").await.unwrap();
- let root = hanging_server().await;
- let kid = env.api_bot(&root).await;
+ let kid = env.claude_bot().await;
let mut rx = env.state.event_sender.subscribe();
let (s, _) = call(
&env.app,
"POST",
"/api/chat/send",
- Some(json!({"kwant_id": kid, "prompt": "hi", "sender_id": "user"})),
+ Some(json!({"kwant_id": kid, "prompt": "GO_SILENT", "sender_id": "user"})),
)
.await;
assert_eq!(s, StatusCode::OK);