The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(threads): replace turn_state store with RPC types
Steven Enamakel00fd2b17e377
diff --git a/crates/openhuman-core/src/threads/turn_state/mod.rs b/crates/openhuman-core/src/threads/turn_state/mod.rsindex 0110ea7903..b0e7b314ac 100644--- a/crates/openhuman-core/src/threads/turn_state/mod.rs+++ b/crates/openhuman-core/src/threads/turn_state/mod.rs@@ -19,14 +19,10 @@//! picture.pub mod mirror;-pub mod store;-pub mod types;+pub mod rpc_types;pub use mirror::TurnStateMirror;--pub use store::TurnStateStore;-pub use types::{+pub use rpc_types::{ClearTurnStateRequest, ClearTurnStateResponse, GetTurnStateForRequestRequest,- GetTurnStateRequest, GetTurnStateResponse, ListTurnStatesResponse, SubagentActivity,- SubagentToolCall, ToolTimelineEntry, ToolTimelineStatus, TurnLifecycle, TurnPhase, TurnState,+ GetTurnStateRequest, GetTurnStateResponse, ListTurnStatesResponse,};diff --git a/crates/openhuman-core/src/threads/turn_state/rpc_types.rs b/crates/openhuman-core/src/threads/turn_state/rpc_types.rsnew file mode 100644index 0000000000..66058d2ca0--- /dev/null+++ b/crates/openhuman-core/src/threads/turn_state/rpc_types.rs@@ -0,0 +1,78 @@+//! RPC payloads for the `threads.turn_state_*` controllers, plus the host+//! conversion from a classified tool failure into its persisted form.+//!+//! The snapshot shapes and the store live in+//! `tinyagents_session::turn_state`; only the OpenHuman RPC envelopes and the+//! `ClassifiedFailure` projection stay host-side.++use serde::{Deserialize, Serialize};+use tinyagents_session::turn_state::types::{PersistedToolFailure, TurnState};++/// Request payload for `openhuman.threads_turn_state_get`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct GetTurnStateRequest {+ pub thread_id: String,+}++/// Response payload for `openhuman.threads_turn_state_get`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct GetTurnStateResponse {+ /// `None` when no snapshot exists for the thread.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub turn_state: Option<TurnState>,+}++/// Response payload for `openhuman.threads_turn_state_list` and+/// `openhuman.threads_turn_state_history`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ListTurnStatesResponse {+ pub turn_states: Vec<TurnState>,+ pub count: usize,+}++/// Request payload for `openhuman.threads_turn_state_get_turn` — a specific+/// turn of a thread, identified by its producing request id.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct GetTurnStateForRequestRequest {+ pub thread_id: String,+ pub request_id: String,+}++/// Request payload for `openhuman.threads_turn_state_clear`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ClearTurnStateRequest {+ pub thread_id: String,+}++/// Response payload for `openhuman.threads_turn_state_clear`.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ClearTurnStateResponse {+ pub cleared: bool,+}++impl From<&crate::tools::status::ClassifiedFailure> for PersistedToolFailure {+ fn from(f: &crate::tools::status::ClassifiedFailure) -> Self {+ // Serialize the enums to their wire variant name so the persisted+ // `class`/`category` strings match exactly what the live socket emits+ // (`ClassifiedFailure` serializes each as its bare variant name).+ fn variant_name<T: Serialize>(v: &T) -> String {+ serde_json::to_value(v)+ .ok()+ .and_then(|j| j.as_str().map(str::to_string))+ .unwrap_or_default()+ }+ Self {+ class: variant_name(&f.class),+ category: variant_name(&f.category),+ recoverable: f.recoverable,+ cause_plain: f.cause_plain.clone(),+ next_action: f.next_action.clone(),+ }+ }+}diff --git a/crates/openhuman-core/src/threads/turn_state/store.rs b/crates/openhuman-core/src/threads/turn_state/store.rsdeleted file mode 100644index ffbca06c84..0000000000--- a/crates/openhuman-core/src/threads/turn_state/store.rs+++ /dev/null@@ -1,718 +0,0 @@-//! Filesystem-backed snapshot store for [`super::types::TurnState`].-//!-//! **Per-turn ring layout.** One JSON file per *turn* under a per-thread-//! directory:-//! `<workspace>/memory/conversations/turn_states/<hex(thread_id)>/<hex(request_id)>.json`.-//! Each turn keeps its own snapshot so a multi-turn thread retains every turn's-//! tool timeline (the "Agentic task insights" trail), not just the latest.-//! Completed turns are pruned to the newest [`COMPLETED_RETENTION`] per thread so-//! history stays bounded.-//!-//! The `get(thread_id)` / `list()` / `delete(thread_id)` / `clear_all` /-//! `mark_all_interrupted` surface is unchanged so existing callers (RPC layer,-//! mirror, cold-boot) keep working: `get`/`list` resolve the *latest* turn per-//! thread. New `get_turn(thread_id, request_id)` and `list_thread(thread_id)`-//! expose the per-turn history.-//!-//! **Legacy migration.** Snapshots written by older cores live as flat files-//! `turn_states/<hex(thread_id)>.json`. They are migrated in place — read once,-//! rewritten under `<hex(thread_id)>/<hex(request_id)>.json`, and the flat file-//! removed — on first access. Migration is idempotent.-//!-//! Mutations are serialised through a single process-wide mutex so the progress-//! consumer cannot interleave a flush against an RPC handler reading the same-//! file.--use std::fs::{self, File};-use std::io::{Read, Write};-use std::path::{Path, PathBuf};--use log::{debug, warn};-use once_cell::sync::Lazy;-use parking_lot::Mutex;-use tempfile::NamedTempFile;--use super::types::{TurnLifecycle, TurnState};--const LOG_PREFIX: &str = "[threads:turn_state]";-const TURN_STATE_DIR: &str = "turn_states";-const SNAPSHOT_EXTENSION: &str = "json";-/// Newest completed turns retained per thread. Older completed turns are pruned-/// on the next completed write so a long-lived thread's history stays bounded-/// (mirrors the timeline registry's soft-cap philosophy — never unbounded).-const COMPLETED_RETENTION: usize = 20;-static TURN_STATE_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));--/// Workspace-rooted handle that reads and writes per-thread turn snapshots.-#[derive(Debug, Clone)]-pub struct TurnStateStore {- workspace_dir: PathBuf,-}--impl TurnStateStore {- pub fn new(workspace_dir: PathBuf) -> Self {- Self { workspace_dir }- }-- /// Workspace root this store persists under. Exposed so the mirror can- /// resolve sibling session transcripts (append the interrupted partial to- /// `session_raw/{root}.jsonl`) without re-plumbing the path.- pub fn workspace_dir(&self) -> &std::path::Path {- &self.workspace_dir- }-- /// Atomically write the snapshot for `state.request_id` under- /// `state.thread_id`. On a `Completed` write, prune the thread's completed- /// turns to the newest [`COMPLETED_RETENTION`].- pub fn put(&self, state: &TurnState) -> Result<(), String> {- let _guard = TURN_STATE_LOCK.lock();- // Fold any pre-existing flat file for this thread into the per-turn- // layout first so the directory is the single source of truth.- self.migrate_thread_locked(&state.thread_id);- let dir = self.ensure_thread_dir(&state.thread_id)?;- let path = self.turn_path(&state.thread_id, &state.request_id);- let mut tmp = NamedTempFile::new_in(&dir)- .map_err(|e| format!("create turn-state tempfile in {}: {e}", dir.display()))?;- let bytes =- serde_json::to_vec_pretty(state).map_err(|e| format!("serialize turn state: {e}"))?;- tmp.write_all(&bytes)- .map_err(|e| format!("write turn-state tempfile: {e}"))?;- tmp.as_file()- .sync_all()- .map_err(|e| format!("fsync turn-state tempfile: {e}"))?;- persist_temp_file(tmp, &path)?;- // Sync the directory entry created by the rename — without this a crash- // or power loss between persist() and the next fs flush can drop the- // snapshot, defeating the cold-boot recovery guarantee. Best-effort on- // platforms where opening a directory for sync is not supported.- if let Err(err) = sync_dir(&dir) {- log::warn!("{LOG_PREFIX} failed to fsync {}: {err}", dir.display());- }- debug!(- "{LOG_PREFIX} wrote snapshot thread={} request={} lifecycle={:?} iter={}/{} timeline={}",- state.thread_id,- state.request_id,- state.lifecycle,- state.iteration,- state.max_iterations,- state.tool_timeline.len()- );- if state.lifecycle == TurnLifecycle::Completed {- self.prune_completed_locked(&state.thread_id);- }- Ok(())- }-- /// Return the latest turn for `thread_id`, or `None` if none exists.- /// "Latest" is the turn with the greatest `started_at` (ties broken by- /// `updated_at`) — the in-flight or most-recent turn.- pub fn get(&self, thread_id: &str) -> Result<Option<TurnState>, String> {- let _guard = TURN_STATE_LOCK.lock();- self.migrate_thread_locked(thread_id);- Ok(latest_turn(self.read_thread_turns(thread_id)?))- }-- /// Return a specific turn by `request_id`, or `None` if absent.- pub fn get_turn(&self, thread_id: &str, request_id: &str) -> Result<Option<TurnState>, String> {- let _guard = TURN_STATE_LOCK.lock();- self.migrate_thread_locked(thread_id);- let path = self.turn_path(thread_id, request_id);- if !path.exists() {- return Ok(None);- }- read_snapshot(&path).map(Some)- }-- /// Delete every turn for `thread_id` (and any legacy flat file). Returns- /// `true` if anything was removed.- pub fn delete(&self, thread_id: &str) -> Result<bool, String> {- let _guard = TURN_STATE_LOCK.lock();- let mut removed = false;- let flat = self.legacy_flat_path(thread_id);- if flat.exists() {- fs::remove_file(&flat)- .map_err(|e| format!("remove legacy turn-state {}: {e}", flat.display()))?;- removed = true;- }- let dir = self.thread_dir(thread_id);- if dir.exists() {- fs::remove_dir_all(&dir)- .map_err(|e| format!("remove turn-state dir {}: {e}", dir.display()))?;- removed = true;- }- if removed {- debug!("{LOG_PREFIX} deleted snapshots thread={}", thread_id);- }- Ok(removed)- }-- /// Delete one turn's snapshot by `request_id`, leaving every other turn on- /// the thread untouched. Returns `true` if a file was removed.- ///- /// Backs edit/regenerate (`threads.edit_message` / `threads.regenerate`):- /// truncating the message log after a cut point orphans the turn- /// snapshots for every dropped request — `delete(thread_id)` would also- /// discard the turns kept *before* the cut, which a client's "Agentic- /// task insights" trail for an earlier answer still needs.- pub fn delete_turn(&self, thread_id: &str, request_id: &str) -> Result<bool, String> {- let _guard = TURN_STATE_LOCK.lock();- self.migrate_thread_locked(thread_id);- let path = self.turn_path(thread_id, request_id);- if !path.exists() {- return Ok(false);- }- fs::remove_file(&path).map_err(|e| format!("remove turn-state {}: {e}", path.display()))?;- debug!("{LOG_PREFIX} deleted snapshot thread={thread_id} request={request_id}");- Ok(true)- }-- /// List the latest turn for every thread. Used by the UI on cold boot to- /// surface interrupted turns from a previous process (one entry per thread,- /// preserving the pre-ring-store contract).- pub fn list(&self) -> Result<Vec<TurnState>, String> {- let _guard = TURN_STATE_LOCK.lock();- self.migrate_all_legacy_locked();- let dir = self.dir();- if !dir.exists() {- return Ok(Vec::new());- }- let mut snapshots = Vec::new();- for thread_id in self.thread_ids()? {- if let Some(latest) = latest_turn(self.read_thread_turns(&thread_id)?) {- snapshots.push(latest);- }- }- Ok(snapshots)- }-- /// List every turn for one thread, newest first (by `started_at`).- pub fn list_thread(&self, thread_id: &str) -> Result<Vec<TurnState>, String> {- let _guard = TURN_STATE_LOCK.lock();- self.migrate_thread_locked(thread_id);- let mut turns = self.read_thread_turns(thread_id)?;- turns.sort_by(|a, b| {- b.started_at- .cmp(&a.started_at)- .then_with(|| b.updated_at.cmp(&a.updated_at))- });- Ok(turns)- }-- /// Remove every snapshot file, readable or not (per-turn files, thread- /// directories, and any legacy flat files). Used by `threads_purge` to- /// guarantee a destructive cleanup leaves nothing — `list()` only returns- /// parseable snapshots, so iterating list+delete would silently leave- /// half-written or schema-skewed files behind. Returns the count of JSON- /// files removed.- pub fn clear_all(&self) -> Result<usize, String> {- let _guard = TURN_STATE_LOCK.lock();- let dir = self.dir();- if !dir.exists() {- return Ok(0);- }- let mut removed = 0usize;- for entry in- fs::read_dir(&dir).map_err(|e| format!("read turn-state dir {}: {e}", dir.display()))?- {- let entry = entry.map_err(|e| format!("read turn-state entry: {e}"))?;- let path = entry.path();- let file_type = entry- .file_type()- .map_err(|e| format!("stat turn-state entry {}: {e}", path.display()))?;- if file_type.is_dir() {- // A per-thread directory: count and remove its JSON files, then- // drop the (now empty) directory.- for sub in fs::read_dir(&path)- .map_err(|e| format!("read thread dir {}: {e}", path.display()))?- {- let sub = sub.map_err(|e| format!("read thread entry: {e}"))?;- let sub_path = sub.path();- if sub_path.extension().and_then(|s| s.to_str()) == Some(SNAPSHOT_EXTENSION) {- fs::remove_file(&sub_path).map_err(|e| {- format!("remove turn-state file {}: {e}", sub_path.display())- })?;- removed += 1;- }- }- fs::remove_dir_all(&path)- .map_err(|e| format!("remove thread dir {}: {e}", path.display()))?;- } else if path.extension().and_then(|s| s.to_str()) == Some(SNAPSHOT_EXTENSION) {- // A legacy flat snapshot.- fs::remove_file(&path)- .map_err(|e| format!("remove turn-state file {}: {e}", path.display()))?;- removed += 1;- }- }- if removed > 0 {- debug!(- "{LOG_PREFIX} cleared {removed} snapshots from {}",- dir.display()- );- }- Ok(removed)- }-- /// Mark every non-terminal turn as `Interrupted`. Intended to run on startup- /// so the UI can distinguish stale turns left behind by a previous process- /// from turns currently being driven. `Completed`/`Interrupted` turns are- /// left as-is (idempotent; completed turns are intentionally kept so the- /// processing panel can replay a finished turn after a reboot).- pub fn mark_all_interrupted(&self, now_rfc3339: &str) -> Result<usize, String> {- let turns = {- let _guard = TURN_STATE_LOCK.lock();- self.migrate_all_legacy_locked();- self.all_turns_locked()?- };- let mut count = 0usize;- for mut snapshot in turns {- if matches!(- snapshot.lifecycle,- TurnLifecycle::Interrupted | TurnLifecycle::Completed- ) {- continue;- }- snapshot.lifecycle = TurnLifecycle::Interrupted;- snapshot.updated_at = now_rfc3339.to_string();- snapshot.active_tool = None;- snapshot.active_subagent = None;- self.put(&snapshot)?;- count += 1;- }- if count > 0 {- debug!("{LOG_PREFIX} marked {count} snapshots as interrupted on startup");- }- 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> {- let dir = self.thread_dir(thread_id);- fs::create_dir_all(&dir)- .map_err(|e| format!("create thread turn-state dir {}: {e}", dir.display()))?;- Ok(dir)- }-- fn dir(&self) -> PathBuf {- self.workspace_dir- .join("memory")- .join("conversations")- .join(TURN_STATE_DIR)- }-- fn thread_dir(&self, thread_id: &str) -> PathBuf {- self.dir().join(hex::encode(thread_id.as_bytes()))- }-- fn turn_path(&self, thread_id: &str, request_id: &str) -> PathBuf {- self.thread_dir(thread_id).join(format!(- "{}.{}",- hex::encode(request_id.as_bytes()),- SNAPSHOT_EXTENSION- ))- }-- fn legacy_flat_path(&self, thread_id: &str) -> PathBuf {- self.dir().join(format!(- "{}.{}",- hex::encode(thread_id.as_bytes()),- SNAPSHOT_EXTENSION- ))- }-- /// Read every parseable turn snapshot in one thread's directory.- /// Unreadable files are logged and skipped (mirrors `list()`'s resilience).- fn read_thread_turns(&self, thread_id: &str) -> Result<Vec<TurnState>, String> {- let dir = self.thread_dir(thread_id);- if !dir.exists() {- return Ok(Vec::new());- }- let mut turns = Vec::new();- for entry in fs::read_dir(&dir)- .map_err(|e| format!("read thread turn-state dir {}: {e}", dir.display()))?- {- let entry = entry.map_err(|e| format!("read thread turn-state entry: {e}"))?;- let path = entry.path();- if path.extension().and_then(|s| s.to_str()) != Some(SNAPSHOT_EXTENSION) {- continue;- }- match read_snapshot(&path) {- Ok(snapshot) => turns.push(snapshot),- Err(err) => warn!(- "{LOG_PREFIX} skip unreadable snapshot {}: {err}",- path.display()- ),- }- }- Ok(turns)- }-- /// hex(thread_id) directory names under the root, decoded back to the- /// thread-id string. Skips legacy flat files (handled by migration).- fn thread_ids(&self) -> Result<Vec<String>, String> {- let dir = self.dir();- if !dir.exists() {- return Ok(Vec::new());- }- let mut ids = Vec::new();- for entry in- fs::read_dir(&dir).map_err(|e| format!("read turn-state dir {}: {e}", dir.display()))?- {- let entry = entry.map_err(|e| format!("read turn-state entry: {e}"))?;- if !entry- .file_type()- .map_err(|e| format!("stat turn-state entry: {e}"))?- .is_dir()- {- continue;- }- let name = entry.file_name();- let Some(name) = name.to_str() else { continue };- match hex::decode(name)- .ok()- .and_then(|b| String::from_utf8(b).ok())- {- Some(thread_id) => ids.push(thread_id),- None => warn!("{LOG_PREFIX} skip non-hex thread dir {name}"),- }- }- Ok(ids)- }-- /// Every turn across every thread. Caller holds the lock.- fn all_turns_locked(&self) -> Result<Vec<TurnState>, String> {- let mut turns = Vec::new();- for thread_id in self.thread_ids()? {- turns.append(&mut self.read_thread_turns(&thread_id)?);- }- Ok(turns)- }-- /// If a legacy flat file exists for `thread_id`, fold it into the per-turn- /// layout and remove the flat file. Best-effort; failures are logged. Caller- /// holds the lock.- fn migrate_thread_locked(&self, thread_id: &str) {- let flat = self.legacy_flat_path(thread_id);- if !flat.exists() {- return;- }- match read_snapshot(&flat) {- Ok(state) => {- if let Err(err) = self.write_turn_file(&state) {- warn!(- "{LOG_PREFIX} legacy migrate write failed thread={thread_id}: {err} (flat file kept)"- );- return;- }- if let Err(err) = fs::remove_file(&flat) {- warn!(- "{LOG_PREFIX} legacy migrate: removed-into-dir but flat delete failed {}: {err}",- flat.display()- );- } else {- debug!(- "{LOG_PREFIX} migrated legacy snapshot thread={thread_id} request={}",- state.request_id- );- }- }- Err(err) => warn!(- "{LOG_PREFIX} legacy migrate: unreadable flat file {} left in place: {err}",- flat.display()- ),- }- }-- /// Migrate every legacy flat file under the root. Caller holds the lock.- fn migrate_all_legacy_locked(&self) {- let dir = self.dir();- if !dir.exists() {- return;- }- let entries = match fs::read_dir(&dir) {- Ok(entries) => entries,- Err(err) => {- warn!("{LOG_PREFIX} migrate scan failed {}: {err}", dir.display());- return;- }- };- for entry in entries.flatten() {- let path = entry.path();- if path.extension().and_then(|s| s.to_str()) != Some(SNAPSHOT_EXTENSION) {- continue; // directories and non-json files- }- match read_snapshot(&path) {- Ok(state) => {- if self.write_turn_file(&state).is_ok() {- let _ = fs::remove_file(&path);- debug!(- "{LOG_PREFIX} migrated legacy snapshot thread={} request={}",- state.thread_id, state.request_id- );- }- }- Err(err) => warn!(- "{LOG_PREFIX} migrate: unreadable flat file {} left in place: {err}",- path.display()- ),- }- }- }-- /// Atomic per-turn write without migration/retention side effects. Used by- /// migration to relocate a snapshot. Caller holds the lock.- fn write_turn_file(&self, state: &TurnState) -> Result<(), String> {- let dir = self.ensure_thread_dir(&state.thread_id)?;- let path = self.turn_path(&state.thread_id, &state.request_id);- let mut tmp = NamedTempFile::new_in(&dir)- .map_err(|e| format!("create turn-state tempfile in {}: {e}", dir.display()))?;- let bytes =- serde_json::to_vec_pretty(state).map_err(|e| format!("serialize turn state: {e}"))?;- tmp.write_all(&bytes)- .map_err(|e| format!("write turn-state tempfile: {e}"))?;- tmp.as_file()- .sync_all()- .map_err(|e| format!("fsync turn-state tempfile: {e}"))?;- persist_temp_file(tmp, &path)?;- if let Err(err) = sync_dir(&dir) {- log::warn!("{LOG_PREFIX} failed to fsync {}: {err}", dir.display());- }- Ok(())- }-- /// Prune a thread's `Completed` turns to the newest [`COMPLETED_RETENTION`]- /// by `updated_at`. Non-completed turns (at most the one live turn) are kept.- /// Caller holds the lock. Best-effort — failures are logged, not fatal.- fn prune_completed_locked(&self, thread_id: &str) {- let turns = match self.read_thread_turns(thread_id) {- Ok(turns) => turns,- Err(err) => {- warn!("{LOG_PREFIX} prune read failed thread={thread_id}: {err}");- return;- }- };- let mut completed: Vec<TurnState> = turns- .into_iter()- .filter(|t| t.lifecycle == TurnLifecycle::Completed)- .collect();- if completed.len() <= COMPLETED_RETENTION {- return;- }- // Newest first, then drop everything past the retention window.- completed.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));- for stale in completed.into_iter().skip(COMPLETED_RETENTION) {- let path = self.turn_path(&stale.thread_id, &stale.request_id);- if let Err(err) = fs::remove_file(&path) {- warn!("{LOG_PREFIX} prune remove failed {}: {err}", path.display());- } else {- debug!(- "{LOG_PREFIX} pruned completed turn thread={thread_id} request={}",- stale.request_id- );- }- }- }-}--#[cfg(windows)]-fn persist_temp_file(tmp: NamedTempFile, path: &Path) -> Result<(), String> {- use std::os::windows::ffi::OsStrExt;- use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_REPLACE_EXISTING};-- let wide_path = |path: &Path| -> Result<Vec<u16>, String> {- let filename = path- .file_name()- .ok_or_else(|| format!("resolve turn-state filename {}", path.display()))?;- let parent = path- .parent()- .ok_or_else(|| format!("resolve turn-state parent {}", path.display()))?- // Canonicalizing the existing parent gives Windows a verbatim- // long-path form before appending the not-yet-existing filename.- .canonicalize()- .map_err(|e| format!("resolve turn-state parent {}: {e}", path.display()))?;- let resolved = parent.join(filename);- let raw: Vec<u16> = resolved.as_os_str().encode_wide().collect();- let mut extended =- if raw.starts_with(&[b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]) {- raw- } else if raw.starts_with(&[b'\\' as u16, b'\\' as u16]) {- // Convert a UNC path from `\\server\share` to- // `\\?\UNC\server\share`.- let mut prefixed: Vec<u16> = r"\\?\UNC\".encode_utf16().collect();- prefixed.extend_from_slice(&raw[2..]);- prefixed- } else {- let mut prefixed: Vec<u16> = r"\\?\".encode_utf16().collect();- prefixed.extend_from_slice(&raw);- prefixed- };- extended.push(0);- Ok(extended)- };- // Compute both paths while `tmp` still owns its file, so any preparation- // error lets NamedTempFile clean the tempfile up automatically.- let source = wide_path(tmp.path())?;- let destination = wide_path(path)?;- let (file, temp_path) = tmp- .keep()- .map_err(|e| format!("persist turn-state file {}: {e}", path.display()))?;- // `keep` transfers ownership to us, so close the handle before replacing- // the destination and explicitly clean it up if the replacement fails.- drop(file);- // SAFETY: both buffers are NUL-terminated and remain alive for the call.- // The paths share a directory, so this is an atomic replacement rather- // than a cross-volume copy-and-delete move.- let moved = unsafe {- MoveFileExW(- source.as_ptr(),- destination.as_ptr(),- MOVEFILE_REPLACE_EXISTING,- )- };- if moved != 0 {- return Ok(());- }-- let error = std::io::Error::last_os_error();- Err({- if let Err(cleanup_err) = fs::remove_file(&temp_path) {- warn!(- "{LOG_PREFIX} failed to remove turn-state tempfile {} after rename failure: {cleanup_err}",- temp_path.display()- );- }- format!("persist turn-state file {}: {error}", path.display())- })-}--#[cfg(not(windows))]-fn persist_temp_file(tmp: NamedTempFile, path: &Path) -> Result<(), String> {- tmp.persist(path)- .map(|_| ())- .map_err(|e| format!("persist turn-state file {}: {e}", path.display()))-}--/// Pick the latest turn (greatest `started_at`, ties broken by `updated_at`).-fn latest_turn(turns: Vec<TurnState>) -> Option<TurnState> {- turns.into_iter().max_by(|a, b| {- a.started_at- .cmp(&b.started_at)- .then_with(|| a.updated_at.cmp(&b.updated_at))- })-}--/// Best-effort `fsync` of a directory entry. On Unix, opens the directory for-/// read and calls `sync_all` on the file handle. On Windows this is a no-op —-/// directory fsync is not exposed by the platform and the rename's durability is-/// provided by NTFS journaling.-#[cfg(unix)]-fn sync_dir(dir: &Path) -> std::io::Result<()> {- File::open(dir)?.sync_all()-}--#[cfg(not(unix))]-fn sync_dir(_dir: &Path) -> std::io::Result<()> {- Ok(())-}--fn read_snapshot(path: &Path) -> Result<TurnState, String> {- let mut file =- File::open(path).map_err(|e| format!("open turn-state {}: {e}", path.display()))?;- let mut buf = String::new();- file.read_to_string(&mut buf)- .map_err(|e| format!("read turn-state {}: {e}", path.display()))?;- serde_json::from_str(&buf).map_err(|e| format!("parse turn-state {}: {e}", path.display()))-}--// Free-function wrappers mirroring `memory::conversations::store` so callers-// at the RPC layer don't have to instantiate `TurnStateStore` themselves.--pub fn put(workspace_dir: PathBuf, state: &TurnState) -> Result<(), String> {- TurnStateStore::new(workspace_dir).put(state)-}--pub fn get(workspace_dir: PathBuf, thread_id: &str) -> Result<Option<TurnState>, String> {- TurnStateStore::new(workspace_dir).get(thread_id)-}--pub fn get_turn(- workspace_dir: PathBuf,- thread_id: &str,- request_id: &str,-) -> Result<Option<TurnState>, String> {- TurnStateStore::new(workspace_dir).get_turn(thread_id, request_id)-}--pub fn delete(workspace_dir: PathBuf, thread_id: &str) -> Result<bool, String> {- TurnStateStore::new(workspace_dir).delete(thread_id)-}--pub fn delete_turn(- workspace_dir: PathBuf,- thread_id: &str,- request_id: &str,-) -> Result<bool, String> {- TurnStateStore::new(workspace_dir).delete_turn(thread_id, request_id)-}--pub fn list(workspace_dir: PathBuf) -> Result<Vec<TurnState>, String> {- TurnStateStore::new(workspace_dir).list()-}--pub fn list_thread(workspace_dir: PathBuf, thread_id: &str) -> Result<Vec<TurnState>, String> {- TurnStateStore::new(workspace_dir).list_thread(thread_id)-}--pub fn clear_all(workspace_dir: PathBuf) -> Result<usize, String> {- TurnStateStore::new(workspace_dir).clear_all()-}--pub fn mark_all_interrupted(workspace_dir: PathBuf, now_rfc3339: &str) -> Result<usize, String> {- TurnStateStore::new(workspace_dir).mark_all_interrupted(now_rfc3339)-}--#[cfg(test)]-#[path = "store_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/threads/turn_state/store_tests.rs b/crates/openhuman-core/src/threads/turn_state/store_tests.rsdeleted file mode 100644index 763c02eaf5..0000000000--- a/crates/openhuman-core/src/threads/turn_state/store_tests.rs+++ /dev/null@@ -1,544 +0,0 @@-//! Unit tests for [`super::TurnStateStore`].--use super::*;-use crate::threads::turn_state::types::{- SubagentActivity, SubagentToolCall, SubagentTranscriptItem, ToolTimelineEntry,- ToolTimelineStatus, TurnLifecycle, TurnPhase, TurnState,-};-use tempfile::tempdir;--#[cfg(windows)]-use std::os::windows::ffi::OsStrExt;--fn sample_state(thread_id: &str) -> TurnState {- TurnState::started(thread_id.to_string(), "req-1", 25, "2026-05-04T10:00:00Z")-}--/// A turn with an explicit request id + started/updated timestamps.-fn turn(thread_id: &str, request_id: &str, started_at: &str) -> TurnState {- let mut s = TurnState::started(thread_id.to_string(), request_id, 25, started_at);- s.updated_at = started_at.to_string();- s-}--fn turn_states_root(dir: &tempfile::TempDir) -> std::path::PathBuf {- dir.path()- .join("memory")- .join("conversations")- .join("turn_states")-}--#[test]-fn put_then_get_roundtrips_state() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let mut state = sample_state("thread-abc");- state.lifecycle = TurnLifecycle::Streaming;- state.iteration = 3;- state.streaming_text = "hello".into();- state.tool_timeline.push(ToolTimelineEntry {- id: "tc-1".into(),- name: "shell".into(),- round: 1,- status: ToolTimelineStatus::Running,- args_buffer: Some("{".into()),- display_name: None,- detail: None,- source_tool_name: None,- subagent: None,- failure: None,- output: None,- seq: Some(0),- });-- store.put(&state).expect("put");- let loaded = store.get("thread-abc").expect("get").expect("present");- assert_eq!(loaded, state);-}--#[cfg(windows)]-#[test]-fn put_roundtrips_snapshot_with_a_path_longer_than_max_path() {- let dir = tempdir().expect("tempdir");- let mut workspace = dir.path().to_path_buf();- let thread_id = "t".repeat(43);- let request_id = "r".repeat(36);- while workspace- .join("memory")- .join("conversations")- .join("turn_states")- .join(hex::encode(&thread_id))- .join(format!("{}.json", hex::encode(&request_id)))- .as_os_str()- .encode_wide()- .count()- <= 260- {- workspace.push("long_workspace_segment");- }- let mut state = turn(&thread_id, &request_id, "2026-05-04T10:00:00Z");- let store = TurnStateStore::new(workspace);-- store.put(&state).expect("persist a snapshot past MAX_PATH");- assert_eq!(store.get(&thread_id).expect("get"), Some(state.clone()));-- // A regular progress flush replaces the same snapshot repeatedly.- state.iteration = 2;- store.put(&state).expect("replace snapshot past MAX_PATH");- assert_eq!(store.get(&thread_id).expect("get replacement"), Some(state));-}--#[test]-fn roundtrips_subagent_interleaved_transcript_with_full_fidelity() {- // A settled turn whose subagent streamed reasoning, called a tool, then- // narrated — the interleaved transcript (not just the flat tool rows) plus- // the per-row `seq` ordering keys must survive a disk round-trip verbatim,- // so a reopened transcript rehydrates without losing the subagent's- // reasoning (the gap SubagentDrawer/chatRuntimeSlice documented).- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let mut state = sample_state("thread-sub");- state.lifecycle = TurnLifecycle::Completed;-- let activity = SubagentActivity {- task_id: "sub-1".into(),- agent_id: "researcher".into(),- status: Some("completed".into()),- mode: Some("typed".into()),- dedicated_thread: Some(false),- child_iteration: Some(1),- child_max_iterations: Some(8),- iterations: Some(2),- elapsed_ms: Some(1234),- output_chars: Some(42),- worker_thread_id: Some("worker-thread-9".into()),- parent_call_id: Some("call-1".into()),- output: Some("done".into()),- tool_calls: vec![SubagentToolCall {- call_id: "c1".into(),- tool_name: "search".into(),- status: ToolTimelineStatus::Success,- iteration: Some(1),- elapsed_ms: Some(12),- output_chars: Some(6),- display_name: Some("Searching".into()),- detail: None,- args: Some(serde_json::json!({ "query": "rust serde" })),- failure: None,- output: Some("3 hits".into()),- }],- transcript: vec![- SubagentTranscriptItem::Thinking {- iteration: Some(1),- text: "let me search.".into(),- },- SubagentTranscriptItem::Tool {- iteration: Some(1),- call_id: "c1".into(),- tool_name: "search".into(),- status: ToolTimelineStatus::Success,- elapsed_ms: Some(12),- output_chars: Some(6),- display_name: Some("Searching".into()),- detail: None,- },- SubagentTranscriptItem::Text {- iteration: Some(1),- text: "Found it.".into(),- },- ],- };-- state.tool_timeline.push(ToolTimelineEntry {- id: "subagent:sub-1".into(),- name: "subagent:researcher".into(),- round: 1,- status: ToolTimelineStatus::Success,- args_buffer: None,- display_name: Some("Researcher".into()),- detail: None,- source_tool_name: Some("spawn_subagent".into()),- subagent: Some(activity),- failure: None,- output: None,- seq: Some(3),- });-- store.put(&state).expect("put");- let loaded = store.get("thread-sub").expect("get").expect("present");- // Structural equality proves nothing in the interleaved transcript,- // subagent activity, or the `seq` ordering keys was dropped or reordered.- assert_eq!(loaded, state);-- // Spot-check the interleaving explicitly so a future regression that keeps- // the fields but loses the ordering still fails here.- let activity = loaded.tool_timeline[0]- .subagent- .as_ref()- .expect("subagent activity restored");- assert_eq!(activity.transcript.len(), 3);- assert!(matches!(- activity.transcript[0],- SubagentTranscriptItem::Thinking { .. }- ));- assert!(matches!(- activity.transcript[1],- SubagentTranscriptItem::Tool { .. }- ));- assert!(matches!(- activity.transcript[2],- SubagentTranscriptItem::Text { .. }- ));- // The child call's arguments are what the reloaded row's "Input" block- // renders from. Spot-checked by value (like the interleaving above) so a- // regression names the field instead of failing as one opaque struct- // inequality (#5987).- assert_eq!(- activity.tool_calls[0].args,- Some(serde_json::json!({ "query": "rust serde" })),- "child tool arguments must survive the disk round-trip"- );- assert_eq!(loaded.tool_timeline[0].seq, Some(3));-}--#[test]-fn get_returns_none_when_absent() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- assert!(store.get("missing").expect("get").is_none());-}--#[test]-fn delete_removes_snapshot_and_reports_presence() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let state = sample_state("thread-x");- store.put(&state).expect("put");- assert!(store.delete("thread-x").expect("delete"));- assert!(!store.delete("thread-x").expect("delete-again"));- assert!(store.get("thread-x").expect("get").is_none());-}--#[test]-fn list_returns_every_snapshot() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- store.put(&sample_state("a")).expect("put a");- store.put(&sample_state("b")).expect("put b");- let mut ids: Vec<String> = store- .list()- .expect("list")- .into_iter()- .map(|s| s.thread_id)- .collect();- ids.sort();- assert_eq!(ids, vec!["a".to_string(), "b".to_string()]);-}--#[test]-fn list_on_missing_dir_is_empty() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- assert!(store.list().expect("list").is_empty());-}--#[test]-fn mark_all_interrupted_promotes_lifecycle_and_clears_active_fields() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let mut state = sample_state("t");- state.lifecycle = TurnLifecycle::Streaming;- state.active_tool = Some("shell".into());- state.active_subagent = Some("researcher".into());- store.put(&state).expect("put");-- let count = store- .mark_all_interrupted("2026-05-04T10:01:00Z")- .expect("mark");- assert_eq!(count, 1);-- let loaded = store.get("t").expect("get").expect("present");- assert_eq!(loaded.lifecycle, TurnLifecycle::Interrupted);- assert_eq!(loaded.updated_at, "2026-05-04T10:01:00Z");- assert!(loaded.active_tool.is_none());- assert!(loaded.active_subagent.is_none());-- // Re-running is a no-op for already-interrupted snapshots.- let count = store- .mark_all_interrupted("2026-05-04T10:02:00Z")- .expect("mark again");- assert_eq!(count, 0);-}--#[test]-fn mark_all_interrupted_leaves_completed_snapshots_untouched() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let mut state = sample_state("t");- // A finished turn is kept as `Completed` so its processing can be replayed;- // startup interrupted-marking must not flip it to `Interrupted`.- state.lifecycle = TurnLifecycle::Completed;- store.put(&state).expect("put");-- let count = store- .mark_all_interrupted("2026-05-04T10:01:00Z")- .expect("mark");- assert_eq!(count, 0);- let loaded = store.get("t").expect("get").expect("present");- assert_eq!(loaded.lifecycle, TurnLifecycle::Completed);-}--#[test]-fn clear_all_removes_corrupted_snapshots_too() {- use std::io::Write as _;- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- store.put(&sample_state("a")).expect("put a");- store.put(&sample_state("b")).expect("put b");-- // Drop a corrupted JSON file alongside — `list()` would skip it,- // but a destructive purge must still remove it.- let corrupt_path = dir- .path()- .join("memory")- .join("conversations")- .join("turn_states")- .join("deadbeef.json");- let mut f = std::fs::File::create(&corrupt_path).expect("create corrupt");- f.write_all(b"{ not valid json").expect("write corrupt");- drop(f);- assert!(corrupt_path.exists());-- let removed = store.clear_all().expect("clear_all");- assert_eq!(removed, 3, "all three snapshots must be removed");- assert!(!corrupt_path.exists(), "corrupted snapshot must be cleared");- assert!(store.list().expect("list").is_empty());-}--#[test]-fn clear_all_on_missing_dir_returns_zero() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- assert_eq!(store.clear_all().expect("clear"), 0);-}--#[test]-fn keeps_a_separate_snapshot_per_turn_and_get_returns_latest() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- store- .put(&turn("t", "req-1", "2026-05-04T10:00:00Z"))- .expect("put turn 1");- store- .put(&turn("t", "req-2", "2026-05-04T10:05:00Z"))- .expect("put turn 2");-- // Both turns are retained...- let history = store.list_thread("t").expect("list_thread");- assert_eq!(history.len(), 2);- // ...newest first.- assert_eq!(history[0].request_id, "req-2");- assert_eq!(history[1].request_id, "req-1");-- // get(thread) resolves the latest turn (greatest started_at).- let latest = store.get("t").expect("get").expect("present");- assert_eq!(latest.request_id, "req-2");-- // get_turn fetches a specific earlier turn.- let earlier = store- .get_turn("t", "req-1")- .expect("get_turn")- .expect("present");- assert_eq!(earlier.request_id, "req-1");- assert!(store.get_turn("t", "nope").expect("get_turn").is_none());-- // list() surfaces exactly one (latest) entry per thread for cold boot.- let latest_per_thread = store.list().expect("list");- assert_eq!(latest_per_thread.len(), 1);- assert_eq!(latest_per_thread[0].request_id, "req-2");-}--#[test]-fn completed_turns_are_pruned_to_the_retention_window() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- // Write 25 completed turns; only the newest COMPLETED_RETENTION (20) survive.- for i in 0..25 {- let mut s = turn(- "t",- &format!("req-{i:02}"),- &format!("2026-05-04T10:{i:02}:00Z"),- );- s.lifecycle = TurnLifecycle::Completed;- s.updated_at = format!("2026-05-04T10:{i:02}:00Z");- store.put(&s).expect("put");- }- let history = store.list_thread("t").expect("list_thread");- assert_eq!(history.len(), super::COMPLETED_RETENTION);- // The oldest five (req-00..req-04) are gone; the newest survive.- assert!(history.iter().any(|t| t.request_id == "req-24"));- assert!(history.iter().all(|t| t.request_id != "req-00"));- assert!(store.get_turn("t", "req-04").expect("get_turn").is_none());- assert!(store.get_turn("t", "req-05").expect("get_turn").is_some());-}--#[test]-fn a_live_turn_is_not_pruned_alongside_completed_history() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- for i in 0..COMPLETED_RETENTION_PLUS {- let mut s = turn(- "t",- &format!("done-{i:02}"),- &format!("2026-05-04T10:{i:02}:00Z"),- );- s.lifecycle = TurnLifecycle::Completed;- s.updated_at = format!("2026-05-04T10:{i:02}:00Z");- store.put(&s).expect("put completed");- }- // A running turn coexists and is never pruned (only completed turns are).- let mut live = turn("t", "live", "2026-05-04T11:00:00Z");- live.lifecycle = TurnLifecycle::Streaming;- store.put(&live).expect("put live");- assert!(store.get_turn("t", "live").expect("get_turn").is_some());- assert_eq!(- store.get("t").expect("get").expect("present").request_id,- "live"- );-}--#[test]-fn migrates_a_legacy_flat_snapshot_into_the_per_turn_layout() {- use std::io::Write as _;- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let root = turn_states_root(&dir);- std::fs::create_dir_all(&root).expect("mkdir root");-- // Hand-write an old-style flat snapshot at `<hex(thread_id)>.json`.- let legacy = turn("legacy-thread", "req-legacy", "2026-05-04T09:00:00Z");- let flat_path = root.join(format!("{}.json", hex::encode("legacy-thread".as_bytes())));- let mut f = std::fs::File::create(&flat_path).expect("create flat");- f.write_all(serde_json::to_vec_pretty(&legacy).unwrap().as_slice())- .expect("write flat");- drop(f);-- // First access migrates it into the dir and removes the flat file.- let loaded = store.get("legacy-thread").expect("get").expect("present");- assert_eq!(loaded.request_id, "req-legacy");- assert!(- !flat_path.exists(),- "flat file must be removed after migration"- );- let per_turn = root- .join(hex::encode("legacy-thread".as_bytes()))- .join(format!("{}.json", hex::encode("req-legacy".as_bytes())));- assert!(- per_turn.exists(),- "snapshot must live under the per-turn path"- );-- // Migration is idempotent — a second access is a no-op.- assert_eq!(- store- .get("legacy-thread")- .expect("get2")- .expect("present")- .request_id,- "req-legacy"- );-}--const COMPLETED_RETENTION_PLUS: usize = super::COMPLETED_RETENTION + 3;--#[test]-fn put_overwrites_previous_snapshot() {- let dir = tempdir().expect("tempdir");- let store = TurnStateStore::new(dir.path().to_path_buf());- let mut state = sample_state("t");- state.iteration = 1;- store.put(&state).expect("put 1");- state.iteration = 7;- state.updated_at = "2026-05-04T10:05:00Z".into();- store.put(&state).expect("put 2");-- let loaded = store.get("t").expect("get").expect("present");- 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/threads/turn_state/types.rs b/crates/openhuman-core/src/threads/turn_state/types.rsdeleted file mode 100644index 2b24ba4a10..0000000000--- a/crates/openhuman-core/src/threads/turn_state/types.rs+++ /dev/null@@ -1,441 +0,0 @@-//! Wire/storage types for per-thread agent-turn snapshots.-//!-//! A [`TurnState`] mirrors the live state held by the web-channel-//! progress consumer so the UI can rehydrate after a cold boot or-//! after the user navigates away mid-turn. The shape intentionally-//! parallels `app/src/store/chatRuntimeSlice.ts` so a snapshot can-//! be applied directly to that slice.--use serde::{Deserialize, Serialize};--/// Lifecycle of an in-flight (or formerly in-flight) turn.-///-/// `Started` is set when the user sends and the agent loop is about-/// to enter the iteration loop. `Streaming` is set after the first-/// progress signal arrives. `Interrupted` is stamped at startup on-/// any snapshot that survived a process restart — there is no live-/// driver to resume it, so the UI should surface a retry affordance.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum TurnLifecycle {- Started,- Streaming,- Interrupted,- /// The turn finished normally. The snapshot is **kept** (not deleted) so- /// the chat "View processing" panel can replay the full transcript +- /// tool timeline after a reload / cold boot — startup interrupted-marking- /// skips this state, and the next turn on the thread overwrites it.- Completed,-}--/// High-level phase the agent is in within an iteration.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum TurnPhase {- Thinking,- ToolUse,- Subagent,-}--/// Per-tool entry shown in the live timeline UI.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum ToolTimelineStatus {- Running,- Success,- Error,-}--/// Persisted, plain-language explanation of a FAILED tool row (#4459).-///-/// Mirrors the live socket `failure` object and the frontend-/// `PersistedToolFailure` (`app/src/types/turnState.ts`) 1:1 — camelCase on the-/// wire, `class`/`category` as the taxonomy's stable variant names — so a-/// settled/reloaded turn keeps its "why + what to do next" copy across a thread-/// switch or a cold boot. Absent on successful rows and on snapshots written-/// before this field.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct PersistedToolFailure {- /// Stable failure-class variant name, e.g. `"Timeout"`, `"Denied"`.- pub class: String,- /// Stable category variant name, e.g. `"Recoverable"`, `"UserDeclined"`.- pub category: String,- /// Whether the core considers the failure automatically recoverable.- pub recoverable: bool,- /// Plain-language cause (`causePlain` on the wire).- pub cause_plain: String,- /// Plain-language next action (`nextAction` on the wire).- pub next_action: String,-}--impl From<&crate::tools::status::ClassifiedFailure> for PersistedToolFailure {- fn from(f: &crate::tools::status::ClassifiedFailure) -> Self {- // Serialize the enums to their wire variant name so the persisted- // `class`/`category` strings match exactly what the live socket emits- // (`ClassifiedFailure` serializes each as its bare variant name).- fn variant_name<T: Serialize>(v: &T) -> String {- serde_json::to_value(v)- .ok()- .and_then(|j| j.as_str().map(str::to_string))- .unwrap_or_default()- }- Self {- class: variant_name(&f.class),- category: variant_name(&f.category),- recoverable: f.recoverable,- cause_plain: f.cause_plain.clone(),- next_action: f.next_action.clone(),- }- }-}--/// One row in the per-turn tool timeline.-///-/// Field names use camelCase on the wire so a snapshot can be applied-/// directly to `chatRuntimeSlice.toolTimelineByThread` without a-/// translation layer in the UI.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ToolTimelineEntry {- pub id: String,- pub name: String,- pub round: u32,- pub status: ToolTimelineStatus,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub args_buffer: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub display_name: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub detail: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub source_tool_name: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub subagent: Option<SubagentActivity>,- /// Plain-language failure explanation for a FAILED row, carried in the- /// snapshot so it survives a thread switch / cold boot (#4459). `None` on- /// success and on legacy snapshots.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub failure: Option<PersistedToolFailure>,- /// Size-capped tool result text, persisted so the "View processing"- /// panel can show what a tool returned after a thread switch / cold- /// boot — the live socket forwards the same capped payload on- /// `tool_result`. `None` while running and on legacy snapshots.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub output: Option<String>,- /// Per-turn monotonic ordering key stamped at the moment the row is first- /// created, so a rehydrated timeline can order rows identically to the live- /// stream (conversations-timeline-refactor, Phase 4 amendment). Shares the- /// per-turn ordering space with [`TranscriptItem::seq`]. `None` on snapshots- /// written before this field.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub seq: Option<u64>,-}--/// Live sub-agent activity nested under a `subagent:*` timeline row.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SubagentActivity {- pub task_id: String,- pub agent_id: String,- /// High-level status: `"running"`, `"awaiting_user"`, `"completed"`,- /// `"failed"`. `None` for legacy snapshots written before this field.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub status: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub mode: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub dedicated_thread: Option<bool>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub child_iteration: Option<u32>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub child_max_iterations: Option<u32>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub iterations: Option<u32>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub elapsed_ms: Option<u64>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub output_chars: Option<usize>,- /// Persistent worker sub-thread backing this delegation, when one was- /// created. Lets the UI reopen the full parent↔subagent conversation- /// from memory after a cold boot / interrupted turn.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub worker_thread_id: Option<String>,- /// The parent turn's tool-call id (the `spawn_subagent` / dispatch call)- /// this delegation is attributed to. Mirrors- /// [`crate::agent::progress::AgentProgress::SubagentSpawned::parent_call_id`].- /// `None` for legacy snapshots and spawn sites the harness gave no call- /// context (e.g. `orchestration::ops`).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub parent_call_id: Option<String>,- /// Size-capped final assistant text, persisted so a rehydrated row can- /// still show what the sub-agent answered — mirrors the live- /// `subagent_completed` socket payload's `subagent.output`. `None`- /// while running, on failure, and on legacy snapshots.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub output: Option<String>,- #[serde(default)]- pub tool_calls: Vec<SubagentToolCall>,- /// Ordered reasoning/narration/tool transcript for this sub-agent — what- /// the inline "Agentic task insights" thoughts render from. Persisted (not- /// live-only) so the thoughts survive a settled turn / reload.- /// `#[serde(default)]` so snapshots written before this field load empty.- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub transcript: Vec<SubagentTranscriptItem>,-}--/// One child tool call performed by a running sub-agent.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SubagentToolCall {- pub call_id: String,- pub tool_name: String,- pub status: ToolTimelineStatus,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub iteration: Option<u32>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub elapsed_ms: Option<u64>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub output_chars: Option<usize>,- /// Server-computed human label for this child call (e.g. "Reading file"),- /// or `None` to defer to the client formatter. Mirrors the parent- /// [`ToolTimelineEntry::display_name`] so the same reusable row renderer- /// reads the same field for both main-agent and sub-agent calls.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub display_name: Option<String>,- /// Server-computed contextual detail (e.g. the path / recipient).- #[serde(default, skip_serializing_if = "Option::is_none")]- pub detail: Option<String>,- /// Size-capped arguments the child invoked the tool with, so a rehydrated- /// row shows *what* the sub-agent did and not just which tool it reached- /// for (#5987). Mirrors the live `subagent_tool_call` event's `args`- /// verbatim when it fits the cap; an oversized payload degrades to a- /// truncated string. Taken from the started event when it carries the- /// arguments, otherwise backfilled from- /// [`AgentProgress::SubagentToolCallCompleted::arguments`] — the tinyagents- /// path emits `Value::Null` at start and only captures the input on- /// completion. `None` when the harness captured no input at all- /// (`PayloadCapture::tool_io` off) and on legacy snapshots.- ///- /// Deliberately absent from [`SubagentTranscriptItem::Tool`]: like- /// `output` and `failure`, this is a heavy payload that lives once on the- /// call row, and the frontend grafts it onto the matching transcript item- /// by `call_id` when it rehydrates.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub args: Option<serde_json::Value>,- /// Plain-language failure explanation for a FAILED child call, so a- /// sub-agent's failed row carries the same "why + next" copy as a- /// main-agent row and it survives a snapshot round-trip (#4459). `None` on- /// success and on legacy snapshots.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub failure: Option<PersistedToolFailure>,- /// Size-capped child tool result text, persisted for the same reason as- /// [`ToolTimelineEntry::output`]. `None` while running and on legacy- /// snapshots.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub output: Option<String>,-}--/// One ordered item in a sub-agent's processing transcript — its streamed-/// reasoning (`thinking`), visible narration (`text`), or a tool call, in the-/// exact order they occurred. Mirrors the frontend `SubagentTranscriptItem`-/// union 1:1 (order = push order; no `seq` is needed because each sub-agent's-/// transcript is built as a single ordered list). Persisting these lets the-/// inline "Agentic task insights" thoughts survive a settled turn / reload.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-// `rename_all` renames the variant tags; `rename_all_fields` renames the-// fields *inside* the struct variants (call_id → callId, …) — without the-// latter the FE would read `undefined` for camelCase fields.-#[serde(- rename_all = "camelCase",- rename_all_fields = "camelCase",- tag = "kind"-)]-pub enum SubagentTranscriptItem {- /// The sub-agent's hidden reasoning.- Thinking {- #[serde(default, skip_serializing_if = "Option::is_none")]- iteration: Option<u32>,- text: String,- },- /// The sub-agent's visible narration.- Text {- #[serde(default, skip_serializing_if = "Option::is_none")]- iteration: Option<u32>,- text: String,- },- /// A child tool call at the point it occurred (self-contained so a- /// rehydrated row renders without cross-referencing `tool_calls`).- Tool {- #[serde(default, skip_serializing_if = "Option::is_none")]- iteration: Option<u32>,- call_id: String,- tool_name: String,- status: ToolTimelineStatus,- #[serde(default, skip_serializing_if = "Option::is_none")]- elapsed_ms: Option<u64>,- #[serde(default, skip_serializing_if = "Option::is_none")]- output_chars: Option<usize>,- #[serde(default, skip_serializing_if = "Option::is_none")]- display_name: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- detail: Option<String>,- },-}--/// One ordered item in the parent turn's processing transcript.-///-/// Unlike [`ToolTimelineEntry`] (a flat list of tool rows), the transcript-/// preserves the **interleaving** of the agent's visible narration, its-/// hidden reasoning, and its tool calls in the exact order they streamed —-/// so the chat "View processing" panel can render prose between tool groups-/// the way Claude / Hermes does. `seq` is a monotonic per-turn ordering key-/// (round alone can't order narration vs thinking within one round). Tool-/// items hold only a `call_id` pointer into [`TurnState::tool_timeline`] so-/// the row's status/label live in exactly one place.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-// `rename_all_fields` is required so the `ToolCall.call_id` field serializes as-// `callId` (the FE reads camelCase) — `rename_all` alone only renames variants.-#[serde(- rename_all = "camelCase",- rename_all_fields = "camelCase",- tag = "kind"-)]-pub enum TranscriptItem {- /// The agent's visible assistant text between tool calls.- Narration { round: u32, seq: u32, text: String },- /// The agent's hidden reasoning (when the model emits it).- ///- /// `started_at` / `ended_at` are epoch milliseconds of the block's first- /// and latest delta, so the UI can show "Thought for 12s" after a reload.- /// Absent on rows written before timing was recorded.- Thinking {- round: u32,- seq: u32,- text: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- started_at: Option<u64>,- #[serde(default, skip_serializing_if = "Option::is_none")]- ended_at: Option<u64>,- },- /// A pointer to a tool row in [`TurnState::tool_timeline`].- ToolCall {- round: u32,- seq: u32,- call_id: String,- },-}--/// Persisted snapshot of an in-flight (or just-finished) agent turn for one-/// thread.-///-/// Written to disk by the web-channel progress consumer at iteration-/// boundaries, tool start/complete, and on terminal events. On normal-/// completion it is marked [`TurnLifecycle::Completed`] and **kept** (so the-/// "View processing" panel can replay the finished turn's transcript); a-/// non-terminal snapshot surviving startup is marked-/// [`TurnLifecycle::Interrupted`].-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct TurnState {- pub thread_id: String,- pub request_id: String,- pub lifecycle: TurnLifecycle,- pub iteration: u32,- pub max_iterations: u32,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub phase: Option<TurnPhase>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub active_tool: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub active_subagent: Option<String>,- #[serde(default)]- pub streaming_text: String,- #[serde(default)]- pub thinking: String,- #[serde(default)]- pub tool_timeline: Vec<ToolTimelineEntry>,- /// Ordered, interleaved record of the agent's narration, reasoning, and- /// tool calls for the "View processing" panel. `#[serde(default)]` so- /// snapshots written before this field still load (as empty).- #[serde(default, skip_serializing_if = "Vec::is_empty")]- pub transcript: Vec<TranscriptItem>,- pub started_at: String,- pub updated_at: String,-}--/// Request payload for `openhuman.threads_turn_state_get`.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct GetTurnStateRequest {- pub thread_id: String,-}--/// Response payload for `openhuman.threads_turn_state_get`.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct GetTurnStateResponse {- /// `None` when no snapshot exists for the thread.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub turn_state: Option<TurnState>,-}--/// Response payload for `openhuman.threads_turn_state_list` and-/// `openhuman.threads_turn_state_history`.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ListTurnStatesResponse {- pub turn_states: Vec<TurnState>,- pub count: usize,-}--/// Request payload for `openhuman.threads_turn_state_get_turn` — a specific-/// turn of a thread, identified by its producing request id.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct GetTurnStateForRequestRequest {- pub thread_id: String,- pub request_id: String,-}--/// Request payload for `openhuman.threads_turn_state_clear`.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub struct ClearTurnStateRequest {- pub thread_id: String,-}--/// Response payload for `openhuman.threads_turn_state_clear`.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct ClearTurnStateResponse {- pub cleared: bool,-}--impl TurnState {- /// Build a fresh `Started` snapshot for a new turn.- pub fn started(- thread_id: impl Into<String>,- request_id: impl Into<String>,- max_iterations: u32,- now_rfc3339: impl Into<String>,- ) -> Self {- let now = now_rfc3339.into();- Self {- thread_id: thread_id.into(),- request_id: request_id.into(),- lifecycle: TurnLifecycle::Started,- iteration: 0,- max_iterations,- phase: None,- active_tool: None,- active_subagent: None,- streaming_text: String::new(),- thinking: String::new(),- tool_timeline: Vec::new(),- transcript: Vec::new(),- started_at: now.clone(),- updated_at: now,- }- }-}