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
22m: a file dropped while the browser card is open reaches the bot at once (#721)
Oleksandr Ivanchenko11907697a225
diff --git a/frontend/src/components/HumanStepCard.tsx b/frontend/src/components/HumanStepCard.tsxindex 26b30c52..063db693 100644--- a/frontend/src/components/HumanStepCard.tsx+++ b/frontend/src/components/HumanStepCard.tsx@@ -1,5 +1,5 @@import React, { useState } from 'react';-import { CheckCircle2, Clock, Globe, Hand, Loader2, MinusCircle, MonitorPlay, Puzzle } from 'lucide-react';+import { CheckCircle2, Clock, Globe, Hand, Loader2, MinusCircle, MonitorPlay, Paperclip, Puzzle } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { HumanStep, HumanStepMeta, KIND_TEXT, domainOf, humanStepView } from '../humanSteps';@@ -66,6 +66,11 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k<span className="inline-flex items-center gap-1.5 text-zinc-400"><MinusCircle size={13} className="shrink-0" aria-hidden="true" /> Skipped. {kwantName} continues without it.</span>+ ) : status === 'left_for_message' ? (+ // 22m: closed because the person sent a file, not because the step was done+ <span className="inline-flex items-center gap-1.5 text-zinc-400">+ <Paperclip size={13} className="shrink-0" aria-hidden="true" /> Closed: {kwantName} is reading the file you sent.+ </span>) : status === 'cancelled' ? (<span className="inline-flex items-center gap-1.5 text-zinc-400"><MinusCircle size={13} className="shrink-0" aria-hidden="true" /> Closed: the reply was stopped.diff --git a/frontend/src/humanSteps.ts b/frontend/src/humanSteps.tsindex baff3820..3dbbbf91 100644--- a/frontend/src/humanSteps.ts+++ b/frontend/src/humanSteps.ts@@ -4,7 +4,8 @@ import { parseMetaObject } from './questions';import { request } from './threads';export type HumanStepKind = 'sign_in' | 'captcha' | 'two_factor' | 'other';-export type HumanStepStatus = 'open' | 'done' | 'declined' | 'cancelled' | 'resolved_auto' | 'timed_out';+/** `left_for_message` (22m): the person sent a file while the bot waited, so the card closed and the bot reads it. */+export type HumanStepStatus = 'open' | 'done' | 'declined' | 'cancelled' | 'resolved_auto' | 'timed_out' | 'left_for_message';/** Where a CAPTCHA widget sits on the bot's page, in page pixels (1280×800). */export interface CaptchaTarget {@@ -53,7 +54,7 @@ export interface HumanStepMeta {}const STEP_KINDS: HumanStepKind[] = ['sign_in', 'captcha', 'two_factor', 'other'];-const STATUSES: HumanStepStatus[] = ['open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out'];+const STATUSES: HumanStepStatus[] = ['open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out', 'left_for_message'];const kindOf = (v: unknown): HumanStepKind => (STEP_KINDS.includes(v as HumanStepKind) ? (v as HumanStepKind) : 'other');const statusOf = (v: unknown): HumanStepStatus => (STATUSES.includes(v as HumanStepStatus) ? (v as HumanStepStatus) : 'open');diff --git a/frontend/tests/humanSteps.test.mjs b/frontend/tests/humanSteps.test.mjsindex fda37e2d..50be9456 100644--- a/frontend/tests/humanSteps.test.mjs+++ b/frontend/tests/humanSteps.test.mjs@@ -74,10 +74,42 @@ test('closed and stale cards', () => {assert.match(ui.render(props({ live: rec({ status: 'done' }) })), /Done\. Pixel is carrying on/);assert.match(ui.render(props({ live: rec({ status: 'declined' }) })), /Skipped/);assert.match(ui.render(props({ live: rec({ status: 'cancelled' }) })), /reply was stopped/);+ // 22m: a file sent while the bot waited closes the card, and it never reads "done"+ const left = ui.render(props({ live: rec({ status: 'left_for_message' }) }));+ assert.doesNotMatch(left, /<button/);+ assert.match(left, /Closed: Pixel is reading the file you sent\./);+ assert.doesNotMatch(left, /Done|carrying on|waiting for you/);+ assert.equal(h.parseHumanStepMeta(meta({ status: 'left_for_message' })).status, 'left_for_message');assert.match(ui.render(props({ waiting: false })), /stopped waiting/);assert.match(ui.render(props({ meta: h.parseHumanStepMeta(meta({ source: 'auto' })) })), /spotted automatically/);});+test('a late Done or Skip on a closed step reads as a sentence, never the raw status (22m round 2)', () => {+ const closed = ['done', 'declined', 'cancelled', 'resolved_auto', 'timed_out', 'left_for_message'];+ for (const status of closed) {+ for (const which of ['done', 'decline']) {+ const text = h.closedStepText(status, which, 'Pixel');+ assert.notEqual(text, undefined, `${status}/${which}: a closed step is mapped, so the raw 409 text never shows`);+ if (text === null) continue;+ assert.doesNotMatch(text, /left_for_message|resolved_auto|timed_out|already (open|declined|cancelled)\b/, `${status}/${which}: ${text}`);+ assert.doesNotMatch(text, /_/, `${status}/${which}: ${text}`);+ assert.match(text, /^[A-Z].*\.$/, `${status}/${which}: a sentence`);+ }+ }+ // The file closed the card: Done says it didn't land and what to do; Skip says nothing+ assert.equal(+ h.closedStepText('left_for_message', 'done', 'Pixel'),+ "This closed when you sent a file, so Pixel didn't get your Done. If you finished, say so in the chat.",+ );+ assert.equal(h.closedStepText('left_for_message', 'decline', 'Pixel'), null);+ // Other closed statuses show nothing: the card's footer already says how it ended (22v)+ assert.equal(h.closedStepText('done', 'done', 'Pixel'), null);+ assert.equal(h.closedStepText('declined', 'decline', 'Pixel'), null);+ assert.equal(h.closedStepText('cancelled', 'done', 'Pixel'), null);+ // An open step isn't closed: the caller keeps the real error+ assert.equal(h.closedStepText('open', 'done', 'Pixel'), undefined);+});+test('meta line is one inline text run that wraps like a sentence', () => {const html = ui.render(props({ meta: h.parseHumanStepMeta(meta({ source: 'auto' })) }));const m = html.match(/<p data-hs-meta=""([^>]*)>([^]*?)<\/p>/);@@ -138,6 +170,7 @@ test('card icons never shrink when a line wraps on a phone (shrink-0 on every ic'done': props({ live: rec({ status: 'done' }) }),'skipped': props({ live: rec({ status: 'declined' }) }),'cancelled': props({ live: rec({ status: 'cancelled' }) }),+ 'left for a file': props({ live: rec({ status: 'left_for_message' }) }),};const seen = new Set();for (const [name, p] of Object.entries(cards)) {@@ -254,14 +287,21 @@ test('a closed card always says what is next: timed_out tells you to say so; anassert.match(html, /Nobody solved it in time\. Pixel moved on without it\. If you finished, say so in the chat\./, kind);assert.doesNotMatch(html, /<button/, kind);}- // A closed status the card has no line for: the neutral line, no buttons, never the open card's lines, waiting or not+ // A closed status the card has no line for (a newer server's): the neutral line, no buttons, never the open card's lines, waiting or not.+ // Not left_for_message: 22m (#721) gives that one its own line, pinned below.for (const kind of ['sign_in', 'captcha', 'two_factor', 'other']) {for (const waiting of [false, true]) {- const html = ui.render(props({ meta: h.parseHumanStepMeta(meta({ step_kind: kind })), live: rec({ kind, status: 'left_for_message' }), waiting }));+ const html = ui.render(props({ meta: h.parseHumanStepMeta(meta({ step_kind: kind })), live: rec({ kind, status: 'closed_by_newer_server' }), waiting }));assert.match(html, /<span class="inline-flex items-center gap-1\.5 text-zinc-400"><svg[^>]*lucide-circle-minus[^]*?<\/svg> This step is closed\.<\/span>/, `${kind} waiting=${waiting}`);assert.doesNotMatch(html, /Press Done|stopped waiting|paused and waiting|carries on by itself|<button/, `${kind} waiting=${waiting}`);}}+ // left_for_message (22m) has its own line, not the neutral one, and no buttons either+ for (const waiting of [false, true]) {+ const html = ui.render(props({ meta: h.parseHumanStepMeta(meta({ step_kind: 'sign_in' })), live: rec({ status: 'left_for_message' }), waiting }));+ assert.match(html, /Closed: Pixel is reading the file you sent\./, `waiting=${waiting}`);+ assert.doesNotMatch(html, /This step is closed|Press Done|<button/, `waiting=${waiting}`);+ }// The open card after the turn ended keeps its pick-it-up-later line and its buttonsconst open = ui.render(props({ waiting: false, meta: h.parseHumanStepMeta(meta({ step_kind: 'sign_in' })) }));assert.match(open, /stopped waiting\. Press Done any time and it picks up in a new reply\./);diff --git a/src/db/human_steps.rs b/src/db/human_steps.rsindex a661231b..f41cf67c 100644--- a/src/db/human_steps.rs+++ b/src/db/human_steps.rs@@ -1,7 +1,8 @@//! Steps only the person can do in the bot browser (`request_human_step`): sign in, solve a//! CAPTCHA, or something else. A step is `open` until the person marks it done or declines it,//! or its turn is stopped (`cancelled`). A CAPTCHA step also closes by itself when the check-//! is gone from the page (`resolved_auto`) or nobody solved it in time (`timed_out`).+//! is gone from the page (`resolved_auto`) or nobody solved it in time (`timed_out`). A file+//! the person sends in the chat while a turn waits on the step closes it as `left_for_message`.use super::models::{Message, MessageExtra, NewMessage};use super::{Database, DbError};@@ -17,8 +18,9 @@ pub const MAX_OPEN_PER_KWANT: i64 = 5;pub const HUMAN_STEP_KINDS: [&str; 4] = ["sign_in", "captcha", "two_factor", "other"];/// "open", "done", "declined", "cancelled" (its turn was stopped), "resolved_auto" (the-/// CAPTCHA went away on its own or the person solved it without pressing Done) or "timed_out".-pub const HUMAN_STEP_STATUSES: [&str; 6] = ["open", "done", "declined", "cancelled", "resolved_auto", "timed_out"];+/// CAPTCHA went away on its own or the person solved it without pressing Done), "timed_out" or+/// "left_for_message" (22m: the person sent a file while a turn waited on it, so it ended).+pub const HUMAN_STEP_STATUSES: [&str; 7] = ["open", "done", "declined", "cancelled", "resolved_auto", "timed_out", "left_for_message"];#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]pub struct HumanStep {@@ -166,6 +168,12 @@ fn same_sign_in([kwant, channel, direct, thread, browser, site]: [&str; 6]) -> S)}+/// Every column of `human_steps`, as [`CREATE_HUMAN_STEPS`] makes it.+const HUMAN_STEP_COLUMNS: [&str; 17] = [+ "id", "kwant_id", "channel_id", "direct_kwant_id", "thread_id", "turn_id", "kind", "reason", "url", "sandbox_target",+ "target", "source", "status", "message_id", "created_at", "closed_at", "page_key",+];+const CREATE_HUMAN_STEPS: &str = "CREATE TABLE IF NOT EXISTS human_steps (id TEXT PRIMARY KEY,kwant_id TEXT NOT NULL,@@ -179,7 +187,7 @@ const CREATE_HUMAN_STEPS: &str = "CREATE TABLE IF NOT EXISTS human_steps (sandbox_target TEXT,target TEXT,source TEXT NOT NULL CHECK (source IN ('bot', 'auto')),- status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out')),+ status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out', 'left_for_message')),message_id TEXT,created_at TIMESTAMP NOT NULL,closed_at TIMESTAMP,@@ -189,13 +197,15 @@ const CREATE_HUMAN_STEPS: &str = "CREATE TABLE IF NOT EXISTS human_steps (impl Database {pub(super) async fn migrate_human_steps(&self) -> Result<(), DbError> {sqlx::query(CREATE_HUMAN_STEPS).execute(&self.pool).await?;- // Tables made before CAPTCHA auto-resolve lack `target` and the two new statuses, which- // a CHECK can't gain in place: rebuild them once+ // Tables made before a status was added (CAPTCHA auto-resolve's two, 22m's+ // `left_for_message`) can't gain it in their CHECK in place: rebuild them once, keeping+ // every row and every column they havelet sql: Option<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'human_steps'").fetch_optional(&self.pool).await?;- if sql.is_some_and(|(sql,)| !sql.contains("'timed_out'")) {- let columns = "id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, message_id, created_at, closed_at";+ if sql.is_some_and(|(sql,)| !sql.contains("'left_for_message'")) {+ let had: Vec<String> = sqlx::query_scalar("SELECT name FROM pragma_table_info('human_steps')").fetch_all(&self.pool).await?;+ let columns = HUMAN_STEP_COLUMNS.iter().filter(|c| had.iter().any(|h| h == *c)).copied().collect::<Vec<_>>().join(", ");let mut tx = self.pool.begin().await?;sqlx::query("DROP INDEX IF EXISTS human_steps_by_status").execute(&mut *tx).await?;sqlx::query("ALTER TABLE human_steps RENAME TO human_steps_old").execute(&mut *tx).await?;@@ -565,6 +575,44 @@ mod tests {assert!(serde_json::to_value(db.get_human_step(&s.id).await.unwrap().unwrap()).unwrap()["target"].is_null());}+ /// 22m: a table as 0.9.17 left it (every column, no `left_for_message`) is rebuilt once and+ /// keeps its rows whole, the CAPTCHA box and the held page included.+ #[tokio::test]+ async fn a_table_before_left_for_message_gains_it_and_keeps_every_column() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ sqlx::query("DROP TABLE human_steps").execute(&db.pool).await.unwrap();+ let before = CREATE_HUMAN_STEPS.replace(", 'left_for_message'", "");+ assert_ne!(before, CREATE_HUMAN_STEPS);+ sqlx::query(&before).execute(&db.pool).await.unwrap();+ let target = r#"{"kind":"tiktok","x":1,"y":2,"width":30,"height":40}"#;+ sqlx::query(+ "INSERT INTO human_steps (id, kwant_id, channel_id, thread_id, turn_id, kind, reason, url, sandbox_target, target, source, status, message_id, created_at, page_key)+ VALUES ('old', 'k', 'c', 'th', 'tu', 'captcha', 'Solve', 'https://x.com/', 't', ?, 'auto', 'open', 'm1', ?, 't#k#th')",+ )+ .bind(target)+ .bind(Utc::now())+ .execute(&db.pool)+ .await+ .unwrap();+ // Reopened, as kwnt starts (see the page test below for why not under this pool)+ db.pool.close().await;+ let db = Database::init(tmp.path()).await.unwrap();+ db.migrate_human_steps().await.unwrap();+ let old = db.get_human_step("old").await.unwrap().unwrap();+ assert_eq!(+ (old.channel_id.as_deref(), old.thread_id.as_deref(), old.turn_id.as_deref(), old.message_id.as_deref(), old.page_key.as_deref()),+ (Some("c"), Some("th"), Some("tu"), Some("m1"), Some("t#k#th"))+ );+ assert_eq!(serde_json::to_value(&old).unwrap()["target"]["width"], 30);+ assert!(db.close_human_step("old", "left_for_message").await.unwrap());+ assert_eq!(db.get_human_step("old").await.unwrap().unwrap().status, "left_for_message");+ let (sql,): (String,) = sqlx::query_as("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'human_steps'").fetch_one(&db.pool).await.unwrap();+ assert!(sql.contains("'left_for_message'"));+ let bogus = sqlx::query("UPDATE human_steps SET status = 'bogus' WHERE id = 'old'").execute(&db.pool).await;+ assert!(bogus.is_err(), "the CHECK still refuses unknown statuses");+ }+/// 0.9.3: a step holds only its own page; a step saved before pages (no page key, as an/// older kwnt left it) holds its team page, and a table from before the column gains it.#[tokio::test]diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex b0c4bf55..c8876f4d 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -10,6 +10,10 @@//! is gone the step closes as `resolved_auto` and the bot carries on by itself. Nobody solving it//! within `captcha_timeout_minutes` (default 10) closes it as `timed_out`, and the bot is told to//! move on rather than wait.+//!+//! 22m: a file the person drops in the chat while a turn waits on its step closes the step as+//! `left_for_message` and returns that turn at once ([`wake_chat`]), so the message's own turn+//! (with the `[Attached files]` line) starts now instead of after the wait.use super::continuity::{notify, Notification, SelfScope};use super::routes::{scope_for, try_kwant_turn, TurnOpts};@@ -46,6 +50,9 @@ pub enum Outcome {/// Not an answer: another turn of the bot in this chat already asked for the same sign-in and/// is waiting on it, so this turn steps aside. The step stays open.AlreadyAsked,+ /// 22m: the person sent a file in this chat while the turn waited. The step closes (not as+ /// done) and the turn ends so the message's own turn can read it.+ Message,}impl Outcome {@@ -56,6 +63,7 @@ impl Outcome {Outcome::ResolvedAuto => "resolved_auto",Outcome::TimedOut => "timed_out",Outcome::AlreadyAsked => "open",+ Outcome::Message => "left_for_message",}}}@@ -67,9 +75,17 @@ pub const MAX_CAPTCHA_TIMEOUT_MINUTES: u64 = 60;/// between two looks doesn't close it.const GONE_AFTER_MISSES: u32 = 2;+/// A turn waiting on a step, and the bot and chat ([`chat_key`]) it waits in, so a message there+/// can find it ([`HumanStepHub::waiting_in`]). Kept only while the turn waits: every way a wait+/// ends takes it out, so nothing is left behind.+struct Waiter {+ tx: oneshot::Sender<Outcome>,+ chat: Option<(String, String)>,+}+/// The turns waiting on a human step, by step id. Empty (no cost) when unused.pub struct HumanStepHub {- waiters: Mutex<HashMap<String, oneshot::Sender<Outcome>>>,+ waiters: Mutex<HashMap<String, Waiter>>,wait_ms: AtomicU64,/// Tests only: CAPTCHA time limit and probe interval in ms (0 = setting / default).captcha_timeout_ms: AtomicU64,@@ -119,14 +135,28 @@ impl HumanStepHub {}}- fn register(&self, id: &str) -> oneshot::Receiver<Outcome> {+ /// A turn now waits on step `id`; `chat` is its bot and chat ([`chat_key`]), when it has one.+ fn register(&self, id: &str, chat: Option<(String, String)>) -> oneshot::Receiver<Outcome> {let (tx, rx) = oneshot::channel();- self.waiters.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), tx);+ self.waiters.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), Waiter { tx, chat });rx}fn take(&self, id: &str) -> Option<oneshot::Sender<Outcome>> {- self.waiters.lock().unwrap_or_else(|e| e.into_inner()).remove(id)+ self.waiters.lock().unwrap_or_else(|e| e.into_inner()).remove(id).map(|w| w.tx)+ }++ /// The steps a live turn of `kwant` waits on in `chat` ([`chat_key`]): never another bot's,+ /// nor this bot's in another chat.+ pub fn waiting_in(&self, kwant: &str, chat: &str) -> Vec<String> {+ let waiters = self.waiters.lock().unwrap_or_else(|e| e.into_inner());+ let mut ids: Vec<String> = waiters+ .iter()+ .filter(|(_, w)| !w.tx.is_closed() && w.chat.as_ref().is_some_and(|(k, c)| k == kwant && c == chat))+ .map(|(id, _)| id.clone())+ .collect();+ ids.sort();+ ids}/// Wakes the turn waiting on this step; `false` when no live turn waits.@@ -326,7 +356,12 @@ async fn close(state: &AppState, id: &str, status: &'static str) -> Option<Humanlet s = state.db.get_human_step(id).await.ok().flatten()?;release_browser(state, s.page()).await;if let Some(turn) = s.turn_id.as_deref().and_then(super::activity::TurnActivity::find) {- turn.settle(&s.id, if status == "cancelled" { "stopped" } else { status });+ // The wait stopped because a message came, not because the step was done+ let shown = match status {+ "cancelled" | "left_for_message" => "stopped",+ other => other,+ };+ turn.settle(&s.id, shown);}changed(state, &s).await;Some(s)@@ -394,6 +429,10 @@ fn outcome_text(outcome: Option<Outcome>, captcha: bool) -> String {it or ask again now: skip this site and use another source (an official API or a site you're signed in to), \or tell the person you'll try this site later.".into(),+ Some(Outcome::Message) => "The person sent a file in this chat while you were waiting, so the step was closed \+ (they didn't say it is done) and the browser is yours again. End this turn now, at most with one short line; \+ their message and its file come to you in your next turn."+ .into(),Some(Outcome::AlreadyAsked) => "You already asked the person for this sign-in in another turn in this chat, and \that turn is waiting for their answer, so no new card was made. Don't ask again: end your turn now, at most \with one line saying you're waiting for them to sign in. The other turn carries on once they answer."@@ -463,13 +502,15 @@ async fn raise_step(hold_browser(state, place.page_key.as_deref().or(place.sandbox_target.as_deref())).await;// Like ask_user, the step, its card and the waiter appear togetherlet hub = &state.human_steps;+ // The bot and chat this turn waits in, so a file dropped there wakes it (22m)+ let waits_in = chat_key(scope).map(|c| (scope.kwant_id.clone(), c));let target_json = target.and_then(|t| serde_json::to_string(t).ok());let mut waiter = None;let created = state.db.create_human_step_with_card(&place, kind, reason, url, target_json.as_deref(), source, |s| {if wait_for_it {- waiter = Some((s.id.clone(), hub.register(&s.id)));+ waiter = Some((s.id.clone(), hub.register(&s.id, waits_in.clone())));}let mut text = format!("{}: {}", kind_label(&s.kind), s.reason);if let Some(u) = &s.url {@@ -512,7 +553,7 @@ async fn raise_step(// wait on that onelet rx = match waiter {Some((_, rx)) => Some(rx),- None if wait_for_it => Some(hub.register(&step.id)),+ None if wait_for_it => Some(hub.register(&step.id, waits_in)),None => None,};let _guard = rx.is_some().then(|| WaiterGuard { hub, id: step.id.clone() });@@ -883,8 +924,8 @@ async fn resume(state: &AppState, s: &HumanStep, outcome: Outcome) {continue with another source (an official API or a site you're signed in to), or tell the person you'll try this site later.",s.reason),- // Not an answer: nothing to tell a new turn.- Outcome::AlreadyAsked => return,+ // Not an answer: nothing to tell a new turn. A message's own turn reads the message.+ Outcome::AlreadyAsked | Outcome::Message => return,};tokio::spawn(async move {let _job = job;@@ -892,6 +933,27 @@ async fn resume(state: &AppState, s: &HumanStep, outcome: Outcome) {});}+/// 22m: the person sent a file to `kwant` in `chat` ([`chat_key`]) while a turn of that bot waits+/// there on a browser step. Each such step closes as `left_for_message` (the browser goes back to+/// the bot) and its turn returns at once, so the message's own turn, queued or held behind it,+/// starts now instead of after the wait. A step no turn waits on any more stays open: its Done+/// still starts a new turn. Returns how many waiting turns were woken.+pub async fn wake_chat(state: &AppState, kwant: &str, chat: &str) -> usize {+ let mut woke = 0;+ for id in state.human_steps.waiting_in(kwant, chat) {+ // Closed first: a Done or Decline racing this gets 409, never a second answer+ let Some(s) = close(state, &id, Outcome::Message.status()).await else { continue };+ if state.human_steps.wake(&s.id, Outcome::Message) {+ woke += 1;+ tracing::info!(human_step_id = %s.id, kwant_id = %kwant, "a file in the chat woke the turn waiting on its browser step");+ } else {+ // Its wait ended just now; the message starts its own turn anyway+ tracing::info!(human_step_id = %s.id, kwant_id = %kwant, "a file in the chat closed a browser step nobody waited on any more");+ }+ }+ woke+}+/// After a turn was stopped: its open steps are cancelled and the browser handed back.pub async fn cancel_for_turn(state: &AppState, turn_id: &str) {for s in state.db.open_human_steps_for_turn(turn_id).await.unwrap_or_default() {@@ -917,17 +979,43 @@ mod tests {#[tokio::test]async fn the_hub_wakes_the_waiting_turn_once() {let hub = HumanStepHub::default();- let rx = hub.register("s1");+ let rx = hub.register("s1", None);assert!(hub.is_waiting("s1"));assert!(hub.wake("s1", Outcome::Declined));assert_eq!(rx.await.unwrap(), Outcome::Declined);assert!(!hub.is_waiting("s1"));assert!(!hub.wake("s1", Outcome::Done), "nobody waits any more: a new turn starts instead");- let rx = hub.register("s2");+ let rx = hub.register("s2", None);drop(rx);assert!(!hub.wake("s2", Outcome::Done), "the tool call already ended");}+ /// 22m: a message finds only the steps its own bot waits on in its own chat; a wait that ended+ /// (Done, Decline, timeout, the tool call hanging up) leaves nothing behind.+ #[tokio::test]+ async fn a_chat_finds_only_its_own_bots_waiting_steps() {+ let hub = HumanStepHub::default();+ let at = |k: &str, c: &str| Some((k.to_string(), c.to_string()));+ let rx_a = hub.register("a-dm", at("ann", "ann"));+ let _rx_t = hub.register("a-thread", at("ann", "thread-1"));+ let _rx_b = hub.register("b-dm", at("bob", "bob"));+ let _rx_none = hub.register("no-chat", None);+ assert_eq!(hub.waiting_in("ann", "ann"), vec!["a-dm".to_string()]);+ assert_eq!(hub.waiting_in("ann", "thread-1"), vec!["a-thread".to_string()], "the thread, never the DM");+ assert!(hub.waiting_in("ann", "bob").is_empty(), "another bot's chat");+ assert!(hub.waiting_in("bob", "ann").is_empty(), "another bot in this chat");+ assert!(hub.waiting_in("ann", "thread-2").is_empty(), "another thread of the same bot");++ assert!(hub.wake("a-dm", Outcome::Message));+ assert_eq!(rx_a.await.unwrap(), Outcome::Message);+ assert!(hub.waiting_in("ann", "ann").is_empty(), "woken once: gone");+ drop(hub.take("a-thread"));+ assert!(hub.waiting_in("ann", "thread-1").is_empty(), "a wait that ended leaves no entry");+ drop(_rx_b);+ assert!(hub.waiting_in("bob", "bob").is_empty(), "a tool call that hung up wakes nothing");+ assert_eq!(hub.waiters.lock().unwrap().len(), 2, "a hung-up waiter stays until its guard takes it, but never matches");+ }+fn turn(kwant: &str) -> SelfScope {SelfScope {kwant_id: kwant.into(),@@ -1028,5 +1116,9 @@ mod tests {assert!(outcome_text(None, true).contains("closes by itself"));assert_eq!(Outcome::ResolvedAuto.status(), "resolved_auto");assert_eq!(Outcome::TimedOut.status(), "timed_out");+ let message = outcome_text(Some(Outcome::Message), false);+ assert!(message.contains("sent a file") && message.contains("End this turn now") && message.contains("next turn"), "{message}");+ assert!(!message.contains("is done and"), "never says the step is done");+ assert_eq!(Outcome::Message.status(), "left_for_message");}}diff --git a/src/server/routes.rs b/src/server/routes.rsindex dc6a37a5..08c59f87 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4697,6 +4697,7 @@ async fn send_chat_routed(target_kwant.name, target_kwant.title, reason)));+ file_wakes_browser_wait(&state, &target_kwant.id, direct_chat(&payload), !uploads.is_empty(), from_person).await;let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id, from_person).await;execute_single_turn(state.clone(),@@ -4932,6 +4933,7 @@ async fn send_chat_routed(return Ok(Json(v));}let team_keys = active_team.as_ref().map(|t| (t.id.clone(), t.name.clone()));+ file_wakes_browser_wait(&state, &target_kwant.id, direct_chat(&payload), !uploads.is_empty(), from_person).await;let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id, from_person).await;execute_single_turn(state.clone(),@@ -5054,6 +5056,7 @@ async fn send_to_thread(};let prompt = payload.prompt + ¬e;let target = kwant.clone();+ file_wakes_browser_wait(&state, &kwant.id, Some(&thread.id), !uploads.is_empty(), from_person).await;// H3: the message is saved and shows; its turn waits while the bot is stuck or waits on the personlet held = super::bot_status::hold_from(&state, &kwant, &thread.id, "message", &saved.id, from_person).await;let held_id = held.as_ref().map(|_| saved.id.clone());@@ -5076,6 +5079,22 @@ async fn send_to_thread(Ok(Json(reply))}+/// The chat a channel or 1:1 send's turn runs in, as its turn's origin names it+/// ([`super::human_steps::chat_key`]): the channel, else the bot of the 1:1.+fn direct_chat(payload: &SendChatPayload) -> Option<&str> {+ payload.channel_id.as_deref().or(payload.kwant_id.as_deref())+}++/// 22m: a file the person sends to `kwant` in `chat` reaches it at once. A turn of that bot+/// waiting there on a "needs you in the browser" card returns now (the card closes as+/// `left_for_message`), so this message's turn isn't held behind the wait for up to 290 s. Only a+/// message with files from the person wakes it: typed text ("signing in now…") must not take the+/// browser back from someone mid sign-in, so it waits as before (H3).+async fn file_wakes_browser_wait(state: &AppState, kwant_id: &str, chat: Option<&str>, has_files: bool, from_person: bool) {+ let Some(chat) = chat.filter(|_| has_files && from_person) else { return };+ super::human_steps::wake_chat(state, kwant_id, chat).await;+}+/// Holds a chat or 1:1 message to `kwant` while it is stuck or waits on the person elsewhere (H3)./// The person's own message in the chat where the bot gave up after a stall is its Retry and goes/// now (0.9.5).diff --git a/tests/human_step_test.rs b/tests/human_step_test.rsindex 1d0d8d41..e62790b5 100644--- a/tests/human_step_test.rs+++ b/tests/human_step_test.rs@@ -1,17 +1,22 @@//! Human steps: `request_human_step` pauses the turn with a card and a `human_step`//! notification, Done or Decline resumes it with that outcome, Stop cancels it, a late answer//! starts a new turn, and the bot's browser tools are refused while a step is open. Two turns of-//! a bot in one chat asking for the same sign-in share one step.+//! a bot in one chat asking for the same sign-in share one step. A file the person sends in the+//! chat while a turn waits on a step returns that turn at once (22m).mod common;-use axum::http::StatusCode;+use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+};use common::*;use kwnt::server::continuity::{SelfScope, TurnOrigin};use kwnt::server::mcp_runtime;use kwnt::RuntimeEvent;use serde_json::{json, Value};use std::time::Duration;+use tower::ServiceExt;fn step_marker(kind: &str, reason: &str) -> String {call_tool_marker("request_human_step", json!({"kind": kind, "reason": reason, "url": "https://me:[email protected]/login?token=abc"}))@@ -314,3 +319,99 @@ async fn a_sign_in_for_another_site_gets_its_own_step_while_one_is_open() {let (text, is_error) = finished(instagram).await;assert!(!is_error && text.contains("declined the step"), "{text}");}++/// Uploads a small text file, as the composer does before sending; gives its id.+async fn upload(env: &Env, name: &str) -> String {+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/attachments?name={name}"))+ .header("content-type", "application/octet-stream")+ .body(Body::from(format!("contents of {name}\n")))+ .unwrap();+ let resp = env.app.clone().oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::CREATED);+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();+ v["id"].as_str().unwrap().to_string()+}++/// 22m: while bot a waits on its "needs you in the browser" card in its 1:1, typed text and a file+/// sent to another bot leave the wait alone; a file sent to a returns the waiting turn at once+/// (not after the 290 s wait), the card closes as `left_for_message` (never "done") with the+/// browser handed back, and the message's own turn gets the file on its `[Attached files]` line.+#[tokio::test]+async fn a_file_sent_in_the_chat_returns_the_turn_waiting_on_its_step() {+ let env = setup().await;+ send_direct(&env, &env.a, &format!("{} REPLYTAG:w1", step_marker("other", "Upload the MP3 on rss.com")), json!({})).await;+ let s = open_step(&env, &env.a).await;+ let id = s["id"].as_str().unwrap().to_string();+ wait_for("the turn waiting", || async { step(&env, &id).await["waiting"] == true }).await;++ // Typed text (the person may be mid sign-in) and another bot's file don't wake it+ send_direct(&env, &env.a, "doing it now REPLYTAG:w0", json!({})).await;+ let other = upload(&env, "other.txt").await;+ send_direct(&env, &env.b, "for b REPLYTAG:wb", json!({"attachment_ids": [other]})).await;+ wait_reply(&env, &env.b, "answer wb").await;+ let st = step(&env, &id).await;+ assert_eq!((st["step"]["status"].as_str(), st["waiting"].as_bool()), (Some("open"), Some(true)), "{st}");++ let file = upload(&env, "episode.txt").await;+ let started = std::time::Instant::now();+ send_direct(&env, &env.a, "here it is REPLYTAG:w2", json!({"attachment_ids": [file]})).await;+ let first = wait_reply(&env, &env.a, "answer w1").await;+ assert!(started.elapsed() < Duration::from_secs(30), "returned at once, not after the wait");+ assert!(first.text.contains("sent a file in this chat") && first.text.contains("End this turn now"), "{}", first.text);+ assert!(!first.text.contains("TOOLERROR") && !first.text.contains("says the step is done"), "{}", first.text);+ let st = step(&env, &id).await;+ assert_eq!((st["step"]["status"].as_str(), st["waiting"].as_bool()), (Some("left_for_message"), Some(false)), "{st}");+ if let Some(target) = s["page_key"].as_str().or(s["sandbox_target"].as_str()) {+ assert!(!kwnt::server::human_steps::browser_is_held(&env.state, target).await, "the browser is the bot's again");+ }+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.text.starts_with("Your help is needed")).unwrap();+ assert!(card.meta.as_deref().unwrap().contains("\"status\":\"left_for_message\""));+ assert!(!messages(&env, &env.a).await.iter().any(|m| m.sender_role == "user" && m.text == "Done"), "no Done reply is made up");++ // The message's own turn reads the file; the typed one still runs too+ wait_reply(&env, &env.a, "answer w2").await;+ // Any prompt carrying the tag (a later turn may quote it as history): one of them is w2's own, with the file+ let prompts = invocations_with("REPLYTAG:w2");+ assert!(prompts.iter().any(|p| p.contains("[Attached files]") && p.contains(&format!("id {file}"))), "{prompts:?}");+ wait_reply(&env, &env.a, "answer w0").await;+ let (code, _) = call(&env.app, "POST", &format!("/api/human-steps/{id}/done"), None).await;+ assert_eq!(code, StatusCode::CONFLICT, "closed once only");+}++/// 22m in a thread: a file sent to the same bot's 1:1 doesn't wake the thread's wait; one sent in+/// the thread does.+#[tokio::test]+async fn a_file_wakes_only_the_wait_in_its_own_thread() {+ let env = setup().await;+ let thread = env.state.db.create_thread(&env.a, "Podcast upload", "chat", None, "user").await.unwrap();+ let to_thread = |prompt: String, extra: Value| {+ let mut body = json!({"prompt": prompt, "sender_id": "user", "thread_id": thread.id});+ for (k, v) in extra.as_object().unwrap() {+ body[k] = v.clone();+ }+ let app = env.app.clone();+ async move {+ let (code, v) = call(&app, "POST", "/api/chat/send", Some(body)).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ }+ };+ to_thread(format!("{} REPLYTAG:t1", step_marker("sign_in", "Sign in to rss.com")), json!({})).await;+ let s = open_step(&env, &thread.id).await;+ let id = s["id"].as_str().unwrap().to_string();+ wait_for("the thread turn waiting", || async { step(&env, &id).await["waiting"] == true }).await;++ let dm_file = upload(&env, "dm.txt").await;+ send_direct(&env, &env.a, "in the 1:1 REPLYTAG:t0", json!({"attachment_ids": [dm_file]})).await;+ let st = step(&env, &id).await;+ assert_eq!((st["step"]["status"].as_str(), st["waiting"].as_bool()), (Some("open"), Some(true)), "another chat of the same bot: {st}");++ let file = upload(&env, "thread.txt").await;+ to_thread("here REPLYTAG:t2".into(), json!({"attachment_ids": [file]})).await;+ let first = wait_reply(&env, &thread.id, "answer t1").await;+ assert!(first.text.contains("sent a file in this chat"), "{}", first.text);+ assert_eq!(step(&env, &id).await["step"]["status"], "left_for_message");+ wait_reply(&env, &thread.id, "answer t2").await;+ assert!(invocations_with("REPLYTAG:t2").iter().any(|p| p.contains("[Attached files]") && p.contains(&format!("id {file}"))));+}