Skip to content

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

fix(web-chat): settle a turn's state snapshot when the turn ends

M3gA-Mindfffd2d0e9856
diff --git a/crates/openhuman-core/src/flows/ops/streaming.rs b/crates/openhuman-core/src/flows/ops/streaming.rs
index 6379c46318..a61648e8e4 100644
--- a/crates/openhuman-core/src/flows/ops/streaming.rs
+++ b/crates/openhuman-core/src/flows/ops/streaming.rs
@@ -133,6 +133,33 @@ pub(super) async fn finalize_flow_stream(
});
}
}
+ // Settle this turn's snapshot now the turn is over. `attach_flow_progress_bridge`
+ // discards its `ProgressBridgeHandle` and never waits for a drain, and the
+ // bridge is otherwise the only writer that marks a snapshot terminal — it
+ // does so on its way out, which can be minutes late or never. A snapshot
+ // left non-terminal makes `threads_turn_state_get` report the turn as still
+ // running, so re-entering the thread paints a permanent "Thinking..."
+ // indicator under a reply that already landed.
+ if let Ok(config) = crate::config::rpc::load_config_with_timeout().await {
+ let lifecycle = if result.is_ok() {
+ crate::threads::turn_state::TurnLifecycle::Completed
+ } else {
+ crate::threads::turn_state::TurnLifecycle::Interrupted
+ };
+ let now = chrono::Utc::now().to_rfc3339();
+ if let Err(err) =
+ crate::threads::turn_state::TurnStateStore::new(config.workspace_dir.clone())
+ .settle_turn(&target.thread_id, &target.request_id, lifecycle, &now)
+ {
+ tracing::warn!(
+ target: "flows",
+ thread_id = %target.thread_id,
+ request_id = %target.request_id,
+ error = %err,
+ "[flows] failed to settle turn snapshot"
+ );
+ }
+ }
tracing::info!(
target: "flows",
thread_id = %target.thread_id,
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs b/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
index 7bca9f5d48..741a0f7fbb 100644
--- a/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
+++ b/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
@@ -14,12 +14,37 @@ impl TurnStateMirror {
if self.turn_completed {
return;
}
- self.state.lifecycle = TurnLifecycle::Interrupted;
+ // The turn driver settles this snapshot the moment the turn ends
+ // (`TurnStateStore::settle_turn`), because this bridge can outlive its
+ // turn by minutes — it only exits when its progress sender drops, and
+ // for a cached per-thread session that waits for the *next* turn. If the
+ // driver already recorded a terminal outcome, keep it: a late blind
+ // `Interrupted` here would raise a retry banner on a turn that actually
+ // succeeded and whose reply was delivered.
+ let already_completed = matches!(
+ self.store
+ .get_turn(&self.state.thread_id, &self.state.request_id)
+ .ok()
+ .flatten()
+ .map(|snapshot| snapshot.lifecycle),
+ Some(TurnLifecycle::Completed)
+ );
+ self.state.lifecycle = if already_completed {
+ self.state.phase = None;
+ TurnLifecycle::Completed
+ } else {
+ TurnLifecycle::Interrupted
+ };
self.state.active_tool = None;
self.state.active_subagent = None;
self.state.updated_at = chrono::Utc::now().to_rfc3339();
self.flush();
- self.persist_interrupted_partial();
+ // Only a genuinely interrupted turn has a partial answer to carry over;
+ // a settled turn's reply was already delivered and persisted, and
+ // appending it again would duplicate it in the session transcript.
+ if !already_completed {
+ self.persist_interrupted_partial();
+ }
}
/// Append the partial streamed answer of an interrupted turn to the session
diff --git a/crates/openhuman-core/src/threads/turn_state/store.rs b/crates/openhuman-core/src/threads/turn_state/store.rs
index 8b47f10f26..ffbca06c84 100644
--- a/crates/openhuman-core/src/threads/turn_state/store.rs
+++ b/crates/openhuman-core/src/threads/turn_state/store.rs
@@ -284,6 +284,48 @@ impl TurnStateStore {
Ok(count)
}
+ /// Force one turn's snapshot to a terminal `lifecycle` if it is still
+ /// `Started`/`Streaming`. Returns `true` when it changed something; a
+ /// missing or already-terminal snapshot is a no-op.
+ ///
+ /// The progress bridge is normally the only writer that marks a snapshot
+ /// terminal, and it does so on its way out — but it only exits once its
+ /// progress sender drops, and for a cached per-thread session that does not
+ /// happen until the *next* turn replaces the sink. The last turn of a thread
+ /// would otherwise keep a non-terminal snapshot on disk indefinitely
+ /// (`prune_completed_locked` only prunes `Completed` turns, and the startup
+ /// sweep runs once per process), so re-entering the thread hydrates a
+ /// live-looking "Thinking…" indicator under a reply that already landed.
+ /// The turn driver calls this the moment the turn ends, which is the
+ /// earliest point that is known for certain.
+ pub fn settle_turn(
+ &self,
+ thread_id: &str,
+ request_id: &str,
+ lifecycle: TurnLifecycle,
+ now_rfc3339: &str,
+ ) -> Result<bool, String> {
+ let Some(mut snapshot) = self.get_turn(thread_id, request_id)? else {
+ return Ok(false);
+ };
+ if matches!(
+ snapshot.lifecycle,
+ TurnLifecycle::Interrupted | TurnLifecycle::Completed
+ ) {
+ return Ok(false);
+ }
+ snapshot.lifecycle = lifecycle;
+ snapshot.phase = None;
+ snapshot.active_tool = None;
+ snapshot.active_subagent = None;
+ snapshot.updated_at = now_rfc3339.to_string();
+ self.put(&snapshot)?;
+ debug!(
+ "{LOG_PREFIX} settled non-terminal snapshot thread={thread_id} request={request_id} lifecycle={lifecycle:?}"
+ );
+ Ok(true)
+ }
+
// --- internals -------------------------------------------------------
fn ensure_thread_dir(&self, thread_id: &str) -> Result<PathBuf, String> {
diff --git a/crates/openhuman-core/src/threads/turn_state/store_tests.rs b/crates/openhuman-core/src/threads/turn_state/store_tests.rs
index 661f839219..57d1198bde 100644
--- a/crates/openhuman-core/src/threads/turn_state/store_tests.rs
+++ b/crates/openhuman-core/src/threads/turn_state/store_tests.rs
@@ -3,7 +3,7 @@
use super::*;
use crate::threads::turn_state::types::{
SubagentActivity, SubagentToolCall, SubagentTranscriptItem, ToolTimelineEntry,
- ToolTimelineStatus, TurnLifecycle, TurnState,
+ ToolTimelineStatus, TurnLifecycle, TurnPhase, TurnState,
};
use tempfile::tempdir;
@@ -466,3 +466,79 @@ fn put_overwrites_previous_snapshot() {
assert_eq!(loaded.iteration, 7);
assert_eq!(loaded.updated_at, "2026-05-04T10:05:00Z");
}
+
+/// The last turn of a thread is left `Streaming` on disk when its progress
+/// bridge outlives the turn (the bridge only exits when its progress sender
+/// drops, which for a cached session waits for the *next* turn). Re-entering
+/// the thread then hydrates that snapshot into a permanent "Thinking…"
+/// indicator under a reply that already landed, so the turn driver settles it.
+#[test]
+fn settle_turn_marks_a_live_snapshot_terminal() {
+ let dir = tempdir().expect("tempdir");
+ let store = TurnStateStore::new(dir.path().to_path_buf());
+ let mut state = turn("thread-settle", "req-live", "2026-05-04T10:00:00Z");
+ state.lifecycle = TurnLifecycle::Streaming;
+ state.phase = Some(TurnPhase::Thinking);
+ state.active_tool = Some("shell".into());
+ store.put(&state).expect("put");
+
+ let changed = store
+ .settle_turn(
+ "thread-settle",
+ "req-live",
+ TurnLifecycle::Completed,
+ "2026-05-04T10:05:00Z",
+ )
+ .expect("settle_turn");
+ assert!(changed, "a Streaming snapshot must be settled");
+
+ // `get` is what `threads_turn_state_get` serves to the UI, and the UI reads
+ // `lifecycle` alone to decide whether the turn is still running.
+ let loaded = store.get("thread-settle").expect("get").expect("present");
+ assert_eq!(loaded.lifecycle, TurnLifecycle::Completed);
+ assert_eq!(loaded.phase, None);
+ assert_eq!(loaded.active_tool, None);
+ assert_eq!(loaded.updated_at, "2026-05-04T10:05:00Z");
+}
+
+/// Settling is a floor, not an override: a bridge that already recorded the
+/// true outcome must win, so a failed turn can never downgrade a `Completed`
+/// snapshot to `Interrupted` and raise a spurious retry banner.
+#[test]
+fn settle_turn_leaves_an_already_terminal_snapshot_alone() {
+ let dir = tempdir().expect("tempdir");
+ let store = TurnStateStore::new(dir.path().to_path_buf());
+ let mut state = turn("thread-done", "req-done", "2026-05-04T10:00:00Z");
+ state.lifecycle = TurnLifecycle::Completed;
+ store.put(&state).expect("put");
+
+ let changed = store
+ .settle_turn(
+ "thread-done",
+ "req-done",
+ TurnLifecycle::Interrupted,
+ "2026-05-04T10:05:00Z",
+ )
+ .expect("settle_turn");
+ assert!(!changed, "a terminal snapshot must not be rewritten");
+ let loaded = store.get("thread-done").expect("get").expect("present");
+ assert_eq!(loaded.lifecycle, TurnLifecycle::Completed);
+ assert_eq!(loaded.updated_at, "2026-05-04T10:00:00Z");
+}
+
+/// An absent snapshot is a no-op rather than an error — a turn can end before
+/// the bridge ever flushed one (an immediate failure writes nothing).
+#[test]
+fn settle_turn_is_a_noop_when_no_snapshot_exists() {
+ let dir = tempdir().expect("tempdir");
+ let store = TurnStateStore::new(dir.path().to_path_buf());
+ let changed = store
+ .settle_turn(
+ "thread-missing",
+ "req-missing",
+ TurnLifecycle::Completed,
+ "2026-05-04T10:05:00Z",
+ )
+ .expect("settle_turn");
+ assert!(!changed);
+}
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 79df471fef..da35e428cc 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -281,6 +281,35 @@ pub(crate) async fn run_chat_task(
);
}
+ // Settle the turn's own snapshot now the turn is over.
+ //
+ // The bridge marks the snapshot terminal on its way out, but it only exits
+ // once its progress sender drops — and for a cached per-thread session that
+ // does not happen until the *next* turn replaces the sink, so a bridge
+ // routinely outlives its turn by minutes (the `did not drain` warning above
+ // is the visible edge of it). The last turn of a thread has no next turn to
+ // release it, leaving `Streaming` on disk indefinitely: re-entering the
+ // thread then hydrates that snapshot and paints a live "Thinking..."
+ // indicator under a reply that was already delivered. The turn has ended
+ // here by construction, so record that. A bridge that later observes
+ // `TurnCompleted` overwrites this with `Completed`, terminal either way.
+ {
+ let lifecycle = if result.is_ok() {
+ crate::threads::turn_state::TurnLifecycle::Completed
+ } else {
+ crate::threads::turn_state::TurnLifecycle::Interrupted
+ };
+ let now = chrono::Utc::now().to_rfc3339();
+ if let Err(err) = TurnStateStore::new(config.workspace_dir.clone())
+ .settle_turn(thread_id, request_id, lifecycle, &now)
+ {
+ log::warn!(
+ "[web-channel] failed to settle turn snapshot client={client_id} \
+ thread={thread_id} request_id={request_id}: {err}"
+ );
+ }
+ }
+
// The bridge only stamps its `TurnTimingSnapshot` once it has seen the
// parent's `TurnCompleted`, which `wait_drained` above waits for — read
// it now so `chat_done.timing` reports the same first-token/first-tool/