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 staged attachment claiming and consumption
Steven Enamakelcc7955741e5b
diff --git a/crates/openhuman-core/src/threads/attachments.rs b/crates/openhuman-core/src/threads/attachments.rsindex fabad0ea40..0ceec8c312 100644--- a/crates/openhuman-core/src/threads/attachments.rs+++ b/crates/openhuman-core/src/threads/attachments.rs@@ -29,6 +29,15 @@ struct StagedAttachment {expires_at: i64,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+struct StagedAttachmentClaim {+ tenant: crate::core::runtime::Tenant,+ thread_id: String,+ message_id: String,+ part: ContentPart,+}+const STAGED_DIR: &str = "openhuman-staged-attachments";const STAGED_TTL_SECS: i64 = 7 * 24 * 60 * 60;@@ -254,10 +263,12 @@ pub(crate) async fn bind_staged_refs(thread_id: &str,config: &crate::config::Config,requested: &[ContentPart],+ message_id: &str,metadata: &mut Value,) -> Result<Vec<ContentPart>, String> {let entries = read_staged_entries(ctx, thread_id, requested, config).await?;validate_staged_files(ctx, thread_id, config, &entries).await?;+ claim_staged_refs(ctx, thread_id, config, message_id, &entries).await?;Ok(save(metadata,entries@@ -267,6 +278,81 @@ pub(crate) async fn bind_staged_refs())}+async fn claim_staged_refs(+ ctx: &crate::core::runtime::DispatchCtx,+ thread_id: &str,+ config: &crate::config::Config,+ message_id: &str,+ entries: &[StoredAttachment],+) -> Result<(), String> {+ if message_id.is_empty() {+ return Err("staged attachment target message ID is empty".into());+ }+ let tenant = tenant_for(ctx)?;+ let mut created = Vec::new();+ for entry in entries {+ let opaque_id = opaque_media(&entry.part)+ .and_then(|media| media.opaque_id.as_deref())+ .ok_or_else(|| "staged attachment reference is missing".to_string())?;+ let manifest_path = staged_manifest_path(&config.workspace_dir, opaque_id)?;+ let claim_path = manifest_path.with_extension("claim.json");+ let claim = StagedAttachmentClaim {+ tenant: tenant.clone(),+ thread_id: thread_id.to_string(),+ message_id: message_id.to_string(),+ part: entry.part.clone(),+ };+ let bytes = serde_json::to_vec(&claim)+ .map_err(|error| format!("serialize staged attachment claim: {error}"))?;+ let temp_path = manifest_path.with_extension(format!("{}.claim-tmp", uuid::Uuid::new_v4()));+ let result = async {+ use tokio::io::AsyncWriteExt;+ let mut file = tokio::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&temp_path)+ .await+ .map_err(|error| format!("create staged attachment claim: {error}"))?;+ file.write_all(&bytes)+ .await+ .map_err(|error| format!("write staged attachment claim: {error}"))?;+ file.sync_all()+ .await+ .map_err(|error| format!("sync staged attachment claim: {error}"))?;+ match tokio::fs::hard_link(&temp_path, &claim_path).await {+ Ok(()) => Ok(true),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {+ let stored: StagedAttachmentClaim = serde_json::from_slice(+ &tokio::fs::read(&claim_path)+ .await+ .map_err(|read| format!("read staged attachment claim: {read}"))?,+ )+ .map_err(|read| format!("decode staged attachment claim: {read}"))?;+ if stored == claim {+ Ok(false)+ } else {+ Err("staged attachment is already bound to another message".into())+ }+ }+ Err(error) => Err(format!("publish staged attachment claim: {error}")),+ }+ }+ .await;+ let _ = tokio::fs::remove_file(&temp_path).await;+ match result {+ Ok(true) => created.push(claim_path),+ Ok(false) => {}+ Err(error) => {+ for path in created {+ let _ = tokio::fs::remove_file(path).await;+ }+ return Err(error);+ }+ }+ }+ Ok(())+}+/// Stage media supplied with a queued follow-up, returning only opaque refs./// The manifest is bound to this dispatch tenant and thread, and remains/// separate from visible message history until the runner admits the turn.@@ -465,6 +551,8 @@ pub(crate) async fn discard_staged_parts(if let Some(id) = opaque_media(&entry.part).and_then(|media| media.opaque_id.as_deref()) {let manifest_path = staged_manifest_path(&config.workspace_dir, id)?;let _ = tokio::fs::remove_file(manifest_path).await;+ let claim_path = staged_manifest_path(&config.workspace_dir, id)?.with_extension("claim.json");+ let _ = tokio::fs::remove_file(claim_path).await;}}Ok(())@@ -477,6 +565,7 @@ pub(crate) async fn consume_staged_parts(ctx: &crate::core::runtime::DispatchCtx,thread_id: &str,requested: &[ContentPart],+ message_id: &str,) -> Result<(), String> {if requested.is_empty() {return Ok(());@@ -491,20 +580,39 @@ pub(crate) async fn consume_staged_parts(.and_then(|media| media.opaque_id.as_deref()).ok_or_else(|| "staged attachment reference is missing".to_string())?;let path = staged_manifest_path(&config.workspace_dir, id)?;- let bytes = tokio::fs::read(&path)- .await- .map_err(|_| "staged attachment is missing or expired".to_string())?;- let manifest: StagedAttachment = serde_json::from_slice(&bytes)- .map_err(|error| format!("staged attachment record is invalid: {error}"))?;- if manifest.tenant != tenant- || manifest.thread_id != thread_id- || manifest.attachment.part != *part+ let claim_path = path.with_extension("claim.json");+ let claim: StagedAttachmentClaim = serde_json::from_slice(+ &tokio::fs::read(&claim_path)+ .await+ .map_err(|_| "staged attachment is not bound to a persisted message".to_string())?,+ )+ .map_err(|error| format!("staged attachment claim is invalid: {error}"))?;+ if claim.tenant != tenant+ || claim.thread_id != thread_id+ || claim.message_id != message_id+ || claim.part != *part{- return Err("staged attachment belongs to a different scope".into());+ return Err("staged attachment is bound to a different message or scope".into());+ }+ match tokio::fs::read(&path).await {+ Ok(bytes) => {+ let manifest: StagedAttachment = serde_json::from_slice(&bytes)+ .map_err(|error| format!("staged attachment record is invalid: {error}"))?;+ if manifest.tenant != tenant+ || manifest.thread_id != thread_id+ || manifest.attachment.part != *part+ {+ return Err("staged attachment belongs to a different scope".into());+ }+ match tokio::fs::remove_file(path).await {+ Ok(()) => {}+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(format!("remove staged attachment record: {error}")),+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(format!("read staged attachment record: {error}")),}- tokio::fs::remove_file(path)- .await- .map_err(|error| format!("remove staged attachment record: {error}"))?;}Ok(())}diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rsindex fdca3f8a95..aeb6ad11cd 100644--- a/crates/openhuman-core/src/threads/ops/crud.rs+++ b/crates/openhuman-core/src/threads/ops/crud.rs@@ -307,6 +307,7 @@ async fn message_append_with_config(&request.thread_id,config,&typed_attachments,+ &request.message.id,&mut request.message.extra_metadata,).await@@ -479,7 +480,12 @@ async fn message_append_with_config(.await.map_err(|err| ThreadsError::from_thread_scoped_store_error(&request.thread_id, err))?;if let Some(staged_refs) = staged_refs {- crate::threads::attachments::consume_staged_parts(ctx, &request.thread_id, &staged_refs)+ crate::threads::attachments::consume_staged_parts(+ ctx,+ &request.thread_id,+ &staged_refs,+ &message.id,+ ).await.map_err(ThreadsError::Message)?;}