feat: let MCP clients see the images a run returns (#12674)

* feat: let MCP clients see the images a run returns

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: bump ee-repo-ref for the result_image usage kind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: allow the unread image MIME type in builds without mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: leave out images wider or taller than 8000 px in get_run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: attach a scaled JPEG copy of images past get_run's limits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: limit what get_run's image decoders allocate for metadata

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: cap WebP EXIF reads and read listed images one at a time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: move image decoding to images.rs, build it with mcp and bound image reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to 86980494df18137ab695bdf4b538e5ebc23c3947

This commit updates the EE repository reference after PR #1010 was merged in windmill-ee-private.

Previous ee-repo-ref: b3a528dbc13cf18f2ae2c438fd6ee2ae796f4e5d

New ee-repo-ref: 86980494df18137ab695bdf4b538e5ebc23c3947

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
Guilhem
2026-12-02 01:35:58 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot] Ruben Fiszel
parent f8e049d426
commit 67e5de0892
9 changed files with 1084 additions and 64 deletions
+118
View File
@@ -2199,6 +2199,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.2"
@@ -2564,6 +2570,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084"
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -5401,6 +5413,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "ff"
version = "0.13.1"
@@ -6027,6 +6048,16 @@ dependencies = [
"polyval",
]
[[package]]
name = "gif"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "git-version"
version = "0.3.9"
@@ -7075,6 +7106,34 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb"
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -8315,6 +8374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
@@ -8380,6 +8440,16 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "multer"
version = "3.1.0"
@@ -10009,6 +10079,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags 2.13.2",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "polling"
version = "2.8.0"
@@ -10467,6 +10550,18 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quick-xml"
version = "0.37.5"
@@ -15562,6 +15657,12 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "which"
version = "4.4.2"
@@ -15823,6 +15924,8 @@ dependencies = [
"hmac 0.12.1",
"http 1.5.0",
"hyper 1.13.0",
"image",
"image-webp",
"indexmap 2.14.2",
"itertools 0.14.0",
"jsonwebtoken 10.4.0",
@@ -18703,3 +18806,18 @@ dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "zune-core"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18"
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]
+2
View File
@@ -618,6 +618,8 @@ once_cell = "1.17.1"
dashmap = "6.1.0"
gosyn = "0.2.6"
bytes = "1.4.0"
image = { version = "0.25.10", default-features = false, features = ["gif", "jpeg", "png", "webp"] }
image-webp = "0.2.4"
gethostname = "0.4.3"
# Not pinned exactly: the excluded `parsers/windmill-parser-wasm` workspace pins
# =0.2.103 to match its vendored `cli/wasm/*` artifacts, yet path-depends on
+1 -1
View File
@@ -1 +1 @@
c7bab879047c8f68e472fcb2e524458171e9cbdd
86980494df18137ab695bdf4b538e5ebc23c3947
+3 -1
View File
@@ -48,7 +48,7 @@ sqs_trigger = ["dep:windmill-trigger-sqs", "windmill-store/sqs_trigger"]
gcp_trigger = ["dep:windmill-trigger-gcp", "windmill-store/gcp_trigger"]
azure_trigger = ["dep:windmill-trigger-azure", "windmill-store/azure_trigger"]
cloud = ["windmill-common/cloud", "windmill-api-auth/cloud", "windmill-store/cloud", "windmill-api-workspaces/cloud"]
mcp = ["dep:windmill-mcp", "windmill-mcp/server", "windmill-mcp/auth", "windmill-api-auth/mcp", "windmill-store/mcp"]
mcp = ["dep:windmill-mcp", "dep:image", "dep:image-webp", "windmill-mcp/server", "windmill-mcp/auth", "windmill-api-auth/mcp", "windmill-store/mcp"]
bedrock = ["windmill-ai/bedrock"]
python = ["windmill-dep-map/python", "dep:windmill-parser-py", "dep:windmill-parser-py-imports", "windmill-api-scripts/python", "windmill-api-configs/python", "windmill-api-agent-workers?/python", "windmill-trigger/python", "windmill-common/python"]
no_auth = ["windmill-api-auth/no_auth", "windmill-store/no_auth", "windmill-api-users/no_auth"]
@@ -107,6 +107,8 @@ chrono.workspace = true
hex.workspace = true
base64.workspace = true
base32.workspace = true
image = { workspace = true, optional = true }
image-webp = { workspace = true, optional = true }
serde_urlencoded.workspace = true
serde_yml.workspace = true
cron.workspace = true
@@ -0,0 +1,382 @@
//! Image files handed to an MCP client's model: a file within the limits as it is, a file past
//! them as a JPEG copy, and why an image is left out. Which results are images is `runs.rs`'s.
use std::time::Duration;
use tokio::sync::{Semaphore, SemaphorePermit};
use super::ToolImage;
/// The largest image handed to the model, in bytes. Its base64 is at most 5,000,000
/// characters: the 5 MB per image that Claude takes on Amazon Bedrock, the lowest of its
/// platforms (the Claude API takes 10 MB).
pub(super) const MAX_IMAGE_BYTES: usize = 3_750_000;
/// The largest file read to be copied, and its base64 in characters.
pub(super) const MAX_SOURCE_BYTES: usize = 30_000_000;
pub(super) const MAX_SOURCE_CHARS: usize = MAX_SOURCE_BYTES / 3 * 4;
/// A server reads this many images at once, from the read of a file to the end of its copy:
/// each holds its file, up to 30 MB, and decoding the largest peaks at about 200 MB. A call
/// that waits longer than `READ_WAIT` leaves its image out rather than queue.
static READ_SLOTS: Semaphore = Semaphore::const_new(2);
const READ_WAIT: Duration = Duration::from_secs(5);
pub(super) type ReadSlot = SemaphorePermit<'static>;
pub(super) async fn read_slot() -> Result<ReadSlot, Unattached> {
match tokio::time::timeout(READ_WAIT, READ_SLOTS.acquire()).await {
Ok(Ok(slot)) => Ok(slot),
_ => Err(Unattached {
key: "busy",
why: "the server is busy reading other images, call get_run again".to_string(),
}),
}
}
/// An image as the model is handed it, and for a file past the limits, the copy it is.
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
pub(super) struct Attachment {
pub image: ToolImage,
pub copy: Option<String>,
}
/// Why an image is left out of an answer: what the model reads, and the `feature_usage`
/// key it counts under.
#[derive(Debug)]
pub(super) struct Unattached {
pub key: &'static str,
pub why: String,
}
pub(super) fn too_large() -> Unattached {
let why = format!("larger than {} MB", MAX_SOURCE_BYTES as f64 / 1e6);
Unattached { key: "too_large", why }
}
pub(super) fn not_image(why: &str) -> Unattached {
Unattached { key: "not_image", why: why.to_string() }
}
pub(super) fn unreadable(why: String) -> Unattached {
Unattached { key: "unreadable", why }
}
/// An image of a result's base64, `slot` held when its read took one.
pub(super) async fn decode_inline_image(
data: &str,
slot: Option<ReadSlot>,
) -> Result<Attachment, Unattached> {
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD};
use base64::Engine;
let data: String = data.chars().filter(|c| !matches!(c, '\n' | '\r')).collect();
let bytes = STANDARD
.decode(&data)
.or_else(|_| STANDARD_NO_PAD.decode(&data))
.map_err(|_| not_image("its content is not base64"))?;
image_from_bytes(bytes, slot).await
}
/// A file within the limits as it is, a file past them as a JPEG copy, made holding `slot`,
/// or one taken here. The header is read first, so an image already in the result and within
/// the limits never waits for another's copy.
#[cfg(feature = "mcp")]
pub(super) async fn image_from_bytes(
bytes: Vec<u8>,
slot: Option<ReadSlot>,
) -> Result<Attachment, Unattached> {
let (bytes, format, as_is) = blocking(move || {
let format = image_format(&bytes)?;
let as_is = image_as_is(&bytes, format)?;
Ok((bytes, format, as_is))
})
.await?;
if let Some(attachment) = as_is {
return Ok(attachment);
}
let slot = match slot {
Some(slot) => slot,
None => read_slot().await?,
};
blocking(move || {
// Held until the decoding ends, also when the answer is no longer awaited.
let _slot = slot;
image_copy(&bytes, format)
})
.await
}
/// Only an MCP client is handed images, and the image crates are built only with it.
#[cfg(not(feature = "mcp"))]
pub(super) async fn image_from_bytes(
_bytes: Vec<u8>,
_slot: Option<ReadSlot>,
) -> Result<Attachment, Unattached> {
Err(unreadable(
"images are read only for MCP clients".to_string(),
))
}
/// The widest or tallest image handed to the model: the Claude API refuses a larger one, and
/// with it the whole request.
#[cfg(feature = "mcp")]
const MAX_IMAGE_SIDE: u32 = 8000;
/// The longest side of the JPEG copy handed for an image past either limit: the most Claude
/// reads, which scales a larger image down itself.
#[cfg(feature = "mcp")]
const COPY_SIDE: u32 = 2576;
/// The most memory an image copied takes decoded: a 6000x4000 RGBA image, or a 42 MP photo.
#[cfg(feature = "mcp")]
const MAX_DECODED_BYTES: u64 = 128_000_000;
/// The most a decoder allocates besides the pixels, for the file's metadata mostly. A PNG's
/// color profile is compressed, and the decoder's default allowance (512 MiB) lets a file of
/// a few hundred KB inflate it to hundreds of MB.
#[cfg(feature = "mcp")]
const MAX_METADATA_BYTES: u64 = 16_000_000;
/// A file's type, read from its bytes: the key or extension only says an image is worth
/// reading, and a provider can refuse the whole request for an image whose bytes are not the
/// type it is sent as.
#[cfg(feature = "mcp")]
fn image_format(bytes: &[u8]) -> Result<image::ImageFormat, Unattached> {
use image::ImageFormat;
image::guess_format(bytes)
.ok()
.filter(|format| {
matches!(
format,
ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::Gif | ImageFormat::WebP
)
})
.ok_or_else(|| not_image("not a PNG, JPEG, GIF or WebP file"))
}
/// The file itself, when it is within the limits.
#[cfg(feature = "mcp")]
fn image_as_is(bytes: &[u8], format: image::ImageFormat) -> Result<Option<Attachment>, Unattached> {
use base64::Engine;
let (width, height) = image_reader(bytes, format)
.into_dimensions()
.map_err(|_| not_image("its width and height cannot be read"))?;
if bytes.len() > MAX_IMAGE_BYTES || width.max(height) > MAX_IMAGE_SIDE {
return Ok(None);
}
let data = base64::engine::general_purpose::STANDARD.encode(bytes);
let image = ToolImage { data, mime_type: format.to_mime_type() };
Ok(Some(Attachment { image, copy: None }))
}
/// Work that takes CPU time, run off the async threads. A decoder that panics leaves the
/// image out.
#[cfg(feature = "mcp")]
async fn blocking<T: Send + 'static>(
work: impl FnOnce() -> Result<T, Unattached> + Send + 'static,
) -> Result<T, Unattached> {
tokio::task::spawn_blocking(work)
.await
.unwrap_or_else(|_| Err(not_image("it cannot be decoded")))
}
/// A reader whose decoder allocates at most `MAX_METADATA_BYTES` besides the pixels.
#[cfg(feature = "mcp")]
fn image_reader(
bytes: &[u8],
format: image::ImageFormat,
) -> image::ImageReader<std::io::Cursor<&[u8]>> {
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_METADATA_BYTES);
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format);
reader.limits(limits);
reader
}
/// A JPEG copy of an image, at most `COPY_SIDE` on its longest side and its quality lowered
/// until it is within `MAX_IMAGE_BYTES`.
#[cfg(feature = "mcp")]
fn image_copy(bytes: &[u8], format: image::ImageFormat) -> Result<Attachment, Unattached> {
use base64::Engine;
use image::codecs::jpeg::JpegEncoder;
use image::metadata::Orientation;
use image::{DynamicImage, ImageDecoder};
let undecodable =
|error: image::ImageError| not_image(&format!("it cannot be decoded: {error}"));
let mut decoder = image_reader(bytes, format)
.into_decoder()
.map_err(undecodable)?;
let (mut width, mut height) = decoder.dimensions();
if decoder.total_bytes() > MAX_DECODED_BYTES {
let why = format!("{width}x{height} px, too large to decode");
return Err(Unattached { key: "too_large", why });
}
let orientation = match format {
image::ImageFormat::WebP => webp_orientation(bytes),
_ => decoder.orientation().ok(),
}
.unwrap_or(Orientation::NoTransforms);
let mut pixels = DynamicImage::from_decoder(decoder).map_err(undecodable)?;
if width.max(height) > COPY_SIDE {
pixels = pixels.thumbnail(COPY_SIDE, COPY_SIDE);
}
// The copy keeps no EXIF data, so a photo taken sideways is turned as viewers show it.
pixels.apply_orientation(orientation);
if matches!(
orientation,
Orientation::Rotate90
| Orientation::Rotate270
| Orientation::Rotate90FlipH
| Orientation::Rotate270FlipH
) {
(width, height) = (height, width);
}
let pixels = over_white(pixels);
for quality in [85, 70, 50, 30] {
let mut jpeg = Vec::new();
JpegEncoder::new_with_quality(&mut jpeg, quality)
.encode_image(&pixels)
.map_err(|error| unreadable(format!("its copy cannot be encoded: {error}")))?;
if jpeg.len() <= MAX_IMAGE_BYTES {
let data = base64::engine::general_purpose::STANDARD.encode(&jpeg);
let (copy_width, copy_height) = pixels.dimensions();
let copy =
format!("a {copy_width}x{copy_height} JPEG copy of the {width}x{height} px file");
let image = ToolImage { data, mime_type: "image/jpeg" };
return Ok(Attachment { image, copy: Some(copy) });
}
}
let why = format!(
"larger than {} MB even as a JPEG copy",
MAX_IMAGE_BYTES as f64 / 1e6
);
Err(Unattached { key: "too_large", why })
}
/// A WebP's orientation, from its EXIF chunk. image's WebP decoder ignores `max_alloc`, and
/// allocates an EXIF chunk at the length its header declares, up to 4 GB, before reading it,
/// so the chunk is read through image-webp with the metadata limit.
#[cfg(feature = "mcp")]
fn webp_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).ok()?;
decoder.set_memory_limit(MAX_METADATA_BYTES as usize);
image::metadata::Orientation::from_exif_chunk(&decoder.exif_metadata().ok()??)
}
/// An image's pixels as RGB, its transparent parts over white: a JPEG keeps no transparency,
/// and the color under it is often black, the color of the text drawn on it.
#[cfg(feature = "mcp")]
fn over_white(pixels: image::DynamicImage) -> image::RgbImage {
if !pixels.has_alpha() {
return pixels.into_rgb8();
}
let rgba = pixels.into_rgba8();
image::RgbImage::from_fn(rgba.width(), rgba.height(), |x, y| {
let [r, g, b, a] = rgba.get_pixel(x, y).0.map(u32::from);
let over = |c: u32| ((c * a + 255 * (255 - a)) / 255) as u8;
image::Rgb([over(r), over(g), over(b)])
})
}
#[cfg(all(test, feature = "mcp"))]
mod tests {
use super::*;
/// A black JPEG of `width` x `height`.
fn jpeg(width: u32, height: u32) -> Vec<u8> {
let mut file = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut file)
.encode_image(&image::RgbImage::new(width, height))
.unwrap();
file
}
fn decoded(attachment: &Attachment) -> image::DynamicImage {
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD
.decode(&attachment.image.data)
.unwrap();
image::load_from_memory(&bytes).unwrap()
}
#[tokio::test]
async fn an_image_within_the_limits_is_sent_as_the_type_its_bytes_are() {
use base64::Engine;
// A `{"png": ...}` holding a JPEG goes out as one, unchanged but for its line breaks.
let data = base64::engine::general_purpose::STANDARD.encode(jpeg(3, 2));
let wrapped = format!("{}\n{}", &data[..8], &data[8..]);
let sent = decode_inline_image(&wrapped, None).await.unwrap();
assert_eq!(
(sent.image.mime_type, sent.image.data.as_str(), sent.copy),
("image/jpeg", data.as_str(), None)
);
let page = decode_inline_image("PGh0bWw+", None).await;
assert!(matches!(page, Err(Unattached { key: "not_image", .. })));
}
#[tokio::test]
async fn an_image_past_the_limits_is_sent_as_a_jpeg_copy() {
// EXIF orientation 6, a photo taken sideways: the copy is turned as viewers show it.
let exif = b"\xff\xe1\0\x22Exif\0\0MM\0\x2a\0\0\0\x08\0\x01\x01\x12\0\x03\0\0\0\x01\0\x06\0\0\0\0\0\0";
let file = jpeg(9000, 10);
let sideways = [&file[..2], exif.as_slice(), &file[2..]].concat();
let sent = image_from_bytes(sideways, None).await.unwrap();
assert_eq!(
sent.copy.as_deref(),
Some("a 3x2576 JPEG copy of the 10x9000 px file")
);
let copy = decoded(&sent);
assert_eq!(
(sent.image.mime_type, copy.width(), copy.height()),
("image/jpeg", 3, 2576)
);
// Transparent parts are drawn over white.
let mut png = Vec::new();
image::RgbaImage::new(9000, 2)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let copy = decoded(&image_from_bytes(png, None).await.unwrap()).to_rgb8();
assert!(copy.pixels().all(|pixel| pixel.0.iter().all(|&c| c > 250)));
// An image too large to decode is refused from its header: a 10000x10000 GIF.
let gif = b"GIF89a\x10\x27\x10\x27\0\0\0,\0\0\0\0\x10\x27\x10\x27\0\x02\x02\x44\x01\0;";
let refused = image_from_bytes(gif.to_vec(), None).await;
assert!(matches!(refused, Err(Unattached { key: "too_large", .. })));
}
#[test]
fn a_color_profile_past_the_metadata_limit_is_dropped() {
use image::{ImageDecoder, ImageEncoder};
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
encoder
.set_icc_profile(vec![0; MAX_METADATA_BYTES as usize + 1])
.unwrap();
encoder
.write_image(&[0; 3], 1, 1, image::ExtendedColorType::Rgb8)
.unwrap();
let mut decoder = image_reader(&png, image::ImageFormat::Png)
.into_decoder()
.unwrap();
assert_eq!(decoder.icc_profile().unwrap(), None);
}
#[test]
fn a_webp_exif_chunk_past_the_metadata_limit_is_not_read() {
use image::ImageEncoder;
// EXIF orientation 6: viewers turn the image a quarter turn clockwise.
let mut exif = b"II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0".to_vec();
let copy = |exif: &[u8]| {
let mut webp = Vec::new();
let mut encoder = image::codecs::webp::WebPEncoder::new_lossless(&mut webp);
encoder.set_exif_metadata(exif.to_vec()).unwrap();
encoder
.write_image(&[0; 6], 2, 1, image::ExtendedColorType::Rgb8)
.unwrap();
image_copy(&webp, image::ImageFormat::WebP)
.unwrap()
.copy
.unwrap()
};
assert_eq!(copy(&exif), "a 1x2 JPEG copy of the 1x2 px file");
exif.resize(MAX_METADATA_BYTES as usize + 1, 0);
assert_eq!(copy(&exif), "a 2x1 JPEG copy of the 2x1 px file");
}
}
+107 -20
View File
@@ -64,6 +64,7 @@ mod data;
mod deploy;
mod flows;
mod guidance;
mod images;
#[cfg(feature = "mcp")]
mod instructions;
mod items;
@@ -254,6 +255,14 @@ pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator<Item = ToolI
/// What a tool hands back: the text the model reads, or the message of a failed call.
pub(super) type ToolResult = Result<String, String>;
/// An image the model reads beside a tool's text: an MCP `image` content block.
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
pub(crate) struct ToolImage {
/// Standard base64.
pub data: String,
pub mime_type: &'static str,
}
/// The caller, and the API reached as them.
pub(crate) struct Ctx<'a> {
pub auth: &'a ApiAuthed,
@@ -273,6 +282,8 @@ pub(crate) struct Ctx<'a> {
/// What the card draws of this call, as `(key, value)`: returned in the result's
/// `_meta`, which the model never reads.
pub view: std::sync::Mutex<Option<(&'static str, Value)>>,
/// The images the model reads beside the text, returned as MCP content blocks.
pub images: std::sync::Mutex<Vec<ToolImage>>,
}
impl<'a> Ctx<'a> {
@@ -293,9 +304,17 @@ impl<'a> Ctx<'a> {
effects: Default::default(),
jwt: Default::default(),
view: Default::default(),
images: Default::default(),
}
}
/// Whether the model reads images beside the text. The chat's providers take a tool
/// result as text only (OpenAI's tool messages cannot carry an image), so only an MCP
/// client is handed any.
pub(super) fn reads_images(&self) -> bool {
self.surface == Surface::Mcp
}
/// Hand the chat something to apply. A no-op for MCP, which has no editor.
pub(super) fn effect(&self, effect: chat::Effect) {
if self.surface == Surface::Chat {
@@ -329,6 +348,43 @@ impl Ctx<'_> {
body: Option<Value>,
timeout: std::time::Duration,
) -> ToolResult {
let (status, bytes) = self.send(method, path, body, timeout, usize::MAX).await?;
let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default()).into_owned();
match status.is_success() {
true => Ok(text),
false => Err(api_error(status, &text)),
}
}
/// `GET` an answer as bytes, at most `max_bytes` of them: `None` for a longer answer,
/// which is not read past the limit.
pub async fn get_bytes(
&self,
path: &str,
max_bytes: usize,
) -> Result<Option<bytes::Bytes>, String> {
let (status, bytes) = self
.send("GET", path, None, REQUEST_TIMEOUT, max_bytes)
.await?;
match status.is_success() {
true => Ok(bytes),
false => {
let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default());
Err(api_error(status, &text))
}
}
}
/// Call the API as the caller and read at most `max_bytes` of the answer: `None` past
/// that.
async fn send(
&self,
method: &str,
path: &str,
body: Option<Value>,
timeout: std::time::Duration,
max_bytes: usize,
) -> Result<(http::StatusCode, Option<bytes::Bytes>), String> {
let url = guarded_url(self.base_internal_url, self.w_id, method, path, self.access)?;
// No route scope: this server only admits `mcp:all`, several routes (hub, embeddings)
// map to none, and `guarded_url` is what keeps a call on its route. The tag fence
@@ -347,21 +403,15 @@ impl Ctx<'_> {
.unwrap()
.get(self.base_internal_url)
.cloned();
let (status, text) = match router {
match router {
Some(router) => {
self.call_router(router, method, &url, body, scopes, timeout)
.await?
self.call_router(router, method, &url, body, scopes, timeout, max_bytes)
.await
}
None => {
self.call_http(method, &url, body, scopes, timeout, max_bytes)
.await
}
None => self.call_http(method, &url, body, scopes, timeout).await?,
};
if status.is_success() {
Ok(text)
} else if text.trim().is_empty() {
// What a browser's request reports for an answer with no body.
let reason = status.canonical_reason().unwrap_or_default();
Err(format!("{}: {reason}", status.as_u16()))
} else {
Err(format!("{}: {}", status.as_u16(), text))
}
}
@@ -375,7 +425,8 @@ impl Ctx<'_> {
body: Option<Value>,
scopes: Option<Vec<String>>,
timeout: std::time::Duration,
) -> Result<(http::StatusCode, String), String> {
max_bytes: usize,
) -> Result<(http::StatusCode, Option<bytes::Bytes>), String> {
use tower::ServiceExt;
let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?;
// The router does not see the base URL's own path prefix.
@@ -405,10 +456,8 @@ impl Ctx<'_> {
tokio::time::timeout(timeout, async {
let Ok(response) = router.oneshot(request).await;
let status = response.status();
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.map_err(|e| e.to_string())?;
Ok((status, String::from_utf8_lossy(&bytes).into_owned()))
let body = read_capped(response.into_body().into_data_stream(), max_bytes).await?;
Ok((status, body))
})
.await
.map_err(|_| format!("Failed to execute request: {method} {url} timed out"))?
@@ -422,7 +471,8 @@ impl Ctx<'_> {
body: Option<Value>,
scopes: Option<Vec<String>>,
timeout: std::time::Duration,
) -> Result<(http::StatusCode, String), String> {
max_bytes: usize,
) -> Result<(http::StatusCode, Option<bytes::Bytes>), String> {
let method = http::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?;
let token = self
.jwt
@@ -441,7 +491,14 @@ impl Ctx<'_> {
.await
.map_err(|e| format!("Failed to execute request: {e}"))?;
let status = response.status();
Ok((status, response.text().await.map_err(|e| e.to_string())?))
if response
.content_length()
.is_some_and(|len| len > max_bytes as u64)
{
return Ok((status, None));
}
let body = read_capped(response.bytes_stream(), max_bytes).await?;
Ok((status, body))
}
pub async fn get(&self, path: &str) -> Result<Value, String> {
@@ -499,6 +556,36 @@ impl Ctx<'_> {
}
}
/// A failed API call as the session reads it: the status code, then the answer.
fn api_error(status: http::StatusCode, body: &str) -> String {
if body.trim().is_empty() {
// What a browser's request reports for an answer with no body.
let reason = status.canonical_reason().unwrap_or_default();
format!("{}: {reason}", status.as_u16())
} else {
format!("{}: {body}", status.as_u16())
}
}
/// A body read in full while it stays within `max` bytes: `None` once it passes that,
/// without reading the rest.
async fn read_capped<E: std::fmt::Display>(
stream: impl futures::Stream<Item = Result<bytes::Bytes, E>>,
max: usize,
) -> Result<Option<bytes::Bytes>, String> {
use futures::StreamExt;
let mut stream = std::pin::pin!(stream);
let mut body = bytes::BytesMut::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| e.to_string())?;
if body.len().saturating_add(chunk.len()) > max {
return Ok(None);
}
body.extend_from_slice(&chunk);
}
Ok(Some(body.freeze()))
}
/// Routes outside the workspace that a tool reads.
const INSTANCE_ROUTES: &[&str] = &[
"/docs/",
+461 -40
View File
@@ -7,6 +7,10 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use super::chat::{Effect, RunPhase};
use super::images::{
decode_inline_image, image_from_bytes, not_image, read_slot, too_large, unreadable, Attachment,
Unattached, MAX_IMAGE_BYTES, MAX_SOURCE_BYTES, MAX_SOURCE_CHARS,
};
use super::workspace::{
api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc,
};
@@ -216,6 +220,9 @@ pub(super) async fn finish_run(
"\n\nFor per-step statuses and results (subflow steps included), call get_run with id=\"{id}\"."
));
}
if ctx.reads_images() {
summary.push_str(&image_hint(&id, job.get("result")).unwrap_or_default());
}
summary.push_str(&run_page);
Ok(summary)
}
@@ -2311,10 +2318,15 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
enc(step)
);
let response = ctx.get(&route).await?;
if let Some(job_id) = finished_step_job(&response) {
let finished = finished_step_job(&response);
if let Some(job_id) = finished {
ctx.effect(Effect::InspectedRun { job_id: job_id.to_string() });
}
return Ok(step_result(&response, step));
let images = match finished.filter(|_| ctx.reads_images() && !card) {
Some(job_id) => step_images(ctx, job_id, &response["entries"][0]).await,
None => None,
};
return Ok(step_result(&response, step, images.as_ref()));
}
// Only the job read is load-bearing: logs and the step tree each answer part of
@@ -2396,7 +2408,12 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
None => report_run(ctx, id, Some(job), details),
}
}
let run = shape_run(id, &job?, logs, &results);
let job = job?;
let images = match ctx.reads_images() && !card {
true => attach_result_images(ctx, id, job.get("result"), results["entries"].get(0)).await,
false => None,
};
let run = shape_run(id, &job, logs, &results, images.as_ref());
ctx.effect(Effect::InspectedRun { job_id: id.to_string() });
Ok(match ctx.link(&format!("/run/{}", enc(id))) {
Some(url) => format!("{run}\n\nRun page: {url}"),
@@ -2404,6 +2421,24 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
})
}
/// The kind of image a result the job read swapped for a marker looks like (`png`, `jpeg`,
/// `gif` or `svg`), from the head of it the step tree carries, and the result's length in
/// characters.
fn too_big_image<'a>(result: Option<&Value>, root: Option<&'a Value>) -> Option<(&'a str, u64)> {
if result? != TOO_BIG {
return None;
}
let root = root?;
let kind = root["result_prefix"]
.as_str()?
.strip_prefix("{\"")?
.split('"')
.next()?;
["png", "jpeg", "gif", "svg"]
.contains(&kind)
.then_some((kind, root["result_length"].as_u64()?))
}
/// The job read swaps a result past ~90 KB for a marker, so an image under the card's cap
/// is read again by its one field. The step tree's head of the result says which it is.
async fn big_image_result(
@@ -2412,29 +2447,30 @@ async fn big_image_result(
job: &Value,
root: Option<&Value>,
) -> Option<Value> {
if job.get("result")? != TOO_BIG {
return None;
}
let root = root?;
let kind = root["result_prefix"]
.as_str()?
.strip_prefix("{\"")?
.split('"')
.next()?;
if !["png", "jpeg", "gif", "svg"].contains(&kind)
|| root["result_length"].as_u64()? > CARD_IMAGE_CHARS as u64 + 64
{
let (kind, length) = too_big_image(job.get("result"), root)?;
if length > CARD_IMAGE_CHARS as u64 + 64 {
return None;
}
read_whole_image(ctx, id, kind, length).await.ok().flatten()
}
/// A swapped result read again by its one field `kind`, `length` being the result's text in
/// characters: `None` when the result holds more than that field.
async fn read_whole_image(
ctx: &Ctx<'_>,
id: &str,
kind: &str,
length: u64,
) -> Result<Option<Value>, String> {
let route = ctx.ws(&format!(
"jobs/completed/get_result/{}?json_path={kind}",
enc(id)
));
let field = ctx.get(&route).await.ok()?;
let field = ctx.get(&route).await?;
// The field alone must be the whole result, as `card_image` requires: a result with more
// keys is no image, and keeps its marker. The length is the result's text, in characters.
let whole = json!({ kind: field });
(jsonb_text_len(&whole) == root["result_length"].as_u64()?).then_some(whole)
Ok((jsonb_text_len(&whole) == length).then_some(whole))
}
/// The length in characters of a value as PostgreSQL prints a jsonb: `", "` between items
@@ -2457,6 +2493,316 @@ fn jsonb_text_len(value: &Value) -> u64 {
}
}
// ============================================================================
// Images the model reads: a result Windmill draws as an image, attached to
// `get_run`'s answer for an MCP client.
// ============================================================================
/// The images one answer carries at most, and their bytes together.
const MAX_IMAGES: usize = 4;
const MAX_IMAGES_BYTES: usize = 2 * MAX_IMAGE_BYTES;
/// The object storage files the run page draws as an image, and GIFs, which models read.
const IMAGE_EXTENSIONS: [&str; 5] = [".png", ".jpg", ".jpeg", ".gif", ".webp"];
/// Where an image result's bytes are.
#[derive(Debug, PartialEq)]
enum ImageRef<'a> {
/// Base64 in the result itself, under the kind its key names.
Inline { kind: &'a str, data: &'a str },
/// A file in the workspace's object storage.
S3 { key: &'a str, storage: Option<&'a str> },
}
/// The images a result is, in the shapes the run page draws as one: `{png|jpeg|gif}` of
/// base64, a file in object storage with an image extension, or a list of such files.
fn image_refs(result: &Value) -> Vec<ImageRef<'_>> {
match result.as_array() {
// The run page lists files only when every item is one, up to 100 of them.
Some(items)
if items.len() <= 100
&& items
.iter()
.all(|item| item.is_object() && s3_file(item).is_some()) =>
{
items.iter().filter_map(s3_image).collect()
}
Some(_) => Vec::new(),
None => inline_image(result)
.or_else(|| s3_image(result))
.into_iter()
.collect(),
}
}
/// The object storage file a value names, `{s3, storage?}` or `s3://<storage>/<key>`, as
/// its key and storage.
fn s3_file(value: &Value) -> Option<(&str, Option<&str>)> {
let (key, storage) = match value {
Value::String(uri) => {
let (storage, key) = uri.strip_prefix("s3://")?.split_once('/')?;
(key, Some(storage))
}
Value::Object(file) => (
file.get("s3")?.as_str()?,
file.get("storage").and_then(Value::as_str),
),
_ => return None,
};
(!key.is_empty()).then_some((key, storage.filter(|s| !s.is_empty())))
}
fn s3_image(value: &Value) -> Option<ImageRef<'_>> {
let (key, storage) = s3_file(value)?;
let lower = key.to_ascii_lowercase();
IMAGE_EXTENSIONS
.iter()
.any(|ext| lower.ends_with(ext))
.then_some(ImageRef::S3 { key, storage })
}
/// A one-key result's value as text, bare or as a file's `content`: how a script returns
/// an image or a page inline, as `{"png": "<base64>"}`.
fn single_file(result: &Value) -> Option<(&str, &str)> {
let [(kind, value)] = result.as_object()?.iter().collect::<Vec<_>>()[..] else {
return None;
};
let data = value
.as_str()
.or_else(|| value.get("content").and_then(Value::as_str))
.filter(|d| !d.is_empty())?;
Some((kind.as_str(), data))
}
fn is_base64(data: &str) -> bool {
data.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'\n' | b'\r'))
}
fn inline_image(result: &Value) -> Option<ImageRef<'_>> {
let (kind, data) = single_file(result)?;
(matches!(kind, "png" | "jpeg" | "gif") && is_base64(data))
.then_some(ImageRef::Inline { kind, data })
}
/// What `get_run` writes beside a result's images: under `key`, what became of them, and
/// for an inline image the label standing in for its base64, which tells the model nothing.
struct ImageNote {
key: &'static str,
text: String,
label: Option<String>,
}
fn image_label(kind: &str) -> String {
format!("{} image", kind.to_uppercase())
}
/// Attach the images `result` is, `entry` being its job's entry in the step tree, which
/// says what a result the job read swapped for a marker was. `None` for a result that is no
/// image. A failed read leaves its image out and says why; it never fails the answer.
async fn attach_result_images(
ctx: &Ctx<'_>,
job_id: &str,
result: Option<&Value>,
entry: Option<&Value>,
) -> Option<ImageNote> {
let result = result?;
let swapped = too_big_image(Some(result), entry).filter(|(kind, _)| *kind != "svg");
let (label, total, reads) = match swapped {
Some((kind, length)) => {
let read = read_swapped_image(ctx, job_id, kind, length).await?;
(Some(image_label(kind)), 1, vec![(None, read)])
}
None => {
let refs = image_refs(result);
let label = match refs.first()? {
ImageRef::Inline { kind, .. } => Some(image_label(kind)),
ImageRef::S3 { .. } => None,
};
// One after another, so an answer holds one of the server's read slots at a time.
let mut reads = Vec::new();
for image in refs.iter().take(MAX_IMAGES) {
let name = match image {
ImageRef::S3 { key, .. } => Some(*key),
ImageRef::Inline { .. } => None,
};
reads.push((name, read_image(ctx, image).await));
}
(label, refs.len(), reads)
}
};
let mut budget = MAX_IMAGES_BYTES;
let outcomes: Vec<(Option<&str>, Result<Option<String>, String>)> = reads
.into_iter()
.map(|(name, read)| {
let outcome = read.and_then(|Attachment { image, copy }| {
let bytes = image.data.len() / 4 * 3;
if bytes > budget {
let why = format!(
"this answer already carries {} MB of images",
MAX_IMAGES_BYTES as f64 / 1e6
);
return Err(Unattached { key: "too_large", why });
}
budget -= bytes;
ctx.images.lock().unwrap().push(image);
Ok(copy)
});
// Only an object storage file is named, by its key.
let source = if name.is_some() { "s3" } else { "inline" };
let key = match &outcome {
Ok(Some(_)) => "copy",
Ok(None) => source,
Err(skip) => skip.key,
};
windmill_common::feature_usage::log_feature_usage("mcp_workspace", "result_image", key);
(name, outcome.map_err(|skip| skip.why))
})
.collect();
Some(ImageNote {
key: if result.is_array() {
"result_images"
} else {
"result_image"
},
text: image_note_text(&outcomes, total, result.is_array()),
label,
})
}
fn image_note_text(
outcomes: &[(Option<&str>, Result<Option<String>, String>)],
total: usize,
listed: bool,
) -> String {
if !listed {
return match outcomes.first().map(|(_, outcome)| outcome) {
Some(Err(why)) => format!("not attached: {why}"),
Some(Ok(Some(copy))) => format!("attached as {copy}"),
_ => "attached".to_string(),
};
}
let attached = outcomes.iter().filter(|(_, o)| o.is_ok()).count();
let mut text = format!("{attached} of {total} images attached");
for (name, outcome) in outcomes {
if let Ok(Some(copy)) = outcome {
text.push_str(&format!("; {} as {copy}", name.unwrap_or("image")));
}
}
let failed: Vec<String> = outcomes
.iter()
.filter_map(|(name, outcome)| {
let why = outcome.as_ref().err()?;
Some(format!("{} ({why})", name.unwrap_or("image")))
})
.collect();
if !failed.is_empty() {
text.push_str(&format!("; not attached: {}", failed.join(", ")));
}
if total > outcomes.len() {
text.push_str(&format!(
"; an answer carries at most {MAX_IMAGES}, the rest are on the run page"
));
}
text
}
/// One image as the model is handed it, or why not.
async fn read_image(ctx: &Ctx<'_>, image: &ImageRef<'_>) -> Result<Attachment, Unattached> {
match *image {
ImageRef::Inline { data, .. } => decode_inline_image(data, None).await,
ImageRef::S3 { key, storage } => read_s3_image(ctx, key, storage).await,
}
}
/// An inline image the job read swapped for a marker, read again by its one field. `None`
/// when the result holds more than that field, and so is no image.
async fn read_swapped_image(
ctx: &Ctx<'_>,
job_id: &str,
kind: &str,
length: u64,
) -> Option<Result<Attachment, Unattached>> {
if length > MAX_SOURCE_CHARS as u64 + 64 {
return Some(Err(too_large()));
}
let slot = match read_slot().await {
Ok(slot) => slot,
Err(busy) => return Some(Err(busy)),
};
let whole = match read_whole_image(ctx, job_id, kind, length).await {
Ok(whole) => whole?,
Err(error) => {
let why = format!("its read failed: {}", js_head(api_message(&error), 300));
return Some(Err(unreadable(why)));
}
};
Some(match inline_image(&whole) {
Some(ImageRef::Inline { data, .. }) => decode_inline_image(data, Some(slot)).await,
_ => Err(not_image("its content is not base64")),
})
}
/// A file of the workspace's object storage, read as the caller through the route the run
/// page previews it with, so the same storage permission rules apply.
async fn read_s3_image(
ctx: &Ctx<'_>,
key: &str,
storage: Option<&str>,
) -> Result<Attachment, Unattached> {
if !cfg!(all(feature = "private", feature = "parquet")) {
let why = "reading object storage needs Windmill Enterprise Edition";
return Err(unreadable(why.to_string()));
}
let storage = storage
.map(|s| format!("&storage={}", enc(s)))
.unwrap_or_default();
let route = ctx.ws(&format!(
"job_helpers/load_image_preview?file_key={}{storage}",
enc(key)
));
let slot = read_slot().await?;
match ctx.get_bytes(&route, MAX_SOURCE_BYTES).await {
Ok(Some(bytes)) => image_from_bytes(bytes.into(), Some(slot)).await,
Ok(None) => Err(too_large()),
Err(error) => Err(unreadable(format!(
"object storage answered: {}",
js_head(api_message(&error), 300)
))),
}
}
/// The images of a finished step's result. Its entry carries the whole result when it is
/// short, and only its head otherwise.
async fn step_images(ctx: &Ctx<'_>, job_id: &str, entry: &Value) -> Option<ImageNote> {
let prefix = entry["result_prefix"].as_str()?;
let whole = entry["result_length"]
.as_u64()
.is_none_or(|length| length == prefix.chars().count() as u64);
let result = match whole {
true => serde_json::from_str(prefix).ok()?,
false => json!(TOO_BIG),
};
attach_result_images(ctx, job_id, Some(&result), Some(entry)).await
}
/// What a run tool adds about a result only `get_run` attaches: an image, or a result too
/// big to show, which may be one.
fn image_hint(id: &str, result: Option<&Value>) -> Option<String> {
let result = result?;
if result == TOO_BIG {
return Some(format!(
"\n\nThe result is too large to show here. If it is an image, get_run with id=\"{id}\" attaches it."
));
}
if image_refs(result).is_empty() {
return None;
}
Some(match result.is_array() {
true => format!("\n\nThe result lists images: call get_run with id=\"{id}\" to see them."),
false => format!("\n\nThe result is an image: call get_run with id=\"{id}\" to see it."),
})
}
/// The end of a job's log, read without the rest of it: an offset past the end returns
/// no log but where it ends, and a second read starts just before that. A log grows as long
/// as its job runs, and the card asks again on every refresh. The result stream's offset is
@@ -2933,19 +3279,9 @@ fn describe_result(result: &Value) -> Option<String> {
/// An image result as Windmill draws it, for the card to draw too: base64 for PNG, JPEG and
/// GIF, the markup itself for SVG, either bare or as a file's `content`.
fn card_image(result: &Value) -> Option<Value> {
let [(kind, value)] = result.as_object()?.iter().collect::<Vec<_>>()[..] else {
return None;
};
let data = value
.as_str()
.or_else(|| value.get("content").and_then(Value::as_str))
.filter(|d| !d.is_empty() && d.len() <= CARD_IMAGE_CHARS)?;
let base64 = |d: &str| {
d.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'\n' | b'\r'))
};
match kind.as_str() {
"png" | "jpeg" | "gif" if base64(data) => Some(json!({ "type": kind, "data": data })),
let (kind, data) = single_file(result).filter(|(_, data)| data.len() <= CARD_IMAGE_CHARS)?;
match kind {
"png" | "jpeg" | "gif" if is_base64(data) => Some(json!({ "type": kind, "data": data })),
"svg" => Some(json!({ "type": "svg", "data": data })),
_ => None,
}
@@ -3094,8 +3430,14 @@ fn run_card(id: &str, job: Option<&Value>) -> Map<String, Value> {
/// A run as `get_run` reports it: its summary, args, result and logs around the step
/// tree. `logs` is the log read's own outcome, so a failed read is told apart from an
/// empty log.
fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Value) -> String {
/// empty log. `images` says what became of the images the result is.
fn shape_run(
id: &str,
job: &Value,
logs: Result<String, String>,
results: &Value,
images: Option<&ImageNote>,
) -> String {
let mut run = summarize_run(job);
run.shift_remove("id");
// Why a run ended badly.
@@ -3115,8 +3457,8 @@ fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Valu
run.insert("steps_unavailable".into(), true.into());
}
// The server swaps a payload too big to send for a marker, each field in its own
// form. That is reported, never fetched around: the result keeps the head the step
// tree carries.
// form. That is reported, and fetched around only for an image the model is handed:
// otherwise the result keeps the head the step tree carries.
if let Some(job_args) = job.get("args").filter(|a| truthy(Some(a))) {
let too_big = job_args
.as_object()
@@ -3128,10 +3470,19 @@ fn shape_run(id: &str, job: &Value, logs: Result<String, String>, results: &Valu
}
}
if let Some(result) = job.get("result") {
if result == TOO_BIG {
run.insert("result_truncated".into(), true.into());
} else {
run.insert("result".into(), cap(&stringify(result), false).into());
match images.and_then(|note| note.label.as_deref()) {
Some(label) => {
run.insert("result".into(), label.into());
}
None if result == TOO_BIG => {
run.insert("result_truncated".into(), true.into());
}
None => {
run.insert("result".into(), cap(&stringify(result), false).into());
}
}
if let Some(note) = images {
run.insert(note.key.into(), note.text.clone().into());
}
}
let logs = match logs {
@@ -3160,7 +3511,8 @@ fn finished_step_job(response: &Value) -> Option<&str> {
}
/// One step's result in full, from the single entry the server resolved its address to.
fn step_result(response: &Value, step: &str) -> String {
/// `images` says what became of the images the result is.
fn step_result(response: &Value, step: &str, images: Option<&ImageNote>) -> String {
if let Some(error) = response["step_error"].as_str().filter(|e| !e.is_empty()) {
let hidden = if truthy(response.get("scope_filtered")) {
" (Steps running on tags outside your token’s scope are hidden.)"
@@ -3187,7 +3539,14 @@ fn step_result(response: &Value, step: &str) -> String {
} else {
String::new()
};
format!("Step \"{step}\" (job {job_id}, {status}) result:\n{prefix}{truncated}")
let mut body = match images.and_then(|note| note.label.as_deref()) {
Some(label) => label.to_string(),
None => format!("{prefix}{truncated}"),
};
if let Some(note) = images {
body.push_str(&format!("\n\n{}: {}", note.key, note.text));
}
format!("Step \"{step}\" (job {job_id}, {status}) result:\n{body}")
}
#[cfg(test)]
@@ -3585,6 +3944,68 @@ mod tests {
);
}
#[test]
fn image_results_are_the_shapes_the_run_page_draws() {
let inline = |kind, data| vec![ImageRef::Inline { kind, data }];
let s3 = |key, storage| ImageRef::S3 { key, storage };
assert_eq!(
image_refs(&json!({ "png": "iVBORw0KGgo=" })),
inline("png", "iVBORw0KGgo=")
);
assert_eq!(
image_refs(&json!({ "jpeg": { "content": "/9j/4A==" } })),
inline("jpeg", "/9j/4A==")
);
assert_eq!(
image_refs(&json!({ "s3": "charts/q3.PNG" })),
vec![s3("charts/q3.PNG", None)]
);
assert_eq!(
image_refs(&json!("s3://secondary/a.webp")),
vec![s3("a.webp", Some("secondary"))]
);
// A list counts when every item is a file, and only its images are read.
let files = json!([{ "s3": "a.png", "storage": "secondary" }, { "s3": "b.csv" }, { "s3": "c.jpg" }]);
assert_eq!(
image_refs(&files),
vec![s3("a.png", Some("secondary")), s3("c.jpg", None)]
);
for not_an_image in [
json!([{ "s3": "a.png" }, { "rows": 1 }]),
json!({ "svg": "<svg/>" }),
json!({ "chart": { "png": "iVBORw0KGgo=" } }),
json!({ "png": "iVBORw0KGgo=", "rows": 1 }),
json!({ "png": "not base64!" }),
json!({ "s3": "report.pdf" }),
] {
assert!(image_refs(&not_an_image).is_empty(), "{not_an_image}");
}
}
#[test]
fn an_attached_inline_image_reads_as_its_label() {
let job =
json!({ "type": "CompletedJob", "success": true, "result": { "png": "iVBORw0KGgo=" } });
let note = ImageNote {
key: "result_image",
text: "attached".into(),
label: Some("PNG image".into()),
};
let text = shape_run(
"j",
&job,
Ok(String::new()),
&json!({ "entries": [] }),
Some(&note),
);
assert!(
text.contains(r#""result": "PNG image""#)
&& text.contains(r#""result_image": "attached""#),
"{text}"
);
assert!(!text.contains("iVBORw0KGgo"), "{text}");
}
#[test]
fn steps_are_named_from_the_flow_at_any_depth() {
let flow = json!({ "modules": [{
+9 -1
View File
@@ -129,7 +129,15 @@ pub(super) async fn call_session_tool(
}
})?;
windmill_common::feature_usage::log_feature_usage("mcp_workspace", "tool_call", name);
let content = vec![ContentBlock::text(outcome.text)];
let mut content = vec![ContentBlock::text(outcome.text)];
if !outcome.is_error {
let images = std::mem::take(&mut *ctx.images.lock().unwrap());
content.extend(
images
.into_iter()
.map(|image| ContentBlock::image(image.data, image.mime_type)),
);
}
let mut result = if outcome.is_error {
CallToolResult::error(content)
} else {
+1 -1
View File
@@ -4,7 +4,7 @@
anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick"
without any identifying data leaving the instance.
It currently carries 116 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`,
It currently carries 117 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`,
`autoscaling_diagnostics`, `code_mode`,
`ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`,
`flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`,