Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
test(host): cover routine unread counts on the current chat model (#156)
Kai Wu51aa27aac899
diff --git a/docs/features/routines.md b/docs/features/routines.mdindex 55b68626..68308730 100644--- a/docs/features/routines.md+++ b/docs/features/routines.md@@ -237,7 +237,10 @@ session recovery, hung-agent timeout, recurring work after failure, single-hostownership, silent completion, and the advertised routine MCP server (including keyrotation). `host/tests/routine_retry_e2e.rs` checks a webhook run that failed beforeacting waiting 1 minute with its event (and running at once on a test run), and one-that acted waiting for `retryRoutineRun`, which reuses the event once. Unit tests cover+that acted waiting for `retryRoutineRun`, which reuses the event once.+`host/tests/routine_unread_e2e.rs` checks that a routine result counts one unread in the+main chat, that `markRead` clears it once the run has released its session, and that a+follow-up reply counts once again when it is final. Unit tests coverthe retry ladder, a queued scheduled fire standing in for the retry, paused routines,keeping only the latest failure's event, the user retry's busy/paused refusals anddeleting the routine (`routines/retry.rs`), waiting retries vs. Stop, the tick and adiff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.mdindex 5f2f41e4..36a0b10f 100644--- a/docs/reference/compatibility.md+++ b/docs/reference/compatibility.md@@ -117,7 +117,7 @@ trails them (App Store review), so nudging a computer from it would only be nois### Wire shape snapshot-`wire_shape_matches_the_snapshot` (`host/tests/e2e.rs`) runs a full turn against a real host+`wire_shape_matches_the_snapshot` (`host/tests/e2e/wire_shape.rs`) runs a full turn against a real host(fake agent: user message, narration, tool call with a diff, plan, permission, final reply),then records every field path and JSON type of `hello` and the event stream's catch-up (botand entry events, entries per kind) in `host/tests/fixtures/wire-shape.json`, together with@@ -131,7 +131,7 @@ the host's `minApp`.So a breaking change can't land by accident: it either keeps the old field or raises thefloor. `null` fields match any type. Not covered: subtrees that depend on the machine rather-than the code (`backends`, `screen`, `urls`, `usage`), fields the sample turn doesn't produce+than the code (`backends`, `screen`, `urls`, `usage`, including asynchronous usage events), fields the sample turn doesn't produce(replies, group chats, routines and other method responses), and what the hostaccepts in requests. Changes there still follow the rule by review.diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rsindex f6b604bd..968fccdc 100644--- a/host/tests/common/mod.rs+++ b/host/tests/common/mod.rs@@ -26,9 +26,9 @@ pub async fn serve(home: &Path) -> (Child, String) {.spawn().expect("start the host");while child.try_wait().expect("host state").is_none() {- match reqwest::get(format!("{base}/health")).await {- Ok(_) => return (child, base),- Err(e) => last = format!("{e:?}"),+ match ready(&base, home).await {+ Ok(()) => return (child, base),+ Err(e) => last = e,}assert!(Instant::now() < deadline, "{}", not_started(&log, &last));tokio::time::sleep(Duration::from_millis(50)).await;@@ -37,12 +37,25 @@ pub async fn serve(home: &Path) -> (Child, String) {}}-/// Why a test host didn't answer: the last health check's error and the end of the host's log.+/// Why a test host didn't answer: the last readiness check's error and the end of the host's log.fn not_started(log: &Path, last: &str) -> String {let text = std::fs::read_to_string(log).unwrap_or_default();let lines: Vec<&str> = text.lines().collect();let tail = lines[lines.len().saturating_sub(30)..].join("\n");- format!("host didn't start; last health check: {last}\n--- host log ---\n{tail}")+ format!("host didn't start; last readiness check: {last}\n--- host log ---\n{tail}")+}++/// Whether `base` is this home's host: on a reused port another test's host answers `/health` too.+pub async fn ready(base: &str, home: &Path) -> Result<(), String> {+ let token = std::fs::read_to_string(home.join("token")).map_err(|e| format!("no token yet: {e}"))?;+ let res = reqwest::Client::new()+ .get(format!("{base}/events?since=0&client=test"))+ .bearer_auth(token.trim())+ .timeout(Duration::from_secs(1))+ .send()+ .await+ .map_err(|e| format!("{e:?}"))?;+ res.status().is_success().then_some(()).ok_or_else(|| format!("status {}", res.status()))}/// Stops a test host the way launchd does (SIGTERM), so it shuts down its own@@ -117,6 +130,18 @@ pub async fn snapshot(base: &str, token: &str) -> serde_json::Value {serde_json::json!({"rev": rev, "bots": bots, "entries": entries})}+/// How many routine runs still hold a session in `home`'s store: the host keeps each as a+/// `lane.session.<bot>@<bot>/routine-<run>` row (`store::model::run_session_key`) and forgets+/// it when the run ends.+#[allow(dead_code, reason = "only the routine tests wait for runs")]+pub fn routine_sessions(home: &Path) -> i64 {+ rusqlite::Connection::open(home.join("codync.db"))+ .and_then(|db| {+ db.query_row("SELECT COUNT(*) FROM kv WHERE k GLOB 'lane.session.*/routine-*'", [], |r| r.get(0))+ })+ .expect("read the host's store")+}+/// Bot `id` in a [`snapshot`] (which also holds the lead bot every host makes).#[allow(dead_code, reason = "not every test binary looks bots up")]pub fn bot<'a>(sync: &'a serde_json::Value, id: &str) -> &'a serde_json::Value {diff --git a/host/tests/e2e.rs b/host/tests/e2e.rsindex c785ddd5..36ecd154 100644--- a/host/tests/e2e.rs+++ b/host/tests/e2e.rs@@ -5,6 +5,9 @@mod common;+#[path = "e2e/wire_shape.rs"]+mod wire_shape;+/// The host's wire crypto doubles as this test's device implementation.#[path = "../src/remote/crypto.rs"]#[allow(dead_code)]@@ -79,6 +82,34 @@ async fn health_names_this_binary() {assert_eq!(health["binaryPath"], exe.strip_prefix(r"\\?\").unwrap_or(exe));}+#[tokio::test]+async fn readiness_needs_this_homes_token() {+ use axum::http::{HeaderMap, StatusCode};+ use axum::{Router, routing::get};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ let router = Router::new().route(+ "/events",+ get(|headers: HeaderMap| async move {+ if headers.get("authorization").and_then(|v| v.to_str().ok()) == Some("Bearer listener-token") {+ StatusCode::OK+ } else {+ StatusCode::UNAUTHORIZED+ }+ }),+ );+ let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });+ let home = std::env::temp_dir().join(format!("codync-readiness-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&home).unwrap();+ assert!(common::ready(&base, &home).await.is_err(), "a foreign listener does not make a new home ready");+ std::fs::write(home.join("token"), "different-token").unwrap();+ assert!(common::ready(&base, &home).await.is_err(), "an existing token from a restart must match the listener");+ std::fs::write(home.join("token"), "listener-token").unwrap();+ assert!(common::ready(&base, &home).await.is_ok());+ server.abort();+ std::fs::remove_dir_all(home).unwrap();+}+// SIGTERM is Unix only; Windows stops the host by ending its process.#[cfg(unix)]#[tokio::test]@@ -405,192 +436,3 @@ async fn personal_workspaces_are_unique_persistent_and_optional() {assert_eq!(group["bot"]["cwd"], "");assert_eq!(group["bot"]["managedWorkspace"], false);}--// ---------- wire shape snapshot (docs/reference/compatibility.md) ------------/// Snapshot of what clients decode: field paths and JSON types of `hello` and the event-/// stream after a full turn. Values aren't kept, only the shape.-const WIRE_SHAPE: &str = "tests/fixtures/wire-shape.json";-/// Re-records the snapshot (refused while a field is removed or retyped without a new `minApp`).-const UPDATE_ENV: &str = "CODYNC_UPDATE_WIRE_SHAPE";-/// Depends on the machine (installed harnesses, displays, addresses, local usage), not the code.-const MACHINE_DEPENDENT: [&str; 4] = ["backends", "screen", "urls", "usage"];--fn json_type(v: &Value) -> &'static str {- match v {- Value::Null => "null",- Value::Bool(_) => "bool",- Value::Number(_) => "number",- Value::String(_) => "string",- Value::Array(_) => "array",- Value::Object(_) => "object",- }-}--/// Every field path under `v` with its type; array elements merge under `[]`.-fn shape(v: &Value, path: &str, out: &mut std::collections::BTreeMap<String, String>) {- out.insert(path.to_owned(), json_type(v).to_owned());- match v {- Value::Object(map) => {- for (k, child) in map {- if !MACHINE_DEPENDENT.contains(&k.as_str()) {- shape(child, &format!("{path}.{k}"), out);- }- }- }- Value::Array(items) => {- for item in items {- shape(item, &format!("{path}[]"), out);- }- }- _ => {}- }-}--/// The shape of a stream event, keyed by its type (and an entry's kind: their data differ).-fn event_shape(ev: &Value, out: &mut std::collections::BTreeMap<String, String>) {- let ty = ev["type"].as_str().unwrap_or("?");- let key = match ev["entry"]["kind"].as_str() {- Some(kind) if ty == "entry" => format!("event:entry({kind})"),- _ => format!("event:{ty}"),- };- shape(ev, &key, out);-}--/// What changed between the recorded and the current shape: (breaking, additions).-/// A field that was `null` on either side can't be judged by its type.-fn shape_diff(- recorded: &std::collections::BTreeMap<String, String>,- current: &std::collections::BTreeMap<String, String>,-) -> (Vec<String>, Vec<String>) {- let mut breaking = vec![];- for (path, ty) in recorded {- match current.get(path) {- None => breaking.push(format!("removed {path} ({ty})")),- Some(now) if now != ty && now != "null" && ty != "null" => {- breaking.push(format!("retyped {path}: {ty} → {now}"));- }- Some(_) => {}- }- }- let added = current- .iter()- .filter(|(path, ty)| recorded.get(*path).is_none_or(|old| old == "null" && *ty != "null"))- .map(|(path, ty)| format!("{path} ({ty})"))- .collect();- (breaking, added)-}--#[test]-fn shape_diff_tells_breaking_from_additive() {- let map = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();- let recorded = map(&[("a", "object"), ("a.x", "string"), ("a.y", "null"), ("a.z", "number")]);- let current = map(&[("a", "object"), ("a.x", "number"), ("a.y", "string"), ("a.w", "bool")]);- let (breaking, added) = shape_diff(&recorded, ¤t);- assert_eq!(breaking, ["retyped a.x: string → number", "removed a.z (number)"]);- assert_eq!(added, ["a.w (bool)", "a.y (string)"]);-}--/// Reads the event stream's catch-up until it goes quiet.-async fn catch_up(host: &Host) -> Vec<Value> {- let res = reqwest::Client::new()- .get(format!("{}/events?since=0&client=test", host.base))- .bearer_auth(&host.token)- .send()- .await- .unwrap();- let mut body = res.bytes_stream();- let (mut buf, mut events) = (String::new(), vec![]);- while let Ok(Some(Ok(chunk))) = tokio::time::timeout(Duration::from_millis(1500), body.next()).await {- buf.push_str(&String::from_utf8_lossy(&chunk));- while let Some(i) = buf.find('\n') {- let line: String = buf.drain(..=i).collect();- if let Some(data) = line.trim_end().strip_prefix("data:")- && let Ok(v) = serde_json::from_str::<Value>(data.trim_start())- // A live usage refresh lands whenever the agents' usage poll finishes (later on a- // busy machine); its shape is `hello.usage`'s.- && v["type"] != "usage"- {- events.push(v);- }- }- }- events-}--/// Older apps read what the host sends: a removed or retyped field breaks them. This fails-/// until the field is kept, or `MIN_APP` is raised the two-release way and the snapshot-/// re-recorded. New fields only need recording (`CODYNC_UPDATE_WIRE_SHAPE=1`).-#[tokio::test]-async fn wire_shape_matches_the_snapshot() {- if Command::new(common::python()).arg("--version").output().is_err() {- eprintln!("skipping: Python not available");- return;- }- let host = start_host().await;- let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_agent.py");- let bot = host- .call(- "createBot",- json!({- "name": "Tester", "backend": "custom", "command": common::python_agent(&agent),- "cwd": host.home.to_string_lossy(), "permission": "ask",- }),- )- .await["bot"]["id"]- .as_str()- .unwrap()- .to_owned();- host.call("send", json!({"botId": bot, "text": "go", "clientNonce": "n1"})).await;- let card = host.wait_for(&bot, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;- host.call("respondPermission", json!({"entryId": card["id"], "optionId": "allow"})).await;- host.wait_for(&bot, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- // A bot another bot created: its `createdBy`.- let lead = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");- let lead = host- .call(- "createBot",- json!({"name": "Lead", "backend": "custom", "command": common::python_agent(&lead), "connectors": [],- "permission": "auto", "manageTeam": true}),- )- .await["bot"]["id"]- .as_str()- .unwrap()- .to_owned();- host.call("send", json!({"botId": lead, "text": "MANAGE create_bot {\"name\": \"Made\"}", "clientNonce": "n2"}))- .await;- let made = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;- assert!(made["data"]["text"].as_str().unwrap().starts_with("Done: "), "{made}");-- let hello = host.call("hello", json!({})).await;- let min_app = hello["minApp"].as_str().unwrap().to_owned();- let mut current = std::collections::BTreeMap::new();- shape(&hello, "hello", &mut current);- for ev in catch_up(&host).await {- event_shape(&ev, &mut current);- }- assert!(current.keys().any(|k| k.starts_with("event:entry(tool)")), "the turn's entries are missing");-- let file = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(WIRE_SHAPE);- let recorded: Value = std::fs::read_to_string(&file).map_or(Value::Null, |s| serde_json::from_str(&s).unwrap());- let recorded_shapes: std::collections::BTreeMap<String, String> =- serde_json::from_value(recorded["shapes"].clone()).unwrap_or_default();- let (breaking, added) = shape_diff(&recorded_shapes, ¤t);- let floor_raised = recorded["minApp"].as_str() != Some(min_app.as_str());- assert!(- breaking.is_empty() || floor_raised,- "Older apps would break: {breaking:#?}\nKeep these fields, or follow the two-release rule \- in docs/reference/compatibility.md: raise MIN_APP (host/src/compat.rs) once that iPhone \- version is live, then re-record with {UPDATE_ENV}=1 cargo test --test e2e wire_shape"- );- if std::env::var_os(UPDATE_ENV).is_some() {- let json = json!({"minApp": min_app, "shapes": current});- std::fs::write(&file, serde_json::to_string_pretty(&json).unwrap() + "\n").unwrap();- return;- }- assert!(- breaking.is_empty() && added.is_empty() && !floor_raised,- "The wire shape changed.\nAdded: {added:#?}\nRemoved or retyped (minApp was raised): {breaking:#?}\n\- Record it with {UPDATE_ENV}=1 cargo test --test e2e wire_shape"- );-}diff --git a/host/tests/e2e/wire_shape.rs b/host/tests/e2e/wire_shape.rsnew file mode 100644index 00000000..04b8af0c--- /dev/null+++ b/host/tests/e2e/wire_shape.rs@@ -0,0 +1,190 @@+//! Wire shape snapshot (docs/reference/compatibility.md).++use super::*;++/// Snapshot of what clients decode: field paths and JSON types of `hello` and the event+/// stream after a full turn. Values aren't kept, only the shape.+const WIRE_SHAPE: &str = "tests/fixtures/wire-shape.json";+/// Re-records the snapshot (refused while a field is removed or retyped without a new `minApp`).+const UPDATE_ENV: &str = "CODYNC_UPDATE_WIRE_SHAPE";+/// Depends on the machine (installed harnesses, displays, addresses, local usage), not the code.+const MACHINE_DEPENDENT: [&str; 4] = ["backends", "screen", "urls", "usage"];++fn json_type(v: &Value) -> &'static str {+ match v {+ Value::Null => "null",+ Value::Bool(_) => "bool",+ Value::Number(_) => "number",+ Value::String(_) => "string",+ Value::Array(_) => "array",+ Value::Object(_) => "object",+ }+}++/// Every field path under `v` with its type; array elements merge under `[]`.+fn shape(v: &Value, path: &str, out: &mut std::collections::BTreeMap<String, String>) {+ out.insert(path.to_owned(), json_type(v).to_owned());+ match v {+ Value::Object(map) => {+ for (k, child) in map {+ if !MACHINE_DEPENDENT.contains(&k.as_str()) {+ shape(child, &format!("{path}.{k}"), out);+ }+ }+ }+ Value::Array(items) => {+ for item in items {+ shape(item, &format!("{path}[]"), out);+ }+ }+ _ => {}+ }+}++/// The shape of a stream event, keyed by its type (and an entry's kind: their data differ).+fn event_shape(ev: &Value, out: &mut std::collections::BTreeMap<String, String>) {+ let ty = ev["type"].as_str().unwrap_or("?");+ let key = match ev["entry"]["kind"].as_str() {+ Some(kind) if ty == "entry" => format!("event:entry({kind})"),+ _ => format!("event:{ty}"),+ };+ shape(ev, &key, out);+}++/// What changed between the recorded and the current shape: (breaking, additions).+/// A field that was `null` on either side can't be judged by its type.+fn shape_diff(+ recorded: &std::collections::BTreeMap<String, String>,+ current: &std::collections::BTreeMap<String, String>,+) -> (Vec<String>, Vec<String>) {+ let mut breaking = vec![];+ for (path, ty) in recorded {+ match current.get(path) {+ None => breaking.push(format!("removed {path} ({ty})")),+ Some(now) if now != ty && now != "null" && ty != "null" => {+ breaking.push(format!("retyped {path}: {ty} → {now}"));+ }+ Some(_) => {}+ }+ }+ let added = current+ .iter()+ .filter(|(path, ty)| recorded.get(*path).is_none_or(|old| old == "null" && *ty != "null"))+ .map(|(path, ty)| format!("{path} ({ty})"))+ .collect();+ (breaking, added)+}++#[test]+fn shape_diff_tells_breaking_from_additive() {+ let map = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();+ let recorded = map(&[("a", "object"), ("a.x", "string"), ("a.y", "null"), ("a.z", "number")]);+ let current = map(&[("a", "object"), ("a.x", "number"), ("a.y", "string"), ("a.w", "bool")]);+ let (breaking, added) = shape_diff(&recorded, ¤t);+ assert_eq!(breaking, ["retyped a.x: string → number", "removed a.z (number)"]);+ assert_eq!(added, ["a.w (bool)", "a.y (string)"]);+}++/// Reads the event stream's catch-up until it goes quiet.+async fn catch_up(host: &Host) -> Vec<Value> {+ let res = reqwest::Client::new()+ .get(format!("{}/events?since=0&client=test", host.base))+ .bearer_auth(&host.token)+ .send()+ .await+ .unwrap();+ let mut body = res.bytes_stream();+ let (mut buf, mut events) = (String::new(), vec![]);+ while let Ok(Some(Ok(chunk))) = tokio::time::timeout(Duration::from_millis(1500), body.next()).await {+ buf.push_str(&String::from_utf8_lossy(&chunk));+ while let Some(i) = buf.find('\n') {+ let line: String = buf.drain(..=i).collect();+ if let Some(data) = line.trim_end().strip_prefix("data:")+ && let Ok(v) = serde_json::from_str::<Value>(data.trim_start())+ // A live usage refresh lands whenever the agents' usage poll finishes (later on a+ // busy machine); its shape is `hello.usage`'s.+ && v["type"] != "usage"+ {+ events.push(v);+ }+ }+ }+ events+}++/// Older apps read what the host sends: a removed or retyped field breaks them. This fails+/// until the field is kept, or `MIN_APP` is raised the two-release way and the snapshot+/// re-recorded. New fields only need recording (`CODYNC_UPDATE_WIRE_SHAPE=1`).+#[tokio::test]+async fn wire_shape_matches_the_snapshot() {+ if Command::new(common::python()).arg("--version").output().is_err() {+ eprintln!("skipping: Python not available");+ return;+ }+ let host = start_host().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_agent.py");+ let bot = host+ .call(+ "createBot",+ json!({+ "name": "Tester", "backend": "custom", "command": common::python_agent(&agent),+ "cwd": host.home.to_string_lossy(), "permission": "ask",+ }),+ )+ .await["bot"]["id"]+ .as_str()+ .unwrap()+ .to_owned();+ host.call("send", json!({"botId": bot, "text": "go", "clientNonce": "n1"})).await;+ let card = host.wait_for(&bot, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;+ host.call("respondPermission", json!({"entryId": card["id"], "optionId": "allow"})).await;+ host.wait_for(&bot, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ // A bot another bot created: its `createdBy`.+ let lead = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ let lead = host+ .call(+ "createBot",+ json!({"name": "Lead", "backend": "custom", "command": common::python_agent(&lead), "connectors": [],+ "permission": "auto", "manageTeam": true}),+ )+ .await["bot"]["id"]+ .as_str()+ .unwrap()+ .to_owned();+ host.call("send", json!({"botId": lead, "text": "MANAGE create_bot {\"name\": \"Made\"}", "clientNonce": "n2"}))+ .await;+ let made = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ assert!(made["data"]["text"].as_str().unwrap().starts_with("Done: "), "{made}");++ let hello = host.call("hello", json!({})).await;+ let min_app = hello["minApp"].as_str().unwrap().to_owned();+ let mut current = std::collections::BTreeMap::new();+ shape(&hello, "hello", &mut current);+ for ev in catch_up(&host).await {+ event_shape(&ev, &mut current);+ }+ assert!(current.keys().any(|k| k.starts_with("event:entry(tool)")), "the turn's entries are missing");++ let file = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(WIRE_SHAPE);+ let recorded: Value = std::fs::read_to_string(&file).map_or(Value::Null, |s| serde_json::from_str(&s).unwrap());+ let recorded_shapes: std::collections::BTreeMap<String, String> =+ serde_json::from_value(recorded["shapes"].clone()).unwrap_or_default();+ let (breaking, added) = shape_diff(&recorded_shapes, ¤t);+ let floor_raised = recorded["minApp"].as_str() != Some(min_app.as_str());+ assert!(+ breaking.is_empty() || floor_raised,+ "Older apps would break: {breaking:#?}\nKeep these fields, or follow the two-release rule \+ in docs/reference/compatibility.md: raise MIN_APP (host/src/compat.rs) once that iPhone \+ version is live, then re-record with {UPDATE_ENV}=1 cargo test --test e2e wire_shape"+ );+ if std::env::var_os(UPDATE_ENV).is_some() {+ let json = json!({"minApp": min_app, "shapes": current});+ std::fs::write(&file, serde_json::to_string_pretty(&json).unwrap() + "\n").unwrap();+ return;+ }+ assert!(+ breaking.is_empty() && added.is_empty() && !floor_raised,+ "The wire shape changed.\nAdded: {added:#?}\nRemoved or retyped (minApp was raised): {breaking:#?}\n\+ Record it with {UPDATE_ENV}=1 cargo test --test e2e wire_shape"+ );+}diff --git a/host/tests/routine_unread_e2e.rs b/host/tests/routine_unread_e2e.rsnew file mode 100644index 00000000..e4b07c4f--- /dev/null+++ b/host/tests/routine_unread_e2e.rs@@ -0,0 +1,65 @@+//! Routine results and subsequent replies each count once in the main chat.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use common::host::Host;+use serde_json::{Value, json};+use std::time::Duration;++async fn unread(host: &Host, bot: &str) -> Value {+ common::bot(&host.snapshot().await, bot)["unread"].clone()+}++async fn wait_for_run_cleanup(host: &Host, bot: &str, routine: &str) {+ tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let listing = host.call("routines", json!({"botId": bot})).await;+ if listing["runs"]+ .as_array()+ .unwrap()+ .iter()+ .any(|r| r["routineId"] == routine && r["status"] == "succeeded")+ && common::routine_sessions(&host.home) == 0+ {+ return;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .expect("routine must finish and release its session before the follow-up");+}++#[tokio::test]+async fn a_routine_result_and_a_followup_each_become_read_without_hidden_unreads() {+ let host = Host::start().await;+ let bot = host.fixture_bot("routine-unread", "team_agent.py", "").await;+ let saved = host+ .call(+ "saveRoutine",+ json!({"botId": bot, "name": "Status", "instruction": "Report status", "triggers": [{"type": "webhook"}]}),+ )+ .await;+ let routine = saved["routine"]["id"].as_str().unwrap();+ host.call("runRoutine", json!({"botId": bot, "id": routine})).await;+ wait_for_run_cleanup(&host, &bot, routine).await;+ let history = host.call("history", json!({"botId": bot})).await;+ let results: Vec<_> = history["entries"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)+ .collect();+ assert_eq!(results.len(), 1, "a routine has one visible result, without a second published copy");+ assert_eq!(unread(&host, &bot).await, 1);+ host.call("markRead", json!({"botId": bot})).await;+ assert_eq!(unread(&host, &bot).await, 0);++ host.reply(&bot, "FOLLOWUP").await;+ // Streaming the text does not make it unread until the host finalizes the reply.+ assert_eq!(unread(&host, &bot).await, 1);+ host.call("markRead", json!({"botId": bot})).await;+ assert_eq!(unread(&host, &bot).await, 0);+}diff --git a/host/tests/routines_e2e.rs b/host/tests/routines_e2e.rsindex 5c73598a..6c9d7c89 100644--- a/host/tests/routines_e2e.rs+++ b/host/tests/routines_e2e.rs@@ -6,6 +6,9 @@#[allow(dead_code)]mod common;+#[path = "routines_e2e/timeout.rs"]+mod timeout;+use serde_json::{Value, json};use std::path::PathBuf;use std::process::{Child, Command, Stdio};@@ -175,15 +178,11 @@ async fn routines_execute_pause_deduplicate_and_reject_wrong_webhook_keys() {.await.unwrap();assert_eq!(first["run"]["id"], second["run"]["id"]);- let db = rusqlite::Connection::open(host.home.join("codync.db")).unwrap();- let run_sessions = || -> i64 {- db.query_row("SELECT COUNT(*) FROM kv WHERE k GLOB 'lane.session.*/routine-*'", [], |r| r.get(0)).unwrap()- };tokio::time::timeout(Duration::from_secs(20), async {loop {let listing = host.call("routines", json!({"botId":bot})).await;// A finished run's session is forgotten.- if listing["runs"][0]["status"] == "succeeded" && run_sessions() == 0 {+ if listing["runs"][0]["status"] == "succeeded" && common::routine_sessions(&host.home) == 0 {break;}assert_ne!(listing["runs"][0]["status"], "failed", "{listing}");@@ -392,21 +391,6 @@ async fn busy_bot_keeps_work_pending_and_honors_pause_delete_and_edit_across_res}));}-#[tokio::test]-async fn a_hung_routine_times_out_and_the_next_task_still_runs() {- let host = Host::start().await;- let bot = host.stable_bot("timeout").await;- let hung = host.save(&bot, "hung", "BLOCK[forever] IGNORE_CANCEL", json!([{"type":"webhook"}]), 2).await;- let next = host.save(&bot, "next", "AFTER_TIMEOUT", json!([{"type":"webhook"}]), 30).await;- host.call("runRoutine", json!({"botId":bot,"id":hung})).await;- host.wait_event("timeout", "started", "BLOCK[forever]").await;- host.call("runRoutine", json!({"botId":bot,"id":next})).await;- let failed = host.wait_status(&bot, &hung, "failed").await;- assert!(failed["detail"].as_str().unwrap().contains("time limit"));- host.wait_status(&bot, &next, "succeeded").await;- host.wait_event("timeout", "finished", "AFTER_TIMEOUT").await;-}-#[tokio::test]async fn unavailable_resume_never_replays_work_in_a_fresh_session() {let mut host = Host::start().await;diff --git a/host/tests/routines_e2e/timeout.rs b/host/tests/routines_e2e/timeout.rsnew file mode 100644index 00000000..a5bca2ef--- /dev/null+++ b/host/tests/routines_e2e/timeout.rs@@ -0,0 +1,21 @@+//! Timeout recovery after the agent has finished cold startup.++use super::*;++#[tokio::test]+async fn a_hung_routine_times_out_and_the_next_task_still_runs() {+ let host = Host::start().await;+ let bot = host.stable_bot("timeout").await;+ // Exercise a hung prompt, not cold process startup (which can exceed 2 s on Windows).+ host.send(&bot, "WARMUP").await;+ host.wait_event("timeout", "finished", "WARMUP").await;+ let hung = host.save(&bot, "hung", "BLOCK[forever] IGNORE_CANCEL", json!([{"type":"webhook"}]), 2).await;+ let next = host.save(&bot, "next", "AFTER_TIMEOUT", json!([{"type":"webhook"}]), 30).await;+ host.call("runRoutine", json!({"botId":bot,"id":hung})).await;+ host.wait_event("timeout", "started", "BLOCK[forever]").await;+ host.call("runRoutine", json!({"botId":bot,"id":next})).await;+ let failed = host.wait_status(&bot, &hung, "failed").await;+ assert!(failed["detail"].as_str().unwrap().contains("time limit"));+ host.wait_status(&bot, &next, "succeeded").await;+ host.wait_event("timeout", "finished", "AFTER_TIMEOUT").await;+}