Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(web_chat): address review on the idle guard and shell progress

killbill15ec188bdc62
diff --git a/crates/openhuman-core/src/sandbox/shell_progress.rs b/crates/openhuman-core/src/sandbox/shell_progress.rs
index 838e65624f..63aed175a2 100644
--- a/crates/openhuman-core/src/sandbox/shell_progress.rs
+++ b/crates/openhuman-core/src/sandbox/shell_progress.rs
@@ -24,10 +24,21 @@ pub(crate) const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
/// Longest last-output line carried in a status line, in characters.
const LAST_LINE_CHARS: usize = 120;
+/// Most characters of an unfinished output line kept until its terminator
+/// arrives. Only the first [`LAST_LINE_CHARS`] are ever shown, so this bounds
+/// memory without changing what a status line says.
+const PENDING_LINE_CHARS: usize = 1_024;
+
#[derive(Debug, Default)]
struct Meter {
bytes: u64,
+ /// The last complete, non-empty output line.
last_line: Option<String>,
+ /// The start of the line still being written. Output arrives in chunks
+ /// that can split a line anywhere, so a line only counts once its
+ /// terminator arrives; otherwise a status line could quote half of one.
+ pending: String,
+ pending_chars: usize,
}
/// Output written so far by the shell call running on this task. Cheap to
@@ -36,13 +47,27 @@ struct Meter {
pub(crate) struct ShellOutputMeter(Arc<Mutex<Meter>>);
impl ShellOutputMeter {
- /// Fold one chunk of stdout or stderr into the figures.
+ /// Fold one chunk of stdout or stderr into the figures. `\n` and `\r`
+ /// both end a line, so a progress bar redrawn with `\r` reports its
+ /// latest state.
pub(crate) fn record(&self, chunk: &[u8]) {
let mut meter = self.0.lock().unwrap_or_else(|p| p.into_inner());
meter.bytes = meter.bytes.saturating_add(chunk.len() as u64);
let text = String::from_utf8_lossy(chunk);
- if let Some(line) = text.lines().map(str::trim).rfind(|line| !line.is_empty()) {
- meter.last_line = Some(line.chars().take(LAST_LINE_CHARS).collect());
+ for (index, piece) in text.split(['\n', '\r']).enumerate() {
+ if index > 0 {
+ // A terminator preceded this piece: the pending line is done.
+ let line = std::mem::take(&mut meter.pending);
+ meter.pending_chars = 0;
+ let line = line.trim();
+ if !line.is_empty() {
+ meter.last_line = Some(line.chars().take(LAST_LINE_CHARS).collect());
+ }
+ }
+ let room = PENDING_LINE_CHARS - meter.pending_chars;
+ let kept: String = piece.chars().take(room).collect();
+ meter.pending_chars += kept.chars().count();
+ meter.pending.push_str(&kept);
}
}
@@ -109,8 +134,15 @@ pub(crate) async fn with_shell_progress<F: std::future::Future>(
output = &mut work => return output,
_ = ticker.tick() => {
let (bytes, last_line) = meter.snapshot();
- let message = progress_message(started.elapsed(), bytes, last_line.as_deref());
- tracing::debug!(%message, "[shell] reporting progress");
+ let elapsed = started.elapsed();
+ // The status line can quote command output, so only its
+ // content-free figures are logged.
+ tracing::debug!(
+ elapsed_secs = elapsed.as_secs(),
+ output_bytes = bytes,
+ "[shell] reporting progress"
+ );
+ let message = progress_message(elapsed, bytes, last_line.as_deref());
context.report_progress(ToolProgress::message(message));
}
}
diff --git a/crates/openhuman-core/src/sandbox/shell_progress_tests.rs b/crates/openhuman-core/src/sandbox/shell_progress_tests.rs
index 10b5169ee3..ff73f8faa5 100644
--- a/crates/openhuman-core/src/sandbox/shell_progress_tests.rs
+++ b/crates/openhuman-core/src/sandbox/shell_progress_tests.rs
@@ -47,11 +47,35 @@ fn meter_counts_bytes_and_keeps_the_last_non_empty_line() {
#[test]
fn meter_truncates_a_long_last_line() {
let meter = ShellOutputMeter::default();
- meter.record("x".repeat(500).as_bytes());
+ meter.record(format!("{}\n", "x".repeat(5_000)).as_bytes());
let (_, line) = meter.snapshot();
assert_eq!(line.unwrap().chars().count(), LAST_LINE_CHARS);
}
+/// A line split across chunks is reported whole, never from its second half.
+#[test]
+fn meter_joins_a_line_split_across_chunks() {
+ let meter = ShellOutputMeter::default();
+ meter.record(b"Compil");
+ assert_eq!(
+ meter.snapshot().1,
+ None,
+ "an unfinished line is not reported"
+ );
+ meter.record(b"ing serde v1.0\nDown");
+ assert_eq!(meter.snapshot().1.as_deref(), Some("Compiling serde v1.0"));
+ meter.record(b"loading\n");
+ assert_eq!(meter.snapshot().1.as_deref(), Some("Downloading"));
+}
+
+/// A progress bar redrawn with carriage returns reports its latest state.
+#[test]
+fn meter_treats_a_carriage_return_as_a_line_end() {
+ let meter = ShellOutputMeter::default();
+ meter.record(b"\r 10%\r 55%\r");
+ assert_eq!(meter.snapshot().1.as_deref(), Some("55%"));
+}
+
/// A 40s command that writes output reports twice, with the output it has
/// written so far, through the meter scoped on its task.
#[tokio::test(start_paused = true)]
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
index 73b8f3b46b..d26614f74c 100644
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@ -67,6 +67,11 @@ pub(super) struct TurnIds {
pub(super) request_id: String,
}
+/// Upper bound on closing a stopped turn: config, snapshot read and the
+/// closing model call (itself bounded at 45s). Past it the stop is reported as
+/// a `turn_timeout` error, so closing can never be what hangs the turn.
+const CLOSE_REPLY_BUDGET: Duration = Duration::from_secs(60);
+
/// Which guard stopped the turn.
enum Stop {
Ceiling(Duration),
@@ -157,15 +162,26 @@ where
let Some(ids) = ids else {
return Err(fallback);
};
+ let (config, locale) = activity.turn_context();
let stopped = StoppedTurn {
thread_id: &ids.thread_id,
request_id: &ids.request_id,
cause,
stuck,
+ config,
+ locale,
};
- match super::super::turn_close::close_reply(stopped).await {
- Some(reply) => Ok(reply),
- None => Err(fallback),
+ let close = super::super::turn_close::close_reply(stopped);
+ match tokio::time::timeout(CLOSE_REPLY_BUDGET, close).await {
+ Ok(Some(reply)) => Ok(reply),
+ Ok(None) => Err(fallback),
+ Err(_) => {
+ log::warn!(
+ "[web-channel] closing the stopped turn took over {}s; reporting turn_timeout",
+ CLOSE_REPLY_BUDGET.as_secs()
+ );
+ Err(fallback)
+ }
}
}
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 3aefab78e1..f36d6972e0 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -120,6 +120,11 @@ pub(crate) async fn run_chat_task(
log::debug!("[web-channel] thread working folder applied thread_id={thread_id}");
config.action_dir = dir;
}
+ // A guard that stops this turn closes it from this turn's own config and
+ // reply language, not from whatever profile is active when it fires.
+ if let Some(activity) = super::turn_activity::current() {
+ activity.remember_turn(std::sync::Arc::new(config.clone()), locale.clone());
+ }
let model_override = normalize_model_override(model_override);
// The cached session (or a cold-boot resumed one) is the thread's single
// live history; every turn on the thread checks it out through this path.
diff --git a/crates/openhuman-core/src/web_chat/turn_activity.rs b/crates/openhuman-core/src/web_chat/turn_activity.rs
index bac7b6e639..ccfaea8b9c 100644
--- a/crates/openhuman-core/src/web_chat/turn_activity.rs
+++ b/crates/openhuman-core/src/web_chat/turn_activity.rs
@@ -72,6 +72,10 @@ struct State {
/// What the last event said the turn did, for the stop reply.
last_step: Option<Cow<'static, str>>,
turn_completed: bool,
+ /// The config and reply locale the turn itself resolved, so a stop reply
+ /// is written to the turn's own workspace and in its language.
+ turn_config: Option<Arc<crate::config::Config>>,
+ locale: Option<String>,
}
/// Where a turn was when it went silent, for the reply that closes it.
@@ -155,6 +159,8 @@ impl TurnActivity {
model_call_open: false,
last_step: None,
turn_completed: false,
+ turn_config: None,
+ locale: None,
})),
}
}
@@ -203,6 +209,21 @@ impl TurnActivity {
}
impl TurnActivity {
+ /// Record the config and reply locale the turn resolved. A stop reply
+ /// uses these rather than whatever profile is active when it fires.
+ pub(crate) fn remember_turn(&self, config: Arc<crate::config::Config>, locale: Option<String>) {
+ let mut state = self.lock();
+ state.turn_config = Some(config);
+ state.locale = locale;
+ }
+
+ /// The config and locale recorded by [`Self::remember_turn`], if the turn
+ /// got that far.
+ pub(crate) fn turn_context(&self) -> (Option<Arc<crate::config::Config>>, Option<String>) {
+ let state = self.lock();
+ (state.turn_config.clone(), state.locale.clone())
+ }
+
/// Where the turn was when its last event arrived.
pub(crate) fn stuck_point(&self) -> StuckPoint {
let state = self.lock();
diff --git a/crates/openhuman-core/src/web_chat/turn_activity_tests.rs b/crates/openhuman-core/src/web_chat/turn_activity_tests.rs
index 670ef257ed..33401b03d7 100644
--- a/crates/openhuman-core/src/web_chat/turn_activity_tests.rs
+++ b/crates/openhuman-core/src/web_chat/turn_activity_tests.rs
@@ -244,3 +244,14 @@ async fn stuck_point_names_where_the_turn_went_quiet() {
});
assert_eq!(activity.stuck_point(), StuckPoint::AfterRun);
}
+
+#[test]
+fn the_turn_context_is_what_the_turn_recorded() {
+ let activity = TurnActivity::new();
+ assert!(activity.turn_context().0.is_none());
+ let config = Arc::new(crate::config::Config::default());
+ activity.remember_turn(config.clone(), Some("de".into()));
+ let (seen, locale) = activity.turn_context();
+ assert!(Arc::ptr_eq(&seen.expect("config recorded"), &config));
+ assert_eq!(locale.as_deref(), Some("de"));
+}
diff --git a/crates/openhuman-core/src/web_chat/turn_close.rs b/crates/openhuman-core/src/web_chat/turn_close.rs
index 222f22889d..55e9977840 100644
--- a/crates/openhuman-core/src/web_chat/turn_close.rs
+++ b/crates/openhuman-core/src/web_chat/turn_close.rs
@@ -83,6 +83,20 @@ pub(crate) struct StoppedTurn<'a> {
pub(crate) request_id: &'a str,
pub(crate) cause: StopCause,
pub(crate) stuck: StuckPoint,
+ /// The config the turn resolved, when it got that far. Its workspace is
+ /// where the turn's snapshot lives and where the reply is saved, even if
+ /// the active profile changed since.
+ pub(crate) config: Option<std::sync::Arc<crate::config::Config>>,
+ /// The turn's reply locale, so the close is written in its language.
+ pub(crate) locale: Option<String>,
+}
+
+impl StoppedTurn<'_> {
+ /// Whether the agent never received the user's request: the turn stopped
+ /// before its run began, so there is nothing to continue from.
+ fn request_unseen(&self) -> bool {
+ self.stuck == StuckPoint::BeforeRun
+ }
}
/// What the turn recorded while it ran, as evidence lines.
@@ -186,23 +200,41 @@ pub(crate) fn plain_reply(turn: &StoppedTurn<'_>, evidence: &Evidence) -> String
out.push('\n');
}
}
- out.push_str("\nSay \"continue\" and I'll pick up from here.");
+ if turn.request_unseen() {
+ out.push_str(
+ "\nYour message didn't reach me before the turn stopped. Please send it again.",
+ );
+ } else {
+ out.push_str("\nSay \"continue\" and I'll pick up from here.");
+ }
out
}
fn close_request(turn: &StoppedTurn<'_>, evidence: &Evidence) -> ModelRequest {
+ let next_step = if turn.request_unseen() {
+ "The assistant never received the user's request, so it cannot continue it. Ask the \
+ user to send the request again; do not suggest saying \"continue\"."
+ } else {
+ "The user can say \"continue\" to pick up from here."
+ };
let user_prompt = format!(
- "The turn was stopped because {}.\nWhere it got stuck: {}.\n\n{}",
+ "The turn was stopped because {}.\nWhere it got stuck: {}.\n{next_step}\n\n{}",
turn.cause.describe(),
turn.stuck.describe(),
evidence.render()
);
+ let mut system = CLOSE_SYSTEM_PROMPT.to_string();
+ if let Some(directive) = turn
+ .locale
+ .as_deref()
+ .and_then(super::session::locale_reply_directive)
+ {
+ system.push_str("\n\n");
+ system.push_str(&directive);
+ }
provider::openhuman_backend_model::without_reasoning(
- ModelRequest::new(vec![
- Message::system(CLOSE_SYSTEM_PROMPT),
- Message::user(user_prompt),
- ])
- .with_temperature(0.2),
+ ModelRequest::new(vec![Message::system(system), Message::user(user_prompt)])
+ .with_temperature(0.2),
)
}
@@ -248,28 +280,55 @@ async fn model_reply(
}
}
-/// The reply that closes `turn`, or `None` when even the configuration
-/// cannot be read (the caller then reports the stop as an error).
-pub(crate) async fn close_reply(turn: StoppedTurn<'_>) -> Option<WebChatTaskResult> {
- let config = match config_rpc::load_config_with_timeout().await {
- Ok(config) => config,
+/// Read the turn's snapshot off the async worker: it is a synchronous disk
+/// read, and a stalled filesystem must not pin the runtime thread.
+async fn read_snapshot(
+ workspace: std::path::PathBuf,
+ thread_id: &str,
+ request_id: &str,
+) -> Option<TurnState> {
+ let (thread_id, request_id) = (thread_id.to_string(), request_id.to_string());
+ let read = tokio::task::spawn_blocking(move || {
+ TurnStateStore::new(workspace).get_turn(&thread_id, &request_id)
+ })
+ .await;
+ match read {
+ Ok(Ok(snapshot)) => snapshot,
+ Ok(Err(error)) => {
+ log::warn!("{LOG_PREFIX} turn snapshot unreadable: {error}");
+ None
+ }
Err(error) => {
- log::warn!(
- "{LOG_PREFIX} config load failed request_id={}: {error}",
- turn.request_id
- );
- return None;
+ log::warn!("{LOG_PREFIX} turn snapshot read did not finish: {error}");
+ None
}
+ }
+}
+
+/// The reply that closes `turn`, or `None` when no configuration is available
+/// (the caller then reports the stop as an error). The caller bounds the
+/// whole call.
+pub(crate) async fn close_reply(turn: StoppedTurn<'_>) -> Option<WebChatTaskResult> {
+ let config = match turn.config.clone() {
+ Some(config) => config,
+ // The turn stopped before it resolved its own config.
+ None => match config_rpc::load_config_with_timeout().await {
+ Ok(config) => std::sync::Arc::new(config),
+ Err(error) => {
+ log::warn!(
+ "{LOG_PREFIX} config load failed request_id={}: {error}",
+ turn.request_id
+ );
+ return None;
+ }
+ },
};
- let snapshot = TurnStateStore::new(config.workspace_dir.clone())
- .get_turn(turn.thread_id, turn.request_id)
- .unwrap_or_else(|error| {
- log::warn!(
- "{LOG_PREFIX} turn snapshot unreadable request_id={}: {error}",
- turn.request_id
- );
- None
- });
+ let snapshot = read_snapshot(
+ config.workspace_dir.clone(),
+ turn.thread_id,
+ turn.request_id,
+ )
+ .await;
let evidence = Evidence::from_snapshot(snapshot.as_ref());
let reply = match model_reply(&config, &turn, &evidence).await {
Some(reply) => reply,
diff --git a/crates/openhuman-core/src/web_chat/turn_close_tests.rs b/crates/openhuman-core/src/web_chat/turn_close_tests.rs
index a2a19d900a..610266be02 100644
--- a/crates/openhuman-core/src/web_chat/turn_close_tests.rs
+++ b/crates/openhuman-core/src/web_chat/turn_close_tests.rs
@@ -46,6 +46,8 @@ fn stopped(cause: StopCause, stuck: StuckPoint) -> StoppedTurn<'static> {
request_id: "req-1",
cause,
stuck,
+ config: None,
+ locale: None,
}
}
@@ -136,3 +138,32 @@ fn the_close_request_carries_the_cause_the_stuck_point_and_the_evidence() {
assert!(prompt.contains("still running: shell (git worktree add)"));
assert!(request.tools.is_empty(), "the close call has no tools");
}
+
+/// A turn stopped before its run never handed the request to the agent, so
+/// "continue" would continue nothing: the user is asked to send it again.
+#[test]
+fn a_request_the_agent_never_saw_is_asked_for_again() {
+ let turn = stopped(
+ StopCause::Idle(Duration::from_secs(900)),
+ StuckPoint::BeforeRun,
+ );
+ let reply = plain_reply(&turn, &Evidence::default());
+ assert!(reply.ends_with("Please send it again."), "{reply}");
+ assert!(!reply.contains("continue"), "{reply}");
+ let prompt = format!("{:?}", close_request(&turn, &Evidence::default()).messages);
+ assert!(prompt.contains("never received the user's request"));
+}
+
+#[test]
+fn the_close_request_carries_the_turn_reply_language() {
+ let mut turn = stopped(
+ StopCause::Idle(Duration::from_secs(900)),
+ StuckPoint::AfterRun,
+ );
+ turn.locale = Some("de".into());
+ let prompt = format!("{:?}", close_request(&turn, &Evidence::default()).messages);
+ assert!(prompt.contains("German"), "{prompt}");
+ turn.locale = None;
+ let prompt = format!("{:?}", close_request(&turn, &Evidence::default()).messages);
+ assert!(!prompt.contains("German"));
+}