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
refactor(web_chat): move turn citations into web_chat module
Steven Enamakelbb069aa5a0d9
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rsindex ed6396e867..0c105b0f5e 100644--- a/crates/openhuman-core/src/memory/tools.rs+++ b/crates/openhuman-core/src/memory/tools.rs@@ -18,8 +18,7 @@//! team's). A `reach` in the model's filter is overwritten.use crate::tools::schema_cache::static_schema;-use std::collections::HashMap;-use std::sync::{Arc, Mutex};+use std::sync::Arc;use async_trait::async_trait;use serde_json::{json, Value};@@ -37,78 +36,12 @@ use super::error::MemoryError;use super::ops;pub use super::tool_budget::is_budget_refusal;use super::types::{- FetchParams, ForgetParams, LearnParams, RecallParams, RecallView, TurnCitation,+ FetchParams, ForgetParams, LearnParams, RecallParams, RecallView,};-/// Most citations kept per thread between two drains.-const MAX_TURN_CITATIONS: usize = 20;-/// How many matches one `fetch` returns; the model pages on with `cursor`.const FETCH_TOP: usize = 5;-type TurnCitations = Mutex<HashMap<String, Vec<TurnCitation>>>;--/// Citations `recall` produced during a thread's in-flight turn, drained by-/// the chat surface once the turn returns ([`take_turn_citations`]).-fn turn_citations(ctx: &DispatchCtx) -> Arc<TurnCitations> {- crate::core::runtime::slot_for::<TurnCitations>(ctx)-}--fn record_turn_citations(- ctx: &DispatchCtx,- thread_id: &str,- citations: &[tinymemory_api::Citation],-) {- if citations.is_empty() {- return;- }- let citations_by_thread = turn_citations(ctx);- let mut all = citations_by_thread- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let entry = all.entry(thread_id.to_string()).or_default();- for citation in citations {- if entry.len() >= MAX_TURN_CITATIONS {- break;- }- if !entry.iter().any(|existing| existing.id == citation.id.0) {- entry.push(TurnCitation::from(citation));- }- }-}--/// Records `citations` for `thread_id`'s in-flight turn: what the turn's-/// memory pack cited (`lifecycle::prefetch::pre_turn`), beside what `recall`-/// cites.-pub fn record_pack_citations(ctx: &DispatchCtx, thread_id: &str, citations: Vec<TurnCitation>) {- if citations.is_empty() {- return;- }- let citations_by_thread = turn_citations(ctx);- let mut all = citations_by_thread- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let entry = all.entry(thread_id.to_string()).or_default();- for citation in citations {- if entry.len() >= MAX_TURN_CITATIONS {- break;- }- if !entry.iter().any(|existing| existing.id == citation.id) {- entry.push(citation);- }- }-}--/// Drains the citations `recall` and the turn's pack produced for-/// `thread_id` since the last drain.-#[must_use]-pub fn take_turn_citations(ctx: &DispatchCtx, thread_id: &str) -> Vec<TurnCitation> {- turn_citations(ctx)- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .remove(thread_id)- .unwrap_or_default()-}/// The tool's name.pub const MEMORY_TOOL_NAME: &str = "memory";@@ -369,7 +302,11 @@ pub async fn run_action(.await.map(|view| {if let Some(thread_id) = facts.thread_id.as_deref() {- record_turn_citations(ctx, thread_id, &view.citations);+ crate::web_chat::citations::record_recall_citations(+ ctx,+ thread_id,+ &view.citations,+ );}BUS.publish(DomainEvent::MemoryRecalled {query: question,diff --git a/crates/openhuman-core/src/memory/types.rs b/crates/openhuman-core/src/memory/types.rsindex 05e930e25f..6810f16e03 100644--- a/crates/openhuman-core/src/memory/types.rs+++ b/crates/openhuman-core/src/memory/types.rs@@ -7,9 +7,7 @@use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};-use tinymemory_api::{- Citation, EngineDescriptor, FetchMode, Hit, LearningKind, MemoryMeta, MetaFilter,-};+use tinymemory_api::{EngineDescriptor, FetchMode, LearningKind, MemoryMeta, MetaFilter};use tinymemory_integrations::import::ImportState;use crate::config::schema::MemorySourceKind;@@ -390,65 +388,3 @@ pub struct ImportStateView {pub state: ImportState,}-/// A recall citation attached to a chat reply so the UI can show where a-/// memory-informed answer came from. Same JSON shape the chat surface has-/// always rendered: `key` is the item kind, `namespace` its source kind,-/// `timestamp` when it was observed, `snippet` a short excerpt.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct TurnCitation {- /// Item id.- pub id: String,- /// Item kind (`document`, `conversation`, `learning`).- pub key: String,- /// Source kind (`folder`, `agent`, …).- #[serde(skip_serializing_if = "Option::is_none")]- pub namespace: Option<String>,- /// Relevance, when the engine reports one.- #[serde(skip_serializing_if = "Option::is_none")]- pub score: Option<f64>,- /// When the item was observed (RFC 3339), or empty.- pub timestamp: String,- /// Short excerpt.- pub snippet: String,-}--impl From<&Hit> for TurnCitation {- fn from(hit: &Hit) -> Self {- Self {- id: hit.id.0.clone(),- key: hit.kind.as_str().to_string(),- namespace: Some(hit.meta.source.kind.as_str().to_string()),- score: Some(f64::from(hit.score)).filter(|score| *score > 0.0),- timestamp: hit- .meta- .observed_at- .map(|at| at.to_rfc3339())- .unwrap_or_default(),- snippet: hit.text.chars().take(TURN_CITATION_SNIPPET_CHARS).collect(),- }- }-}--impl From<&Citation> for TurnCitation {- fn from(citation: &Citation) -> Self {- Self {- id: citation.id.0.clone(),- key: citation.kind.as_str().to_string(),- namespace: Some(citation.meta.source.kind.as_str().to_string()),- score: citation.score.map(f64::from),- timestamp: citation- .meta- .observed_at- .map(|at| at.to_rfc3339())- .unwrap_or_default(),- snippet: citation- .snippet- .chars()- .take(TURN_CITATION_SNIPPET_CHARS)- .collect(),- }- }-}--/// Longest snippet a [`TurnCitation`] carries.-pub const TURN_CITATION_SNIPPET_CHARS: usize = 280;diff --git a/crates/openhuman-core/src/web_chat/citations.rs b/crates/openhuman-core/src/web_chat/citations.rsnew file mode 100644index 0000000000..29d75ec837--- /dev/null+++ b/crates/openhuman-core/src/web_chat/citations.rs@@ -0,0 +1,131 @@+//! Citations collected during a chat turn for the web chat surface.++use std::collections::HashMap;+use std::sync::{Arc, Mutex};++use crate::core::runtime::DispatchCtx;++/// A memory citation attached to a chat reply so the UI can show where an+/// answer came from. `key` is the item kind, `namespace` its source kind,+/// `timestamp` when it was observed, and `snippet` a short excerpt.+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct TurnCitation {+ /// Item id.+ pub id: String,+ /// Item kind (`document`, `conversation`, `learning`).+ pub key: String,+ /// Source kind (`folder`, `agent`, …).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub namespace: Option<String>,+ /// Relevance, when the engine reports one.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub score: Option<f64>,+ /// When the item was observed (RFC 3339), or empty.+ pub timestamp: String,+ /// Short excerpt.+ pub snippet: String,+}++impl From<&tinymemory_api::Hit> for TurnCitation {+ fn from(hit: &tinymemory_api::Hit) -> Self {+ Self {+ id: hit.id.0.clone(),+ key: hit.kind.as_str().to_string(),+ namespace: Some(hit.meta.source.kind.as_str().to_string()),+ score: Some(f64::from(hit.score)).filter(|score| *score > 0.0),+ timestamp: hit+ .meta+ .observed_at+ .map(|at| at.to_rfc3339())+ .unwrap_or_default(),+ snippet: hit+ .text+ .chars()+ .take(TURN_CITATION_SNIPPET_CHARS)+ .collect(),+ }+ }+}++impl From<&tinymemory_api::Citation> for TurnCitation {+ fn from(citation: &tinymemory_api::Citation) -> Self {+ Self {+ id: citation.id.0.clone(),+ key: citation.kind.as_str().to_string(),+ namespace: Some(citation.meta.source.kind.as_str().to_string()),+ score: citation.score.map(f64::from),+ timestamp: citation+ .meta+ .observed_at+ .map(|at| at.to_rfc3339())+ .unwrap_or_default(),+ snippet: citation+ .snippet+ .chars()+ .take(TURN_CITATION_SNIPPET_CHARS)+ .collect(),+ }+ }+}++/// Longest snippet a [`TurnCitation`] carries.+pub const TURN_CITATION_SNIPPET_CHARS: usize = 280;++/// Most citations kept per thread between two drains.+const MAX_TURN_CITATIONS: usize = 20;++type TurnCitations = Mutex<HashMap<String, Vec<TurnCitation>>>;++fn turn_citations(ctx: &DispatchCtx) -> Arc<TurnCitations> {+ crate::core::runtime::slot_for::<TurnCitations>(ctx)+}++fn extend_thread(ctx: &DispatchCtx, thread_id: &str, citations: impl IntoIterator<Item = TurnCitation>) {+ let citations_by_thread = turn_citations(ctx);+ let mut all = citations_by_thread+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let entry = all.entry(thread_id.to_string()).or_default();+ for citation in citations {+ if entry.len() >= MAX_TURN_CITATIONS {+ break;+ }+ if !entry.iter().any(|existing| existing.id == citation.id) {+ entry.push(citation);+ }+ }+}++/// Records citations returned by the memory tool for a thread's in-flight+/// turn.+pub(crate) fn record_recall_citations(+ ctx: &DispatchCtx,+ thread_id: &str,+ citations: &[tinymemory_api::Citation],+) {+ if citations.is_empty() {+ return;+ }+ extend_thread(ctx, thread_id, citations.iter().map(TurnCitation::from));+}++/// Records the citations in a turn's prefetched memory pack.+pub(crate) fn record_pack_citations(+ ctx: &DispatchCtx,+ thread_id: &str,+ citations: Vec<TurnCitation>,+) {+ if !citations.is_empty() {+ extend_thread(ctx, thread_id, citations);+ }+}++/// Drains the citations produced for `thread_id` since the last drain.+#[must_use]+pub(crate) fn take_turn_citations(ctx: &DispatchCtx, thread_id: &str) -> Vec<TurnCitation> {+ turn_citations(ctx)+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .remove(thread_id)+ .unwrap_or_default()+}diff --git a/crates/openhuman-core/src/web_chat/citations_tests.rs b/crates/openhuman-core/src/web_chat/citations_tests.rsnew file mode 100644index 0000000000..79c5b22c5b--- /dev/null+++ b/crates/openhuman-core/src/web_chat/citations_tests.rs@@ -0,0 +1,105 @@+use super::*;+use crate::core::runtime::{context::CoreContext, ContextOverlay, DispatchCtx, DomainSet};+use std::collections::HashSet;+use std::sync::Arc;+use tinymemory_api::{ItemKind, MemoryMeta};++fn agent(parent: &Arc<CoreContext>, id: &str) -> Arc<CoreContext> {+ parent.derive_with(+ ContextOverlay::new(+ crate::config::Config::default(),+ DomainSet::kernel(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .session_agent(id),+ )+}++fn citation(id: &str) -> TurnCitation {+ TurnCitation {+ id: id.to_string(),+ key: "learning".to_string(),+ namespace: None,+ score: None,+ timestamp: String::new(),+ snippet: String::new(),+ }+}++#[tokio::test]+async fn turn_citations_stay_with_the_agent_that_recorded_them() {+ let root = CoreContext::for_test(DomainSet::full(), None);+ let alpha = agent(&root, "alpha");+ let beta = agent(&root, "beta");+ let thread = "shared-thread";++ {+ let scope_ctx = DispatchCtx::new(Arc::clone(&alpha));+ record_pack_citations(&scope_ctx, thread, vec![citation("alpha-cite")]);+ }+ {+ let scope_ctx = DispatchCtx::new(Arc::clone(&beta));+ record_pack_citations(&scope_ctx, thread, vec![citation("beta-cite")]);+ }++ let from_beta = take_turn_citations(&DispatchCtx::new(beta), thread);+ let from_alpha = take_turn_citations(&DispatchCtx::new(alpha), thread);++ assert_eq!(+ from_alpha.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(),+ ["alpha-cite"]+ );+ assert_eq!(+ from_beta.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(),+ ["beta-cite"]+ );+}++#[test]+fn turn_citations_are_capped_and_deduplicated() {+ let citation = |n: usize| tinymemory_api::Citation {+ id: tinymemory_api::ItemId(format!("cite-{n}")),+ kind: ItemKind::Learning,+ snippet: "s".repeat(1000),+ score: Some(0.5),+ meta: MemoryMeta::default(),+ };+ let thread = "thread-cap";+ let many: Vec<_> = (0..MAX_TURN_CITATIONS + 10).map(citation).collect();+ let ctx = DispatchCtx::ambient();+ record_recall_citations(&ctx, thread, &many);+ record_recall_citations(&ctx, thread, &many[..2]);+ record_recall_citations(&ctx, thread, &[]);+ let drained = take_turn_citations(&ctx, thread);+ assert_eq!(drained.len(), MAX_TURN_CITATIONS);+ assert_eq!(+ drained+ .iter()+ .map(|c| c.id.clone())+ .collect::<HashSet<_>>()+ .len(),+ MAX_TURN_CITATIONS+ );+ assert!(drained[0].snippet.chars().count() <= TURN_CITATION_SNIPPET_CHARS);+ assert_eq!(drained[0].key, "learning");+}++#[test]+fn citations_drain_per_thread_and_merge_pack_and_recall_sources() {+ let ctx = DispatchCtx::ambient();+ record_pack_citations(&ctx, "thread-a", vec![citation("pack"), citation("shared")]);+ record_pack_citations(&ctx, "thread-b", vec![citation("other-thread")]);+ let recall = tinymemory_api::Citation {+ id: tinymemory_api::ItemId("shared".to_string()),+ kind: ItemKind::Learning,+ snippet: "duplicate".to_string(),+ score: Some(0.5),+ meta: MemoryMeta::default(),+ };+ record_recall_citations(&ctx, "thread-a", &[recall]);++ let thread_a = take_turn_citations(&ctx, "thread-a");+ assert_eq!(thread_a.iter().map(|item| item.id.as_str()).collect::<Vec<_>>(), ["pack", "shared"]);+ assert_eq!(take_turn_citations(&ctx, "thread-a"), []);+ assert_eq!(take_turn_citations(&ctx, "thread-b")[0].id, "other-thread");+}diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rsindex 5f575a6c7c..72570ec5fd 100644--- a/crates/openhuman-core/src/web_chat/mod.rs+++ b/crates/openhuman-core/src/web_chat/mod.rs@@ -27,6 +27,9 @@//! contract), `types.rs` (shared param/state types).mod channel_event;+mod citations;+#[cfg(test)]+mod citations_tests;mod egress_surface;mod event_bus;mod event_bus_channel;@@ -61,6 +64,7 @@ pub use channel_event::{ChatSuggestion, GuardrailPayload, GuardrailReason, QueueItemPayload, SubagentProgressDetail,SubagentUsagePayload, TurnTimingPayload, TurnUsagePayload, WebChannelEvent,};+pub use citations::{TurnCitation, TURN_CITATION_SNIPPET_CHARS};pub use egress_surface::register_egress_surface_subscriber;pub use event_bus::{approval_request_event, plan_review_request_event, publish_web_channel_event,