Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: make image work (#3687)

Eric Hayesffe8b0eccb65
diff --git a/.env-local.enc b/.env-local.enc
index dca30f545c..8fbfd5bf96 100644
--- a/.env-local.enc
+++ b/.env-local.enc
@@ -107,7 +107,7 @@ SNS_FCM_PLATFORM_ARN=ENC[AES256_GCM,data:mCOCaN0491cCMqBMlN0iKW1UelMREUarRV2zzL4
STATIC_FILE_SERVICE_DYNAMODB_TABLE_NAME=ENC[AES256_GCM,data:uSaCwpDlOuCszbwea1gbO5guixvnzw==,iv:0y+IxlCDWP9rLCKygRV3yQBpOFRIuAtv0WhvUBXtAmo=,tag:CHeGCg4sL9EbFPa9z1OdSw==,type:str]
STATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL=ENC[AES256_GCM,data:RjIJHnW7VjPCdtAiQyb6g12iOc/aPXNQwP7jlkDZ1fGHOIPZyaoaIAbIQBTlyv7EX6eSEncOkBR3z0zWFT2KtIS0PdkBaxbB+nICuMI=,iv:9j60gjhwt48Qk3z7A+MvY7VHGEdEWbnZunznaOtoaCM=,tag:aT5HMS8LQDhHaUx2xRfguw==,type:str]
STATIC_FILE_SERVICE_SERVICE_URL=ENC[AES256_GCM,data:iCYjAQzaK/RJCjrdtphOv+a5bkT6jVSjDhNZ,iv:m17iOpoPPT5+h+3GJSLZS5I0yOHScK4e6a1rA4BGJ3w=,tag:0vHdPul3RlzwfCpx2cR1YA==,type:str]
-STATIC_FILE_SERVICE_URL=ENC[AES256_GCM,data:27EO0Ix+oVjfikQaMK59wC/5tz7ofNk=,iv:vQF4yvAIuu7aHgFybxQlGuhu5e1DBnpzYEvpe/v/+QM=,tag:iet3mhqxKO8yQLZrzU2TUQ==,type:str]
+STATIC_FILE_SERVICE_URL=ENC[AES256_GCM,data:baO+Ro0YvdnFkguU1A5TXGvy26T9mFfz25um,iv:y0IBX5SpgkuIwyA5Plbg8LZdwq1Eb4GsxqhcKVoMge8=,tag:vGspmGi3nScE5UH2pj9sRw==,type:str]
STATIC_STORAGE_BUCKET=ENC[AES256_GCM,data:kj1OLwasPOP30NqdkiSVYn0Q8WUn,iv:VtGYpDPyi46cPWvPoL2MQHNsILMt/LmJ5+njuBJc3KM=,tag:usKaaU1XXa1DsVGonL75eg==,type:str]
STRIPE_PRICE_ID=ENC[AES256_GCM,data:F/XRar5AcKiLkCBdbgnKIzpNC5u5,iv:2rUgOqgOjrWPQA9Gspo4N5kSkt2+QIpgWHyz3kcPfwU=,tag:zykO8kFOJi3H8lu/uXwz/Q==,type:str]
STRIPE_SECRET_KEY=ENC[AES256_GCM,data:PzbiZPofcgMxd0VzYfZU3t5lquzq69qT76qND0cNrN921d0lRWfChC6FNao=,iv:KZgQXsrLvAomivgaeDr17r9twa0KJ9jD579AGrcEmGM=,tag:5itJ/BHP9JPEX2KZSf/kmg==,type:str]
@@ -146,7 +146,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480
sops_kms__list_1__map_aws_profile=
sops_kms__list_1__map_created_at=2026-03-03T19:32:07Z
sops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==
-sops_lastmodified=2026-05-29T22:49:06Z
-sops_mac=ENC[AES256_GCM,data:Z9sFo/yho9fkOZizDS1A5rFPZD+vjESmUkHzB/1fkpOj52MMO7jpOu/sOpl2GGBETehvVBIgwyDl7svOJ3/crc0SjGdNqM3KbvvN+4M6GcJqOQLrtgI/79rM10tj3II0WR0SONizAl1KaFNbf36Oby+GMjNjCigjG4BItDLhT6c=,iv:8BV0/0WELgki57QnZJigX2wXzN706ZVLp03WQ5TfTjo=,tag:1t7b9hC393apNbHUG0lsWg==,type:str]
+sops_lastmodified=2026-06-01T17:01:06Z
+sops_mac=ENC[AES256_GCM,data:R4rozJzs5EXyDjcGrOq62ywJiFGLSkN4VGE3o8zNisFAQuzFFk8MXh4aK9ws0J+KCojGK3QOVAHOhGOHB1iaoAr5Wlcz/kDlas9IQyZ74T8iusoKEhaOamjEviNQYqopAF7qgELeoeftj3ixvn5jeZNNTTvHV1/o4xL52VSE8MQ=,iv:SHb61xBNdK3w/SdhOQDVV0rBvbQVmTeJyhsUnPmUHgQ=,tag:BCu3E/suxKCUyft/KfcHlw==,type:str]
sops_unencrypted_suffix=_unencrypted
sops_version=3.12.2
diff --git a/js/bun.lock b/js/bun.lock
index 102287cfcb..9af37d685c 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -824,7 +824,7 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],
"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],
@@ -2544,7 +2544,7 @@
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 9ce138fa9b..946fca0a6b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -55,6 +55,8 @@ dependencies = [
"attachment",
"futures",
"macro_user_id",
+ "model-entity",
+ "non_empty",
"rig-core",
"schemars 1.2.1",
"serde",
diff --git a/rust/cloud-storage/agent/Cargo.toml b/rust/cloud-storage/agent/Cargo.toml
index b61663f121..515ad2d65f 100644
--- a/rust/cloud-storage/agent/Cargo.toml
+++ b/rust/cloud-storage/agent/Cargo.toml
@@ -25,3 +25,7 @@ tracing = { workspace = true }
ai_toolset = { path = "../ai_toolset" }
attachment = { path = "../attachment" }
macro_user_id = { path = "../macro_user_id" }
+
+[dev-dependencies]
+model-entity = { path = "../model-entity" }
+non_empty = { path = "../non_empty" }
diff --git a/rust/cloud-storage/agent/src/convert.rs b/rust/cloud-storage/agent/src/convert.rs
index 72e4ffa97a..0038300f23 100644
--- a/rust/cloud-storage/agent/src/convert.rs
+++ b/rust/cloud-storage/agent/src/convert.rs
@@ -3,11 +3,73 @@ mod test;
/// Conversions between agent message types and `rig` message types.
use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};
+use attachment::image::ImageData;
+use attachment::{AttachmentContent, AttachmentPart, Attachments};
use rig_core::OneOrMany;
use rig_core::message::{
- AssistantContent, Message, ToolCall, ToolFunction, ToolResultContent, UserContent,
+ AssistantContent, ImageMediaType, Message, ToolCall, ToolFunction, ToolResultContent,
+ UserContent,
};
+/// Conversion of an attachment value into RIG user-content blocks.
+///
+/// Implemented for the attachment tree types so a user message's resolved
+/// attachments can be flattened into the [`UserContent`] blocks RIG sends to
+/// the model. Foreign-type orphan rules rule out a `From` impl, so this local
+/// trait carries the conversions instead.
+trait ToUserContent {
+ /// Convert `self` into zero or more RIG user-content blocks.
+ fn to_user_content(&self) -> Vec<UserContent>;
+}
+
+impl ToUserContent for Attachments<'_> {
+ fn to_user_content(&self) -> Vec<UserContent> {
+ // Failed resolutions carry no content useful to the model; skip them.
+ self.parts()
+ .iter()
+ .filter_map(|resolved| resolved.as_ref().ok())
+ .flat_map(ToUserContent::to_user_content)
+ .collect()
+ }
+}
+
+impl ToUserContent for AttachmentContent<'_> {
+ fn to_user_content(&self) -> Vec<UserContent> {
+ self.content
+ .iter()
+ .flat_map(ToUserContent::to_user_content)
+ .collect()
+ }
+}
+
+impl ToUserContent for AttachmentPart<'_> {
+ fn to_user_content(&self) -> Vec<UserContent> {
+ match self {
+ Self::Content(text) => vec![UserContent::text(text.clone())],
+ Self::Image(image) => image.to_user_content(),
+ Self::Metadata { key, value } => vec![UserContent::text(format!("{key}: {value}"))],
+ // Errors, child references, and resolved children are not
+ // represented as inline model content here.
+ Self::ImageError(_) | Self::Child(_) | Self::ChildReference(_) => vec![],
+ }
+ }
+}
+
+impl ToUserContent for ImageData {
+ fn to_user_content(&self) -> Vec<UserContent> {
+ let content = match self {
+ // `Base64Image` is always a downscaled WebP by construction.
+ Self::Base64(image) => UserContent::image_base64(
+ image.base64_data().to_owned(),
+ Some(ImageMediaType::WEBP),
+ None,
+ ),
+ Self::StaticUrl(url) => UserContent::image_url(url.clone(), None, None),
+ };
+ vec![content]
+ }
+}
+
/// Convert a slice of [`ChatMessage`] into RIG [`Message`]s.
///
/// System messages are skipped (the system prompt is set on the agent).
@@ -23,14 +85,40 @@ pub fn to_rig_messages(messages: &[ChatMessage]) -> Vec<Message> {
fn convert_one(msg: &ChatMessage) -> Vec<Message> {
match msg.role {
Role::System => vec![],
- Role::User => {
- let text = msg.content.message_text();
- vec![Message::user(text)]
- }
+ Role::User => convert_user(msg),
Role::Assistant => convert_assistant(msg),
}
}
+/// Convert a user message into a single RIG [`Message::User`].
+///
+/// The message text becomes a leading [`UserContent::Text`] block (when
+/// non-empty) and any resolved [`attachments`](ChatMessage::attachments) are
+/// appended as additional text and image content blocks. Without this, image
+/// attachments would never reach the model.
+fn convert_user(msg: &ChatMessage) -> Vec<Message> {
+ let mut content: Vec<UserContent> = Vec::new();
+
+ let text = msg.content.message_text();
+ if !text.is_empty() {
+ content.push(UserContent::text(text));
+ }
+
+ if let Some(attachments) = &msg.attachments {
+ content.extend(attachments.to_user_content());
+ }
+
+ // A user turn must contain at least one content block.
+ if content.is_empty() {
+ content.push(UserContent::text(String::new()));
+ }
+
+ match OneOrMany::many(content) {
+ Ok(content) => vec![Message::User { content }],
+ Err(_) => vec![Message::user(msg.content.message_text())],
+ }
+}
+
fn convert_assistant(msg: &ChatMessage) -> Vec<Message> {
let parts = match &msg.content {
ChatMessageContent::Text(text) => {
diff --git a/rust/cloud-storage/agent/src/convert/test.rs b/rust/cloud-storage/agent/src/convert/test.rs
index db279a9536..de1c78a820 100644
--- a/rust/cloud-storage/agent/src/convert/test.rs
+++ b/rust/cloud-storage/agent/src/convert/test.rs
@@ -1,7 +1,37 @@
use super::*;
-use rig_core::message::{AssistantContent, Message, UserContent};
+use attachment::image::ImageData;
+use attachment::{AttachmentContent, AttachmentPart, Attachments};
+use model_entity::EntityType;
+use non_empty::NonEmpty;
+use rig_core::message::{AssistantContent, DocumentSourceKind, Message, UserContent};
use serde_json::json;
+/// A minimal valid 1x1 PNG, used to exercise the image-normalization path.
+#[rustfmt::skip]
+const ONE_BY_ONE_PNG: &[u8] = &[
+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
+ 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00,
+ 0x0C, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0xF8, 0xCF, 0xC0, 0x00,
+ 0x00, 0x03, 0x01, 0x01, 0x00, 0xC9, 0xFE, 0x92, 0xEF, 0x00, 0x00, 0x00,
+ 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
+];
+
+/// Build a user message carrying a single resolved attachment made of `parts`.
+fn user_msg_with_attachment(text: &str, parts: Vec<AttachmentPart<'static>>) -> ChatMessage {
+ let content = AttachmentContent {
+ reference: EntityType::StaticFile.with_entity_string(String::new()),
+ name: None,
+ content: NonEmpty::new(parts).expect("at least one part"),
+ };
+ let attachments = Attachments::new(NonEmpty::one(Ok(content)));
+ ChatMessage {
+ role: Role::User,
+ content: ChatMessageContent::Text(text.to_owned()),
+ attachments: Some(attachments),
+ }
+}
+
fn user_msg(text: &str) -> ChatMessage {
ChatMessage {
role: Role::User,
@@ -348,6 +378,97 @@ fn full_conversation_with_tool_round_trip() {
assert_eq!(text.text, "Found 2 cats.");
}
+#[test]
+fn user_message_with_image_url_attachment_includes_image_content() {
+ let msg = user_msg_with_attachment(
+ "what is in this image?",
+ vec![AttachmentPart::Image(ImageData::StaticUrl(
+ "https://example.com/cat.png".to_owned(),
+ ))],
+ );
+ let messages = to_rig_messages(&[msg]);
+ assert_eq!(messages.len(), 1);
+
+ let Message::User { content } = &messages[0] else {
+ panic!("expected user message");
+ };
+ // text block + image block
+ assert_eq!(content.len(), 2);
+
+ let mut iter = content.iter();
+ let UserContent::Text(text) = iter.next().unwrap() else {
+ panic!("expected leading text");
+ };
+ assert_eq!(text.text, "what is in this image?");
+
+ let UserContent::Image(image) = iter.next().unwrap() else {
+ panic!("expected image content");
+ };
+ assert!(matches!(
+ &image.data,
+ DocumentSourceKind::Url(url) if url == "https://example.com/cat.png"
+ ));
+}
+
+#[test]
+fn user_message_with_base64_image_is_sent_as_webp() {
+ // A non-WebP source is normalized to a downscaled WebP, so the model
+ // always receives base64 WebP content.
+ let image = ImageData::try_from_bytes(ONE_BY_ONE_PNG.to_vec()).expect("valid image");
+ assert!(matches!(image, ImageData::Base64(_)));
+
+ let msg = user_msg_with_attachment("look", vec![AttachmentPart::Image(image)]);
+ let messages = to_rig_messages(&[msg]);
+
+ let Message::User { content } = &messages[0] else {
+ panic!("expected user message");
+ };
+ let UserContent::Image(image) = content.iter().nth(1).unwrap() else {
+ panic!("expected image content");
+ };
+ assert_eq!(image.media_type, Some(ImageMediaType::WEBP));
+ let DocumentSourceKind::Base64(data) = &image.data else {
+ panic!("expected base64 image data");
+ };
+ assert!(!data.is_empty(), "base64 payload should not be empty");
+}
+
+#[test]
+fn user_message_with_text_attachment_appends_text_block() {
+ let msg = user_msg_with_attachment(
+ "summarize",
+ vec![AttachmentPart::Content("attached document body".to_owned())],
+ );
+ let messages = to_rig_messages(&[msg]);
+
+ let Message::User { content } = &messages[0] else {
+ panic!("expected user message");
+ };
+ assert_eq!(content.len(), 2);
+ let UserContent::Text(text) = content.iter().nth(1).unwrap() else {
+ panic!("expected attachment text");
+ };
+ assert_eq!(text.text, "attached document body");
+}
+
+#[test]
+fn user_message_with_only_attachment_and_empty_text_omits_text_block() {
+ let mut msg = user_msg_with_attachment(
+ "",
+ vec![AttachmentPart::Image(ImageData::StaticUrl(
+ "https://example.com/x.png".to_owned(),
+ ))],
+ );
+ msg.content = ChatMessageContent::Text(String::new());
+
+ let messages = to_rig_messages(&[msg]);
+ let Message::User { content } = &messages[0] else {
+ panic!("expected user message");
+ };
+ assert_eq!(content.len(), 1);
+ assert!(matches!(content.first(), UserContent::Image(_)));
+}
+
mod merge_consecutive_parts_tests {
use super::*;
diff --git a/rust/cloud-storage/attachment/src/image/base_64_image.rs b/rust/cloud-storage/attachment/src/image/base_64_image.rs
index e0cf7f3102..ce8897fb90 100644
--- a/rust/cloud-storage/attachment/src/image/base_64_image.rs
+++ b/rust/cloud-storage/attachment/src/image/base_64_image.rs
@@ -1,136 +1,81 @@
-use anyhow::{anyhow, bail};
+#[cfg(test)]
+mod test;
+
+use anyhow::{Result, anyhow};
use base64::Engine;
use base64::engine::general_purpose;
use image::{DynamicImage, GenericImageView};
-use model_file_type::FileType;
use serde::{Deserialize, Serialize};
use webp::Encoder;
const ENCODING_QUALITY: f32 = 75.0;
-const MAX_SIZE_W: u32 = 1080;
-const MAX_SIZE_H: u32 = 720;
+/// The maximum length, in pixels, of an image's longest side.
+const MAX_DIMENSION: u32 = 1080;
-/// A base64-encoded image with a known format.
+/// A base64-encoded WebP image.
///
-/// Images are optionally downscaled to fit within 1080x720 and re-encoded as
-/// WebP at 75% quality to reduce token cost when sent to an AI model.
+/// All images are normalized on construction: downscaled so their longest side
+/// is at most [`MAX_DIMENSION`] pixels and (re-)encoded as WebP at 75% quality
+/// to reduce token cost when sent to an AI model. The type itself is the
+/// guarantee that its data is a downscaled WebP — there is no other format to
+/// track.
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct Base64Image {
+ /// Raw base64-encoded WebP data, without any `data:` URI prefix.
data: String,
- format: ImageFormat,
-}
-
-/// Supported image formats for base64 encoding.
-#[derive(Clone, Debug, Copy, Eq, PartialEq, Serialize, Deserialize)]
-pub enum ImageFormat {
- /// WebP format.
- WebP,
- /// JPG format (three-letter extension).
- Jpg,
- /// JPEG format (four-letter extension).
- Jpeg,
- /// PNG format.
- Png,
-}
-
-impl TryFrom<FileType> for ImageFormat {
- type Error = anyhow::Error;
- fn try_from(value: FileType) -> Result<Self, Self::Error> {
- match value {
- FileType::Jpg => Ok(Self::Jpg),
- FileType::Jpeg => Ok(Self::Jpeg),
- FileType::Png => Ok(Self::Png),
- FileType::Webp => Ok(Self::WebP),
- _ => bail!("No conversion"),
- }
- }
}
impl Base64Image {
- /// Compress and re-encode raw image bytes into a base64 WebP.
- pub fn downscale_and_reencode(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
- Self::make_downscaled_base64_webp(bytes)
- }
-
- pub(crate) fn try_from_string(s: &str) -> Result<Self, anyhow::Error> {
- if s.starts_with("data:") {
- let prefix = s.split_once(";").ok_or(anyhow!("Unexpected format"))?.0;
- let image = prefix
- .split_once("/")
- .ok_or(anyhow!("Unexpected format"))?
- .1;
- let format = ImageFormat::try_from(image)?;
+ /// Normalize raw image bytes of any format into a downscaled base64 WebP.
+ ///
+ /// Bytes that are already a WebP within the size bound are kept verbatim;
+ /// anything else is decoded, downscaled, and re-encoded as WebP.
+ pub fn downscale_and_reencode(bytes: Vec<u8>) -> Result<Self> {
+ let img = image::load_from_memory(&bytes)?;
+ let (width, height) = img.dimensions();
- Ok(Self {
- data: s.to_owned(),
- format,
- })
- } else {
- Err(anyhow::anyhow!("not a base64 encoded image"))
+ let already_webp = image::guess_format(&bytes).ok() == Some(image::ImageFormat::WebP);
+ if already_webp && width <= MAX_DIMENSION && height <= MAX_DIMENSION {
+ return Ok(Self::from_webp_bytes(&bytes));
}
- }
-}
-
-impl Base64Image {
- fn prefix(&self) -> String {
- format!("data:image/{};base64,", self.format)
- }
-}
-impl std::fmt::Display for Base64Image {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}{}", self.prefix(), self.data)
+ let resized = Self::resize_if_needed(img);
+ let rgb = resized.to_rgb8();
+ let encoder = Encoder::from_rgb(&rgb, rgb.width(), rgb.height());
+ let webp = encoder.encode(ENCODING_QUALITY);
+ Ok(Self::from_webp_bytes(&webp))
}
-}
-impl std::fmt::Display for ImageFormat {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}",
- match self {
- Self::WebP => "webp",
- Self::Jpg => "jpg",
- Self::Jpeg => "jpeg",
- Self::Png => "png",
- }
- )
+ /// Parse a base64 `data:` URI and normalize it into a downscaled WebP.
+ pub(crate) fn try_from_string(s: &str) -> Result<Self> {
+ let base64 = s
+ .strip_prefix("data:")
+ .and_then(|rest| rest.split_once(";base64,"))
+ .map(|(_, data)| data)
+ .ok_or_else(|| anyhow!("not a base64-encoded data URI"))?;
+ let bytes = general_purpose::STANDARD.decode(base64)?;
+ Self::downscale_and_reencode(bytes)
}
-}
-impl std::fmt::Debug for Base64Image {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}[{} bytes]", self.prefix(), self.data.len())
+ /// The raw base64-encoded WebP data, without any `data:` URI prefix.
+ pub fn base64_data(&self) -> &str {
+ &self.data
}
-}
-impl Base64Image {
- fn make_downscaled_base64_webp(image_bytes: Vec<u8>) -> Result<Self, anyhow::Error> {
- let img = image::load_from_memory(&image_bytes)?;
- let resized_img = Self::resize_if_needed(img);
- let rgb_img = resized_img.to_rgb8();
- let encoder = Encoder::from_rgb(&rgb_img, rgb_img.width(), rgb_img.height());
- let webp_data = encoder.encode(ENCODING_QUALITY);
- let base64_string = general_purpose::STANDARD.encode(&*webp_data);
- Ok(Self {
- data: base64_string,
- format: ImageFormat::WebP,
- })
+ fn from_webp_bytes(webp: &[u8]) -> Self {
+ Self {
+ data: general_purpose::STANDARD.encode(webp),
+ }
}
fn resize_if_needed(img: DynamicImage) -> DynamicImage {
let (width, height) = img.dimensions();
-
- // Check if resize is needed
- if width <= MAX_SIZE_W && height <= MAX_SIZE_H {
+ if width <= MAX_DIMENSION && height <= MAX_DIMENSION {
return img;
}
- // Calculate new dimensions while maintaining aspect ratio
- let width_ratio = MAX_SIZE_W as f32 / width as f32;
- let height_ratio = MAX_SIZE_H as f32 / height as f32;
- let ratio = width_ratio.min(height_ratio);
-
+ // Scale the longest side down to MAX_DIMENSION, preserving aspect ratio.
+ let ratio = (MAX_DIMENSION as f32 / width as f32).min(MAX_DIMENSION as f32 / height as f32);
let new_width = (width as f32 * ratio) as u32;
let new_height = (height as f32 * ratio) as u32;
@@ -138,26 +83,14 @@ impl Base64Image {
}
}
-impl From<ImageFormat> for image::ImageFormat {
- fn from(value: ImageFormat) -> Self {
- match value {
- ImageFormat::Jpeg => Self::Jpeg,
- ImageFormat::Jpg => Self::Jpeg,
- ImageFormat::WebP => Self::WebP,
- ImageFormat::Png => Self::Png,
- }
+impl std::fmt::Display for Base64Image {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "data:image/webp;base64,{}", self.data)
}
}
-impl TryFrom<&str> for ImageFormat {
- type Error = anyhow::Error;
- fn try_from(value: &str) -> Result<Self, Self::Error> {
- match value {
- "webp" => Ok(Self::WebP),
- "jpg" => Ok(Self::Jpg),
- "jpeg" => Ok(Self::Jpeg),
- "png" => Ok(Self::Png),
- _ => bail!("No conversion"),
- }
+impl std::fmt::Debug for Base64Image {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "data:image/webp;base64,[{} bytes]", self.data.len())
}
}
diff --git a/rust/cloud-storage/attachment/src/image/base_64_image/test.rs b/rust/cloud-storage/attachment/src/image/base_64_image/test.rs
new file mode 100644
index 0000000000..6e459aca56
--- /dev/null
+++ b/rust/cloud-storage/attachment/src/image/base_64_image/test.rs
@@ -0,0 +1,75 @@
+use super::*;
+use base64::Engine;
+use base64::engine::general_purpose;
+use image::{GenericImageView, ImageFormat, RgbImage};
+
+/// Encode an in-memory RGB image of the given size to bytes in `format`.
+fn encode(width: u32, height: u32, format: ImageFormat) -> Vec<u8> {
+ let img = RgbImage::from_pixel(width, height, image::Rgb([10, 120, 240]));
+ let mut bytes = std::io::Cursor::new(Vec::new());
+ image::DynamicImage::ImageRgb8(img)
+ .write_to(&mut bytes, format)
+ .expect("encode test image");
+ bytes.into_inner()
+}
+
+/// Decode the WebP payload back into an image to inspect format and dimensions.
+fn decode(image: &Base64Image) -> image::DynamicImage {
+ let bytes = general_purpose::STANDARD
+ .decode(image.base64_data())
+ .expect("valid base64");
+ assert_eq!(
+ image::guess_format(&bytes).ok(),
+ Some(ImageFormat::WebP),
+ "output must always be WebP",
+ );
+ image::load_from_memory(&bytes).expect("decode webp")
+}
+
+#[test]
+fn png_is_converted_to_webp() {
+ let png = encode(64, 64, ImageFormat::Png);
+ let result = Base64Image::downscale_and_reencode(png).expect("normalize");
+ // `decode` asserts the payload is WebP.
+ let img = decode(&result);
+ assert_eq!(img.dimensions(), (64, 64), "small image keeps its size");
+}
+
+#[test]
+fn oversized_image_is_downscaled_to_1080_longest_side() {
+ let png = encode(3000, 1500, ImageFormat::Png);
+ let result = Base64Image::downscale_and_reencode(png).expect("normalize");
+ let (width, height) = decode(&result).dimensions();
+ assert_eq!(width, MAX_DIMENSION, "longest side capped at 1080");
+ assert!(height <= MAX_DIMENSION);
+ // Aspect ratio (2:1) is preserved.
+ assert_eq!(height, MAX_DIMENSION / 2);
+}
+
+#[test]
+fn small_webp_is_kept_without_reencoding() {
+ let webp = encode(32, 32, ImageFormat::WebP);
+ let expected = general_purpose::STANDARD.encode(&webp);
+ let result = Base64Image::downscale_and_reencode(webp).expect("normalize");
+ assert_eq!(
+ result.base64_data(),
+ expected,
+ "an already-correct WebP is passed through verbatim",
+ );
+}
+
+#[test]
+fn data_uri_string_is_normalized_to_webp() {
+ let png = encode(48, 48, ImageFormat::Png);
+ let data_uri = format!(
+ "data:image/png;base64,{}",
+ general_purpose::STANDARD.encode(&png)
+ );
+ let result = Base64Image::try_from_string(&data_uri).expect("normalize data uri");
+ decode(&result); // asserts WebP output
+}
+
+#[test]
+fn non_data_uri_string_is_rejected() {
+ assert!(Base64Image::try_from_string("https://example.com/cat.png").is_err());
+}
diff --git a/rust/cloud-storage/attachment/src/image/mod.rs b/rust/cloud-storage/attachment/src/image/mod.rs
index 8d558f415c..782a9a2b8e 100644
--- a/rust/cloud-storage/attachment/src/image/mod.rs
+++ b/rust/cloud-storage/attachment/src/image/mod.rs
@@ -2,7 +2,7 @@
mod base_64_image;
-pub use base_64_image::{Base64Image, ImageFormat};
+pub use base_64_image::Base64Image;
/// An image that can be included in an attachment.
#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ImageData {
diff --git a/rust/cloud-storage/documents/src/inbound/attachment/service.rs b/rust/cloud-storage/documents/src/inbound/attachment/service.rs
index 0bac6cdeea..03649deb39 100644
--- a/rust/cloud-storage/documents/src/inbound/attachment/service.rs
+++ b/rust/cloud-storage/documents/src/inbound/attachment/service.rs
@@ -231,6 +231,11 @@ impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentService
}
pub(super) async fn fetch_url_bytes(url: &str) -> Result<Vec<u8>, AttachmentError> {
+ // Presigned/distribution URLs are minted with the browser-facing `localhost`
+ // host; rewrite to the in-network LocalStack host so this server-side fetch
+ // works inside Docker. No-op outside local AWS.
+ let url = macro_aws_config::transform_aws_url_for_internal_fetch(url);
+ let url = url.as_str();
let response = reqwest::get(url)
.await
.map_err(|e| AttachmentError::Internal(e.into()))?;
diff --git a/rust/cloud-storage/macro_aws_config/src/lib.rs b/rust/cloud-storage/macro_aws_config/src/lib.rs
index 44b0ca5c5c..7247e7c5f9 100644
--- a/rust/cloud-storage/macro_aws_config/src/lib.rs
+++ b/rust/cloud-storage/macro_aws_config/src/lib.rs
@@ -85,5 +85,41 @@ pub fn transform_aws_url(url: &str) -> String {
url.to_string()
}
+/// internal method to transform a browser-facing local url into one reachable
+/// from inside the docker network
+fn transform_internal_url(url: &str) -> String {
+ // NOTE: it is ok to use expect as this is only run locally
+ let parsed = url::Url::parse(url).expect("valid url");
+ let host = parsed.host_str().unwrap();
+ let port = parsed.port().unwrap_or(4566);
+ let path = parsed.path();
+ let query = parsed.query().map(|q| format!("?{q}")).unwrap_or_default();
+
+ // Browser-facing local URLs use `localhost`, which inside a container
+ // resolves to the container itself. Swap it for the `localstack` service
+ // hostname so service-to-service fetches reach LocalStack. Leave any other
+ // host untouched.
+ if host == "localhost" || host == "localstack" {
+ return format!("http://localstack:{port}{path}{query}");
+ }
+
+ url.to_string()
+}
+
+/// Transforms a browser-facing local URL into one reachable from inside the
+/// app's own containers when fetching an object server-side.
+///
+/// The inverse of [`transform_aws_url`]: presigned and distribution URLs are
+/// minted with the `localhost` host so the browser on the host machine can
+/// reach LocalStack, but a service fetching the same object from inside the
+/// Docker network must use the `localstack` service hostname instead. No-op
+/// outside local AWS.
+pub fn transform_aws_url_for_internal_fetch(url: &str) -> String {
+ if is_local_aws() {
+ return transform_internal_url(url);
+ }
+ url.to_string()
+}
+
#[cfg(test)]
mod test;
diff --git a/rust/cloud-storage/macro_aws_config/src/test.rs b/rust/cloud-storage/macro_aws_config/src/test.rs
index 0f696f48f9..b5d18fa200 100644
--- a/rust/cloud-storage/macro_aws_config/src/test.rs
+++ b/rust/cloud-storage/macro_aws_config/src/test.rs
@@ -109,3 +109,39 @@ fn test_transform_url_default_port_localhost() {
let result = transform_local_url(input);
assert_eq!(result, expected);
}
+
+#[test]
+fn test_internal_fetch_rewrites_localhost_to_localstack() {
+ let input = "http://localhost:4566/doc-storage/macro%7Cteo%40macro.com/doc/1";
+ let expected = "http://localstack:4566/doc-storage/macro%7Cteo%40macro.com/doc/1";
+
+ let result = transform_internal_url(input);
+ assert_eq!(result, expected);
+}
+
+#[test]
+fn test_internal_fetch_preserves_query_params() {
+ let input = "http://localhost:4566/doc-storage/key?versionId=123";
+ let expected = "http://localstack:4566/doc-storage/key?versionId=123";
+
+ let result = transform_internal_url(input);
+ assert_eq!(result, expected);
+}
+
+#[test]
+fn test_internal_fetch_localstack_is_idempotent() {
+ let input = "http://localstack:4566/doc-storage/key";
+ let expected = "http://localstack:4566/doc-storage/key";
+
+ let result = transform_internal_url(input);
+ assert_eq!(result, expected);
+}
+
+#[test]
+fn test_internal_fetch_leaves_remote_url_untouched() {
+ let input = "https://d123.cloudfront.net/doc-storage/key?Signature=abc";
+ let expected = "https://d123.cloudfront.net/doc-storage/key?Signature=abc";
+
+ let result = transform_internal_url(input);
+ assert_eq!(result, expected);
+}