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): add thread search operation
Steven Enamakelb71a88b8527e
diff --git a/crates/openhuman-core/src/threads/ops.rs b/crates/openhuman-core/src/threads/ops.rsindex d051f38e25..acdbe92188 100644--- a/crates/openhuman-core/src/threads/ops.rs+++ b/crates/openhuman-core/src/threads/ops.rs@@ -8,6 +8,7 @@ mod crud;mod edit;mod live_state;mod purge;+mod search;mod support;mod title_generation;mod transcript;@@ -26,6 +27,7 @@ pub use live_state::{goal_get, todos_get, ThreadGoalGetResponse, ThreadLiveStateRequest, ThreadTodosGetResponse,};pub use purge::threads_purge;+pub use search::{thread_search, ThreadSearchHit, ThreadSearchRequest, ThreadSearchResponse};pub use title_generation::thread_generate_title;pub use transcript::{transcript_get, TranscriptGetRequest};pub use turn_state_ops::{diff --git a/crates/openhuman-core/src/threads/ops/search.rs b/crates/openhuman-core/src/threads/ops/search.rsnew file mode 100644index 0000000000..19c2716dc7--- /dev/null+++ b/crates/openhuman-core/src/threads/ops/search.rs@@ -0,0 +1,112 @@+//! `threads.search` — find messages across every thread, for the global+//! (`Cmd`/`Ctrl+K`) search. A thin RPC over [`transcript_search`]: the same+//! trigram/CJK-bigram inverted index the cross-chat context reader uses.+//!+//! Each hit carries a short snippet around the match rather than the whole+//! message, so a broad query never ships every long transcript to the UI.++use super::crud::transcript_search;+use super::support::envelope;+use crate::core::Outcome;+use crate::threads::ApiEnvelope;++/// Hits returned when the caller does not ask for a number.+const DEFAULT_LIMIT: usize = 20;+/// Upper bound on hits per search.+const MAX_LIMIT: usize = 100;+/// Characters of context kept on each side of the match.+const SNIPPET_CONTEXT: usize = 60;++/// Request for [`thread_search`].+#[derive(Debug, Clone, serde::Deserialize)]+pub struct ThreadSearchRequest {+ pub query: String,+ #[serde(default)]+ pub limit: Option<usize>,+}++/// One matched message.+#[derive(Debug, Clone, PartialEq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ThreadSearchHit {+ pub thread_id: String,+ pub message_id: String,+ pub role: String,+ /// The message text around the first match, with `…` where it was cut.+ pub snippet: String,+ pub created_at: String,+}++/// Response for [`thread_search`]: hits newest first.+#[derive(Debug, Clone, serde::Serialize)]+pub struct ThreadSearchResponse {+ pub hits: Vec<ThreadSearchHit>,+}++/// See the module docs. A blank query answers no hits without reading.+pub async fn thread_search(+ request: ThreadSearchRequest,+) -> Result<Outcome<ApiEnvelope<ThreadSearchResponse>>, String> {+ let query = request.query.trim();+ if query.is_empty() {+ return Ok(envelope(+ ThreadSearchResponse { hits: Vec::new() },+ None,+ None,+ ));+ }+ let limit = request.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT);+ let hits = transcript_search(query, limit, None)+ .await?+ .into_iter()+ .map(|hit| ThreadSearchHit {+ snippet: snippet(&hit.content, query),+ thread_id: hit.thread_id,+ message_id: hit.message_id,+ role: hit.role,+ created_at: hit.created_at,+ })+ .collect();+ Ok(envelope(ThreadSearchResponse { hits }, None, None))+}++/// `content` cut to [`SNIPPET_CONTEXT`] characters either side of the first+/// case-insensitive occurrence of `query`, whitespace collapsed. The index+/// matches on trigrams, so a hit need not contain the query verbatim; then+/// the snippet is the message's start.+pub(super) fn snippet(content: &str, query: &str) -> String {+ let text: Vec<char> = content+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+ .chars()+ .collect();+ let fold = |c: &char| c.to_lowercase().next().unwrap_or(*c);+ let needle: Vec<char> = query.chars().map(|c| fold(&c)).collect();+ let lower: Vec<char> = text.iter().map(fold).collect();+ let at = if needle.is_empty() || needle.len() > lower.len() {+ None+ } else {+ (0..=lower.len() - needle.len()).find(|&i| lower[i..i + needle.len()] == needle[..])+ };+ let (start, end) = match at {+ Some(i) => (+ i.saturating_sub(SNIPPET_CONTEXT),+ (i + needle.len() + SNIPPET_CONTEXT).min(text.len()),+ ),+ None => (0, (SNIPPET_CONTEXT * 2).min(text.len())),+ };+ let mut out = String::new();+ if start > 0 {+ out.push('…');+ }+ out.extend(&text[start..end]);+ if end < text.len() {+ out.push('…');+ }+ out+}++#[cfg(test)]+#[path = "search_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/threads/ops/search_tests.rs b/crates/openhuman-core/src/threads/ops/search_tests.rsnew file mode 100644index 0000000000..9360dda948--- /dev/null+++ b/crates/openhuman-core/src/threads/ops/search_tests.rs@@ -0,0 +1,45 @@+//! Behavior tests for `threads::ops::search`.++use super::*;++#[test]+fn snippet_keeps_short_text_whole() {+ assert_eq!(snippet("Hello world\nagain", "world"), "Hello world again");+}++#[test]+fn snippet_centres_on_the_match_and_marks_cuts() {+ let content = format!("{} needle {}", "a".repeat(200), "b".repeat(200));+ let out = snippet(&content, "NEEDLE");+ assert!(out.starts_with('…') && out.ends_with('…'), "{out}");+ assert!(out.contains("needle"), "{out}");+ assert_eq!(out.chars().count(), 2 + 6 + 2 * SNIPPET_CONTEXT);+}++#[test]+fn snippet_without_a_verbatim_match_is_the_start() {+ let content = "x".repeat(300);+ let out = snippet(&content, "zzz");+ assert_eq!(out.chars().count(), 2 * SNIPPET_CONTEXT + 1);+ assert!(out.ends_with('…'));+}++#[test]+fn request_limit_is_optional() {+ let parsed: ThreadSearchRequest =+ serde_json::from_value(serde_json::json!({ "query": "hi" })).unwrap();+ assert_eq!(parsed.query, "hi");+ assert_eq!(parsed.limit, None);+}++#[tokio::test]+async fn blank_query_answers_no_hits() {+ let out = thread_search(ThreadSearchRequest {+ query: " ".into(),+ limit: None,+ })+ .await+ .unwrap();+ let json = out.into_cli_compatible_json().unwrap();+ assert_eq!(json["data"]["hits"], serde_json::json!([]), "{json}");+}diff --git a/crates/openhuman-core/src/threads/schemas/handlers.rs b/crates/openhuman-core/src/threads/schemas/handlers.rsindex 91e5303e99..21db37c7fb 100644--- a/crates/openhuman-core/src/threads/schemas/handlers.rs+++ b/crates/openhuman-core/src/threads/schemas/handlers.rs@@ -155,6 +155,13 @@ pub(super) fn handle_todos_get(params: Map<String, Value>) -> ControllerFuture {})}+pub(super) fn handle_search(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ops::ThreadSearchRequest>(params)?;+ to_json(ops::thread_search(p).await?)+ })+}+pub(super) fn handle_edit_message(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let p = parse::<ops::EditMessageRequest>(params)?;diff --git a/crates/openhuman-core/src/threads/schemas/registry.rs b/crates/openhuman-core/src/threads/schemas/registry.rsindex 8e504a4082..ac62edb74c 100644--- a/crates/openhuman-core/src/threads/schemas/registry.rs+++ b/crates/openhuman-core/src/threads/schemas/registry.rs@@ -7,7 +7,7 @@ use crate::core::ControllerSchema;use super::handlers::{handle_create_new, handle_delete, handle_edit_message, handle_generate_title, handle_goal_get,handle_list, handle_message_append, handle_message_update, handle_messages_list, handle_purge,- handle_regenerate, handle_todos_get, handle_token_usage, handle_transcript_get,+ handle_regenerate, handle_search, handle_todos_get, handle_token_usage, handle_transcript_get,handle_turn_state_clear, handle_turn_state_get, handle_turn_state_get_turn,handle_turn_state_history, handle_turn_state_list, handle_update_labels, handle_update_title,handle_update_working_dir, handle_upsert,@@ -39,6 +39,7 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {schemas("todos_get"),schemas("edit_message"),schemas("regenerate"),+ schemas("search"),]}@@ -136,5 +137,9 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {schema: schemas("regenerate"),handler: handle_regenerate,},+ RegisteredController {+ schema: schemas("search"),+ handler: handle_search,+ },]}diff --git a/crates/openhuman-core/src/threads/schemas/schema_defs.rs b/crates/openhuman-core/src/threads/schemas/schema_defs.rsindex 446755a18e..3e35499eb6 100644--- a/crates/openhuman-core/src/threads/schemas/schema_defs.rs+++ b/crates/openhuman-core/src/threads/schemas/schema_defs.rs@@ -534,6 +534,32 @@ pub(crate) fn schemas(function: &str) -> ControllerSchema {required: true,}],},+ "search" => ControllerSchema {+ namespace: "threads",+ function: "search",+ description:+ "Search message text across every thread (global search). Hits are newest first, each with a snippet around the match.",+ inputs: vec![+ FieldSchema {+ name: "query",+ ty: TypeSchema::String,+ comment: "Text to find; blank returns no hits.",+ required: true,+ },+ FieldSchema {+ name: "limit",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Max hits (default 20, capped at 100).",+ required: false,+ },+ ],+ outputs: vec![FieldSchema {+ name: "result",+ ty: TypeSchema::Json,+ comment: "Envelope with hits: threadId, messageId, role, snippet, createdAt.",+ required: true,+ }],+ },_other => ControllerSchema {namespace: "threads",function: "unknown",