diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index 1fce2471d9..fafbc31e63 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -780,6 +780,39 @@ project installation remains unsupported; choose user scope to install on the serving host. Mobile/bot controls, CLI peers and Detached Dispatch do not gain a marketplace configuration or installation entry point. +## Files sent through WeChat + +Send an ordinary file or a native video in the paired WeChat chat to make it available to the +selected Agent session. OpenBitFun downloads and decrypts the file, saves it in +a unique `.openbitfun-inbound-` directory inside that session's workspace, +and supplies its path to the Agent. Existing files are not overwritten. File +contents stay out of the message text; the Agent can read the saved file using +its tools. Files remain available for later turns and can be removed manually +when no longer needed. On POSIX filesystems, directories use `0700` and files +use `0600` permissions. + +A message accepts up to five files totaling 30 MiB. Missing download information, +failed downloads, and unavailable workspaces produce an explicit error instead +of submitting an empty message. Complete pending menu selections or approvals +before sending a file. + +SSH workspaces use the session's remote filesystem and never fall back to the +host's local filesystem. Cross-device bot sessions negotiate `session_attachments_v1`, +transfer the bytes through encrypted device RPC, and use the path returned by the +execution host. Upgrade an older target host when prompted; file input is never +silently omitted. Accepted writes finish on the target even if the controller +disconnects. Retries with the same attachment identity reuse identical saved bytes +and reject changed or incomplete content. This input path does not submit +attachments to Detached Dispatch jobs. + +Messages from one WeChat peer finish attachment preparation and turn admission in +receive order. Model replies run independently, so approvals and follow-up input +remain available. Failed image downloads also reject the message with a visible +error instead of silently submitting empty or partial media input. Native videos +are delivered as unchanged `.mp4` files through the same local/remote path; +video analysis depends on the Agent's available tools. Voice messages without +transcripts currently return an unsupported notice. + ## WeChat session result notifications While the WeChat bot is running, completed turns in its currently selected local diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs index 5f617cf522..d696769869 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/command_router.rs @@ -3147,6 +3147,29 @@ pub(crate) async fn execute_forwarded_turn( verbose_mode: bool, runtime_fence: &super::BotRuntimeFence, identity_epoch: u64, +) -> ForwardedTurnResult { + execute_forwarded_turn_with_submission( + forward, + interaction_handler, + message_sender, + verbose_mode, + runtime_fence, + identity_epoch, + None, + ) + .await +} + +/// Notify an ingress queue after admission, without holding it for model output +/// or a user interaction. Dropping the sender also releases failed/cancelled input. +pub(crate) async fn execute_forwarded_turn_with_submission( + forward: ForwardRequest, + interaction_handler: Option, + message_sender: Option, + verbose_mode: bool, + runtime_fence: &super::BotRuntimeFence, + identity_epoch: u64, + submission_finished: Option>, ) -> ForwardedTurnResult { if !runtime_fence.is_lifecycle_current() || runtime_fence.identity_epoch() != identity_epoch { return ForwardedTurnResult { @@ -3156,8 +3179,14 @@ pub(crate) async fn execute_forwarded_turn( }; } if forward.remote_target.is_some() { - return execute_remote_forward(forward, interaction_handler, runtime_fence, identity_epoch) - .await; + return execute_remote_forward( + forward, + interaction_handler, + runtime_fence, + identity_epoch, + submission_finished, + ) + .await; } use crate::service::remote_connect::remote_server::{ get_or_init_global_dispatcher, TrackerEvent, @@ -3173,7 +3202,7 @@ pub(crate) async fn execute_forwarded_turn( let target_turn_id = forward.turn_id.clone(); - if let Err(e) = dispatcher + let submission = dispatcher .send_message( &forward.session_id, forward.content, @@ -3182,8 +3211,9 @@ pub(crate) async fn execute_forwarded_turn( RemoteConnectSubmissionSource::Bot, Some(forward.turn_id.clone()), ) - .await - { + .await; + drop(submission_finished); + if let Err(e) = submission { let msg = format!("{}{e}", s.send_failed_prefix); return ForwardedTurnResult { completed_remote_tools: Vec::new(), @@ -3375,6 +3405,7 @@ async fn execute_remote_forward( interaction_handler: Option, fence: &super::BotRuntimeFence, epoch: u64, + submission_finished: Option>, ) -> ForwardedTurnResult { use openbitfun_services_integrations::remote_connect::bot::remote_turn::observe_turn; let s = strings_for(current_bot_language().await); @@ -3396,6 +3427,7 @@ async fn execute_remote_forward( "image_contexts":forward.image_contexts, })) .await; + drop(submission_finished); if !current() { return empty(); } @@ -4439,15 +4471,22 @@ mod handle_chat_tests { turn_id: "turn".into(), image_contexts: vec![], }; - let result = execute_forwarded_turn( + let (submission_finished, admission) = tokio::sync::oneshot::channel(); + let result = execute_forwarded_turn_with_submission( forward, None, None, false, &fence, fence.identity_epoch() + 1, + Some(submission_finished), ) .await; + assert!( + tokio::time::timeout(std::time::Duration::from_secs(1), admission) + .await + .is_ok() + ); assert!(result.display_text.is_empty()); assert!(result.full_text.is_empty()); } @@ -4650,6 +4689,7 @@ mod handle_chat_tests { "send_message" => { assert_eq!(command["session_id"],"session-a"); assert_eq!(command["image_contexts"][0]["data_url"],"data:image/png;base64,AP8B"); + assert_eq!(command["content"].as_str().unwrap().contains("/remote/session-a/key.pem"), supports_interaction); // Legacy hosts may select their own accepted turn ID. serde_json::json!({"resp":"message_sent","session_id":"session-a","turn_id":"accepted-turn"}) } @@ -4672,8 +4712,17 @@ mod handle_chat_tests { } } "get_workspace_info" => serde_json::json!({"resp":"workspace_info", "capabilities": - if supports_interaction { vec!["user_question_interaction_v1"] } else { vec![] } + if supports_interaction { vec!["user_question_interaction_v1", "session_attachments_v1"] } else { vec![] } }), + "store_session_attachment" => { + assert!(supports_interaction); + assert_eq!(command["session_id"], "session-a"); + assert_eq!(command["attachment"]["content_base64"], "AP8B"); + assert!(uuid::Uuid::parse_str(command["attachment"]["attachment_id"].as_str().unwrap()).is_ok()); + serde_json::json!({"resp":"session_attachment_stored","session_id":"session-a", + "attachment":{"attachment_id":command["attachment"]["attachment_id"], + "name":"key.pem","path":"/remote/session-a/key.pem","size":3}}) + } "start_question_interaction" => { assert!(supports_interaction); assert_eq!(command["session_id"], "session-a"); @@ -4726,7 +4775,7 @@ mod handle_chat_tests { mime_type: "image/png".into(), metadata: None, }; - let forward = handle_chat( + let mut forward = handle_chat( &mut state, "render", vec![image], @@ -4738,6 +4787,23 @@ mod handle_chat_tests { let target = forward.remote_target.clone().unwrap(); state.select_local_device(); state.current_session_id = Some("unrelated-local-session".into()); + let capable = target.require_session_attachments().await; + if supports_interaction { + capable.unwrap(); + let path = target.store_attachment(&openbitfun_services_integrations::remote_connect::bot::inbound_files::InboundFile { + name: "key.pem".into(), bytes: vec![0, 255, 1], + }).await.unwrap(); + assert_eq!(path, "/remote/session-a/key.pem"); + forward.content.push_str(&path); + } else { + assert!(capable.unwrap_err().contains("upgrade")); + assert!(!calls + .lock() + .unwrap() + .iter() + .any(|call| call["cmd"] == "store_session_attachment")); + } + let handler: BotInteractionHandler = Arc::new(move |request| { Box::pin(async move { assert!(request.reply.contains("Device A")); @@ -4765,19 +4831,26 @@ mod handle_chat_tests { }) }); let fence = super::super::BotRuntimeFence::standalone(); - let result = tokio::time::timeout( - std::time::Duration::from_secs(20), - execute_forwarded_turn( - forward, - Some(handler), - None, - false, - &fence, - fence.identity_epoch(), - ), - ) - .await - .unwrap(); + let (submission_finished, admission) = tokio::sync::oneshot::channel(); + let execution = execute_forwarded_turn_with_submission( + forward, + Some(handler), + None, + false, + &fence, + fence.identity_epoch(), + Some(submission_finished), + ); + tokio::pin!(execution); + // Ingress is released after the encrypted submit ACK, while polling and + // interactive replies continue independently (including reconnection). + tokio::select! { + _ = admission => {}, + _ = &mut execution => panic!("Turn completed before releasing ingress"), + } + let result = tokio::time::timeout(std::time::Duration::from_secs(20), &mut execution) + .await + .unwrap(); assert_eq!(result.full_text, "![image](result.png)"); assert_eq!(result.completed_remote_tools.len(), 2); assert!(result diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs index 3a509aa514..a72f110baf 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs @@ -20,9 +20,9 @@ use std::time::Duration; use tokio::sync::{Mutex, Notify, RwLock}; use super::command_router::{ - complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command, - parse_command, welcome_message, BotChatState, BotInteractionHandler, BotInteractiveRequest, - BotMessageSender, HandleResult, + complete_im_bot_pairing, current_bot_language, execute_forwarded_turn_with_submission, + handle_command, parse_command, welcome_message, BotChatState, BotInteractionHandler, + BotInteractiveRequest, BotMessageSender, HandleResult, }; use super::{ load_bot_persistence, update_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, @@ -34,6 +34,17 @@ use openbitfun_agent_runtime::event_bus::EventSubscriberResult; const LONG_POLL_TIMEOUT_SECS: u64 = 36; +fn inbound_file_rejection( + state: &BotChatState, + strings: &'static super::locale::BotStrings, +) -> Option<&'static str> { + if state.pending_action.is_some() { + Some(strings.inbound_file_pending) + } else { + None + } +} + /// Maximum proactive messages held for one peer before they are merged into a /// single reply. Older entries are dropped so a peer that never comes back /// cannot grow the backlog without bound. @@ -744,10 +755,10 @@ impl WeixinBot { async fn inbound_image_attachments_from_message( &self, msg: &Value, - ) -> (Vec, usize) { + ) -> Result<(Vec, usize)> { const MAX_BYTES: usize = 1024 * 1024; - let (raw_images, skipped) = self.api.download_inbound_images(msg).await; + let (raw_images, skipped) = self.api.download_inbound_images(msg).await?; let mut attachments = Vec::with_capacity(raw_images.len()); for raw in raw_images { let data_url = if raw.bytes.len() <= MAX_BYTES { @@ -776,7 +787,7 @@ impl WeixinBot { data_url, }); } - (attachments, skipped) + Ok((attachments, skipped)) } async fn notify_files_ready( @@ -963,6 +974,13 @@ impl WeixinBot { "Please send the 6-digit pairing code from OpenBitFun Desktop Remote Connect." }; self.try_send_text(&peer, err, "pairing-prompt").await; + } else if weixin_provider::has_inbound_file_items(msg) { + self.try_send_text( + &peer, + super::locale::strings_for(language).need_pairing, + "pairing-file-hint", + ) + .await; } else if weixin_provider::has_inbound_image_items(msg) { let err = if language.is_chinese() { "\u{914d}\u{5bf9}\u{8bf7}\u{76f4}\u{63a5}\u{53d1}\u{9001} 6 \u{4f4d}\u{6570}\u{5b57}\u{914d}\u{5bf9}\u{7801}\u{ff1b}\u{5b8c}\u{6210}\u{914d}\u{5bf9}\u{540e}\u{518d}\u{53d1}\u{9001}\u{56fe}\u{7247}\u{4e0e}\u{52a9}\u{624b}\u{5bf9}\u{8bdd}\u{3002}" @@ -981,6 +999,10 @@ impl WeixinBot { self.subscribe_session_output(); self.spawn_outbound_worker(stop_rx.clone()); let mut stop = stop_rx; + // Bounded ingress keeps media downloads and turn admission FIFO per peer. + // Workers release each message after submission, before waiting for output. + let mut inbound_senders: HashMap> = + HashMap::new(); let mut buf = weixin_provider::load_sync_buf(&self.api.config().bot_account_id); let mut long_poll_timeout = Duration::from_secs(LONG_POLL_TIMEOUT_SECS); @@ -989,6 +1011,7 @@ impl WeixinBot { break; } + let poll_identity_epoch = self.runtime_fence.identity_epoch(); let poll = tokio::select! { _ = stop.changed() => break, result = self.api.get_updates_once( @@ -1043,56 +1066,210 @@ impl WeixinBot { if let Some(token) = weixin_provider::context_token(msg) { self.remember_context_token(&peer, token).await; } - let msg_value = msg.clone(); - let bot = self.clone(); - tokio::spawn(async move { - let (images, skipped_images) = - bot.inbound_image_attachments_from_message(&msg_value).await; - let language = current_bot_language().await; - if skipped_images > 0 { - let note = if language.is_chinese() { - format!( - "\u{4ec5}\u{4f1a}\u{5904}\u{7406}\u{524d} {} \u{5f20}\u{56fe}\u{7247}\u{ff0c}\u{5176}\u{4f59} {} \u{5f20}\u{5df2}\u{4e22}\u{5f03}\u{3002}", - MAX_INBOUND_IMAGES, skipped_images - ) - } else { - format!( - "Only the first {} images will be processed; the remaining {} were discarded.", - MAX_INBOUND_IMAGES, skipped_images - ) - }; - bot.try_send_text(&peer, ¬e, "image-truncation-notice") - .await; + inbound_senders.retain(|_, sender| !sender.is_closed()); + let sender = inbound_senders + .entry(peer.clone()) + .or_insert_with(|| self.spawn_inbound_peer(peer.clone(), stop.clone())); + tokio::select! { + _ = stop.changed() => break, + sent = sender.send((msg.clone(), poll_identity_epoch)) => { + if sent.is_err() { warn!("Weixin inbound worker stopped before message admission"); } } - let body = weixin_provider::body_from_message(&msg_value); - let text = if body.trim().is_empty() && !images.is_empty() { - if language.is_chinese() { - "[\u{7528}\u{6237}\u{53d1}\u{9001}\u{4e86}\u{4e00}\u{5f20}\u{56fe}\u{7247}]".to_string() - } else { - "[User sent an image]".to_string() - } - } else { - body - }; - bot.handle_incoming_message(peer, &text, images).await; - }); + } } } self.unsubscribe_session_output(); info!("Weixin message loop stopped"); } + fn spawn_inbound_peer( + self: &Arc, + peer: String, + mut stop: tokio::sync::watch::Receiver, + ) -> tokio::sync::mpsc::Sender<(Value, u64)> { + let (sender, mut receiver) = tokio::sync::mpsc::channel::<(Value, u64)>(32); + let bot = self.clone(); + tokio::spawn(async move { + loop { + let incoming = tokio::select! { + _ = stop.changed() => break, + incoming = receiver.recv() => incoming, + }; + let Some((message, identity_epoch)) = incoming else { + break; + }; + if *stop.borrow() || !bot.runtime_fence.is_lifecycle_current() { + break; + } + bot.process_provider_message(peer.clone(), message, identity_epoch) + .await; + } + }); + sender + } + + async fn process_provider_message( + self: &Arc, + peer: String, + message: Value, + identity_epoch: u64, + ) { + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != identity_epoch + { + return; + } + let language = current_bot_language().await; + if weixin_provider::has_unsupported_media_items(&message) { + self.try_send_text( + &peer, + super::locale::strings_for(language).inbound_media_unsupported, + "media-unsupported", + ) + .await; + return; + } + let downloaded = self.inbound_image_attachments_from_message(&message).await; + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != identity_epoch + { + return; + } + let (images, skipped_images) = match downloaded { + Ok(images) => images, + Err(error) => { + self.try_send_text( + &peer, + &format!( + "{}{error}", + super::locale::strings_for(language).inbound_image_failed_prefix + ), + "image-receive-failed", + ) + .await; + return; + } + }; + if skipped_images > 0 { + let note = if language.is_chinese() { + format!( + "\u{4ec5}\u{4f1a}\u{5904}\u{7406}\u{524d} {} \u{5f20}\u{56fe}\u{7247}\u{ff0c}\u{5176}\u{4f59} {} \u{5f20}\u{5df2}\u{4e22}\u{5f03}\u{3002}", + MAX_INBOUND_IMAGES, skipped_images + ) + } else { + format!( + "Only the first {} images will be processed; the remaining {} were discarded.", + MAX_INBOUND_IMAGES, skipped_images + ) + }; + self.try_send_text(&peer, ¬e, "image-truncation-notice") + .await; + } + let body = weixin_provider::body_from_message(&message); + let text = if body.trim().is_empty() && weixin_provider::has_inbound_file_items(&message) { + super::locale::strings_for(language) + .inbound_file_message + .to_string() + } else if body.trim().is_empty() && !images.is_empty() { + if language.is_chinese() { + "[\u{7528}\u{6237}\u{53d1}\u{9001}\u{4e86}\u{4e00}\u{5f20}\u{56fe}\u{7247}]" + .to_string() + } else { + "[User sent an image]".to_string() + } + } else { + body + }; + if text.trim().is_empty() { + self.try_send_text( + &peer, + super::locale::strings_for(language).inbound_media_unsupported, + "empty-message", + ) + .await; + return; + } + if self.runtime_fence.is_lifecycle_current() + && self.runtime_fence.identity_epoch() == identity_epoch + { + self.handle_incoming_message(peer, &text, images, &message, identity_epoch) + .await; + } + } + + async fn prepare_inbound_files( + &self, + forward: &mut super::command_router::ForwardRequest, + message: &Value, + identity_epoch: u64, + ) -> Result<()> { + use openbitfun_services_integrations::remote_connect::bot::inbound_files::{ + attachment_prompt, save_inbound_file, + }; + // Resolve against the immutable routed session, not current UI/workspace state. + let target = if let Some(remote) = &forward.remote_target { + remote + .require_session_attachments() + .await + .map_err(anyhow::Error::msg)?; + None + } else { + Some( + crate::service_agent_runtime::CoreServiceAgentRuntime::remote_file_target( + ".", + Some(&forward.session_id), + ) + .await + .map_err(anyhow::Error::msg)?, + ) + }; + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != identity_epoch + { + return Err(anyhow!("Bot identity changed before file download")); + } + let files = self.api.download_inbound_files(message).await?; + let mut content = forward.content.clone(); + for file in files { + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != identity_epoch + { + return Err(anyhow!("Bot identity changed during file download")); + } + let path = if let Some(remote) = &forward.remote_target { + remote + .store_attachment(&file) + .await + .map_err(anyhow::Error::msg)? + } else { + save_inbound_file( + target + .as_ref() + .ok_or_else(|| anyhow!("Attachment workspace is unavailable"))?, + &file, + ) + .await? + }; + content.push_str(&attachment_prompt(&file.name, &path, file.bytes.len())); + } + forward.content = content; + Ok(()) + } + async fn handle_incoming_message( self: &Arc, peer_id: String, text: &str, images: Vec, + message: &Value, + command_identity_epoch: u64, ) { - if !self.runtime_fence.is_lifecycle_current() { + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != command_identity_epoch + { return; } let mut states = self.chat_states.write().await; - let command_identity_epoch = self.runtime_fence.identity_epoch(); self.runtime_fence.reconcile_states(&mut states); let state = states.entry(peer_id.clone()).or_insert_with(|| { let mut state = BotChatState::new(peer_id.clone()); @@ -1147,8 +1324,22 @@ impl WeixinBot { if self.runtime_fence.identity_epoch() != command_identity_epoch { return; } + let has_files = weixin_provider::has_inbound_file_items(message); + let strings = super::locale::strings_for(language); + if has_files { + if let Some(reason) = inbound_file_rejection(state, strings) { + drop(states); + self.try_send_text(&peer_id, reason, "file-rejected").await; + return; + } + } let was_remote = state.account_remote_context || state.active_remote_device.is_some(); - let command = parse_command(text); + let command = if has_files { + // A caption is file input, never a menu selection or approval answer. + super::command_router::BotCommand::ChatMessage(text.to_owned()) + } else { + parse_command(text) + }; let mut result = handle_command(state, command, images).await; if !was_remote && (state.account_remote_context || state.active_remote_device.is_some()) { append_remote_push_notice(&mut result, language); @@ -1165,6 +1356,28 @@ impl WeixinBot { return; } + if has_files { + if let Some(forward) = result.forward_to_session.as_mut() { + let prepared = self + .prepare_inbound_files(forward, message, command_identity_epoch) + .await; + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != command_identity_epoch + { + return; + } + if let Err(error) = prepared { + warn!("Weixin inbound file preparation failed: {error}"); + self.try_send_text( + &peer_id, + &format!("{}{error}", strings.inbound_file_failed_prefix), + "file-receive-failed", + ) + .await; + return; + } + } + } self.send_handle_result(&peer_id, &result).await; if let Some(forward) = result.forward_to_session { @@ -1178,6 +1391,7 @@ impl WeixinBot { let peer = peer_id.clone(); let typing_token = self.context_tokens.read().await.get(&peer_id).cloned(); let typing_for_turn = self.api.start_typing(peer_id.clone(), typing_token); + let (submission_finished, admission) = tokio::sync::oneshot::channel(); tokio::spawn(async move { let interaction_bot = bot.clone(); let peer_c = peer.clone(); @@ -1210,13 +1424,14 @@ impl WeixinBot { }) }); let verbose_mode = load_bot_persistence().verbose_mode; - let turn_result = execute_forwarded_turn( + let turn_result = execute_forwarded_turn_with_submission( forward, Some(handler), Some(sender), verbose_mode, &bot.runtime_fence, output_identity_epoch, + Some(submission_finished), ) .await; if !bot.runtime_fence.is_lifecycle_current() @@ -1252,6 +1467,7 @@ impl WeixinBot { .await; typing_for_turn.stop().await; }); + let _ = admission.await; } } @@ -1323,6 +1539,28 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn inbound_files_preserve_pending_answers_on_local_and_remote_devices() { + use super::super::command_router::PendingAction; + use super::super::locale::{strings_for, BotLanguage}; + for language in [BotLanguage::ZhCN, BotLanguage::ZhTW, BotLanguage::EnUS] { + let strings = strings_for(language); + let mut state = BotChatState::new("peer".into()); + assert!(inbound_file_rejection(&state, strings).is_none()); + state.set_pending(PendingAction::SelectDevice { options: vec![] }); + assert_eq!( + inbound_file_rejection(&state, strings), + Some(strings.inbound_file_pending) + ); + assert!(state.pending_action.is_some()); + state.account_remote_context = true; + assert_eq!( + inbound_file_rejection(&state, strings), + Some(strings.inbound_file_pending) + ); + } + } + #[test] fn context_token_error_heuristic_uses_provider_contract() { let app_err = anyhow!( @@ -1636,6 +1874,92 @@ mod tests { (base, rx, task) } + #[tokio::test] + async fn unsupported_media_and_empty_input_never_route_partial_or_empty_turns() { + let (base, mut requests, server) = mock_outbound(vec!["{}"; 3], None).await; + let bot = test_bot(base).await; + bot.chat_states.write().await.clear(); + let epoch = bot.runtime_fence.identity_epoch(); + for message in [ + json!({"item_list":[{"type":3,"voice_item":{}},{"type":1,"text_item":{"text":"transcribe this voice"}}]}), + json!({"item_list":[{"type":3,"voice_item":{}}]}), + json!({"item_list":[{"type":1,"text_item":{"text":" "}}]}), + ] { + bot.process_provider_message("peer".into(), message, epoch) + .await; + let reply = requests.recv().await.unwrap(); + assert!(reply["msg"]["item_list"][0]["text_item"]["text"] + .as_str() + .unwrap() + .contains("Agent")); + assert!(bot.chat_states.read().await.is_empty()); + } + server.await.unwrap(); + assert!(!weixin_provider::has_unsupported_media_items( + &json!({"item_list":[{"type":3,"voice_item":{"text":"transcribed voice"}}]}) + )); + } + + #[tokio::test] + async fn inbound_peer_waits_for_media_failure_before_routing_next_message() { + let (release, gate) = tokio::sync::oneshot::channel(); + let (base, mut requests, server) = mock_outbound(vec!["{}", "{}"], Some(gate)).await; + let bot = test_bot(base).await; + bot.chat_states.write().await.clear(); + let (stop, stopped) = tokio::sync::watch::channel(false); + let sender = bot.spawn_inbound_peer("peer".into(), stopped); + let epoch = bot.runtime_fence.identity_epoch(); + sender + .send((json!({"item_list":[{"type":2}]}), epoch)) + .await + .unwrap(); + let first = tokio::time::timeout(Duration::from_secs(5), requests.recv()) + .await + .unwrap() + .unwrap(); + assert!(first["msg"]["item_list"][0]["text_item"]["text"] + .as_str() + .unwrap() + .contains("Agent")); + sender + .send(( + json!({"item_list":[{"type":1,"text_item":{"text":"hello"}}]}), + epoch, + )) + .await + .unwrap(); + // The failed media reply is still in flight. The subsequent text must + // not route/create state until that first input finishes. + assert!(tokio::time::timeout(Duration::from_millis(30), async { + loop { + if bot.chat_states.read().await.contains_key("peer") { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .is_err()); + release.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(5), requests.recv()) + .await + .unwrap() + .unwrap(); + assert!(bot.chat_states.read().await.contains_key("peer")); + bot.process_provider_message( + "stale-peer".into(), + json!({"item_list":[{"type":1,"text_item":{"text":"hello"}}]}), + epoch + 1, + ) + .await; + assert!(!bot.chat_states.read().await.contains_key("stale-peer")); + stop.send(true).unwrap(); + tokio::time::timeout(Duration::from_secs(5), sender.closed()) + .await + .unwrap(); + server.await.unwrap(); + } + #[tokio::test] async fn proactive_send_ack_preserves_new_output_when_queue_overflows() { let (release, gate) = tokio::sync::oneshot::channel(); diff --git a/src/crates/assembly/core/src/service_agent_runtime.rs b/src/crates/assembly/core/src/service_agent_runtime.rs index db66b67827..c4fa976b3c 100644 --- a/src/crates/assembly/core/src/service_agent_runtime.rs +++ b/src/crates/assembly/core/src/service_agent_runtime.rs @@ -3328,6 +3328,22 @@ impl RemoteDialogRuntimeHost for CoreRemoteDialogRuntimeHost<'_> { #[cfg(feature = "remote-connect")] #[async_trait::async_trait] impl RemoteWorkspaceFileRuntimeHost for CoreRemoteWorkspaceFileRuntimeHost { + async fn store_session_attachment( + &self, + session_id: &str, + attachment: openbitfun_runtime_ports::RemoteSessionAttachment, + ) -> Result { + let target = CoreServiceAgentRuntime::remote_file_target(".", Some(session_id)).await?; + let session_id = session_id.to_owned(); + // Once admitted, storage finishes on the execution host even if its + // controller disconnects. A retry with the same attachment id is safe. + tokio::spawn(async move { + openbitfun_services_integrations::remote_connect::bot::inbound_files::store_session_attachment( + &target, &session_id, attachment, + ).await.map_err(|error| error.to_string()) + }).await.map_err(|error| error.to_string())? + } + async fn resolve_remote_file_workspace_root( &self, session_id: Option<&str>, @@ -4131,6 +4147,15 @@ mod tests { assert!( matches!(result, Err(error) if error.contains("output session workspace is unavailable")) ); + let attachment = openbitfun_runtime_ports::RemoteSessionAttachment { + attachment_id: uuid::Uuid::new_v4().to_string(), + name: "fixture.pem".into(), + content_base64: "Zml4dHVyZQ==".into(), + }; + let stored = CoreRemoteWorkspaceFileRuntimeHost + .store_session_attachment(missing, attachment) + .await; + assert!(matches!(stored, Err(error) if error.contains("no current-workspace fallback"))); } #[tokio::test] diff --git a/src/crates/contracts/runtime-ports/src/remote_workspace_ports.rs b/src/crates/contracts/runtime-ports/src/remote_workspace_ports.rs index 67674bb7a4..1af65d056b 100644 --- a/src/crates/contracts/runtime-ports/src/remote_workspace_ports.rs +++ b/src/crates/contracts/runtime-ports/src/remote_workspace_ports.rs @@ -221,8 +221,43 @@ pub trait RemoteInitialSyncRuntimeHost: Send + Sync { } /// Old remote-connect host compatibility trait for remote file projection. +/// Versioned session attachment input. The execution host chooses its storage path. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteSessionAttachment { + pub attachment_id: String, + pub name: String, + pub content_base64: String, +} + +impl std::fmt::Debug for RemoteSessionAttachment { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RemoteSessionAttachment") + .field("attachment_id", &self.attachment_id) + .field("name", &self.name) + .field("encoded_bytes", &self.content_base64.len()) + .finish_non_exhaustive() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteStoredAttachment { + pub attachment_id: String, + pub name: String, + pub path: String, + pub size: u64, +} + #[async_trait::async_trait] pub trait RemoteWorkspaceFileRuntimeHost: Send + Sync { + /// New controllers negotiate session_attachments_v1 before invoking this. + async fn store_session_attachment( + &self, + _session_id: &str, + _attachment: RemoteSessionAttachment, + ) -> Result { + Err("Session attachments are unsupported on this execution host".into()) + } + async fn resolve_remote_file_workspace_root(&self, session_id: Option<&str>) -> Option; diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index 041b85928e..6dde0fa5b3 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -230,3 +230,14 @@ three serial-baseline / prefetched-cold / revalidated-warm samples. The baseline retains the previous serial chunk algorithm with the same filesystem provider; browser rendering and public-network variability are outside this measurement. Do not turn timing ratios into CI assertions. + +For WeChat inbound CDN files, attachment storage, and provider-neutral bot contracts: + +```bash +cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::bot:: +cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib session_attachment_contract_tests +``` + +The attachment fixtures exercise real local file IO and a simulated POSIX remote +filesystem, including offline rejection. They do not establish live WeChat, SSH, +Peer Device, or Detached Dispatch coverage. diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index 6c1db8aaf8..fa8c6d3e40 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -50,10 +50,11 @@ use openbitfun_runtime_ports::{ }; pub use openbitfun_runtime_ports::{ RemoteAssistantWorkspaceFacts, RemoteFileChunkRange, RemoteInitialSyncRuntimeHost, - RemoteProjectionPort, RemoteRecentWorkspaceFacts, RemoteSessionMetadata, - RemoteSessionWorkspaceIdentity, RemoteWorkspaceFacts, RemoteWorkspaceFileChunk, - RemoteWorkspaceFileContent, RemoteWorkspaceFileInfo, RemoteWorkspaceFileRuntimeHost, - RemoteWorkspaceKind, RemoteWorkspacePort, RemoteWorkspaceRuntimeHost, RemoteWorkspaceUpdate, + RemoteProjectionPort, RemoteRecentWorkspaceFacts, RemoteSessionAttachment, + RemoteSessionMetadata, RemoteSessionWorkspaceIdentity, RemoteStoredAttachment, + RemoteWorkspaceFacts, RemoteWorkspaceFileChunk, RemoteWorkspaceFileContent, + RemoteWorkspaceFileInfo, RemoteWorkspaceFileRuntimeHost, RemoteWorkspaceKind, + RemoteWorkspacePort, RemoteWorkspaceRuntimeHost, RemoteWorkspaceUpdate, }; use openbitfun_services_core::product_identity::hidden_data_directory; pub use page_upload::{ @@ -560,6 +561,7 @@ pub const REMOTE_CAPABILITY_DIALOG_STEER_V1: &str = "dialog_steer_v1"; pub const REMOTE_CAPABILITY_USER_QUESTION_INTERACTION_V1: &str = "user_question_interaction_v1"; pub const REMOTE_CAPABILITY_BACKGROUND_RESULT_DELIVERY_V1: &str = "background_result_delivery_v1"; pub const REMOTE_CAPABILITY_SESSION_ROLLBACK_V1: &str = "session_rollback_v1"; +pub const REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1: &str = "session_attachments_v1"; pub const REMOTE_CAPABILITY_PLAN_BUILD_V1: &str = "plan_build_v1"; pub use host_stream::REMOTE_CAPABILITY_HOST_STREAM_V1; @@ -570,6 +572,7 @@ fn remote_host_capabilities() -> Vec { REMOTE_CAPABILITY_DIALOG_STEER_V1.to_string(), "dialog_queue_v1".to_string(), REMOTE_CAPABILITY_PLAN_BUILD_V1.to_string(), + REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1.to_string(), REMOTE_CAPABILITY_SESSION_ROLLBACK_V1.to_string(), REMOTE_CAPABILITY_USER_QUESTION_INTERACTION_V1.to_string(), REMOTE_CAPABILITY_BACKGROUND_RESULT_DELIVERY_V1.to_string(), @@ -851,6 +854,21 @@ where H: RemoteWorkspaceFileRuntimeHost + ?Sized, { match command { + RemoteCommand::StoreSessionAttachment { + session_id, + attachment, + } => { + match host + .store_session_attachment(session_id, attachment.clone()) + .await + { + Ok(stored) => RemoteResponse::SessionAttachmentStored { + session_id: session_id.clone(), + attachment: stored, + }, + Err(message) => RemoteResponse::Error { message }, + } + } RemoteCommand::ReadFile { path, session_id } => { match host .read_remote_file(path, session_id.as_deref(), REMOTE_FILE_MAX_READ_BYTES) @@ -2808,6 +2826,10 @@ pub enum RemoteCommand { known_msg_count: usize, known_model_catalog_version: Option, }, + StoreSessionAttachment { + session_id: String, + attachment: RemoteSessionAttachment, + }, ReadFile { path: String, session_id: Option, @@ -3077,6 +3099,10 @@ pub enum RemoteResponse { PermissionMode { mode: RemotePermissionMode, }, + SessionAttachmentStored { + session_id: String, + attachment: RemoteStoredAttachment, + }, FileContent { name: String, content_base64: String, @@ -3234,7 +3260,8 @@ where RemoteCommand::PollSession { .. } => host.handle_poll_command(command).await, - RemoteCommand::ReadFile { .. } + RemoteCommand::StoreSessionAttachment { .. } + | RemoteCommand::ReadFile { .. } | RemoteCommand::ReadFileChunk { .. } | RemoteCommand::GetFileInfo { .. } => host.handle_workspace_file_command(command).await, @@ -5787,3 +5814,38 @@ mod tests { assert!(tracker.is_history_snapshot_required()); } } + +#[cfg(test)] +mod session_attachment_contract_tests { + use super::*; + struct LegacyFileHost; + #[async_trait::async_trait] + impl RemoteWorkspaceFileRuntimeHost for LegacyFileHost { + async fn resolve_remote_file_workspace_root( + &self, + _: Option<&str>, + ) -> Option { + None + } + } + #[tokio::test] + async fn attachment_wire_roundtrip_and_unsupported_host_are_explicit() { + let wire = serde_json::json!({"cmd":"store_session_attachment","session_id":"session", + "attachment":{"attachment_id":"id","name":"key.pem","content_base64":"c2VjcmV0"}}); + let command: RemoteCommand = serde_json::from_value(wire.clone()).unwrap(); + assert_eq!(serde_json::to_value(&command).unwrap(), wire); + assert!(!format!("{command:?}").contains("c2VjcmV0")); + let result = handle_remote_workspace_file_command(&LegacyFileHost, &command).await; + assert!(matches!(result, RemoteResponse::Error { .. })); + assert!(remote_host_capabilities() + .iter() + .any(|capability| capability == REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1)); + let legacy: RemoteCommand = serde_json::from_value( + serde_json::json!({"cmd":"send_message","session_id":"session","content":"hello"}), + ) + .unwrap(); + let roundtrip: RemoteCommand = + serde_json::from_value(serde_json::to_value(&legacy).unwrap()).unwrap(); + assert_eq!(legacy, roundtrip); + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/inbound_files.rs b/src/crates/services/services-integrations/src/remote_connect/bot/inbound_files.rs new file mode 100644 index 0000000000..93295e3f03 --- /dev/null +++ b/src/crates/services/services-integrations/src/remote_connect/bot/inbound_files.rs @@ -0,0 +1,504 @@ +//! Incoming attachments are written through the session-selected filesystem. +use crate::remote_connect::file_projection::SessionFileTarget; +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::STANDARD as B64, Engine}; +use openbitfun_runtime_ports::WorkspacePathKind; +use openbitfun_runtime_ports::{RemoteSessionAttachment, RemoteStoredAttachment}; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; + +pub const MAX_SESSION_ATTACHMENT_BYTES: usize = 30 * 1024 * 1024; +// Serializes duplicate RPC retries through validation, write and publication. +static SAVE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +pub async fn store_session_attachment( + target: &SessionFileTarget, + session_id: &str, + attachment: RemoteSessionAttachment, +) -> Result { + if session_id.is_empty() || uuid::Uuid::parse_str(&attachment.attachment_id).is_err() { + bail!("Invalid session attachment identity"); + } + if attachment.name.len() > 1024 + || attachment.content_base64.len() > MAX_SESSION_ATTACHMENT_BYTES.div_ceil(3) * 4 + { + bail!("Session attachment exceeds the transfer limit"); + } + let bytes = B64 + .decode(&attachment.content_base64) + .context("Invalid attachment base64")?; + if bytes.len() > MAX_SESSION_ATTACHMENT_BYTES { + bail!("Session attachment exceeds the transfer limit"); + } + let storage_id = format!( + "{:x}", + Sha256::digest(format!("{session_id}:{}", attachment.attachment_id)) + ); + let file = InboundFile { + name: attachment.name, + bytes, + }; + let path = save_with_id(target, &file, &storage_id, true).await?; + Ok(RemoteStoredAttachment { + attachment_id: attachment.attachment_id, + name: safe_filename(&file.name), + path, + size: file.bytes.len() as u64, + }) +} + +#[derive(Debug)] +pub struct InboundFile { + pub name: String, + pub bytes: Vec, +} + +fn safe_filename(name: &str) -> String { + let name = name.rsplit(['/', '\\']).next().unwrap_or_default(); + let name: String = name + .chars() + .take(120) + .map(|ch| { + if ch.is_control() || "<>:\"|?*".contains(ch) { + '_' + } else { + ch + } + }) + .collect(); + let mut end = name.len().min(180); + while !name.is_char_boundary(end) { + end -= 1; + } + let name = &name[..end]; + let name = name.trim_matches([' ', '.']); + if name.is_empty() { + return "file.bin".into(); + } + // Prefix avoids Windows reserved device names, including names with extensions. + let stem = name + .split('.') + .next() + .unwrap_or_default() + .to_ascii_uppercase(); + if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || (stem.len() == 4 + && (stem.starts_with("COM") || stem.starts_with("LPT")) + && stem.as_bytes()[3].is_ascii_digit()) + { + format!("file-{name}") + } else { + name.to_owned() + } +} + +/// Each attachment gets a private, unique directory. The supplied name cannot +/// select a path or overwrite a workspace file. Return only after the stream is +/// closed, so an Agent never receives a path to a partial download. +pub async fn save_inbound_file(target: &SessionFileTarget, file: &InboundFile) -> Result { + save_with_id(target, file, &uuid::Uuid::new_v4().to_string(), false).await +} + +async fn save_with_id( + target: &SessionFileTarget, + file: &InboundFile, + storage_id: &str, + replay: bool, +) -> Result { + let _guard = SAVE_LOCK.lock().await; + + let root = if target.remote { + if !target.root.starts_with('/') || target.root.split('/').any(|p| p == ".." || p == ".") { + bail!("Remote attachment workspace must be an absolute POSIX path"); + } + let mut ancestor = String::new(); + for part in target.root.split('/').filter(|part| !part.is_empty()) { + ancestor.push('/'); + ancestor.push_str(part); + if target.fs.path_kind_no_follow(&ancestor).await? != Some(WorkspacePathKind::Directory) + { + bail!("Remote attachment workspace is unavailable or traverses a symbolic link"); + } + } + target.root.clone() + } else { + tokio::fs::canonicalize(&target.root) + .await + .context("Attachment workspace is unavailable")? + .to_string_lossy() + .into_owned() + }; + let directory = target + .fs + .join_path(&root, &[&format!(".openbitfun-inbound-{storage_id}")]); + let path = target + .fs + .join_path(&directory, &[&safe_filename(&file.name)]); + if let Some(kind) = target.fs.path_kind_no_follow(&directory).await? { + if replay + && kind == WorkspacePathKind::Directory + && target.fs.path_kind_no_follow(&path).await? == Some(WorkspacePathKind::File) + && target + .fs + .read_file_bounded(&path, file.bytes.len()) + .await? + .as_deref() + == Some(file.bytes.as_slice()) + { + return Ok(path); + } + bail!("Attachment identity already exists with different or incomplete content; resend as a new attachment"); + } + target.fs.create_dir_all(&directory).await?; + let mut file_created = false; + let saved = async { + if target.fs.path_kind_no_follow(&directory).await? != Some(WorkspacePathKind::Directory) { + bail!("Attachment directory is not a regular directory"); + } + if target.remote || cfg!(unix) { + target.fs.set_permissions(&directory, 0o700).await?; + } + let mut writer = target.fs.open_write_new(&path).await?; + file_created = true; + if target.remote || cfg!(unix) { + target.fs.set_permissions(&path, 0o600).await?; + } + writer.write_all(&file.bytes).await?; + writer.shutdown().await?; + Ok::<_, anyhow::Error>(path.clone()) + } + .await; + if saved.is_err() { + // Only clean up this newly created attachment, never existing user data. + if file_created { + let _ = target.fs.remove_file(&path).await; + } + let _ = target.fs.remove_dir(&directory, false).await; + } + saved +} + +pub fn attachment_prompt(name: &str, path: &str, size: usize) -> String { + format!( + "\n\n[User attached a file]\n{}", + serde_json::json!({ + "name": name, "path": path, "size_bytes": size, + }) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use openbitfun_runtime_ports::{WorkspaceDirEntry, WorkspaceFileSystem, WorkspaceWriter}; + use std::{ + path::PathBuf, + sync::{Arc, Mutex}, + }; + + struct TestFs { + root: PathBuf, + remote: bool, + offline: bool, + writes: Mutex>, + } + impl TestFs { + fn local(&self, path: &str) -> PathBuf { + if self.remote { + assert!(path == "/remote" || path.starts_with("/remote/")); + self.root.join( + path.strip_prefix("/remote") + .unwrap() + .trim_start_matches('/'), + ) + } else { + PathBuf::from(path) + } + } + } + #[async_trait::async_trait] + impl WorkspaceFileSystem for TestFs { + fn join_path(&self, root: &str, components: &[&str]) -> String { + if self.remote { + format!("{}/{}", root.trim_end_matches('/'), components.join("/")) + } else { + let mut p = PathBuf::from(root); + p.extend(components); + p.to_string_lossy().into() + } + } + async fn path_kind_no_follow(&self, path: &str) -> Result> { + if self.offline { + bail!("offline"); + } + match tokio::fs::symlink_metadata(self.local(path)).await { + Ok(m) => Ok(Some(if m.is_symlink() { + WorkspacePathKind::Symlink + } else if m.is_dir() { + WorkspacePathKind::Directory + } else { + WorkspacePathKind::File + })), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } + } + async fn create_dir_all(&self, path: &str) -> Result<()> { + Ok(tokio::fs::create_dir_all(self.local(path)).await?) + } + async fn open_write_new(&self, path: &str) -> Result { + self.writes.lock().unwrap().push(path.into()); + Ok(Box::new( + tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(self.local(path)) + .await?, + )) + } + async fn set_permissions(&self, path: &str, mode: u32) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + tokio::fs::set_permissions(self.local(path), std::fs::Permissions::from_mode(mode)) + .await?; + } + #[cfg(not(unix))] + let _ = (path, mode); + Ok(()) + } + async fn read_file(&self, path: &str) -> Result> { + Ok(tokio::fs::read(self.local(path)).await?) + } + async fn read_file_text(&self, _: &str) -> Result { + bail!("unused") + } + async fn write_file(&self, _: &str, _: &[u8]) -> Result<()> { + bail!("unused") + } + async fn exists(&self, _: &str) -> Result { + bail!("unused") + } + async fn is_file(&self, _: &str) -> Result { + bail!("unused") + } + async fn is_dir(&self, _: &str) -> Result { + bail!("unused") + } + async fn read_dir(&self, _: &str) -> Result> { + bail!("unused") + } + } + #[tokio::test] + async fn inbound_files_are_private_unique_and_stay_on_the_selected_filesystem() { + for remote in [false, true] { + let directory = tempfile::tempdir().unwrap(); + let fs = Arc::new(TestFs { + root: directory.path().into(), + remote, + offline: false, + writes: Mutex::new(vec![]), + }); + let root = if remote { + "/remote".into() + } else { + directory.path().to_string_lossy().into_owned() + }; + let target = SessionFileTarget { + fs: fs.clone(), + root, + path: String::new(), + remote, + }; + let file = InboundFile { + name: r"../../C:\keys\KeyPair.pem".into(), + bytes: b"fixture\0\xff".to_vec(), + }; + let first = save_inbound_file(&target, &file).await.unwrap(); + let second = save_inbound_file(&target, &file).await.unwrap(); + assert_ne!(first, second); + assert!(first.ends_with("KeyPair.pem")); + assert_eq!(fs.read_file(&first).await.unwrap(), file.bytes); + assert_eq!(*fs.writes.lock().unwrap(), vec![first.clone(), second]); + if remote { + assert!(first.starts_with("/remote/.openbitfun-inbound-")); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(fs.local(&first)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + assert_eq!( + std::fs::metadata(fs.local(&first).parent().unwrap()) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o700 + ); + } + let prompt = attachment_prompt(&file.name, &first, file.bytes.len()); + let data: serde_json::Value = + serde_json::from_str(prompt.lines().last().unwrap()).unwrap(); + assert_eq!(data["path"], first); + assert_eq!(data["name"], file.name); + } + } + #[tokio::test] + async fn offline_remote_has_no_local_fallback() { + let directory = tempfile::tempdir().unwrap(); + let fs = Arc::new(TestFs { + root: directory.path().into(), + remote: true, + offline: true, + writes: Mutex::new(vec![]), + }); + let target = SessionFileTarget { + fs: fs.clone(), + root: "/remote".into(), + path: String::new(), + remote: true, + }; + assert!(save_inbound_file( + &target, + &InboundFile { + name: "key.pem".into(), + bytes: vec![42] + } + ) + .await + .is_err()); + assert!(fs.writes.lock().unwrap().is_empty()); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0); + } + #[cfg(unix)] + #[tokio::test] + async fn remote_workspace_symlink_is_rejected_before_writing() { + let directory = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(outside.path(), directory.path().join("link")).unwrap(); + let fs = Arc::new(TestFs { + root: directory.path().into(), + remote: true, + offline: false, + writes: Mutex::new(vec![]), + }); + let target = SessionFileTarget { + fs: fs.clone(), + root: "/remote/link".into(), + path: String::new(), + remote: true, + }; + assert!(save_inbound_file( + &target, + &InboundFile { + name: "key.pem".into(), + bytes: vec![42] + } + ) + .await + .is_err()); + assert!(fs.writes.lock().unwrap().is_empty()); + assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0); + } + + #[test] + fn filenames_cannot_escape_or_select_device_paths() { + for (name, expected) in [ + ("..", "file.bin"), + ("../../key.pem", "key.pem"), + (r"C:\keys\key.pem", "key.pem"), + ("CON.txt", "file-CON.txt"), + ("a\n:b.pem", "a__b.pem"), + ] { + assert_eq!(safe_filename(name), expected); + } + assert!(safe_filename(&"文".repeat(200)).len() <= 180); + } + + #[tokio::test] + async fn session_attachment_retries_are_idempotent_scoped_and_conflict_safe() { + let directory = tempfile::tempdir().unwrap(); + let fs = Arc::new(TestFs { + root: directory.path().into(), + remote: true, + offline: false, + writes: Mutex::new(vec![]), + }); + let target = SessionFileTarget { + fs: fs.clone(), + root: "/remote".into(), + path: String::new(), + remote: true, + }; + let request = RemoteSessionAttachment { + attachment_id: uuid::Uuid::new_v4().to_string(), + name: "key.pem".into(), + content_base64: B64.encode(b"fixture"), + }; + let (first, repeated) = tokio::join!( + store_session_attachment(&target, "session-a", request.clone()), + store_session_attachment(&target, "session-a", request.clone()), + ); + let first = first.unwrap(); + assert_eq!(first, repeated.unwrap()); + assert_eq!(fs.writes.lock().unwrap().len(), 1); + let other_session = store_session_attachment(&target, "session-b", request.clone()) + .await + .unwrap(); + assert_ne!(first.path, other_session.path); + let mut conflict = request.clone(); + conflict.content_base64 = B64.encode(b"changed"); + assert!(store_session_attachment(&target, "session-a", conflict) + .await + .is_err()); + assert_eq!(fs.read_file(&first.path).await.unwrap(), b"fixture"); + // A lost ACK can be retried after restart: no in-memory receipt is needed. + assert_eq!( + store_session_attachment(&target, "session-a", request) + .await + .unwrap(), + first + ); + } + + #[tokio::test] + async fn invalid_attachment_wire_payload_never_writes() { + let directory = tempfile::tempdir().unwrap(); + let fs = Arc::new(TestFs { + root: directory.path().into(), + remote: true, + offline: false, + writes: Mutex::new(vec![]), + }); + let target = SessionFileTarget { + fs: fs.clone(), + root: "/remote".into(), + path: String::new(), + remote: true, + }; + for (id, encoded) in [ + ("../escape".into(), B64.encode(b"fixture")), + (uuid::Uuid::new_v4().to_string(), "invalid-base64".into()), + ] { + assert!(store_session_attachment( + &target, + "session", + RemoteSessionAttachment { + attachment_id: id, + name: "key.pem".into(), + content_base64: encoded + } + ) + .await + .is_err()); + } + assert!(fs.writes.lock().unwrap().is_empty()); + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/locale.rs b/src/crates/services/services-integrations/src/remote_connect/bot/locale.rs index 906d266581..06f9c34682 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/locale.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/locale.rs @@ -175,6 +175,11 @@ pub struct BotStrings { pub auto_push_skip_too_large_fmt: &'static str, pub auto_push_failed_fmt: &'static str, pub weixin_remote_push_unsupported: &'static str, + pub inbound_media_unsupported: &'static str, + pub inbound_image_failed_prefix: &'static str, + pub inbound_file_failed_prefix: &'static str, + pub inbound_file_message: &'static str, + pub inbound_file_pending: &'static str, // ── Multi-device control ───────────────────────────────────── pub devices_title: &'static str, @@ -338,6 +343,11 @@ const STRINGS_ZH: BotStrings = BotStrings { auto_push_skip_too_large_fmt: "已跳过「{name}」:{size} 超过 {limit} 上限,请改用桌面端获取。", auto_push_failed_fmt: "发送「{name}」失败:{err}", weixin_remote_push_unsupported: "微信暂不支持主动推送其他设备上的定时任务或桌面会话结果。你从微信发起的请求仍会正常回复。", + inbound_media_unsupported: "此消息含有暂不支持的附件或内容为空,尚未发送给 Agent。请发送文字、图片、视频或普通文件。", + inbound_image_failed_prefix: "图片接收失败,此消息尚未发送给 Agent:", + inbound_file_failed_prefix: "文件接收失败,尚未发送给 Agent:", + inbound_file_message: "[用户发送了文件]", + inbound_file_pending: "请先完成当前的选择或确认,再重新发送文件。文件尚未发送给 Agent。", devices_title: "多设备控制", devices_account_required: "所连接的桌面端尚未使用 GitHub 登录,无法使用多设备控制。请在桌面端的账号登录对话框中登录,机器人会自动继承账号身份。", @@ -500,6 +510,11 @@ const STRINGS_ZH_TW: BotStrings = BotStrings { auto_push_skip_too_large_fmt: "已跳過「{name}」:{size} 超過 {limit} 上限,請改用桌面端獲取。", auto_push_failed_fmt: "發送「{name}」失敗:{err}", weixin_remote_push_unsupported: "微信暫不支援主動推送其他裝置上的排程任務或桌面會話結果。你從微信發起的請求仍會正常回覆。", + inbound_media_unsupported: "此訊息含有暫不支援的附件或內容為空,尚未傳送給 Agent。請傳送文字、圖片、影片或一般檔案。", + inbound_image_failed_prefix: "圖片接收失敗,此訊息尚未傳送給 Agent:", + inbound_file_failed_prefix: "檔案接收失敗,尚未傳送給 Agent:", + inbound_file_message: "[使用者傳送了檔案]", + inbound_file_pending: "請先完成目前的選擇或確認,再重新傳送檔案。檔案尚未傳送給 Agent。", devices_title: "多裝置控制", devices_account_required: "所連接的桌面端尚未使用 GitHub 登入,無法使用多裝置控制。請在桌面端的帳號登入對話框中登入,機器人會自動繼承帳號身份。", @@ -663,6 +678,11 @@ Open Remote Connect in OpenBitFun Desktop and send the 6-digit pairing code here auto_push_skip_too_large_fmt: "Skipping \"{name}\": {size} exceeds the {limit} limit. Please grab it from OpenBitFun Desktop instead.", auto_push_failed_fmt: "Failed to send \"{name}\": {err}", weixin_remote_push_unsupported: "WeChat cannot proactively push scheduled-job or desktop-session results from another device yet. Requests you send from WeChat still receive replies.", + inbound_media_unsupported: "This message contains unsupported media or no usable content and was not sent to the Agent. Send text, images, videos, or ordinary files.", + inbound_image_failed_prefix: "Image could not be received; this message was not sent to the Agent: ", + inbound_file_failed_prefix: "File could not be received and was not sent to the Agent: ", + inbound_file_message: "[User sent a file]", + inbound_file_pending: "Complete the pending selection or confirmation, then resend the file. It has not been sent to the Agent.", devices_title: "Multi-device Control", devices_account_required: "The paired desktop is not logged into a GitHub account, so multi-device control is unavailable. Log in via the desktop's Account Login dialog and the bot will inherit the account identity.", diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs b/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs index 0f8ec22804..debd10bcf4 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/mod.rs @@ -5,6 +5,7 @@ mod command; pub mod feishu; +pub mod inbound_files; mod locale; mod menu; mod ownership; diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs b/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs index 883fe360ba..483dce7bc1 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/remote_turn.rs @@ -6,6 +6,46 @@ use base64::{engine::general_purpose::STANDARD, Engine}; use serde_json::{json, Value}; impl RemoteBotTarget { + pub async fn require_session_attachments(&self) -> Result<(), String> { + let info = self.rpc(json!({"cmd":"get_workspace_info"})).await?; + if !info["capabilities"].as_array().is_some_and(|capabilities| { + capabilities.iter().any(|value| { + value.as_str() + == Some(crate::remote_connect::REMOTE_CAPABILITY_SESSION_ATTACHMENTS_V1) + }) + }) { + return Err("Execution host does not support session attachments; upgrade OpenBitFun on that device".into()); + } + Ok(()) + } + + /// File bytes travel in the existing authenticated, encrypted bulk RPC lane. + /// 30 MiB becomes under 54 MiB after both base64 envelopes (64 MiB limit). + pub async fn store_attachment( + &self, + file: &super::inbound_files::InboundFile, + ) -> Result { + if file.bytes.len() > super::inbound_files::MAX_SESSION_ATTACHMENT_BYTES { + return Err("Session attachment exceeds the transfer limit".into()); + } + let attachment_id = uuid::Uuid::new_v4().to_string(); + let reply = self.rpc(json!({"cmd":"store_session_attachment", "session_id": self.session_id, + "attachment": {"attachment_id":attachment_id,"name":file.name,"content_base64": STANDARD.encode(&file.bytes)} + })).await?; + if reply["resp"] != "session_attachment_stored" + || reply["session_id"] != self.session_id + || reply["attachment"]["attachment_id"] != attachment_id + || reply["attachment"]["size"].as_u64() != Some(file.bytes.len() as u64) + { + return Err("Execution host did not acknowledge the complete attachment".into()); + } + reply["attachment"]["path"] + .as_str() + .filter(|path| !path.is_empty()) + .map(str::to_owned) + .ok_or_else(|| "Execution host omitted the attachment path".into()) + } + async fn rpc_response(&self, command: Value) -> Result { let reply = AccountClient::new() .device_rpc( diff --git a/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs b/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs index 2bf64cdb56..ca4ee572e7 100644 --- a/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs +++ b/src/crates/services/services-integrations/src/remote_connect/bot/weixin.rs @@ -41,6 +41,7 @@ const DEFAULT_CDN_BASE_URL: &str = "https://novac2c.cdn.weixin.qq.com/c2c"; pub const MAX_WEIXIN_FILE_BYTES: u64 = 30 * 1024 * 1024; const CDN_UPLOAD_MAX_RETRIES: u32 = 3; pub const MAX_INBOUND_IMAGES: usize = 5; +pub const MAX_INBOUND_FILES: usize = 5; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WeixinConfig { @@ -634,41 +635,110 @@ impl WeixinProviderClient { .await } - pub async fn download_inbound_images(&self, msg: &Value) -> (Vec, usize) { - let Some(items) = msg["item_list"].as_array() else { - return (vec![], 0); - }; - let total_with_param = items - .iter() - .filter(|item| { - item["type"].as_i64() == Some(2) - && item["image_item"]["media"]["encrypt_query_param"] - .as_str() - .is_some_and(|s| !s.is_empty()) - }) - .count(); - let skipped = total_with_param.saturating_sub(MAX_INBOUND_IMAGES); - + pub async fn download_inbound_images( + &self, + msg: &Value, + ) -> Result<(Vec, usize)> { + let items: Vec<_> = msg["item_list"] + .as_array() + .into_iter() + .flatten() + .filter(|item| item["type"].as_i64() == Some(2)) + .collect(); + let skipped = items.len().saturating_sub(MAX_INBOUND_IMAGES); let mut images = Vec::new(); + for item in items.into_iter().take(MAX_INBOUND_IMAGES) { + // Missing or failed media must not silently become empty/partial input. + let bytes = self.inbound_image_bytes_from_item(item).await?; + images.push(WeixinIncomingImage { + name: format!("weixin_image_{}.jpg", images.len() + 1), + mime_type: sniff_image_mime(&bytes), + bytes, + }); + } + Ok((images, skipped)) + } + + /// Files and native videos use the same CDN encryption as images. Deliver + /// their original bytes as session files; model-specific decoding is separate. + pub async fn download_inbound_files( + &self, + msg: &Value, + ) -> Result> { + let items: Vec<_> = msg["item_list"] + .as_array() + .into_iter() + .flatten() + .filter(|item| matches!(item["type"].as_i64(), Some(4 | 5))) + .collect(); + if items.len() > MAX_INBOUND_FILES { + return Err(anyhow!( + "At most {MAX_INBOUND_FILES} files can be received per message" + )); + } + let mut files = Vec::new(); + let mut remaining = MAX_WEIXIN_FILE_BYTES as usize; for item in items { - if images.len() >= MAX_INBOUND_IMAGES { - break; + let is_video = item["type"].as_i64() == Some(5); + let file = &item[if is_video { "video_item" } else { "file_item" }]; + // The official protocol's file len is plaintext; video_size is + // ciphertext (including AES padding), so never compare it to plaintext. + let declared_size = file["len"] + .as_str() + .and_then(|v| v.parse::().ok()) + .or_else(|| file["len"].as_u64()); + if declared_size.is_some_and(|size| size > remaining as u64) { + return Err(anyhow!("Inbound files exceed the 30 MiB message limit")); } - if item["type"].as_i64() != Some(2) { - continue; + let declared_cipher_size = if is_video { + file["video_size"].as_u64() + } else { + None + }; + if declared_cipher_size + .is_some_and(|size| size > aes_ecb_ciphertext_len(remaining) as u64) + { + return Err(anyhow!("Inbound files exceed the 30 MiB message limit")); } - match self.inbound_image_bytes_from_item(item).await { - Ok(bytes) => { - images.push(WeixinIncomingImage { - name: format!("weixin_image_{}.jpg", images.len() + 1), - mime_type: sniff_image_mime(&bytes), - bytes, - }); - } - Err(err) => warn!("Weixin inbound image download failed: {err}"), + let media = &file["media"]; + let param = media["encrypt_query_param"].as_str().unwrap_or_default(); + let full_url = media["full_url"] + .as_str() + .filter(|url| !url.trim().is_empty()); + if param.is_empty() && full_url.is_none() { + return Err(anyhow!("File download reference is missing")); } + let key = parse_weixin_cdn_aes_key( + media["aes_key"] + .as_str() + .ok_or_else(|| anyhow!("File decryption key is missing"))?, + ) + .map_err(|_| anyhow!("Invalid file decryption key"))?; + let encrypted = self + .fetch_weixin_cdn_bytes(param, full_url, remaining) + .await?; + if declared_cipher_size.is_some_and(|size| size != encrypted.len() as u64) { + return Err(anyhow!("Downloaded video size does not match the message")); + } + let bytes = decrypt_aes_128_ecb_pkcs7(&encrypted, &key) + .map_err(|_| anyhow!("File decryption failed"))?; + if bytes.len() > remaining { + return Err(anyhow!("Inbound files exceed the 30 MiB message limit")); + } + if declared_size.is_some_and(|size| size != bytes.len() as u64) { + return Err(anyhow!("Downloaded file size does not match the message")); + } + remaining -= bytes.len(); + files.push(super::inbound_files::InboundFile { + name: if is_video { + format!("weixin_video_{}.mp4", files.len() + 1) + } else { + file["file_name"].as_str().unwrap_or("file.bin").to_owned() + }, + bytes, + }); } - (images, skipped) + Ok(files) } async fn send_message_with_items( @@ -703,29 +773,52 @@ impl WeixinProviderClient { &self, encrypted_query_param: &str, full_url: Option<&str>, + max_plain_bytes: usize, ) -> Result> { let url = match full_url.map(str::trim).filter(|s| !s.is_empty()) { Some(url) => url.to_string(), - None => build_cdn_download_url(DEFAULT_CDN_BASE_URL, encrypted_query_param), + None if !encrypted_query_param.is_empty() => { + build_cdn_download_url(DEFAULT_CDN_BASE_URL, encrypted_query_param) + } + None => return Err(anyhow!("Media download reference is missing")), }; - let client = crate::reqwest_client_builder() + // Signed URLs, response bodies, and encryption keys stay out of errors/logs. + let mut response = crate::reqwest_client_builder() .timeout(Duration::from_secs(120)) - .build()?; - let resp = client.get(&url).send().await?; - let status = resp.status(); - if !status.is_success() { - let body = resp.text().await.unwrap_or_default(); - return Err(anyhow!("weixin CDN GET {status}: {body}")); + .build()? + .get(url) + .send() + .await + .map_err(|_| anyhow!("Media download request failed"))?; + if !response.status().is_success() { + return Err(anyhow!("Media download failed: HTTP {}", response.status())); + } + let limit = aes_ecb_ciphertext_len(max_plain_bytes); + if response + .content_length() + .is_some_and(|size| size > limit as u64) + { + return Err(anyhow!("Inbound media exceeds the download limit")); + } + let mut encrypted = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|_| anyhow!("Media download interrupted"))? + { + if chunk.len() > limit.saturating_sub(encrypted.len()) { + return Err(anyhow!("Inbound media exceeds the download limit")); + } + encrypted.extend_from_slice(&chunk); } - Ok(resp.bytes().await?.to_vec()) + Ok(encrypted) } async fn inbound_image_bytes_from_item(&self, item: &Value) -> Result> { let image = &item["image_item"]; let param = image["media"]["encrypt_query_param"] .as_str() - .filter(|s| !s.is_empty()) - .ok_or_else(|| anyhow!("image: missing encrypt_query_param"))?; + .unwrap_or_default(); let full_url = image["media"]["full_url"].as_str(); let key = if let Some(hex_s) = image["aeskey"].as_str().filter(|s| !s.is_empty()) { @@ -743,11 +836,18 @@ impl WeixinProviderClient { None }; - let encrypted = self.fetch_weixin_cdn_bytes(param, full_url).await?; - match key { - Some(key) => decrypt_aes_128_ecb_pkcs7(&encrypted, &key), - None => Ok(encrypted), + let encrypted = self + .fetch_weixin_cdn_bytes(param, full_url, MAX_WEIXIN_FILE_BYTES as usize) + .await?; + let bytes = match key { + Some(key) => decrypt_aes_128_ecb_pkcs7(&encrypted, &key) + .map_err(|_| anyhow!("Image decryption failed"))?, + None => encrypted, + }; + if bytes.len() > MAX_WEIXIN_FILE_BYTES as usize { + return Err(anyhow!("Inbound image exceeds the download limit")); } + Ok(bytes) } async fn upload_bytes_to_weixin_cdn( @@ -1362,6 +1462,26 @@ pub fn has_inbound_image_items(msg: &Value) -> bool { }) } +/// Voice transcripts are supported; raw voice currently has no audio input adapter. +pub fn has_unsupported_media_items(msg: &Value) -> bool { + msg["item_list"].as_array().is_some_and(|items| { + items.iter().any(|item| { + item["type"].as_i64() == Some(3) + && !item["voice_item"]["text"] + .as_str() + .is_some_and(|text| !text.trim().is_empty()) + }) + }) +} + +pub fn has_inbound_file_items(msg: &Value) -> bool { + msg["item_list"].as_array().is_some_and(|items| { + items + .iter() + .any(|item| matches!(item["type"].as_i64(), Some(4 | 5))) + }) +} + pub fn body_from_message(msg: &Value) -> String { let Some(items) = msg["item_list"].as_array() else { return String::new(); @@ -2168,4 +2288,172 @@ mod tests { assert!(body.contains("[引用:")); assert!(body.contains("reply")); } + + async fn mock_file_download( + body: Vec, + status: &str, + length: usize, + ) -> (String, tokio::task::JoinHandle<()>) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/file", listener.local_addr().unwrap()); + let headers = + format!("HTTP/1.1 {status}\r\nContent-Length: {length}\r\nConnection: close\r\n\r\n"); + let task = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut request = vec![0; 8192]; + let length = stream.read(&mut request).await.unwrap(); + let request = String::from_utf8_lossy(&request[..length]); + assert!(!request.to_lowercase().contains("authorization:")); + stream.write_all(headers.as_bytes()).await.unwrap(); + let _ = stream.write_all(&body).await; + }); + (url, task) + } + + #[tokio::test] + async fn inbound_file_download_preserves_bytes_and_supports_both_aes_key_encodings() { + let plain = b"pem-file-test-fixture\n\0\xff"; + let key = [42u8; 16]; + for encoded_key in [B64.encode(key), B64.encode(hex::encode(key))] { + let encrypted = encrypt_aes_128_ecb_pkcs7(plain, &key); + let (url, task) = + mock_file_download(encrypted.clone(), "200 OK", encrypted.len()).await; + // A full_url alone is valid in the official plugin, even without a query param. + let message = json!({"item_list":[{"type":4,"file_item":{ + "file_name":"KeyPair.pem", "len":plain.len().to_string(), + "media":{"full_url":url,"aes_key":encoded_key} + }}]}); + assert!(has_inbound_file_items(&message)); + assert_eq!(body_from_message(&message), ""); + let files = test_client("http://unused.invalid".into()) + .download_inbound_files(&message) + .await + .unwrap(); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, "KeyPair.pem"); + assert_eq!(files[0].bytes, plain); + task.await.unwrap(); + } + } + + #[tokio::test] + async fn inbound_file_missing_metadata_and_limits_are_explicit_errors() { + let client = test_client("http://unused.invalid".into()); + assert!(client + .download_inbound_files(&json!({"item_list":[{"type":1,"text_item":{"text":"hello"}}]})) + .await + .unwrap() + .is_empty()); + for item in [ + json!({"type":4}), + json!({"type":4,"file_item":{"media":{"full_url":"http://unused.invalid"}}}), + json!({"type":4,"file_item":{"len":MAX_WEIXIN_FILE_BYTES+1}}), + ] { + assert!(client + .download_inbound_files(&json!({"item_list":[item]})) + .await + .is_err()); + } + assert!(client + .download_inbound_files( + &json!({"item_list":vec![json!({"type":4}); MAX_INBOUND_FILES+1]}) + ) + .await + .is_err()); + } + + #[tokio::test] + async fn inbound_file_http_decrypt_size_and_stream_failures_do_not_become_empty_messages() { + let encrypted = encrypt_aes_128_ecb_pkcs7(b"fixture", &[42; 16]); + for (body, status, length, declared) in [ + (vec![], "403 Forbidden", 0, 7), + (vec![], "200 OK", (MAX_WEIXIN_FILE_BYTES + 32) as usize, 7), + (vec![0], "200 OK", 1, 7), + (encrypted.clone(), "200 OK", encrypted.len(), 8), + (vec![0], "200 OK", 16, 7), + ] { + let (url, task) = mock_file_download(body, status, length).await; + let message = json!({"item_list":[{"type":4,"file_item":{ + "file_name":"file.pem", "len":declared, + "media":{"full_url":url,"aes_key":B64.encode([42;16])} + }}]}); + let error = test_client("http://unused.invalid".into()) + .download_inbound_files(&message) + .await + .unwrap_err(); + assert!(!error.to_string().contains("http://")); + task.await.unwrap(); + } + } + + #[tokio::test] + async fn image_full_url_download_and_missing_media_are_not_silently_skipped() { + let plain = b"binary-image-fixture"; + let encrypted = encrypt_aes_128_ecb_pkcs7(plain, &[42; 16]); + let (url, task) = mock_file_download(encrypted.clone(), "200 OK", encrypted.len()).await; + let client = test_client("http://unused.invalid".into()); + let (images, skipped) = client + .download_inbound_images(&json!({"item_list":[{"type":2,"image_item":{ + "media":{"full_url":url,"aes_key":B64.encode([42;16])} + }}]})) + .await + .unwrap(); + assert_eq!(skipped, 0); + assert_eq!(images[0].bytes, plain); + task.await.unwrap(); + assert!(client + .download_inbound_images(&json!({"item_list":[{"type":2}]})) + .await + .is_err()); + let (url, task) = + mock_file_download(vec![], "200 OK", (MAX_WEIXIN_FILE_BYTES + 32) as usize).await; + let error = client + .download_inbound_images( + &json!({"item_list":[{"type":2,"image_item":{"media":{"full_url":url}}}]}), + ) + .await + .unwrap_err(); + assert!(!error.to_string().contains("http://")); + task.await.unwrap(); + } + + #[tokio::test] + async fn native_video_is_downloaded_as_an_unchanged_mp4_file() { + let plain = b"\0\0\0\x18ftypmp42binary-video-fixture"; + let encrypted = encrypt_aes_128_ecb_pkcs7(plain, &[42; 16]); + assert_ne!(encrypted.len(), plain.len()); + for declared in [encrypted.len(), plain.len()] { + let (url, task) = + mock_file_download(encrypted.clone(), "200 OK", encrypted.len()).await; + let message = json!({"item_list":[{"type":5,"video_item":{ + "video_size":declared, + "media":{"full_url":url,"aes_key":B64.encode([42;16])} + }}]}); + assert!(has_inbound_file_items(&message)); + assert!(!has_unsupported_media_items(&message)); + let result = test_client("http://unused.invalid".into()) + .download_inbound_files(&message) + .await; + if declared == encrypted.len() { + let files = result.unwrap(); + assert_eq!(files[0].name, "weixin_video_1.mp4"); + assert_eq!(files[0].bytes, plain); + } else { + assert!(result.unwrap_err().to_string().contains("video size")); + } + task.await.unwrap(); + } + let client = test_client("http://unused.invalid".into()); + assert!(client + .download_inbound_files(&json!({"item_list":[{"type":5}]})) + .await + .is_err()); + assert!(client + .download_inbound_files( + &json!({"item_list":vec![json!({"type":5}); MAX_INBOUND_FILES+1]}) + ) + .await + .is_err()); + } }