Skip to content

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

feat(threads): persist typed attachments as opaque refs

Steven Enamakel1cfda9d1e5a7
diff --git a/crates/openhuman-core/src/threads/attachments.rs b/crates/openhuman-core/src/threads/attachments.rs
index 339b9a9c0d..f51b22ea33 100644
--- a/crates/openhuman-core/src/threads/attachments.rs
+++ b/crates/openhuman-core/src/threads/attachments.rs
@@ -9,6 +9,8 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tinychannels_bus::{ContentPart, MediaReference};
+use crate::agent::attachments::Attachment;
+
const STORAGE_KEY: &str = "__openhumanStoredAttachments";
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -52,6 +54,89 @@ pub(crate) fn strip_private_metadata(metadata: &mut Value) {
}
}
+/// Pair typed media input with the staged files created from it, storing only
+/// opaque refs publicly and keeping each validated relative path privately.
+pub(crate) fn from_staged_parts(
+ parts: &[ContentPart],
+ files: &[Attachment],
+) -> Result<Vec<(ContentPart, String)>, String> {
+ let media_count = parts
+ .iter()
+ .filter(|part| matches!(part, ContentPart::Image { .. } | ContentPart::Audio { .. } | ContentPart::Video { .. } | ContentPart::File { .. }))
+ .count();
+ if media_count != files.len() {
+ return Err("typed attachment staging did not preserve media ordering".into());
+ }
+
+ let mut files = files.iter();
+ let mut output = Vec::with_capacity(media_count);
+ for part in parts {
+ match part {
+ ContentPart::Image { media, caption, alt_text } => {
+ let file = files.next().expect("media count was checked");
+ output.push((ContentPart::Image {
+ media: stored_media(media, file),
+ caption: caption.clone(),
+ alt_text: alt_text.clone(),
+ }, file.path.clone()));
+ }
+ ContentPart::Audio { media, codec, duration_ms, title, transcript } => {
+ let file = files.next().expect("media count was checked");
+ output.push((ContentPart::Audio {
+ media: stored_media(media, file),
+ codec: codec.clone(),
+ duration_ms: *duration_ms,
+ title: title.clone(),
+ transcript: transcript.clone(),
+ }, file.path.clone()));
+ }
+ ContentPart::Video { media, caption, duration_ms, thumbnail } => {
+ let file = files.next().expect("media count was checked");
+ output.push((ContentPart::Video {
+ media: stored_media(media, file),
+ caption: caption.clone(),
+ duration_ms: *duration_ms,
+ thumbnail: thumbnail.as_ref().map(|thumb| {
+ let mut sanitized = thumb.clone();
+ sanitized.path = None;
+ sanitized.url = None;
+ sanitized.local_cache_path = None;
+ sanitized.opaque_id = None;
+ sanitized
+ }),
+ }, file.path.clone()));
+ }
+ ContentPart::File { media, file_name, caption } => {
+ let file = files.next().expect("media count was checked");
+ let mut stored = stored_media(media, file);
+ if let Some(name) = file_name {
+ stored.file_name = Some(name.clone());
+ }
+ output.push((ContentPart::File {
+ media: stored,
+ file_name: file_name.clone(),
+ caption: caption.clone(),
+ }, file.path.clone()));
+ }
+ ContentPart::Text { .. } | ContentPart::VoiceNote { .. } => {}
+ _ => return Err("typed attachment has an unsupported kind".into()),
+ }
+ }
+ Ok(output)
+}
+
+fn stored_media(input: &MediaReference, file: &Attachment) -> MediaReference {
+ let mut media = input.clone();
+ media.opaque_id = Some(uuid::Uuid::new_v4().simple().to_string());
+ media.path = None;
+ media.url = None;
+ media.local_cache_path = None;
+ media.content_type = Some(file.mime.clone());
+ media.file_name = Some(file.name.clone());
+ media.size_bytes = Some(file.size_bytes as u64);
+ media
+}
+
fn stored(metadata: &Value) -> Result<Vec<StoredAttachment>, String> {
let Some(value) = metadata.get(STORAGE_KEY) else {
return Ok(Vec::new());
diff --git a/crates/openhuman-core/src/threads/mod.rs b/crates/openhuman-core/src/threads/mod.rs
index e177f21e98..b23909aff7 100644
--- a/crates/openhuman-core/src/threads/mod.rs
+++ b/crates/openhuman-core/src/threads/mod.rs
@@ -5,6 +5,7 @@
//! this module owns the RPC surface and controller registry.
pub mod artifact_rows;
+pub(crate) mod attachments;
pub(crate) mod channel_projection;
pub mod error;
pub mod ops;
diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rs
index 817767f757..49a7c71db6 100644
--- a/crates/openhuman-core/src/threads/ops/crud.rs
+++ b/crates/openhuman-core/src/threads/ops/crud.rs
@@ -203,12 +203,45 @@ async fn message_append_with_config(
origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
persistence_dir: &std::path::Path,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
- if request.message.sender == "user" && !request.attachments.is_empty() {
- // Typed attachments become the staging markers here, once, so the
- // rest of this function sees the same content a marker send would.
+ let typed_attachments = if request.message.sender == "user" {
+ std::mem::take(&mut request.attachments)
+ } else {
+ Vec::new()
+ };
+ let typed_media_count = typed_attachments
+ .iter()
+ .filter(|part| {
+ matches!(
+ part,
+ tinychannels_bus::ContentPart::Image { .. }
+ | tinychannels_bus::ContentPart::Audio { .. }
+ | tinychannels_bus::ContentPart::Video { .. }
+ | tinychannels_bus::ContentPart::File { .. }
+ )
+ })
+ .count();
+ if typed_attachments
+ .iter()
+ .any(|part| matches!(part, tinychannels_bus::ContentPart::VoiceNote { .. }))
+ {
+ return Err(ThreadsError::Message(
+ "voice notes must be sent through channel.web_chat".into(),
+ ));
+ }
+ let original_content = request.message.content.clone();
+ if !typed_attachments.is_empty()
+ && (original_content.contains("[IMAGE:")
+ || original_content.contains("[FILE:")
+ || !crate::agent::attachments::parse(&original_content).1.is_empty())
+ {
+ return Err(ThreadsError::Message(
+ "typed attachments cannot be combined with legacy attachment markers".into(),
+ ));
+ }
+ if !typed_attachments.is_empty() {
request.message.content = crate::agent::attachments::parts::fold_into_message(
&request.message.content,
- &request.attachments,
+ &typed_attachments,
)
.map_err(|error| ThreadsError::Message(error.to_string()))?;
}
@@ -307,7 +340,7 @@ async fn message_append_with_config(
"user upload bytes require attachment markers before persistence".into(),
));
}
- request.message.content = crate::agent::attachments::stage_turn(
+ let staged_content = crate::agent::attachments::stage_turn(
&request.message.content,
Some(config),
Some(&tinytools::WorkspaceDescriptor::new(workspace)),
@@ -316,6 +349,27 @@ async fn message_append_with_config(
)
.await
.map_err(|error| ThreadsError::Message(format!("stage user attachments: {error}")))?;
+ if typed_media_count > 0 {
+ let (clean_content, staged_files) =
+ crate::agent::attachments::parse(&staged_content);
+ if staged_files.len() != typed_media_count {
+ return Err(ThreadsError::Message(
+ "typed attachment staging did not preserve media order".into(),
+ ));
+ }
+ let entries = crate::threads::attachments::from_staged_parts(
+ &typed_attachments,
+ &staged_files,
+ )
+ .map_err(ThreadsError::Message)?;
+ request.message.attachments = crate::threads::attachments::save(
+ &mut request.message.extra_metadata,
+ entries,
+ );
+ request.message.content = clean_content.trim().to_string();
+ } else {
+ request.message.content = staged_content;
+ }
if raw_upload || durable_upload {
if let Some(metadata) = request.message.extra_metadata.as_object_mut() {
for field in byte_fields {
diff --git a/crates/openhuman-core/src/threads/ops/support.rs b/crates/openhuman-core/src/threads/ops/support.rs
index 1caff7e460..05f07b86af 100644
--- a/crates/openhuman-core/src/threads/ops/support.rs
+++ b/crates/openhuman-core/src/threads/ops/support.rs
@@ -168,22 +168,28 @@ pub(super) fn thread_to_summary(thread: ConversationThread) -> ConversationThrea
}
pub(super) fn message_to_record(message: ConversationMessage) -> ConversationMessageRecord {
+ let attachments = crate::threads::attachments::public_refs(&message.extra_metadata);
+ let mut extra_metadata = message.extra_metadata;
+ crate::threads::attachments::strip_private_metadata(&mut extra_metadata);
ConversationMessageRecord {
id: message.id,
content: message.content,
+ attachments,
message_type: message.message_type,
- extra_metadata: message.extra_metadata,
+ extra_metadata,
sender: message.sender,
created_at: message.created_at,
}
}
pub(super) fn record_to_message(record: ConversationMessageRecord) -> ConversationMessage {
+ let mut extra_metadata = record.extra_metadata;
+ crate::threads::attachments::strip_private_metadata(&mut extra_metadata);
ConversationMessage {
id: record.id,
content: record.content,
message_type: record.message_type,
- extra_metadata: record.extra_metadata,
+ extra_metadata,
sender: record.sender,
created_at: record.created_at,
}