Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
failed-step-blocked: a failed or refused step that ends waiting on you shows as Blocked (13a) (#634)
Oleksandr Ivanchenkoe8e27a2eba3c
diff --git a/src/server/decide.rs b/src/server/decide.rsindex eb00f0df..3ba1a679 100644--- a/src/server/decide.rs+++ b/src/server/decide.rs@@ -89,6 +89,9 @@ pub struct Held {pub delivery_next: Option<super::routes::DeliveryNext>,/// What the held turn's delivery did so far (an image it shared counts for the decided reply).pub delivery_seen: Option<super::routes::DeliverySeen>,+ /// 13a: the held turn's declined card or failed last step, which its decided reply (a new+ /// turn, with its own activity) counts like its own.+ pub failed_before: super::delivery_check::FailedBefore,}/// Shared with a turn's save step (see [`TurnOpts`]): whether to hold a reply with open choices,@@ -779,6 +782,7 @@ pub(super) async fn decide(scope: &TurnScope, kwant: &Kwant, mut held: Held) ->opts.delivery = held.delivery.clone();opts.delivery_next = held.delivery_next.clone();opts.delivery_seen = held.delivery_seen.clone();+ opts.failed_before = held.failed_before;let mut extra = json!({"decide_first": {"consulted": consulted, "held_turn_id": held.turn_id, "kwant_id": kwant.id}});// The decided reply answers the same routed message: it keeps the routing line and "Wrong bot?"if let Some(routing) = held.meta.as_ref().map(|m| &m["routing"]).filter(|r| !r.is_null()) {diff --git a/src/server/delivery_check.rs b/src/server/delivery_check.rsindex ad238279..99b95976 100644--- a/src/server/delivery_check.rs+++ b/src/server/delivery_check.rs@@ -296,6 +296,101 @@ pub fn promise_line(reply: &str) -> Option<String> {})}+/// Plain asks of the person (13a): "Send me the URL", "paste the output", "approve the command",+/// "tell me to run it". Matched as whole words, and not in a sentence that opens with the bot's own+/// plan ("I'll share…").+const ASKS_PERSON: &[&str] = &["send me", "paste", "share", "upload", "allow", "approve", "sign in", "log in", "connect", "tell me"];+/// Offers, not waits: a reply that only offers ("Let me know if…", "If you'd like, I can…") goes on+/// without the person, so these words are taken out before looking for a wait.+const OFFERS: &[&str] = &[+ "let me know", "i'll be here", "if you want", "if you'd like", "if you would like", "if you like", "if you prefer",+ "if you need anything",+];+/// How much of the ending [`waits_on_person`] keeps.+const WAIT_CHARS: usize = 300;++/// The reply's ending when it waits on the person in prose (13a): its last paragraph has a sentence+/// that waits ("If you approve it, I'll run it", "once you…", "until you…") or asks plainly ("Send me+/// the correct URL", "paste the output", "sign in"), and it isn't a `Done:` or `Blocked:` line or a+/// question (a question is asked on its own path). Returns that paragraph, markdown aside, cut to+/// about [`WAIT_CHARS`] at a word boundary.+pub fn waits_on_person(reply: &str) -> Option<String> {+ if super::keep_going::done_line(reply).is_some() || super::keep_going::blocked_line(reply).is_some() {+ return None;+ }+ let para = reply.split("\n\n").map(str::trim).filter(|p| !p.is_empty()).last()?;+ let bare = para.lines().map(strip_markdown).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ").replace(['’', '‘'], "'");+ let mut lower = bare.to_ascii_lowercase();+ if lower.trim_end_matches(['*', '_', '`', ')', ' ']).ends_with('?') {+ return None;+ }+ for offer in OFFERS {+ lower = lower.replace(offer, "");+ }+ let waits = sentence_spans(&lower).into_iter().any(|(at, end)| {+ let s = lower[at..end].trim_start();+ let planned = PROMISE_OPENERS.iter().any(|o| strip_leads(s).starts_with(o));+ NOT_A_PROMISE.iter().any(|w| s.contains(w)) || (!planned && ASKS_PERSON.iter().any(|w| has_words(s, w)))+ });+ waits.then(|| cut_at_word(&bare, WAIT_CHARS))+}++/// What went wrong before a turn's own tool steps (13a), for [`failed_step_blocked`].+#[derive(Debug, Clone, Copy, Default, PartialEq)]+pub struct FailedBefore {+ /// A step failed before the turn's own tools: kwnt couldn't open the request's link before the+ /// turn, or the held turn this decided reply replaces ended on a failed step. Counts when the+ /// turn ran no tool after it.+ pub failed: bool,+ /// The person declined an approval card in the held turn this decided reply replaces. Counts+ /// like a card declined in the turn itself.+ pub declined: bool,+}++impl FailedBefore {+ /// What a turn that ends held (see [`super::decide::Held`]) leaves for its decided reply: its+ /// last tool step failed (or its link didn't open and no tool ran after), or it had a declined+ /// card. The decided reply runs as a new turn, so these aren't in its own activity.+ pub fn of_turn(activity: Option<&Value>, before: FailedBefore) -> Self {+ let (ran_tools, failed, declined) = tool_steps_in(activity);+ Self { failed: failed.is_some() || (before.failed && !ran_tools), declined: declined || before.declined }+ }+}++/// What a finished turn is blocked on (13a), for `meta.blocked`: its last tool step failed, the+/// person declined an approval card in it, or a step failed `before` its tools and it ran no tool+/// after that; and its reply ends waiting on the person in prose with no `Done:` or `Blocked:` line+/// ([`waits_on_person`]). `activity` is the turn's saved activity.+pub fn failed_step_blocked(reply: &str, activity: Option<&Value>, before: FailedBefore) -> Option<String> {+ let after = FailedBefore::of_turn(activity, before);+ if !after.failed && !after.declined {+ return None;+ }+ waits_on_person(reply)+}++/// `words` in `text` as whole words (ASCII letters and digits around it don't count).+fn has_words(text: &str, words: &str) -> bool {+ text.match_indices(words).any(|(at, m)| {+ let before = text[..at].chars().next_back();+ let after = text[at + m.len()..].chars().next();+ !before.is_some_and(|c| c.is_ascii_alphanumeric()) && !after.is_some_and(|c| c.is_ascii_alphanumeric())+ })+}++/// `text` cut to at most `max` characters at a word boundary, with "…" when cut.+fn cut_at_word(text: &str, max: usize) -> String {+ if text.chars().count() <= max {+ return text.to_string();+ }+ let head: String = text.chars().take(max).collect();+ let head = match head.rfind(char::is_whitespace) {+ Some(i) if i > 0 => &head[..i],+ _ => &head[..],+ };+ format!("{}…", head.trim_end_matches([',', ';', ':', ' ']))+}+/// A line without its leading list marker, heading or quote, and the emphasis around it.fn strip_markdown(line: &str) -> String {let mut s = line.trim();@@ -1046,4 +1141,105 @@ mod tests {assert_eq!(text, format!("{REAL}\n\nRendered with ffmpeg instead: out.mp4."));assert_eq!(last.follow_line, None);}+++ /// The endings of tasks 9 and 10 in Lin's long-task suite (autonomy/long-task-suite/runs,+ /// 093-results.json and 535-results.json): both wait on the person in prose.+ const T9_093: &str = "I didn't run the tests because you denied the approval for the shell command, so I have no result to report.\n\nI would have run `python3 -m unittest` in `/tmp/lts/full/093/run1/t9/work` and reported the pass/fail counts and any failures. If you approve the command, I'll run it right away.";+ const T9_535: &str = "I couldn't run the tests. You denied the approval for the shell command, so `python3 -m unittest` never ran and I have no result to report.\n\nThe command I tried was `python3 -m unittest` from `/tmp/lts/full/535/run1/t9/work`. If you approve it, I'll run it and report the result. You can also run it yourself and paste the output here, and I'll go through any failures with you.";+ const T10_093: &str = "I couldn't download the invoice. `https://billing.example.invalid/invoices` didn't resolve (`net::ERR_NAME_NOT_RESOLVED`), so the page never loaded and nothing was saved to `/tmp/lts/full/093/run1/t10/work/invoice.pdf`.\n\nThe `.invalid` ending is reserved and can never resolve, so this looks like a placeholder address and not your real billing site. I can't guess the real one. Send me the correct URL, for example `https://billing.<yourprovider>.com/invoices`, and I'll open it. If the page needs a login, I'll ask you to sign in in the browser panel, then I'll download the latest invoice and save it as `invoice.pdf`.";+ const T10_535: &str = "I couldn't download the invoice. `https://billing.example.invalid/invoices` didn't resolve (`net::ERR_NAME_NOT_RESOLVED`), so no page loaded and nothing was saved to `invoice.pdf`.\n\nThe `.invalid` ending is a reserved placeholder domain that can never resolve, so it is probably a stand-in and not your real billing address. I can't guess the right one. Look for it in your invoice emails or in your account's billing section. It will usually be something like `billing.<provider>.com/invoices`.\n\nSend me the correct URL and I'll open it. If the site needs a login, I'll ask you to sign in in the browser panel. Then I'll download the latest invoice and save it as `invoice.pdf` in `/tmp/lts/full/535/run1/t10/work`.";+ // Task 9, PR build run 2: the decided reply after the held one (decide first)+ const T9_PR_HELD: &str = "I haven't run the tests, because you declined the approval for `python3 -m unittest` and I didn't ask again. So there is no actual test result.\n\nI haven't edited anything. Running `python3 -m unittest` in that folder would confirm the prediction. Tell me if you want me to run it, or paste the output and I'll check it against the table.";++ #[test]+ fn a_prose_ask_waits_on_the_person() {+ // The real endings: the last paragraph, markdown aside, cut to about 300 characters+ assert_eq!(+ waits_on_person(T9_093).as_deref(),+ Some("I would have run `python3 -m unittest` in `/tmp/lts/full/093/run1/t9/work` and reported the pass/fail counts and any failures. If you approve the command, I'll run it right away.")+ );+ let t9 = waits_on_person(T9_535).unwrap();+ assert!(t9.starts_with("The command I tried was") && t9.contains("If you approve it, I'll run it"), "{t9}");+ for real in [T10_093, T10_535] {+ let w = waits_on_person(real).unwrap();+ assert!(w.chars().count() <= WAIT_CHARS + 1, "{w}");+ assert!(w.contains("Send me the correct URL"), "{w}");+ }+ assert!(waits_on_person(T10_093).unwrap().ends_with('…'), "cut at a word boundary");+ assert!(!waits_on_person(T10_535).unwrap().ends_with('…'), "short enough to keep whole");+ // Plain asks, each as whole words+ for ask in [+ "The page needs a login.\n\nPlease sign in in the browser panel and say continue.",+ "**Upload the CSV** to this chat and I'll combine it.",+ "- Paste the error message here.",+ "Connect your Google account in Settings, then I can read the sheet.",+ "Allow Terminal for this team.",+ "I'll run it as soon as you turn Terminal on.",+ // Task 9 endings of the PR build after a declined card (decided replies, diag runs 2 and 3)+ "The real result is still unconfirmed. If you want it, run `cd work && python3 -m unittest`, or tell me to run it and I'll do so.",+ "If you approve the command, I'll run it and confirm. You can also run `python3 -m unittest` in that folder and paste me the output.",+ ] {+ assert!(waits_on_person(ask).is_some(), "{ask}");+ }+ // A promise ("I'll share…" is the bot's own plan), a Done: or Blocked: line, a question,+ // an offer, or a word that only contains an ask ("connection", "shared", "allowed")+ for not in [+ "The render failed.\n\nI'll retry the render with a smaller size next.",+ "The build failed. Next I'll share the logs with Lin.",+ "Fixed it.\n\nDone: the tests pass.",+ "Blocked: no key for the Stripe API. Add it in Settings.",+ "I can't reach the site. Should I try the mirror instead?",+ "Here's the summary.\n\nLet me know if you want changes.",+ "If you'd like, I can also add a chart.",+ "The connection failed, so I used the cached copy. The report is shared in the folder and the tests are allowed to run.",+ "",+ ] {+ assert_eq!(waits_on_person(not), None, "{not}");+ }+ }++ #[test]+ fn a_failed_or_declined_step_and_a_prose_ask_are_blocked() {+ let steps = |s: Value| Some(json!({ "steps": s }));+ let none = FailedBefore::default();+ let page = FailedBefore { failed: true, declined: false };+ let failed = steps(json!([{ "kind": "tool", "tool": "Bash", "status": "failed", "title": "python3 -m unittest" }]));+ let declined = steps(json!([{ "kind": "approval", "status": "declined" }, { "kind": "tool", "tool": "Read", "status": "ok" }]));+ let fine = steps(json!([{ "kind": "tool", "tool": "Bash", "status": "failed" }, { "kind": "tool", "tool": "Bash", "status": "ok" }]));+ // The last tool step failed, or the person declined a card: the ending is blocked+ assert_eq!(failed_step_blocked(T9_093, failed.as_ref(), none).as_deref(), waits_on_person(T9_093).as_deref());+ assert!(failed_step_blocked(T9_535, declined.as_ref(), none).is_some());+ // The request's link didn't open before the turn (task 10) and no tool ran after it+ assert_eq!(failed_step_blocked(T10_535, None, page).as_deref(), waits_on_person(T10_535).as_deref());+ assert!(failed_step_blocked(T10_093, steps(json!([])).as_ref(), page).is_some());+ // ...but a tool that ran fine after it (the bot found the page another way) clears it+ let ok = steps(json!([{ "kind": "tool", "tool": "WebSearch", "status": "ok" }]));+ assert_eq!(failed_step_blocked(T10_535, ok.as_ref(), page), None);+ // No failed step (an earlier one recovered), or no tools and the link opened: nothing to store+ assert_eq!(failed_step_blocked(T9_093, fine.as_ref(), none), None);+ assert_eq!(failed_step_blocked(T10_535, None, none), None);+ // A failed step and an ending that doesn't wait (a promise, an explicit Blocked: line,+ // which the save step keeps in its own words): none from here+ assert_eq!(failed_step_blocked("It failed.\n\nI'll retry it next.", failed.as_ref(), none), None);+ assert_eq!(failed_step_blocked("It failed.\nBlocked: Terminal is off. Allow it, then say continue.", failed.as_ref(), none), None);+ // A held reply's decided turn (decide first) runs as a new turn: what the held turn's steps+ // left counts as if it were the decided turn's own. Task 9, 2nd run of the PR build: the+ // card was declined in the held turn, the decided turn only read the files+ let held = steps(json!([{ "kind": "approval", "status": "declined" }, { "kind": "tool", "tool": "Bash", "status": "failed" }]));+ let left = FailedBefore::of_turn(held.as_ref(), none);+ assert_eq!(left, FailedBefore { failed: true, declined: true });+ let reads = steps(json!([{ "kind": "tool", "tool": "Bash", "status": "ok" }, { "kind": "tool", "tool": "Read", "status": "ok" }]));+ assert_eq!(failed_step_blocked(T9_PR_HELD, reads.as_ref(), left).as_deref(), waits_on_person(T9_PR_HELD).as_deref());+ assert!(waits_on_person(T9_PR_HELD).is_some_and(|t| t.contains("paste the output")));+ assert_eq!(failed_step_blocked(T9_PR_HELD, reads.as_ref(), none), None, "nothing failed in its own turn");+ // A held turn's failed step (no card) counts only while the decided turn runs no tool+ let failed_only = FailedBefore::of_turn(failed.as_ref(), none);+ assert_eq!(failed_only, FailedBefore { failed: true, declined: false });+ assert!(failed_step_blocked(T9_093, None, failed_only).is_some());+ assert_eq!(failed_step_blocked(T9_093, reads.as_ref(), failed_only), None);+ // ...and a link that didn't open carries over the same way, unless a tool ran after it+ assert_eq!(FailedBefore::of_turn(None, page), page);+ assert_eq!(FailedBefore::of_turn(reads.as_ref(), page), none);+ }}diff --git a/src/server/keep_going.rs b/src/server/keep_going.rsindex f7ea231c..8376908e 100644--- a/src/server/keep_going.rs+++ b/src/server/keep_going.rs@@ -14,7 +14,9 @@//! The `Done:` line is stored on the reply's meta as [`DONE_KEY`]. A lead whose last line is//! `Blocked: <what is blocked>. <what would unblock it>` (0.9.4) never gets a keep-going turn: the//! line becomes a question card at once, like a question, and its answer resumes the chain. The-//! save step stores any reply's `Blocked:` line on its meta as [`BLOCKED_KEY`].+//! save step stores any reply's `Blocked:` line on its meta as [`BLOCKED_KEY`], and (13a) the+//! ending of a reply that waits on the person in prose after a failed or declined tool step; that+//! stored text counts the same.use super::routes::{try_kwant_turn, TurnOpts, TurnScope};use super::AppState;@@ -119,6 +121,18 @@ async fn lead_delegations(state: &AppState, context: &str, lead: &Kwant) -> Vec<.collect()}+/// The `meta.blocked` text saved on `lead`'s `reply` (its newest message with that text that is new+/// since `snap`), if any.+fn saved_blocked(msgs: &[Message], snap: &Snapshot, lead: &Kwant, reply: &str) -> Option<String> {+ let reply = msgs+ .iter()+ .rev()+ .filter(|m| !snap.messages.contains(&m.id))+ .find(|m| m.sender_role == "kwant" && (m.sender_id == lead.id || m.sender_id == lead.name) && m.text.trim() == reply.trim())?;+ let text = meta_of(reply)[BLOCKED_KEY]["text"].as_str()?.trim().to_string();+ (!text.is_empty()).then_some(text)+}+fn meta_of(m: &Message) -> Value {m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)}@@ -196,6 +210,11 @@ async fn verdict(scope: &TurnScope, lead: &Kwant, snap: &Snapshot, reply: &str)if let Some(blocked) = blocked_line(reply) {return Verdict::Asks(format!("Blocked: {blocked}"));}+ // ...or the save step found it blocked without the line (13a: a failed or declined step and a+ // reply that waits on the person in prose), on the lead's newest reply of this turn+ if let Some(blocked) = saved_blocked(&msgs, snap, lead, reply) {+ return Verdict::Asks(format!("Blocked: {blocked}"));+ }let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();if let Some(q) = crate::router::sticky::person_question(reply).filter(|_| !super::asks::hands_on(reply, &names)) {return Verdict::Asks(q);diff --git a/src/server/routes.rs b/src/server/routes.rsindex b8da4934..c56a5c4a 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2083,6 +2083,9 @@ pub(super) struct TurnOpts {/// with "No picture was attached". Each [`try_kwant_turn`] starts a new one, so a later ask/// never inherits it. `None`: only the turn's own pictures and pushes count.pub(super) delivery_seen: Option<DeliverySeen>,+ /// 13a: what the held turn this decided reply replaces left (a declined card, a failed last+ /// step), so the save step counts it like the turn's own (see [`super::decide::Held`]).+ pub(super) failed_before: super::delivery_check::FailedBefore,/// The chat slot passed from a turn to its delivery continuation: the first turn leaves its/// slot here when it holds the chat and the save step asked for a continuation, and the/// continuation starts on it instead of queueing. So a message that arrived meanwhile (and@@ -3023,6 +3026,9 @@ async fn run_kwant_turn_inner(let mut final_prompt = prompt.clone();// A replay opens no page: the bot's browser isn't its scratch folderlet target_url_opt = if opts.rehearse.is_some() || opts.no_tools { None } else { opts.nav_target() };+ // 13a: the request's link couldn't be opened before the turn (it didn't load, or a site rule+ // refused it). A failed first step that isn't in the turn's activity+ let mut page_failed = false;if let Some(target_url) = target_url_opt {event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(@@ -3079,6 +3085,7 @@ async fn run_kwant_turn_inner(};}Err(crate::sandbox::BrowserError::Navigation(reason)) => {+ page_failed = true;let shown_url = ctrl.current_url.lock().await.clone().unwrap_or_else(|| target_url.clone());if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {event_broadcast.send(RuntimeEvent::BrowserScreenshot {@@ -3094,6 +3101,7 @@ async fn run_kwant_turn_inner();}Err(crate::sandbox::BrowserError::SiteRule(refusal)) => {+ page_failed = true;final_prompt = format!("{}\n\n[Sandbox Browser State: {} Tell the user this address is outside the sites your browser may open; don't try another way to reach it.]",prompt, refusal.message@@ -4006,8 +4014,22 @@ async fn run_kwant_turn_inner(meta.get_or_insert_with(|| serde_json::json!({}))["delivery"] = delivery;}// 0.9.4: a reply that ends with `Blocked: <what>. <what unblocks it>` says so in its meta- if let Some(blocked) = super::keep_going::blocked_line(&asst_msg.text) {- meta.get_or_insert_with(|| serde_json::json!({}))[super::keep_going::BLOCKED_KEY] = serde_json::json!({ "text": blocked });+ // 13a: with no such line, a turn whose last tool step failed (or was declined, or whose+ // link didn't open and it ran no tool) and whose reply ends waiting on the person in+ // prose is blocked too, in the bot's own words. Not while kwnt sends the turn one more+ // try (a continuation): that reply isn't the last word. A decided reply counts what+ // its held turn left too+ let before = super::delivery_check::FailedBefore { failed: page_failed || opts.failed_before.failed, ..opts.failed_before };+ let blocked = super::keep_going::blocked_line(&asst_msg.text)+ .map(|text| serde_json::json!({ "text": text }))+ .or_else(|| {+ let text = super::delivery_check::failed_step_blocked(&asst_msg.text, activity.as_ref(), before).filter(|_| verdict.continue_with.is_none() || opts.delivery_next.is_none())?;+ Some(serde_json::json!({ "text": text, "from": "failed_step" }))+ });+ // ...and if this reply is held, its decided reply (a new turn) counts what this one left+ let failed_before = super::delivery_check::FailedBefore::of_turn(activity.as_ref(), before);+ if let Some(blocked) = blocked {+ meta.get_or_insert_with(|| serde_json::json!({}))[super::keep_going::BLOCKED_KEY] = blocked;}let meta = super::decide::with_decisions(meta, &decisions);let meta = super::activity::with_activity(meta, activity);@@ -4047,6 +4069,7 @@ async fn run_kwant_turn_inner(delivery: plan.clone(),delivery_next: opts.delivery_next.clone(),delivery_seen: opts.delivery_seen.clone(),+ failed_before,});}}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 18f48710..f7fd5d32 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -19,8 +19,9 @@//! slow reply, or a stall when it waits past the stall limit).//! - `FAILTURN`: die with no output. `APIERROR:<tag>` / `APIERRORPLAIN:<tag>`: end with "API Error://! 500 test stub" as claude's error result / as plain text, once per tag.-//! - `FAILSTEP:<tag>` / `BLOCKSTEP:<tag>` in the current request (not the history): run a Bash-//! tool step that fails, then end on a plan ("I'll retry the render…") / on a `Blocked:` line.+//! - `FAILSTEP:<tag>` / `BLOCKSTEP:<tag>` / `WAITSTEP:<tag>` in the current request (not the+//! history): run a Bash tool step that fails, then end on a plan ("I'll retry the render…") / on a+//! `Blocked:` line / waiting on the person in prose ("If you approve the command, …").//! - `STREAMLINES:<base64 text>`: print that text (claude `stream-json` lines: an init line, tool//! calls and their results) before the reply; once per marker.//!@@ -100,10 +101,10 @@ if cap:text = "partial " + cap[-1] + noteprint(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": text}))sys.exit(0)-# FAILSTEP:<tag> / BLOCKSTEP:<tag> in the current request: a Bash step that fails, then a reply-# that ends on a plan / on a Blocked: line+# FAILSTEP:<tag> / BLOCKSTEP:<tag> / WAITSTEP:<tag> in the current request: a Bash step that fails,+# then a reply that ends on a plan / on a Blocked: line / waiting on the person in prosereq = prompt.rsplit("Current User Request:\n", 1)[-1]-fs = re.findall(r"(FAIL|BLOCK)STEP:([A-Za-z0-9_]+)", req)+fs = re.findall(r"(FAIL|BLOCK|WAIT)STEP:([A-Za-z0-9_]+)", req)if fs:kind, tag = fs[-1]tid = "toolu_" + tag@@ -111,8 +112,9 @@ if fs:{"type": "tool_use", "id": tid, "name": "Bash", "input": {"command": "render.sh", "description": "render the intro"}}]}}))print(json.dumps({"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": tid, "is_error": True, "content": "Permission to use Bash has been denied."}]}}))- end = ("I'll retry the render with a smaller size next." if kind == "FAIL"- else "Blocked: terminal commands are off for this bot. Allow Terminal for this team, then say continue.")+ end = {"FAIL": "I'll retry the render with a smaller size next.",+ "BLOCK": "Blocked: terminal commands are off for this bot. Allow Terminal for this team, then say continue.",+ "WAIT": "If you approve the command, I'll run the render right away."}[kind]print(json.dumps({"type": "result", "is_error": False, "num_turns": 2,"result": "The render command was refused (" + tag + ").\n\n" + end}))sys.exit(0)diff --git a/tests/decide_first_test.rs b/tests/decide_first_test.rsindex e59129be..9cb582b9 100644--- a/tests/decide_first_test.rs+++ b/tests/decide_first_test.rs@@ -27,10 +27,12 @@ use std::time::Duration;use tower::ServiceExt;/// - kwant's one automatic delivery continuation: a reply with a PR link;+/// - the hidden round's prompt for REFUSED's held reply: a decided reply that waits on the person;/// - the hidden round's prompt: a decided reply with a [DECISIONS] block;/// - a teammate's view: "I'd pick B";/// - CHOICE: the screenshot's ending ("A, B or C?"), naming Bob;/// - SEND: an ask about sending an email;+/// - REFUSED: a Bash step that fails (refused), then an ask to pick (13a);/// - anything else: "answer".const FAKE_CLAUDE: &str = r#"#!/bin/shcase "$1" in@@ -39,10 +41,16 @@ esacfor a; do last="$a"; donecase "$last" in*"[kwnt: one automatic continuation."*) out='Pushed the footer change: https://github.com/o/r/pull/7' ;;+ *"[Decide first] Your last reply"*"unittest run was refused"*)+ out="I went with B and read the code: one test should fail.\n\nIf you approve the command, I'll run the unittest suite and confirm." ;;*"[Decide first] Your last reply"*)out='I checked contrast on A and C and went with B: Wax seal. Change it any time.\n\n[DECISIONS]\nquestion: Which direction? | options: A: Classic; B: Wax seal; C: Green desk | picked: B: Wax seal | why: reads best\n[/DECISIONS]' ;;*"[Decide first]"*) out="I'd pick B: it reads best." ;;*CHOICE*) out='Three directions are ready. Bob only looked at B; nobody looked at A and C.\n\nTwo decisions for you:\n1. A, B or C?\n2. FM monogram or plain?' ;;+ *REFUSED*)+ printf '{"type":"assistant","message":{"id":"msg_f","content":[{"type":"tool_use","id":"toolu_f","name":"Bash","input":{"command":"python3 -m unittest"}}]}}\n'+ printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_f","is_error":true,"content":"The user denied this tool call."}]}}\n'+ out='The unittest run was refused, so I have no result yet. Bob can check the code.\n\nTwo decisions for you:\n1. A, B or C?\n2. Verbose or quiet?' ;;*SEND*) out='The draft is ready.\n\nShould I send the email to Mia now, or wait until Monday?' ;;*) out="answer" ;;esac@@ -330,3 +338,28 @@ async fn a_decided_change_without_a_link_is_continued_once() {assert!(replies[1].text.ends_with("No picture was attached to this reply."), "{}", replies[1].text);assert!(replies[0].created_at <= replies[1].created_at);}++/// 13a: the held turn's step was refused and the decided reply (a new turn, with none of its own+/// steps) ends waiting on the person in prose: it is blocked, in the decided reply's own words.+/// Task 9 of the long-task suite missed this way on the PR build before the held turn's steps+/// were carried over.+#[tokio::test]+async fn a_refused_step_in_the_held_turn_makes_the_decided_reply_blocked() {+ let env = setup().await;+ env.say("@Ann run the tests REFUSED").await;+ let reply = env.wait_for_reply().await;+ assert_eq!(reply.text, "I went with B and read the code: one test should fail.\n\nIf you approve the command, I'll run the unittest suite and confirm.");+ let m = meta(&reply);+ assert!(m["decide_first"]["held_turn_id"].is_string(), "{m}");+ assert!(!m["activity"]["steps"].as_array().into_iter().flatten().any(|s| s["status"] == "failed"), "the failed step was in the held turn: {m}");+ assert_eq!(m["blocked"], json!({"text": "If you approve the command, I'll run the unittest suite and confirm.", "from": "failed_step"}));+}++/// ...and a held reply with no failed step stays unblocked when decided.+#[tokio::test]+async fn a_decided_reply_without_a_failed_step_is_not_blocked() {+ let env = setup().await;+ env.say("@Ann make three directions for the hero CHOICE").await;+ let reply = env.wait_for_reply().await;+ assert!(meta(&reply)["blocked"].is_null(), "{}", meta(&reply));+}diff --git a/tests/follow_through_test.rs b/tests/follow_through_test.rsindex 0f9c9992..c52bbeb0 100644--- a/tests/follow_through_test.rs+++ b/tests/follow_through_test.rs@@ -1,7 +1,8 @@//! 0.9.4 follow-through: a turn whose last tool step failed and whose reply ends on a plan it//! didn't carry out ("I'll retry the render…") gets exactly one automatic continuation, with no//! delivery plan needed. A reply that ends with `Blocked: …` instead gets none, and its meta keeps-//! the line (`meta.blocked`).+//! the line (`meta.blocked`). So does one that ends waiting on the person in prose (13a): its meta+//! keeps that ending, from "failed_step".//!//! The bot's folder isn't a git repository and the asks aren't for a picture or a change, so//! nothing but follow-through can continue them.@@ -58,6 +59,7 @@ async fn a_failed_step_and_a_promise_get_one_continuation() {let first = meta_of(&replies[0]);assert_eq!(first["delivery"]["missing"], serde_json::json!(["follow_through"]), "{first}");assert_eq!(first["delivery"]["continues"], true, "{first}");+ assert!(first.get("blocked").is_none(), "a plan, not a wait: {first}");let steps = first["activity"]["steps"].as_array().cloned().unwrap_or_default();assert!(steps.iter().any(|s| s["kind"] == "tool" && s["status"] == "failed"), "the failed step is in the activity: {first}");@@ -101,3 +103,26 @@ async fn a_blocked_line_ends_it_without_a_continuation() {assert!(!all.iter().any(|r| r.contains(FOLLOW)), "{all:#?}");assert_eq!(all.len(), 1, "{all:#?}");}++#[tokio::test]+async fn a_failed_step_and_a_prose_ask_are_blocked_without_a_continuation() {+ let env = setup().await;+ let a = env.a.clone();+ send_direct(&env, &a, "How long are the credits' frames? WAITSTEP:zqwait REPLYTAG:zqwait", serde_json::json!({})).await;+ wait_for("a reply", || async { !replies_of(&env, &a).await.is_empty() }).await;+ wait_for("the bot to finish", || async { bot_idle(&env, &a) }).await;+ tokio::time::sleep(Duration::from_millis(800)).await;++ let replies = replies_of(&env, &a).await;+ assert_eq!(replies.len(), 1, "no continuation: {replies:#?}");+ let meta = meta_of(&replies[0]);+ assert_eq!(+ meta["blocked"],+ serde_json::json!({"text": "If you approve the command, I'll run the render right away.", "from": "failed_step"}),+ "{meta}"+ );+ assert_ne!(meta["delivery"]["continues"], true, "{meta}");+ let all = requests(&env);+ assert!(!all.iter().any(|r| r.contains(FOLLOW)), "{all:#?}");+ assert_eq!(all.len(), 1, "{all:#?}");+}diff --git a/tests/keep_going_test.rs b/tests/keep_going_test.rsindex d986af51..bd74a824 100644--- a/tests/keep_going_test.rs+++ b/tests/keep_going_test.rs@@ -30,7 +30,8 @@ use tower::ServiceExt;/// queue `<dir>/res`), or anything else (the lead's first turn, a teammate's task, a turn on an/// answer), which replies "ok"; a teammate's task with "SPECHOLD:<file>" waits for that file/// first. Each queue line is one reply (`\n` for a line break); an empty queue replies "Here is-/// where things stand.". A line "HOLD:<file> <reply>" waits for the file, then replies. Every+/// where things stand.". A line "HOLD:<file> <reply>" waits for the file, then replies; a line+/// "FAILED:<reply>" runs a Bash step that fails first, then replies. Every/// prompt is saved as `<dir>/prompts/<kind>-…`.const FAKE_CLAUDE: &str = r#"#!/bin/shcase "$1" in@@ -62,6 +63,11 @@ elseout="Here is where things stand."ficase "$out" in+ FAILED:*)+ out=${out#FAILED:}+ printf '{"type":"assistant","message":{"id":"msg_f","content":[{"type":"tool_use","id":"toolu_f","name":"Bash","input":{"command":"run_tests.sh"}}]}}\n'+ printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_f","is_error":true,"content":"Permission to use Bash has been denied."}]}}\n'+ ;;HOLD:*)f=${out#HOLD:}; f=${f%% *}; out=${out#HOLD:* }i=0@@ -407,6 +413,31 @@ async fn a_blocked_line_becomes_a_card_not_a_keep_going_turn() {assert_eq!(meta_of(last)[keep_going::DONE_KEY]["text"], "rendered the intro and checked its length.");}+/// 13a: a lead whose last tool step failed and whose reply waits on the person in prose, with no+/// `Blocked:` line, is blocked too: its ending is stored as `meta.blocked` (from "failed_step") and+/// becomes a question card at once, never a keep-going turn.+#[tokio::test]+async fn a_failed_step_and_a_prose_ask_become_a_card_not_a_keep_going_turn() {+ let env = setup().await;+ env.queue("res", &["FAILED:The test run was refused, so I have no results.\\n\\nIf you approve the command, I'll run the tests and report back."]);+ person_asks(&env, "Run the tests.").await;+ hand_off(&env, "Check the test setup", true).await;+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;+ settled(&env).await;+ assert!(env.prompts("kg").is_empty(), "blocked: asked, never pushed on");+ let msgs = messages(&env).await;+ let reply = lead_replies(&env, &msgs).into_iter().find(|m| m.text.starts_with("The test run was refused")).expect("the reply");+ let meta = meta_of(reply);+ let steps = meta["activity"]["steps"].as_array().cloned().unwrap_or_default();+ assert!(steps.iter().any(|s| s["kind"] == "tool" && s["status"] == "failed"), "the failed step is in the activity: {meta}");+ let text = "If you approve the command, I'll run the tests and report back.";+ assert_eq!(meta[keep_going::BLOCKED_KEY], json!({"text": text, "from": "failed_step"}));+ let open = open_questions(&env).await;+ assert_eq!(open.len(), 1, "{open:?}");+ assert_eq!(open[0].question, format!("Blocked: {text}"));+ assert_eq!(card_meta(&env, &open[0]).await[keep_going::ASK_KEY], true);+}+/// Two keep-going turns that still hand nothing on: one "Keep going?" card, never a second./// "Keep going" is a person message: a fresh allowance and a keep-going turn at once.#[tokio::test]