Skip to content

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

chore(threads): remove unused test files and consolidate ops modules

Steven Enamakelb6f82e15a550
diff --git a/crates/openhuman-core/src/platform/doctor/core/config_checks.rs b/crates/openhuman-core/src/platform/doctor/core/config_checks.rs
new file mode 100644
index 0000000000..e879f8975f
--- /dev/null
+++ b/crates/openhuman-core/src/platform/doctor/core/config_checks.rs
@@ -0,0 +1,224 @@
+//! Config semantic validation: [`check_config_semantics`] and its embedding
+//! provider URL check.
+
+use crate::config::Config;
+
+use super::types::DiagnosticItem;
+
+
+pub(super) fn check_config_semantics(config: &Config, items: &mut Vec<DiagnosticItem>) {
+ let cat = "config";
+
+ // Config file exists
+ if config.config_path.exists() {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!("config file: {}", config.config_path.display()),
+ ));
+ } else {
+ items.push(DiagnosticItem::error(
+ cat,
+ format!("config file not found: {}", config.config_path.display()),
+ ));
+ }
+
+ // Backend API URL
+ if let Some(url) = config
+ .api_url
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ {
+ items.push(DiagnosticItem::ok(cat, format!("api_url: {url}")));
+ } else {
+ let resolved = crate::api::config::effective_api_url(&config.api_url);
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!("api_url: (unset) resolved to {resolved}"),
+ ));
+ }
+
+ match crate::api::jwt::get_session_token(config) {
+ Ok(Some(token)) if !token.trim().is_empty() => {
+ items.push(DiagnosticItem::ok(cat, "signed in with app session JWT"));
+ }
+ Ok(_) => {
+ items.push(DiagnosticItem::warn(
+ cat,
+ "no app session JWT — not signed in",
+ ));
+ }
+ Err(err) => {
+ items.push(DiagnosticItem::error(
+ cat,
+ format!("failed to read app session JWT: {err}"),
+ ));
+ }
+ }
+
+ // Model configured
+ if config.default_model.is_some() {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!(
+ "default model: {}",
+ config.default_model.as_deref().unwrap_or("?")
+ ),
+ ));
+ } else {
+ items.push(DiagnosticItem::warn(cat, "no default_model configured"));
+ }
+
+ // Temperature range
+ if config.default_temperature >= 0.0 && config.default_temperature <= 2.0 {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!(
+ "temperature {:.1} (valid range 0.0-2.0)",
+ config.default_temperature
+ ),
+ ));
+ } else {
+ items.push(DiagnosticItem::error(
+ cat,
+ format!(
+ "temperature {:.1} is out of range (expected 0.0-2.0)",
+ config.default_temperature
+ ),
+ ));
+ }
+
+ // Reliability: fallback providers (legacy; ignored at runtime)
+ if !config.reliability.fallback_providers.is_empty() {
+ items.push(DiagnosticItem::warn(
+ cat,
+ "reliability.fallback_providers is set but ignored (single backend)",
+ ));
+ }
+
+ // Model routes validation
+ for route in &config.model_routes {
+ if route.hint.is_empty() {
+ items.push(DiagnosticItem::warn(cat, "model route with empty hint"));
+ }
+ if route.model.is_empty() {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!("model route \"{}\" has empty model", route.hint),
+ ));
+ }
+ }
+
+ // Embedding routes validation
+ for route in &config.embedding_routes {
+ if route.hint.trim().is_empty() {
+ items.push(DiagnosticItem::warn(cat, "embedding route with empty hint"));
+ }
+ if let Some(reason) = embedding_provider_validation_error(&route.provider) {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!(
+ "embedding route \"{}\" uses invalid provider \"{}\": {}",
+ route.hint, route.provider, reason
+ ),
+ ));
+ }
+ if route.model.trim().is_empty() {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!("embedding route \"{}\" has empty model", route.hint),
+ ));
+ }
+ if route.dimensions.is_some_and(|value| value == 0) {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!(
+ "embedding route \"{}\" has invalid dimensions=0",
+ route.hint
+ ),
+ ));
+ }
+ }
+
+ if let Some(hint) = config
+ .memory
+ .embedding_model
+ .strip_prefix("hint:")
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ {
+ if !config
+ .embedding_routes
+ .iter()
+ .any(|route| route.hint.trim() == hint)
+ {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!(
+ "memory.embedding_model uses hint \"{hint}\" but no matching [[embedding_routes]] entry exists"
+ ),
+ ));
+ }
+ }
+
+ // Channel: at least one configured
+ let cc = &config.channels_config;
+ let has_channel = cc.telegram.is_some()
+ || cc.discord.is_some()
+ || cc.slack.is_some()
+ || cc.imessage.is_some()
+ || cc.matrix.is_some()
+ || cc.whatsapp.is_some()
+ || cc.email.is_some()
+ || cc.irc.is_some()
+ || cc.lark.is_some()
+ || cc.webhook.is_some();
+
+ if has_channel {
+ items.push(DiagnosticItem::ok(cat, "at least one channel configured"));
+ } else {
+ items.push(DiagnosticItem::warn(
+ cat,
+ "no channels configured - configure one in the UI",
+ ));
+ }
+
+ // Delegate agents
+ let mut agent_names: Vec<_> = config.agents.keys().collect();
+ agent_names.sort();
+ for name in agent_names {
+ let agent = config.agents.get(name).unwrap();
+ if agent.model.trim().is_empty() {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!("delegate agent \"{name}\" has empty model"),
+ ));
+ }
+ }
+}
+
+fn embedding_provider_validation_error(name: &str) -> Option<String> {
+ let normalized = name.trim();
+ if normalized.eq_ignore_ascii_case("none") || normalized.eq_ignore_ascii_case("openai") {
+ return None;
+ }
+
+ let Some(url) = normalized.strip_prefix("custom:") else {
+ return Some("supported values: none, openai, custom:<url>".into());
+ };
+
+ let url = url.trim();
+ if url.is_empty() {
+ return Some("custom provider requires a non-empty URL after 'custom:'".into());
+ }
+
+ match reqwest::Url::parse(url) {
+ Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => None,
+ Ok(parsed) => Some(format!(
+ "custom provider URL must use http/https, got '{}'",
+ parsed.scheme()
+ )),
+ Err(err) => Some(format!("invalid custom provider URL: {err}")),
+ }
+}
+
diff --git a/crates/openhuman-core/src/platform/doctor/core/workspace_checks.rs b/crates/openhuman-core/src/platform/doctor/core/workspace_checks.rs
new file mode 100644
index 0000000000..c24cd4673e
--- /dev/null
+++ b/crates/openhuman-core/src/platform/doctor/core/workspace_checks.rs
@@ -0,0 +1,177 @@
+//! Workspace integrity: [`check_workspace`] and its disk-space and probe-path
+//! helpers.
+
+use std::io::Write;
+use std::path::Path;
+
+use crate::config::Config;
+
+use super::types::DiagnosticItem;
+
+
+pub(super) fn check_workspace(config: &Config, items: &mut Vec<DiagnosticItem>) {
+ let cat = "workspace";
+ let ws = &config.workspace_dir;
+
+ if ws.exists() {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!("directory exists: {}", ws.display()),
+ ));
+ } else {
+ items.push(DiagnosticItem::error(
+ cat,
+ format!("directory missing: {}", ws.display()),
+ ));
+ return;
+ }
+
+ // Writable check
+ let probe = workspace_probe_path(ws);
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&probe)
+ {
+ Ok(mut probe_file) => {
+ let write_result = probe_file.write_all(b"probe");
+ drop(probe_file);
+ let _ = std::fs::remove_file(&probe);
+ match write_result {
+ Ok(()) => items.push(DiagnosticItem::ok(cat, "directory is writable")),
+ Err(e) => items.push(DiagnosticItem::error(
+ cat,
+ format!("directory write probe failed: {e}"),
+ )),
+ }
+ }
+ Err(e) => {
+ items.push(DiagnosticItem::error(
+ cat,
+ format!("directory is not writable: {e}"),
+ ));
+ }
+ }
+
+ // Minimal workspace folders
+ let mem_dir = ws.join("memory");
+ if mem_dir.exists() {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!("memory directory: {}", mem_dir.display()),
+ ));
+ } else {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!("memory directory missing: {}", mem_dir.display()),
+ ));
+ }
+
+ // Check for config templates or docs
+ let prompt = ws.join("SYSTEM.md");
+ if prompt.exists() {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!("SYSTEM prompt: {}", prompt.display()),
+ ));
+ } else {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!("SYSTEM prompt missing: {}", prompt.display()),
+ ));
+ }
+
+ // Disk space warning (best-effort)
+ if let Some(avail_mb) = available_disk_space_mb(ws) {
+ if avail_mb < 512 {
+ items.push(DiagnosticItem::warn(
+ cat,
+ format!("low disk space: {avail_mb} MB free"),
+ ));
+ } else {
+ items.push(DiagnosticItem::ok(
+ cat,
+ format!("disk space OK: {avail_mb} MB free"),
+ ));
+ }
+ }
+}
+
+fn available_disk_space_mb(path: &Path) -> Option<u64> {
+ #[cfg(target_os = "windows")]
+ {
+ available_disk_space_mb_windows(path)
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ {
+ let output = std::process::Command::new("df")
+ .arg("-m")
+ .arg(path)
+ .output()
+ .ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ parse_df_available_mb(&stdout)
+ }
+}
+
+#[cfg(not(target_os = "windows"))]
+fn parse_df_available_mb(stdout: &str) -> Option<u64> {
+ let line = stdout.lines().rev().find(|line| !line.trim().is_empty())?;
+ let avail = line.split_whitespace().nth(3)?;
+ avail.parse::<u64>().ok()
+}
+
+#[cfg(target_os = "windows")]
+fn available_disk_space_mb_windows(path: &Path) -> Option<u64> {
+ use std::path::{Component, Prefix};
+
+ let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
+ let letter = canonical.components().find_map(|c| match c {
+ Component::Prefix(pc) => match pc.kind() {
+ Prefix::Disk(b) | Prefix::VerbatimDisk(b) => Some((b as char).to_ascii_uppercase()),
+ _ => None,
+ },
+ _ => None,
+ })?;
+
+ // PowerShell is ubiquitous on supported Windows; `Get-PSDrive` needs no admin
+ // and returns free bytes as a single integer line.
+ let script = format!("(Get-PSDrive -Name {letter} -ErrorAction Stop).Free");
+ let mut cmd = std::process::Command::new("powershell");
+ cmd.args([
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-Command",
+ &script,
+ ]);
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
+ }
+ let output = cmd.output().ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ let bytes: u64 = String::from_utf8_lossy(&output.stdout)
+ .trim()
+ .parse()
+ .ok()?;
+ Some(bytes / (1024 * 1024))
+}
+
+fn workspace_probe_path(workspace_dir: &Path) -> std::path::PathBuf {
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |duration| duration.as_nanos());
+ workspace_dir.join(format!(
+ ".openhuman_doctor_probe_{}_{}",
+ std::process::id(),
+ nanos
+ ))
+}
diff --git a/crates/openhuman-core/src/security/credentials/profiles_tests_part_02_tests.rs b/crates/openhuman-core/src/security/credentials/profiles_persistence_migration_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/credentials/profiles_tests_part_02_tests.rs
rename to crates/openhuman-core/src/security/credentials/profiles_persistence_migration_tests.rs
diff --git a/crates/openhuman-core/src/security/credentials/profiles_tests_part_01_tests.rs b/crates/openhuman-core/src/security/credentials/profiles_store_lock_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/credentials/profiles_tests_part_01_tests.rs
rename to crates/openhuman-core/src/security/credentials/profiles_store_lock_tests.rs
diff --git a/crates/openhuman-core/src/threads/ops_tests_part_01_tests.rs b/crates/openhuman-core/src/threads/ops_conversion_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/threads/ops_tests_part_01_tests.rs
rename to crates/openhuman-core/src/threads/ops_conversion_tests.rs
diff --git a/crates/openhuman-core/src/threads/ops_tests_part_02_tests.rs b/crates/openhuman-core/src/threads/ops_create_and_validate_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/threads/ops_tests_part_02_tests.rs
rename to crates/openhuman-core/src/threads/ops_create_and_validate_tests.rs
diff --git a/crates/openhuman-core/src/threads/ops_part_01.rs b/crates/openhuman-core/src/threads/ops_part_01.rs
deleted file mode 100644
index 0a14ef8601..0000000000
--- a/crates/openhuman-core/src/threads/ops_part_01.rs
+++ /dev/null
@@ -1,671 +0,0 @@
-use crate::core::runtime::context::CoreContext;
-use crate::config::Config;
-use crate::inference::provider;
-use crate::memory::{
- ApiEnvelope, ApiMeta, AppendConversationMessageRequest, ConversationMessageRecord,
- ConversationMessagesRequest, ConversationMessagesResponse, ConversationThreadSummary,
- ConversationThreadsListResponse, CreateConversationThreadRequest,
- DeleteConversationThreadRequest, DeleteConversationThreadResponse, EmptyRequest,
- GenerateConversationThreadTitleRequest, PaginationMeta, PurgeConversationThreadsResponse,
- UpdateConversationMessageRequest, UpdateConversationThreadLabelsRequest,
- UpdateConversationThreadTitleRequest, UpsertConversationThreadRequest,
-};
-// Every conversation-store call in this module goes through
-// `conversations::blocking::*`, which runs the store's synchronous,
-// globally-locked, fsync'ing operations on tokio's blocking pool. Calling the
-// sync entry points directly from these handlers parked async worker threads on
-// the store's `parking_lot` mutex, which starved the runtime and made
-// `threads_create_new` blow the frontend's 30 s RPC budget (#5156).
-use crate::memory::conversations;
-use crate::memory::conversations::{
- ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
- CrossThreadHit,
-};
-use crate::threads::title::{
- build_title_request, is_auto_generated_thread_title, sanitize_generated_title,
- title_from_user_message, title_log_fingerprint, THREAD_TITLE_LOG_PREFIX,
-};
-use crate::threads::turn_state::{
- self, ClearTurnStateRequest, ClearTurnStateResponse, GetTurnStateForRequestRequest,
- GetTurnStateRequest, GetTurnStateResponse, ListTurnStatesResponse,
-};
-use crate::threads::ThreadsError;
-use crate::web_chat as web_channel;
-use crate::rpc::RpcOutcome;
-use serde::Serialize;
-use std::collections::BTreeMap;
-use std::path::PathBuf;
-
-fn request_id() -> String {
- uuid::Uuid::new_v4().to_string()
-}
-
-fn counts(entries: impl IntoIterator<Item = (&'static str, usize)>) -> BTreeMap<String, usize> {
- entries
- .into_iter()
- .map(|(k, v)| (k.to_string(), v))
- .collect()
-}
-
-fn envelope<T: Serialize>(
- data: T,
- counts: Option<BTreeMap<String, usize>>,
- pagination: Option<PaginationMeta>,
-) -> RpcOutcome<ApiEnvelope<T>> {
- RpcOutcome::new(
- ApiEnvelope {
- data: Some(data),
- error: None,
- meta: ApiMeta {
- request_id: request_id(),
- latency_seconds: None,
- cached: None,
- counts,
- pagination,
- },
- },
- vec![],
- )
-}
-
-async fn workspace_dir() -> Result<PathBuf, String> {
- Config::load_or_init()
- .await
- .map(|c| c.workspace_dir)
- .map_err(|e| format!("load config: {e}"))
-}
-
-/// Run a destructive sequence to completion even if the caller's future is
-/// dropped (client disconnect, RPC timeout).
-///
-/// Moving the store onto the blocking pool (#5156) introduced a cancellation
-/// point that did not exist before. `spawn_blocking` work is never cancelled
-/// when its `JoinHandle` is dropped, so the store mutation lands regardless —
-/// but the `.await` on that handle *is* a yield point, and previously the
-/// synchronous store call had none. Dropping the handler there leaves the thread
-/// deleted while the cleanup that follows it never runs: the web-channel session
-/// stays live and can append to a thread index row that no longer exists,
-/// detached sub-agents keep running and queueing completions, and the turn
-/// snapshot survives to resurface as `Interrupted` for a thread that is gone.
-/// Those are precisely the invariants `thread_delete`'s ordering comments exist
-/// to hold.
-///
-/// Owning the mutation *and* its cleanup in one spawned task decouples the
-/// sequence from the caller's lifetime. The ambient [`CoreContext`] is carried
-/// across explicitly: a bare `tokio::spawn` drops the `task_local` scope, and
-/// `CoreContext::current` then silently falls back to the process default —
-/// which under multi-tenant scoped dispatch is the wrong workspace.
-async fn run_to_completion<T, F>(operation: &'static str, fut: F) -> Result<T, String>
-where
- F: std::future::Future<Output = Result<T, String>> + Send + 'static,
- T: Send + 'static,
-{
- let ctx = CoreContext::current();
- tokio::spawn(async move {
- match ctx {
- Some(ctx) => CoreContext::scope(ctx, fut).await,
- None => fut.await,
- }
- })
- .await
- .unwrap_or_else(|error| {
- tracing::warn!(
- operation,
- error = %error,
- "[threads] destructive task failed to join"
- );
- Err(format!("{operation} task failed: {error}"))
- })
-}
-
-fn thread_to_summary(thread: ConversationThread) -> ConversationThreadSummary {
- ConversationThreadSummary {
- id: thread.id,
- title: thread.title,
- chat_id: thread.chat_id,
- is_active: thread.is_active,
- message_count: thread.message_count,
- last_message_at: thread.last_message_at,
- created_at: thread.created_at,
- parent_thread_id: thread.parent_thread_id,
- labels: thread.labels,
- personality_id: thread.personality_id,
- }
-}
-
-fn message_to_record(message: ConversationMessage) -> ConversationMessageRecord {
- ConversationMessageRecord {
- id: message.id,
- content: message.content,
- message_type: message.message_type,
- extra_metadata: message.extra_metadata,
- sender: message.sender,
- created_at: message.created_at,
- }
-}
-
-fn record_to_message(record: ConversationMessageRecord) -> ConversationMessage {
- ConversationMessage {
- id: record.id,
- content: record.content,
- message_type: record.message_type,
- extra_metadata: record.extra_metadata,
- sender: record.sender,
- created_at: record.created_at,
- }
-}
-
-fn fallback_title_from_user_message(thread_id: &str, user_message: &str) -> Option<String> {
- let title = title_from_user_message(user_message);
- if let Some(title) = &title {
- tracing::debug!(
- thread_id = %thread_id,
- title_len = title.chars().count(),
- title_hash = %title_log_fingerprint(title),
- "{THREAD_TITLE_LOG_PREFIX} derived fallback title from user message"
- );
- } else {
- tracing::debug!(
- thread_id = %thread_id,
- "{THREAD_TITLE_LOG_PREFIX} user message did not yield fallback title"
- );
- }
- title
-}
-
-async fn update_thread_with_fallback_title(
- dir: PathBuf,
- thread: ConversationThread,
- user_message: &str,
-) -> Result<ConversationThread, String> {
- let Some(title) = fallback_title_from_user_message(&thread.id, user_message) else {
- return Ok(thread);
- };
- if title == thread.title {
- return Ok(thread);
- }
- conversations::blocking::update_thread_title(
- dir,
- thread.id.clone(),
- title,
- chrono::Utc::now().to_rfc3339(),
- )
- .await
-}
-
-/// Lists all conversation threads.
-pub async fn threads_list(
- _request: EmptyRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadsListResponse>>, String> {
- let dir = workspace_dir().await?;
- let threads = conversations::blocking::list_threads(dir)
- .await?
- .into_iter()
- .map(thread_to_summary)
- .collect::<Vec<_>>();
- let count = threads.len();
- Ok(envelope(
- ConversationThreadsListResponse { threads, count },
- Some(counts([("num_threads", count)])),
- None,
- ))
-}
-
-/// Creates or refreshes a conversation thread.
-pub async fn thread_upsert(
- request: UpsertConversationThreadRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {
- let dir = workspace_dir().await?;
- let thread = conversations::blocking::ensure_thread(
- dir,
- CreateConversationThread {
- id: request.id,
- title: request.title,
- created_at: request.created_at,
- parent_thread_id: request.parent_thread_id,
- labels: request.labels,
- personality_id: request.personality_id,
- },
- )
- .await?;
- Ok(envelope(
- thread_to_summary(thread),
- Some(counts([("num_threads", 1)])),
- None,
- ))
-}
-
-/// Creates a new conversation thread with auto-generated ID and title.
-pub async fn thread_create_new(
- request: CreateConversationThreadRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {
- let dir = workspace_dir().await?;
- let id = format!("thread-{}", uuid::Uuid::new_v4());
- let now = chrono::Local::now();
- let title = format!("Chat {} {}", now.format("%b %-d"), now.format("%-I:%M %p"));
- let created_at = chrono::Utc::now().to_rfc3339();
- let thread = conversations::blocking::ensure_thread(
- dir,
- CreateConversationThread {
- id,
- title,
- created_at,
- parent_thread_id: None,
- // Pass labels through as-is; the store's infer_labels() applies
- // the same default on index rebuild, so this is the single source
- // of truth for default labels.
- labels: request.labels,
- personality_id: request.personality_id,
- },
- )
- .await?;
- tracing::debug!(
- thread_id = %thread.id,
- labels = ?thread.labels,
- "[threads] created new thread"
- );
- Ok(envelope(
- thread_to_summary(thread),
- Some(counts([("num_threads", 1)])),
- None,
- ))
-}
-
-/// Lists messages for a conversation thread.
-pub async fn messages_list(
- request: ConversationMessagesRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationMessagesResponse>>, String> {
- let dir = workspace_dir().await?;
- let messages = conversations::blocking::get_messages(dir, request.thread_id.clone())
- .await?
- .into_iter()
- .map(message_to_record)
- .collect::<Vec<_>>();
- let count = messages.len();
- Ok(envelope(
- ConversationMessagesResponse { messages, count },
- Some(counts([("num_messages", count)])),
- None,
- ))
-}
-
-/// Search messages across **every** thread in the workspace for a query,
-/// returning up to `limit` of the most-recent matches (newest first). Backed
-/// by the trigram/CJK-bigram inverted index in `memory_conversations` — the
-/// same cross-chat reader the durable-context pipeline uses (issue #1505).
-///
-/// Read-only and workspace-scoped. `exclude_thread_id` lets a caller drop the
-/// active chat from the results when it already has that context in hand.
-pub async fn transcript_search(
- query: &str,
- limit: usize,
- exclude_thread_id: Option<&str>,
-) -> Result<Vec<CrossThreadHit>, String> {
- let dir = workspace_dir().await?;
- log::debug!(
- "[threads][transcript_search] query_chars={} limit={} exclude={:?}",
- query.chars().count(),
- limit,
- exclude_thread_id
- );
- let hits = conversations::blocking::search_cross_thread_messages(
- dir,
- query.to_string(),
- limit,
- exclude_thread_id.map(str::to_string),
- )
- .await?;
- log::debug!("[threads][transcript_search] hits={}", hits.len());
- Ok(hits)
-}
-
-/// Appends a message to a conversation thread.
-pub async fn message_append(
- request: AppendConversationMessageRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
- let dir = workspace_dir().await?;
- let message = conversations::blocking::append_message(
- dir,
- request.thread_id.clone(),
- record_to_message(request.message),
- )
- .await
- .map_err(|err| ThreadsError::from_thread_scoped_store_error(&request.thread_id, err))?;
- Ok(envelope(
- message_to_record(message),
- Some(counts([("num_messages", 1)])),
- None,
- ))
-}
-
-/// Generates a durable thread title from the first user message and assistant reply.
-pub async fn thread_generate_title(
- request: GenerateConversationThreadTitleRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, ThreadsError> {
- let config = Config::load_or_init()
- .await
- .map_err(|e| format!("load config: {e}"))?;
- let dir = config.workspace_dir.clone();
- let Some(thread) = conversations::blocking::list_threads(dir.clone())
- .await?
- .into_iter()
- .find(|thread| thread.id == request.thread_id)
- else {
- return Err(ThreadsError::not_found(request.thread_id));
- };
-
- if !is_auto_generated_thread_title(&thread.title) {
- tracing::debug!(
- thread_id = %request.thread_id,
- title_len = thread.title.chars().count(),
- title_hash = %title_log_fingerprint(&thread.title),
- "{THREAD_TITLE_LOG_PREFIX} skipping non-placeholder title"
- );
- return Ok(envelope(
- thread_to_summary(thread),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- }
-
- let messages =
- conversations::blocking::get_messages(dir.clone(), request.thread_id.clone()).await?;
- let Some(first_user_message) = messages
- .iter()
- .find(|message| message.sender == "user" && !message.content.trim().is_empty())
- .map(|message| message.content.trim().to_string())
- else {
- tracing::debug!(
- thread_id = %request.thread_id,
- "{THREAD_TITLE_LOG_PREFIX} no user message yet; skipping"
- );
- return Ok(envelope(
- thread_to_summary(thread),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- };
-
- let assistant_message = request
- .assistant_message
- .as_deref()
- .map(str::trim)
- .filter(|message| !message.is_empty())
- .map(ToOwned::to_owned)
- .or_else(|| {
- messages
- .iter()
- .find(|message| message.sender == "agent" && !message.content.trim().is_empty())
- .map(|message| message.content.trim().to_string())
- });
-
- let Some(assistant_message) = assistant_message else {
- tracing::debug!(
- thread_id = %request.thread_id,
- "{THREAD_TITLE_LOG_PREFIX} no assistant message yet; applying fallback title"
- );
- let updated = update_thread_with_fallback_title(dir, thread, &first_user_message).await?;
- return Ok(envelope(
- thread_to_summary(updated),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- };
-
- // `_with_model_id` rather than the plain constructor: the debug line below
- // reports the model this call actually dispatches on, and only the factory
- // knows what the `summarization` role resolved to for this configuration.
- let (chat_model, resolved_model) =
- match provider::create_chat_model_with_model_id("summarization", &config, 0.2) {
- Ok(resolved) => resolved,
- Err(error) => {
- tracing::warn!(
- thread_id = %request.thread_id,
- error = %error,
- "{THREAD_TITLE_LOG_PREFIX} provider init failed; applying fallback title"
- );
- let updated =
- update_thread_with_fallback_title(dir, thread, &first_user_message).await?;
- return Ok(envelope(
- thread_to_summary(updated),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- }
- };
-
- tracing::debug!(
- thread_id = %request.thread_id,
- user_len = first_user_message.len(),
- assistant_len = assistant_message.len(),
- model = %resolved_model,
- "{THREAD_TITLE_LOG_PREFIX} generating thread title"
- );
-
- let raw_title = match chat_model
- .invoke(
- &(),
- build_title_request(&first_user_message, &assistant_message),
- )
- .await
- {
- Ok(response) => response.text(),
- Err(error) => {
- tracing::warn!(
- thread_id = %request.thread_id,
- error = %error,
- "{THREAD_TITLE_LOG_PREFIX} title generation failed; applying fallback title"
- );
- let updated =
- update_thread_with_fallback_title(dir, thread, &first_user_message).await?;
- return Ok(envelope(
- thread_to_summary(updated),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- }
- };
-
- let Some(title) = sanitize_generated_title(&raw_title) else {
- tracing::warn!(
- thread_id = %request.thread_id,
- raw_title_len = raw_title.chars().count(),
- raw_title_hash = %title_log_fingerprint(&raw_title),
- "{THREAD_TITLE_LOG_PREFIX} generated empty title after sanitization; applying fallback title"
- );
- let updated = update_thread_with_fallback_title(dir, thread, &first_user_message).await?;
- return Ok(envelope(
- thread_to_summary(updated),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- };
-
- if title == thread.title {
- return Ok(envelope(
- thread_to_summary(thread),
- Some(counts([("num_threads", 1)])),
- None,
- ));
- }
-
- let updated = conversations::blocking::update_thread_title(
- dir,
- request.thread_id.clone(),
- title,
- chrono::Utc::now().to_rfc3339(),
- )
- .await
- .map_err(|err| ThreadsError::from_thread_scoped_store_error(&request.thread_id, err))?;
-
- tracing::debug!(
- thread_id = %request.thread_id,
- title_len = updated.title.chars().count(),
- title_hash = %title_log_fingerprint(&updated.title),
- "{THREAD_TITLE_LOG_PREFIX} updated thread title"
- );
-
- Ok(envelope(
- thread_to_summary(updated),
- Some(counts([("num_threads", 1)])),
- None,
- ))
-}
-
-/// Updates labels for a conversation thread.
-///
-/// An empty `labels` vec is valid and clears all labels from the thread,
-/// making it invisible in every non-"All" filter view. Callers should
-/// ensure this is intentional.
-pub async fn thread_update_labels(
- request: UpdateConversationThreadLabelsRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {
- let dir = workspace_dir().await?;
- let thread = conversations::blocking::update_thread_labels(
- dir,
- request.thread_id.clone(),
- request.labels.clone(),
- chrono::Utc::now().to_rfc3339(),
- )
- .await?;
- tracing::debug!(
- thread_id = %request.thread_id,
- labels = ?request.labels,
- "[threads] updated thread labels"
- );
- Ok(envelope(
- thread_to_summary(thread),
- Some(counts([("num_threads", 1)])),
- None,
- ))
-}
-
-/// Sets a user-specified title on a conversation thread, bypassing AI generation.
-pub async fn thread_update_title(
- request: UpdateConversationThreadTitleRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {
- let dir = workspace_dir().await?;
- let title = request.title.trim().to_string();
- if title.is_empty() {
- return Err("title must not be empty".to_string());
- }
- let updated = conversations::blocking::update_thread_title(
- dir,
- request.thread_id.clone(),
- title,
- chrono::Utc::now().to_rfc3339(),
- )
- .await
- .map_err(|err| format!("update title: {err}"))?;
- tracing::debug!(
- thread_id = %request.thread_id,
- title_len = updated.title.chars().count(),
- "[threads] user updated thread title"
- );
- Ok(envelope(
- thread_to_summary(updated),
- Some(counts([("num_threads", 1)])),
- None,
- ))
-}
-
-/// Updates metadata on an existing conversation message.
-pub async fn message_update(
- request: UpdateConversationMessageRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ConversationMessageRecord>>, String> {
- let dir = workspace_dir().await?;
- let message = conversations::blocking::update_message(
- dir,
- request.thread_id.clone(),
- request.message_id.clone(),
- ConversationMessagePatch {
- extra_metadata: request.extra_metadata,
- },
- )
- .await?;
- Ok(envelope(
- message_to_record(message),
- Some(counts([("num_messages", 1)])),
- None,
- ))
-}
-
-/// Deletes a conversation thread and its message log.
-///
-/// The store mutation and every cleanup step it implies run inside one
-/// [`run_to_completion`] task, so a caller that disconnects mid-delete cannot
-/// leave the thread gone from the store with its sessions, sub-agents and turn
-/// snapshot still live.
-pub async fn thread_delete(
- request: DeleteConversationThreadRequest,
-) -> Result<RpcOutcome<ApiEnvelope<DeleteConversationThreadResponse>>, String> {
- let dir = workspace_dir().await?;
- run_to_completion("thread_delete", thread_delete_inner(dir, request)).await
-}
-
-async fn thread_delete_inner(
- dir: PathBuf,
- request: DeleteConversationThreadRequest,
-) -> Result<RpcOutcome<ApiEnvelope<DeleteConversationThreadResponse>>, String> {
- let deleted = conversations::blocking::delete_thread(
- dir.clone(),
- request.thread_id.clone(),
- request.deleted_at.clone(),
- )
- .await?;
- // Invalidate the in-process web-channel session BEFORE the
- // turn-state cleanup. The snapshot deletion is fallible and
- // returns early on error; if invalidation ran after, an active
- // session for the now-deleted thread could linger and try to
- // append to a thread index row that no longer exists.
- web_channel::invalidate_thread_sessions(&request.thread_id).await;
- // Cancel any detached sub-agents this thread spawned BEFORE clearing their
- // queued results: abort the in-flight ones first so a child can't record a
- // completion in the gap between the two calls, then discard anything already
- // queued for delivery. Both target a thread that's being deleted, so there's
- // nowhere left to deliver to — abort + cleanup is the whole behavior.
- let cancelled = crate::agent::orchestration::running_subagents::cancel_for_thread(
- &request.thread_id,
- );
- let discarded =
- crate::agent::orchestration::background_completions::discard_for_thread(
- &request.thread_id,
- );
- log::debug!(
- "[threads] thread_delete thread_id={} cancelled_subagents={} discarded_completions={}",
- request.thread_id,
- cancelled,
- discarded
- );
- // Drop any persisted in-flight turn snapshot for this thread —
- // otherwise `threads_turn_state_list` keeps surfacing it (as
- // `Interrupted` on next restart) for a thread that no longer
- // exists. Failure here is surfaced as an RPC error so callers
- // can't observe a thread "deleted" while its snapshot (which
- // mirrors conversation-derived state) remains on disk; the
- // thread row itself is already gone at this point so the caller
- // sees a partial failure they can act on instead of silent drift.
- turn_state::store::delete(dir, &request.thread_id).map_err(|err| {
- format!(
- "thread {} deleted but turn-snapshot cleanup failed: {err}",
- request.thread_id
- )
- })?;
- Ok(envelope(
- DeleteConversationThreadResponse { deleted },
- None,
- None,
- ))
-}
-
-/// Purges all conversation threads and messages.
-///
-/// Same cancellation contract as [`thread_delete`]: the purge and its sub-agent
-/// / turn-snapshot cleanup are one [`run_to_completion`] unit, so a dropped
-/// caller cannot leave every thread wiped while their sub-agents keep running.
-pub async fn threads_purge(
- _request: EmptyRequest,
-) -> Result<RpcOutcome<ApiEnvelope<PurgeConversationThreadsResponse>>, String> {
- let dir = workspace_dir().await?;
- run_to_completion("threads_purge", threads_purge_inner(dir)).await
-}
diff --git a/crates/openhuman-core/src/threads/ops_part_02.rs b/crates/openhuman-core/src/threads/ops_part_02.rs
deleted file mode 100644
index fdb2c03e08..0000000000
--- a/crates/openhuman-core/src/threads/ops_part_02.rs
+++ /dev/null
@@ -1,321 +0,0 @@
-
-async fn threads_purge_inner(
- dir: PathBuf,
-) -> Result<RpcOutcome<ApiEnvelope<PurgeConversationThreadsResponse>>, String> {
- let stats = conversations::blocking::purge_threads(dir.clone()).await?;
- // No parent thread survives a purge, so cancel every detached sub-agent and
- // wipe every queued result. Same ordering as `thread_delete`: abort the
- // in-flight runs first, then clear the delivery queue. Tombstone each
- // cancelled sub-agent's thread BEFORE the final wipe so a straggler that
- // wins the cooperative-abort race (records after the wipe) is still dropped
- // by `record_completion` rather than delivered into a purged thread.
- use crate::agent::orchestration::{background_completions, running_subagents};
- let cancelled_threads = running_subagents::cancel_all();
- let mut discarded = 0;
- for thread_id in &cancelled_threads {
- discarded += background_completions::discard_for_thread(thread_id);
- }
- discarded += background_completions::clear_all();
- log::debug!(
- "[threads] threads_purge cancelled_threads={} discarded_completions={}",
- cancelled_threads.len(),
- discarded
- );
- // Threads are gone, so any orphan turn snapshots can never be
- // reattached to a live thread. Wipe them in the same call so
- // `turn_state_list` returns an empty set after a purge. Use the
- // parse-independent `clear_all` so corrupted / half-written
- // snapshot files (which `list()` would warn-and-skip) are also
- // removed — a destructive cleanup must not leave behind anything
- // it failed to deserialize. Failures surface as RPC errors.
- turn_state::store::clear_all(dir.clone())
- .map_err(|err| format!("threads purged but turn-snapshot cleanup failed: {err}"))?;
- Ok(envelope(
- PurgeConversationThreadsResponse {
- messages_deleted: stats.message_count,
- agent_threads_deleted: stats.thread_count,
- agent_messages_deleted: stats.message_count,
- },
- None,
- None,
- ))
-}
-
-/// Returns the persisted in-flight turn snapshot for a thread, if any.
-pub async fn turn_state_get(
- request: GetTurnStateRequest,
-) -> Result<RpcOutcome<ApiEnvelope<GetTurnStateResponse>>, String> {
- let dir = workspace_dir().await?;
- let turn_state = turn_state::store::get(dir, &request.thread_id)?;
- let present = turn_state.is_some();
- Ok(envelope(
- GetTurnStateResponse { turn_state },
- Some(counts([("present", usize::from(present))])),
- None,
- ))
-}
-
-/// Lists every persisted turn snapshot — used by the UI on cold boot to
-/// surface interrupted turns from a previous process.
-pub async fn turn_state_list(
- _request: EmptyRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ListTurnStatesResponse>>, String> {
- let dir = workspace_dir().await?;
- let turn_states = turn_state::store::list(dir)?;
- let count = turn_states.len();
- Ok(envelope(
- ListTurnStatesResponse { turn_states, count },
- Some(counts([("num_turn_states", count)])),
- None,
- ))
-}
-
-/// Lists every persisted turn snapshot for one thread, newest first — the
-/// per-turn history that lets the UI render each answer's own process trail.
-pub async fn turn_state_history(
- request: GetTurnStateRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ListTurnStatesResponse>>, String> {
- let dir = workspace_dir().await?;
- let turn_states = turn_state::store::list_thread(dir, &request.thread_id)?;
- let count = turn_states.len();
- Ok(envelope(
- ListTurnStatesResponse { turn_states, count },
- Some(counts([("num_turn_states", count)])),
- None,
- ))
-}
-
-/// Returns one specific turn of a thread by its producing request id — used by
-/// the UI to lazily load a past turn's full timeline when its insights block is
-/// first expanded.
-pub async fn turn_state_get_turn(
- request: GetTurnStateForRequestRequest,
-) -> Result<RpcOutcome<ApiEnvelope<GetTurnStateResponse>>, String> {
- let dir = workspace_dir().await?;
- let turn_state = turn_state::store::get_turn(dir, &request.thread_id, &request.request_id)?;
- let present = turn_state.is_some();
- Ok(envelope(
- GetTurnStateResponse { turn_state },
- Some(counts([("present", usize::from(present))])),
- None,
- ))
-}
-
-/// Clears the persisted turn snapshot for a thread (e.g. after the user
-/// dismisses an "interrupted" banner).
-pub async fn turn_state_clear(
- request: ClearTurnStateRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ClearTurnStateResponse>>, String> {
- let dir = workspace_dir().await?;
- let cleared = turn_state::store::delete(dir, &request.thread_id)?;
- Ok(envelope(ClearTurnStateResponse { cleared }, None, None))
-}
-
-/// Request for [`token_usage`]: the thread whose persisted usage to total.
-#[derive(Debug, Clone, serde::Deserialize)]
-pub struct ThreadTokenUsageRequest {
- pub thread_id: String,
-}
-
-/// Request for [`transcript_get`]: the thread to project, plus newest-first
-/// pagination controls. `cursor` is the opaque token from a prior page's
-/// `nextCursor`; `limit` defaults to one screen.
-#[derive(Debug, Clone, serde::Deserialize)]
-pub struct TranscriptGetRequest {
- pub thread_id: String,
- #[serde(default)]
- pub cursor: Option<String>,
- #[serde(default)]
- pub limit: Option<usize>,
-}
-
-/// Project a thread's settled transcript (derived from `session_raw/*.jsonl`)
-/// into typed display items, newest-first paginated. Returns an empty page with
-/// `hasTranscript: false` when the thread has no persisted transcript yet.
-pub async fn transcript_get(
- request: TranscriptGetRequest,
-) -> Result<
- RpcOutcome<ApiEnvelope<crate::threads::transcript_view::TranscriptPage>>,
- String,
-> {
- let dir = workspace_dir().await?;
- let thread_id = request.thread_id.trim();
- if thread_id.is_empty() {
- return Err("thread_id is required".to_string());
- }
- let page = crate::threads::transcript_view::get_page(
- &dir,
- thread_id,
- request.cursor.as_deref(),
- request.limit,
- );
- let counts = counts([
- ("items", page.items.len()),
- ("total", page.total),
- ("has_transcript", usize::from(page.has_transcript)),
- ]);
- let pagination = Some(PaginationMeta {
- limit: request
- .limit
- .unwrap_or(crate::threads::transcript_view::DEFAULT_LIMIT),
- offset: request
- .cursor
- .as_deref()
- .and_then(|c| c.trim().parse::<usize>().ok())
- .unwrap_or(0),
- count: page.total,
- });
- Ok(envelope(page, Some(counts), pagination))
-}
-
-/// Aggregated token/cost usage for one thread, read back from its persisted
-/// session transcripts. Seeds the UI footer when the user selects a thread so
-/// the totals reflect prior turns instead of starting at zero.
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct ThreadTokenUsageResponse {
- pub thread_id: String,
- pub input_tokens: u64,
- pub output_tokens: u64,
- pub cached_input_tokens: u64,
- pub cost_usd: f64,
- pub turn_count: usize,
- /// Tokens of the most recent turn — numerator for the context-window gauge.
- pub last_turn_input_tokens: u64,
- pub last_turn_output_tokens: u64,
- /// Context window (tokens) inferred from the last model; `0` when unknown.
- pub context_window: u64,
- pub model: Option<String>,
- pub updated: Option<String>,
- /// `false` when the thread has no persisted turns yet (all zeros).
- pub has_usage: bool,
- /// Per-archetype sub-agent spend (re-audited at current pricing). The
- /// top-level totals already include this; it's broken out for the UI's
- /// per-agent footer rows.
- pub subagents: Vec<SubagentUsageDto>,
-}
-
-/// One sub-agent archetype's contribution within a thread.
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct SubagentUsageDto {
- pub agent_id: String,
- pub input_tokens: u64,
- pub output_tokens: u64,
- pub cost_usd: f64,
- pub runs: usize,
-}
-
-/// Total a thread's persisted token/cost usage across its root transcripts.
-pub async fn token_usage(
- request: ThreadTokenUsageRequest,
-) -> Result<RpcOutcome<ApiEnvelope<ThreadTokenUsageResponse>>, String> {
- let dir = workspace_dir().await?;
- let summary = crate::agent::harness::session::transcript::read_thread_usage_summary(
- &dir,
- &request.thread_id,
- );
-
- // Re-audit cost at CURRENT pricing rather than trusting the
- // `charged_amount_usd` persisted in the transcript: those values were
- // stamped at turn time and don't reflect later tier-pricing corrections.
- // Recompute from the persisted token counts using the last-known model's
- // rates; falls back to `fallback` only when the model is unknown.
- let audit_cost =
- |model: Option<&str>, input: u64, output: u64, cached: u64, fallback: f64| match model {
- Some(m) => crate::agent::cost::estimate_call_cost_usd(
- m,
- &crate::inference::provider::UsageInfo {
- input_tokens: input,
- output_tokens: output,
- cached_input_tokens: cached,
- ..Default::default()
- },
- ),
- None => fallback,
- };
-
- let response = match summary {
- Some(s) => {
- let context_window = s
- .model
- .as_deref()
- .and_then(crate::inference::model_context::context_window_for_model)
- .unwrap_or(0);
-
- // Orchestrator (root) spend, re-audited.
- let orchestrator_cost = audit_cost(
- s.model.as_deref(),
- s.input_tokens,
- s.output_tokens,
- s.cached_input_tokens,
- s.cost_usd,
- );
-
- // Sub-agent archetypes, each re-audited with its own model. Older
- // sub-agent transcripts didn't persist a model on their messages, so
- // fall back to the thread's (root) model rather than pricing them at
- // $0 — sub-agents usually run on the same managed tier as the parent.
- let mut subagents = Vec::with_capacity(s.subagents.len());
- let (mut sub_in, mut sub_out, mut sub_cached, mut sub_cost) = (0u64, 0u64, 0u64, 0.0);
- for g in &s.subagents {
- let sub_model = g.model.as_deref().or(s.model.as_deref());
- let cost = audit_cost(
- sub_model,
- g.input_tokens,
- g.output_tokens,
- g.cached_input_tokens,
- 0.0,
- );
- sub_in = sub_in.saturating_add(g.input_tokens);
- sub_out = sub_out.saturating_add(g.output_tokens);
- sub_cached = sub_cached.saturating_add(g.cached_input_tokens);
- sub_cost += cost;
- subagents.push(SubagentUsageDto {
- agent_id: g.agent_id.clone(),
- input_tokens: g.input_tokens,
- output_tokens: g.output_tokens,
- cost_usd: cost,
- runs: g.runs,
- });
- }
-
- // Top-level totals = orchestrator + all sub-agents.
- ThreadTokenUsageResponse {
- thread_id: request.thread_id.clone(),
- input_tokens: s.input_tokens.saturating_add(sub_in),
- output_tokens: s.output_tokens.saturating_add(sub_out),
- cached_input_tokens: s.cached_input_tokens.saturating_add(sub_cached),
- cost_usd: orchestrator_cost + sub_cost,
- turn_count: s.turn_count,
- last_turn_input_tokens: s.last_turn_input_tokens,
- last_turn_output_tokens: s.last_turn_output_tokens,
- context_window,
- model: s.model,
- updated: Some(s.updated),
- has_usage: true,
- subagents,
- }
- }
- None => ThreadTokenUsageResponse {
- thread_id: request.thread_id.clone(),
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- cost_usd: 0.0,
- turn_count: 0,
- last_turn_input_tokens: 0,
- last_turn_output_tokens: 0,
- context_window: 0,
- model: None,
- updated: None,
- has_usage: false,
- subagents: Vec::new(),
- },
- };
-
- let has_usage = response.has_usage;
- Ok(envelope(
- response,
- Some(counts([("has_usage", usize::from(has_usage))])),
- None,
- ))
-}
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
new file mode 100644
index 0000000000..21012c33a8
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -0,0 +1,565 @@
+//! The primary (non-parallel) turn entry point: ingress validation and
+//! attachment preprocessing, prompt-injection and approval-reply routing,
+//! run-queue dispatch, and the spawned turn body that delivers a response or
+//! classifies and reports a failure.
+
+use serde_json::json;
+use tokio_util::sync::CancellationToken;
+use uuid::Uuid;
+
+use crate::core::events::DomainEvent;
+use crate::core::socketio::WebChannelEvent;
+use crate::security::prompt_injection::{
+ enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,
+};
+
+use super::super::event_bus::publish_web_channel_event;
+use super::super::run_task::run_chat_task;
+use super::super::types::ChatRequestMetadata;
+use super::super::web_errors::classify_inference_error;
+use super::parallel_turn::spawn_parallel_turn;
+use super::state::{cancel_in_flight_gracefully, key_for, IN_FLIGHT};
+use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag};
+
+fn prompt_guard_user_message(action: PromptEnforcementAction) -> &'static str {
+ match action {
+ PromptEnforcementAction::Allow => "Message accepted.",
+ PromptEnforcementAction::Blocked => {
+ "Your message was blocked by a security policy. Please rephrase and remove instruction-override or secret-exfiltration requests."
+ }
+ PromptEnforcementAction::ReviewBlocked => {
+ "Your message was flagged for security review and was not processed. Please rephrase the request in a direct, task-focused way."
+ }
+ }
+}
+
+pub async fn start_chat(
+ client_id: &str,
+ thread_id: &str,
+ message: &str,
+ model_override: Option<String>,
+ temperature: Option<f64>,
+ profile_id: Option<String>,
+ locale: Option<String>,
+ queue_mode: Option<String>,
+ metadata: ChatRequestMetadata,
+) -> Result<String, String> {
+ let client_id = client_id.trim().to_string();
+ let thread_id = thread_id.trim().to_string();
+ let message = message.trim().to_string();
+
+ if client_id.is_empty() {
+ return Err("client_id is required".to_string());
+ }
+ if thread_id.is_empty() {
+ return Err("thread_id is required".to_string());
+ }
+ if message.is_empty() {
+ return Err("message is required".to_string());
+ }
+
+ // [pdf/image-attach fix] Process attachments at ingress, BEFORE the message is
+ // injection-scanned, persisted to history/JSONL, or auto-saved to the memory
+ // store. Otherwise a multi-MB base64 data URI floods every upstream stage
+ // (N-chunk embed → Voyage 400, cross-thread index) and stalls the turn.
+ // [FILE:data:…] → [FILE-EXTRACTED]text (or [FILE-ATTACHED] placeholder)
+ // [IMAGE:data:…] → [Image: … #att:<id>] placeholder + out-of-band stash
+ // Images are rehydrated to a data URI at provider dispatch for vision-capable
+ // models only.
+ let mut message = if message.contains("[FILE:") || message.contains("[IMAGE:") {
+ let before_chars = message.chars().count();
+ log::debug!(
+ "[web-channel][ingress] preprocessing attachment markers thread_id={} client_id={} chars={}",
+ thread_id,
+ client_id,
+ before_chars
+ );
+ // Fail CLOSED on a config-load error: process with default limits rather
+ // than passing the raw `[FILE:data:…]`/`[IMAGE:data:…]` blob through —
+ // otherwise the injection scan, history/JSONL persistence, and memory
+ // autosave all see the multi-MB data URI again, reopening the flood path.
+ let (file_cfg, image_cfg) = match crate::config::rpc::load_config_with_timeout()
+ .await
+ {
+ Ok(cfg) => {
+ log::debug!(
+ "[web-channel][ingress] using configured multimodal limits thread_id={}",
+ thread_id
+ );
+ (cfg.multimodal_files, cfg.multimodal)
+ }
+ Err(err) => {
+ log::warn!(
+ "[web-channel][ingress] config load failed; using default limits (fail-closed) thread_id={} err={err}",
+ thread_id
+ );
+ (
+ crate::config::MultimodalFileConfig::default(),
+ crate::config::MultimodalConfig::default(),
+ )
+ }
+ };
+ let extracted =
+ crate::agent::multimodal::inline_file_attachments(&message, &file_cfg).await;
+ let processed =
+ crate::agent::multimodal::stash_image_attachments(&extracted, &image_cfg)
+ .await;
+ log::debug!(
+ "[web-channel][ingress] attachment preprocessing complete thread_id={} before_chars={} after_chars={}",
+ thread_id,
+ before_chars,
+ processed.chars().count()
+ );
+ processed
+ } else {
+ message
+ };
+
+ let request_id = Uuid::new_v4().to_string();
+ let prompt_decision = enforce_prompt_input(
+ &message,
+ PromptEnforcementContext {
+ source: "web_chat.start_chat",
+ request_id: Some(&request_id),
+ user_id: Some(&client_id),
+ session_id: Some(&thread_id),
+ },
+ );
+ if !matches!(prompt_decision.action, PromptEnforcementAction::Allow) {
+ log::warn!(
+ "[web-channel] prompt rejected client_id={} thread_id={} request_id={} action={} score={:.2} reasons={} hash={} chars={}",
+ client_id,
+ thread_id,
+ request_id,
+ match prompt_decision.action {
+ PromptEnforcementAction::Allow => "allow",
+ PromptEnforcementAction::Blocked => "block",
+ PromptEnforcementAction::ReviewBlocked => "review_blocked",
+ },
+ prompt_decision.score,
+ prompt_decision
+ .reasons
+ .iter()
+ .map(|r| r.code.as_str())
+ .collect::<Vec<_>>()
+ .join(","),
+ prompt_decision.prompt_hash,
+ prompt_decision.prompt_chars,
+ );
+ return Err(prompt_guard_user_message(prompt_decision.action).to_string());
+ }
+
+ // Chat-native approval: if this thread has a parked approval and the message
+ // is a yes/no reply, route it to the gate rather than starting a new turn.
+ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
+ if let Some(request_id) = gate.pending_for_thread(&thread_id) {
+ if let Some(decision) =
+ crate::security::approval::parse_approval_reply(&message)
+ {
+ match gate.decide(&request_id, decision) {
+ Ok(Some(_)) => {
+ log::info!(
+ "[web-channel] routed chat reply to approval gate thread_id={} request_id={} decision={}",
+ thread_id,
+ request_id,
+ decision.as_str()
+ );
+ return Ok(request_id);
+ }
+ Ok(None) => {
+ log::warn!(
+ "[web-channel] approval reply targeted a non-pending/already-decided request thread_id={} request_id={} decision={} — dispatching as fresh turn",
+ thread_id,
+ request_id,
+ decision.as_str()
+ );
+ }
+ Err(err) => {
+ log::warn!(
+ "[web-channel] failed to route chat reply to approval gate thread_id={} request_id={} decision={} err={}",
+ thread_id,
+ request_id,
+ decision.as_str(),
+ err
+ );
+ }
+ }
+ }
+ }
+ }
+
+ // Configured `beforeSubmitPrompt` hooks. Deliberately after the
+ // approval-reply routing above: a bare "yes" answering a parked approval is
+ // not a prompt the user is submitting to the model, and handing it to a
+ // prompt hook would let a hook that blocks short messages strand a turn
+ // waiting for an approval it can no longer receive.
+ //
+ // The message here is post-attachment-processing, so a hook sees extracted
+ // text and placeholders rather than a multi-megabyte data URI on stdin.
+ match crate::hooks::ops::prompt_submitted(
+ crate::hooks::context::TurnIdentity {
+ conversation_id: Some(thread_id.clone()),
+ ..Default::default()
+ },
+ &message,
+ Vec::new(),
+ )
+ .await
+ {
+ crate::hooks::PromptVerdict::Submit { additional_context } => {
+ if let Some(context) = additional_context {
+ log::debug!(
+ "[web-channel] beforeSubmitPrompt hook added {} chars of context thread_id={}",
+ context.chars().count(),
+ thread_id
+ );
+ message = format!("{message}\n\n{context}");
+ }
+ }
+ crate::hooks::PromptVerdict::Block(reason) => {
+ log::info!(
+ "[web-channel] prompt blocked by a configured hook thread_id={thread_id}: {reason}"
+ );
+ return Err(reason);
+ }
+ }
+
+ let map_key = key_for(&thread_id);
+
+ let parsed_mode = match queue_mode.as_deref() {
+ Some("steer") => crate::agent::harness::run_queue::QueueMode::Steer,
+ Some("followup") => crate::agent::harness::run_queue::QueueMode::Followup,
+ Some("collect") => crate::agent::harness::run_queue::QueueMode::Collect,
+ Some("parallel") => crate::agent::harness::run_queue::QueueMode::Parallel,
+ _ => crate::agent::harness::run_queue::QueueMode::Interrupt,
+ };
+
+ // Parallel mode: spawn an independent forked turn that runs alongside any
+ // in-flight turn for this thread. It does not touch IN_FLIGHT (no
+ // interrupt/steer/queue) — it lives in its own request-keyed lane.
+ if matches!(
+ parsed_mode,
+ crate::agent::harness::run_queue::QueueMode::Parallel
+ ) {
+ log::info!(
+ "[web-channel] starting PARALLEL forked turn thread_id={} request_id={}",
+ thread_id,
+ request_id
+ );
+ spawn_parallel_turn(
+ &client_id,
+ &thread_id,
+ request_id.clone(),
+ &message,
+ model_override,
+ temperature,
+ profile_id,
+ locale,
+ metadata,
+ )
+ .await;
+ return Ok(request_id);
+ }
+
+ // Non-interrupt modes: push into the running turn's queue and return.
+ if !matches!(
+ parsed_mode,
+ crate::agent::harness::run_queue::QueueMode::Interrupt
+ ) {
+ let in_flight = IN_FLIGHT.lock().await;
+ if let Some(existing) = in_flight.get(&map_key) {
+ let queued_msg = crate::agent::harness::run_queue::QueuedMessage {
+ text: message.clone(),
+ mode: parsed_mode,
+ client_id: client_id.clone(),
+ thread_id: thread_id.clone(),
+ queued_at_ms: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64,
+ model_override: model_override.clone(),
+ temperature,
+ profile_id: profile_id.clone(),
+ locale: locale.clone(),
+ };
+ existing.run_queue.push(queued_msg).await;
+ let status = existing.run_queue.status().await;
+ log::info!(
+ "[web-channel] queued {} message thread_id={} request_id={} queue_depth={}",
+ parsed_mode,
+ thread_id,
+ request_id,
+ status.total
+ );
+ crate::core::bus::BUS.publish(DomainEvent::RunQueueMessageQueued {
+ thread_id: thread_id.clone(),
+ mode: parsed_mode.to_string(),
+ queue_depth: status.total,
+ });
+ return Ok(json!({
+ "queued": true,
+ "queue_mode": parsed_mode.to_string(),
+ "client_id": client_id,
+ "thread_id": thread_id,
+ "request_id": request_id,
+ "queue_depth": status.total,
+ })
+ .to_string());
+ }
+ log::info!(
+ "[web-channel] no in-flight turn for {} mode thread_id={} — starting fresh",
+ parsed_mode,
+ thread_id
+ );
+ }
+
+ {
+ let mut in_flight = IN_FLIGHT.lock().await;
+
+ if let Some(existing) = in_flight.remove(&map_key) {
+ let cancelled_id = cancel_in_flight_gracefully(existing);
+ log::info!(
+ "[web-channel] interrupted in-flight turn thread_id={} cancelled_request_id={}",
+ thread_id,
+ cancelled_id
+ );
+ crate::core::bus::BUS.publish(DomainEvent::RunQueueInterrupted {
+ thread_id: thread_id.clone(),
+ cancelled_request_id: cancelled_id.clone(),
+ });
+ publish_web_channel_event(WebChannelEvent {
+ event: "chat_error".to_string(),
+ client_id: client_id.clone(),
+ thread_id: thread_id.clone(),
+ request_id: cancelled_id,
+ message: Some("Cancelled by newer request".to_string()),
+ error_type: Some("cancelled".to_string()),
+ ..Default::default()
+ });
+ }
+ }
+
+ let turn_run_queue = crate::agent::harness::run_queue::RunQueue::new();
+ let turn_run_queue_task = turn_run_queue.clone();
+
+ let client_id_task = client_id.clone();
+ let thread_id_task = thread_id.clone();
+ let request_id_task = request_id.clone();
+ let map_key_task = map_key.clone();
+
+ // Cooperative cancellation for this turn. The token lives in the
+ // `InFlightEntry`; interrupt / cancel paths cancel it to tear the turn
+ // future down gracefully at the next await point.
+ let cancel_token = CancellationToken::new();
+ let task_cancel_token = cancel_token.clone();
+
+ let user_message = message.clone();
+ let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
+ async move {
+ let approval_ctx = crate::security::approval::ApprovalChatContext {
+ thread_id: thread_id_task.clone(),
+ client_id: client_id_task.clone(),
+ };
+ let origin = crate::agent::turn_origin::AgentTurnOrigin::WebChat {
+ thread_id: thread_id_task.clone(),
+ client_id: client_id_task.clone(),
+ request_id: Some(request_id_task.clone()),
+ };
+ // `None` => the turn was cancelled cooperatively before producing a
+ // result; the interrupting/cancelling side already emitted the
+ // user-facing `chat_error`, so we just unwind quietly here.
+ let result = run_turn_under_cancel_and_deadline(
+ task_cancel_token,
+ origin,
+ approval_ctx,
+ run_chat_task(
+ &client_id_task,
+ &thread_id_task,
+ &request_id_task,
+ &user_message,
+ model_override,
+ temperature,
+ profile_id,
+ locale,
+ turn_run_queue_task,
+ metadata,
+ /* fork */ false,
+ ),
+ )
+ .await;
+
+ let result = match result {
+ Some(res) => res,
+ None => {
+ log::info!(
+ "[web-channel] turn cancelled cooperatively client_id={} thread_id={} request_id={}",
+ client_id_task,
+ thread_id_task,
+ request_id_task
+ );
+ // Release any in-flight slot we still own and stop. The
+ // `request_id` guard below prevents clobbering a newer turn that
+ // replaced us on the interrupt path.
+ let mut in_flight = IN_FLIGHT.lock().await;
+ if let Some(current) = in_flight.get(&map_key_task) {
+ if current.request_id == request_id_task {
+ in_flight.remove(&map_key_task);
+ }
+ }
+ return;
+ }
+ };
+
+ match result {
+ Ok(chat_result) => {
+ crate::web_chat::presentation::deliver_response(
+ &client_id_task,
+ &thread_id_task,
+ &request_id_task,
+ &chat_result.full_response,
+ &user_message,
+ &chat_result.citations,
+ chat_result.usage.as_ref(),
+ // The workspace the turn ran in, so the reply is stored
+ // there before it is announced (#6034).
+ Some(chat_result.workspace_dir.as_path()),
+ )
+ .await;
+ }
+ Err(err) => {
+ log::warn!(
+ "[web-channel] run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task,
+ thread_id_task,
+ request_id_task,
+ err
+ );
+ let detailed = format!(
+ "run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task, thread_id_task, request_id_task, err
+ );
+ let classified = classify_inference_error(&err);
+ let classified_type = classified.error_type;
+ let classified_type_string = classified_type.to_string();
+ if let Some(reason) = sentry_suppression_reason(&detailed) {
+ log::info!(
+ target: "web_channel",
+ "[web_channel.run_chat_task] suppressed Sentry emission for {} \
+ client_id={} thread_id={} request_id={} error_type={} message={}",
+ reason,
+ client_id_task,
+ thread_id_task,
+ request_id_task,
+ classified_type,
+ detailed
+ );
+ } else {
+ crate::core::observability::report_error_or_expected(
+ detailed.as_str(),
+ "web_channel",
+ "run_chat_task",
+ &[
+ ("channel", "web"),
+ ("error_type", classified_type),
+ ("thread_id", thread_id_task.as_str()),
+ ("request_id", request_id_task.as_str()),
+ // Names which ceiling fired for the harness
+ // timeouts this arm now reports (#5804); "none"
+ // for every other error type.
+ ("timeout_bound", timeout_bound_tag(&detailed)),
+ ],
+ );
+ }
+ publish_web_channel_event(WebChannelEvent {
+ event: "chat_error".to_string(),
+ client_id: client_id_task.clone(),
+ thread_id: thread_id_task.clone(),
+ request_id: request_id_task.clone(),
+ message: Some(classified.message),
+ error_type: Some(classified_type_string),
+ error_source: Some(classified.source.to_string()),
+ error_retryable: Some(classified.retryable),
+ error_retry_after_ms: classified.retry_after_ms,
+ error_provider: classified.provider,
+ error_fallback_available: classified.fallback_available,
+ ..Default::default()
+ });
+ }
+ }
+
+ // Drain followup messages queued during this turn.
+ let followups = {
+ let mut in_flight = IN_FLIGHT.lock().await;
+ let followups = if let Some(current) = in_flight.get(&map_key_task) {
+ if current.request_id == request_id_task {
+ let fups = current.run_queue.drain_followups().await;
+ in_flight.remove(&map_key_task);
+ fups
+ } else {
+ Vec::new()
+ }
+ } else {
+ Vec::new()
+ };
+ followups
+ };
+ if !followups.is_empty() {
+ log::info!(
+ "[web-channel] dispatching {} followup(s) thread_id={}",
+ followups.len(),
+ thread_id_task
+ );
+ crate::core::bus::BUS.publish(
+ crate::core::events::DomainEvent::RunQueueFollowupDispatched {
+ thread_id: thread_id_task.clone(),
+ followup_count: followups.len(),
+ },
+ );
+ dispatch_followups(followups);
+ }
+ },
+ ));
+
+ {
+ let mut in_flight = IN_FLIGHT.lock().await;
+ in_flight.insert(
+ map_key,
+ crate::web_chat::types::InFlightEntry {
+ request_id: request_id.clone(),
+ handle,
+ run_queue: turn_run_queue,
+ cancel_token,
+ },
+ );
+ }
+
+ Ok(request_id)
+}
+
+fn dispatch_followups(followups: Vec<crate::agent::harness::run_queue::QueuedMessage>) {
+ for fup in followups {
+ tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
+ async move {
+ if let Err(err) = start_chat(
+ &fup.client_id,
+ &fup.thread_id,
+ &fup.text,
+ fup.model_override,
+ fup.temperature,
+ fup.profile_id,
+ fup.locale,
+ Some("followup".to_string()),
+ ChatRequestMetadata::default(),
+ )
+ .await
+ {
+ log::warn!(
+ "[web-channel] failed to dispatch followup thread_id={} err={}",
+ fup.thread_id,
+ err
+ );
+ }
+ },
+ ));
+ }
+}