diff --git a/crates/desktop-protocol/src/astrbot.rs b/crates/desktop-protocol/src/astrbot.rs index a209ea8..077f111 100644 --- a/crates/desktop-protocol/src/astrbot.rs +++ b/crates/desktop-protocol/src/astrbot.rs @@ -355,6 +355,9 @@ impl AstrBotStreamMapper { fn map_media(&mut self, frame: AstrBotStreamFrame) -> Vec { let mut events = Vec::new(); + let file_name = text_from_value(&frame.data) + .as_deref() + .and_then(attachment_file_name); if let Some(message_id) = frame.message_id { if self .active_base_id() @@ -368,6 +371,19 @@ impl AstrBotStreamMapper { } self.active_message_id = Some(message_id); } + + // The media frame carries the file name, and AstrBot's own dashboard + // fetches a chat image by name. The id in the following + // `attachment_saved` frame addresses a different resource, so waiting + // for that frame both loses the name and produces an unusable marker. + if frame.frame_type == "image" + && let Some(file_name) = file_name + { + self.pending_media = None; + events.extend(self.emit_delta(format!("![image](astrbot-attachment://{file_name})"))); + return events; + } + self.pending_media = Some(PendingMedia { media_type: frame.frame_type, }); @@ -542,6 +558,25 @@ impl AstrBotStreamMapper { } } +/// Extracts a usable file name from a media frame's reference. +/// +/// Observed form is `[IMAGE]{uuid}.jpg`: a bracketed type tag followed by a +/// bare name, with no scheme and no path separator. Anything carrying a path or +/// a scheme is rejected rather than guessed at, because the fetch below only +/// knows how to ask AstrBot for a name. +fn attachment_file_name(reference: &str) -> Option { + let name = reference + .rsplit_once(']') + .map_or(reference, |(_, tail)| tail) + .trim(); + let usable = !name.is_empty() + && name.len() <= 200 + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')); + usable.then(|| name.to_owned()) +} + fn string_from_value(value: &Value) -> Option { match value { Value::Null => None, @@ -687,12 +722,39 @@ mod tests { } } + /// The media frame names the file; the id that follows addresses something + /// else. AstrBot's dashboard fetches a chat image by name, and asking the + /// by-id endpoint for the `attachment_saved` id returned the dashboard's own + /// HTML with HTTP 200, which surfaced as a broken image. #[test] - fn maps_image_frames_to_persistable_attachment_markers() { + fn maps_image_frames_to_markers_naming_the_file() { + let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); + let events = mapper + .push_line(r#"data: {"type":"image","data":"[IMAGE]happy.png","message_id":"m1"}"#) + .expect("image frame"); + let delta = events + .iter() + .find_map(|event| match &event.body { + GatewayEventBody::MessageDelta(payload) => Some(payload.delta.as_str()), + _ => None, + }) + .expect("image delta"); + assert_eq!(delta, "![image](astrbot-attachment://happy.png)"); + + // The follow-up frame must not append a second marker for the same image. + let extra = mapper + .push_line(r#"data: {"type":"attachment_saved","data":{"id":"att-1","type":"image"},"message_id":"m1"}"#) + .expect("attachment frame"); + assert!(extra.is_empty(), "{extra:?}"); + } + + /// Falls back to the saved id when the media frame names nothing usable. + #[test] + fn uses_the_saved_id_when_the_media_frame_carries_no_file_name() { let mut mapper = AstrBotStreamMapper::new("astrbot-test", "stream-a"); assert!( mapper - .push_line(r#"data: {"type":"image","data":"[IMAGE]happy.png","message_id":"m1"}"#) + .push_line(r#"data: {"type":"image","data":"","message_id":"m1"}"#) .expect("image frame") .is_empty() ); @@ -709,6 +771,23 @@ mod tests { assert_eq!(delta, "![image](astrbot-attachment://att-1)"); } + #[test] + fn attachment_file_names_reject_paths_and_schemes() { + assert_eq!( + attachment_file_name("[IMAGE]0d9b2f14-1c8e-4a7d-9f31-2b6c5e8a0d47.jpg").as_deref(), + Some("0d9b2f14-1c8e-4a7d-9f31-2b6c5e8a0d47.jpg") + ); + assert_eq!( + attachment_file_name("plain.png").as_deref(), + Some("plain.png") + ); + // Anything the by-name fetch cannot express is refused rather than guessed. + assert_eq!(attachment_file_name("https://host/a.png"), None); + assert_eq!(attachment_file_name("[IMAGE]/var/data/a.png"), None); + assert_eq!(attachment_file_name("[IMAGE]"), None); + assert_eq!(attachment_file_name(""), None); + } + /// Replays the frame order of a captured stream that destroyed its own reply. /// /// The server sent `complete` and then continued: `image`, @@ -743,8 +822,9 @@ mod tests { assert_eq!(completions.len(), 2, "{completions:?}"); assert_eq!(completions[0], ("m1", "完整的回复正文")); - // The attachment lands in a message of its own, leaving the reply intact. - assert_eq!(completions[1].1, "![image](astrbot-attachment://att-9)"); + // The attachment lands in a message of its own, leaving the reply intact, + // and names the file rather than the id of the frame that followed. + assert_eq!(completions[1].1, "![image](astrbot-attachment://sticker.png)"); assert_ne!( completions[1].0, "m1", "the attachment must not reuse the finished message id" diff --git a/src-tauri/src/networking/astrbot_client.rs b/src-tauri/src/networking/astrbot_client.rs index 8fd6ff7..6339b67 100644 --- a/src-tauri/src/networking/astrbot_client.rs +++ b/src-tauri/src/networking/astrbot_client.rs @@ -433,7 +433,7 @@ impl AstrBotClient { let form = reqwest::multipart::Form::new().part("file", part); let response = self .http - .post(self.url("/api/v1/file")) + .post(self.url("/api/v1/files")) .multipart(form) .send() .await?; @@ -482,7 +482,15 @@ impl AstrBotClient { } let response = self .http - .get(self.url(&format!("/api/v1/files/{attachment_id}/content"))) + // AstrBot's dashboard fetches a chat image by name via + // `/api/v1/files/content?filename=`. The by-id form + // `/api/v1/files/{id}/content` also exists, but the id carried by + // `attachment_saved` does not address the file — asking for it + // returned the dashboard's own HTML shell with HTTP 200. + .get(self.url(&format!( + "/api/v1/files/content?filename={}", + urlencoding_username(attachment_id) + ))) .send() .await?; if response.status().as_u16() == 401 || response.status().as_u16() == 403 {