mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-03 08:10:27 +00:00
feat: draw result images and files in the run card, with a Download button (#12769)
* 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> * feat: draw object storage and large image results in the run card 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> * feat: draw result file thumbnails and download them from the run card Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: space the run card's file parts and align tile names Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: offer download of file results past the job read limit, bound thumbnail waits 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. * feat: show a long file list's other files as a tile in the run card Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: say when the run card draws a smaller copy of an image Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: read a swapped result image through one function Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: offer download for a file result up to the size load_file reads Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- 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>
This commit is contained in:
co-authored by
Claude Opus 5.5
windmill-internal-app[bot]
parent
1dedda79ca
commit
d303cb855a
@@ -11,10 +11,23 @@ use super::ToolImage;
|
||||
/// 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 longest side of the JPEG copy handed for an image past either limit: the most Claude
|
||||
/// reads, which scales a larger image down itself.
|
||||
const COPY_SIDE: u32 = 2576;
|
||||
pub(super) const MODEL_FIT: Fit = Fit { max_bytes: MAX_IMAGE_BYTES, copy_side: COPY_SIDE };
|
||||
/// 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;
|
||||
|
||||
/// What an image handed on must fit in: as it is, within `max_bytes` and `MAX_IMAGE_SIDE`;
|
||||
/// past either, as a JPEG copy at most `copy_side` on its longest side, within `max_bytes`.
|
||||
#[derive(Clone, Copy)]
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
pub(super) struct Fit {
|
||||
pub max_bytes: usize,
|
||||
pub copy_side: u32,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -37,7 +50,29 @@ pub(super) async fn read_slot() -> Result<ReadSlot, Unattached> {
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
pub(super) struct Attachment {
|
||||
pub image: ToolImage,
|
||||
pub copy: Option<String>,
|
||||
pub copy: Option<ImageCopy>,
|
||||
}
|
||||
|
||||
/// A JPEG copy's sides, and the file's it stands for, as viewers show them.
|
||||
#[cfg_attr(not(feature = "mcp"), allow(dead_code))]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct ImageCopy {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub of_width: u32,
|
||||
pub of_height: u32,
|
||||
pub of_bytes: usize,
|
||||
pub of_mime_type: &'static str,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ImageCopy {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let Self { width, height, of_width, of_height, .. } = self;
|
||||
write!(
|
||||
f,
|
||||
"a {width}x{height} JPEG copy of the {of_width}x{of_height} px file"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an image is left out of an answer: what the model reads, and the `feature_usage`
|
||||
@@ -65,6 +100,7 @@ pub(super) fn unreadable(why: String) -> Unattached {
|
||||
pub(super) async fn decode_inline_image(
|
||||
data: &str,
|
||||
slot: Option<ReadSlot>,
|
||||
fit: Fit,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD};
|
||||
use base64::Engine;
|
||||
@@ -73,7 +109,7 @@ pub(super) async fn decode_inline_image(
|
||||
.decode(&data)
|
||||
.or_else(|_| STANDARD_NO_PAD.decode(&data))
|
||||
.map_err(|_| not_image("its content is not base64"))?;
|
||||
image_from_bytes(bytes, slot).await
|
||||
image_from_bytes(bytes, slot, fit).await
|
||||
}
|
||||
|
||||
/// A file within the limits as it is, a file past them as a JPEG copy, made holding `slot`,
|
||||
@@ -83,10 +119,11 @@ pub(super) async fn decode_inline_image(
|
||||
pub(super) async fn image_from_bytes(
|
||||
bytes: Vec<u8>,
|
||||
slot: Option<ReadSlot>,
|
||||
fit: Fit,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
let (bytes, format, as_is) = blocking(move || {
|
||||
let format = image_format(&bytes)?;
|
||||
let as_is = image_as_is(&bytes, format)?;
|
||||
let as_is = image_as_is(&bytes, format, fit)?;
|
||||
Ok((bytes, format, as_is))
|
||||
})
|
||||
.await?;
|
||||
@@ -100,7 +137,7 @@ pub(super) async fn image_from_bytes(
|
||||
blocking(move || {
|
||||
// Held until the decoding ends, also when the answer is no longer awaited.
|
||||
let _slot = slot;
|
||||
image_copy(&bytes, format)
|
||||
image_copy(&bytes, format, fit)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -111,6 +148,7 @@ pub(super) async fn image_from_bytes(
|
||||
pub(super) async fn image_from_bytes(
|
||||
_bytes: Vec<u8>,
|
||||
_slot: Option<ReadSlot>,
|
||||
_fit: Fit,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
Err(unreadable(
|
||||
"this server was built without image support".to_string(),
|
||||
@@ -121,10 +159,6 @@ pub(super) async fn image_from_bytes(
|
||||
/// 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;
|
||||
@@ -153,12 +187,16 @@ fn image_format(bytes: &[u8]) -> Result<image::ImageFormat, Unattached> {
|
||||
|
||||
/// 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> {
|
||||
fn image_as_is(
|
||||
bytes: &[u8],
|
||||
format: image::ImageFormat,
|
||||
fit: Fit,
|
||||
) -> 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 {
|
||||
if bytes.len() > fit.max_bytes || width.max(height) > MAX_IMAGE_SIDE {
|
||||
return Ok(None);
|
||||
}
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
@@ -190,10 +228,15 @@ fn image_reader(
|
||||
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`.
|
||||
/// A JPEG copy of an image, at most `fit.copy_side` on its longest side and its quality
|
||||
/// lowered until it is within `fit.max_bytes`, then smaller: noise or a dense photo can stay
|
||||
/// past it even at quality 30.
|
||||
#[cfg(feature = "mcp")]
|
||||
fn image_copy(bytes: &[u8], format: image::ImageFormat) -> Result<Attachment, Unattached> {
|
||||
fn image_copy(
|
||||
bytes: &[u8],
|
||||
format: image::ImageFormat,
|
||||
fit: Fit,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
use base64::Engine;
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
use image::metadata::Orientation;
|
||||
@@ -213,12 +256,8 @@ fn image_copy(bytes: &[u8], format: image::ImageFormat) -> Result<Attachment, Un
|
||||
_ => 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);
|
||||
let source = DynamicImage::from_decoder(decoder).map_err(undecodable)?;
|
||||
let longest = width.max(height);
|
||||
if matches!(
|
||||
orientation,
|
||||
Orientation::Rotate90
|
||||
@@ -228,24 +267,39 @@ fn image_copy(bytes: &[u8], format: image::ImageFormat) -> Result<Attachment, Un
|
||||
) {
|
||||
(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 first = longest.min(fit.copy_side);
|
||||
for side in [first, first * 3 / 4, first / 2] {
|
||||
let mut pixels = match longest > side {
|
||||
true => source.thumbnail(side, side),
|
||||
false => source.clone(),
|
||||
};
|
||||
// The copy keeps no EXIF data, so a photo taken sideways is turned as viewers show it.
|
||||
pixels.apply_orientation(orientation);
|
||||
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() <= fit.max_bytes {
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(&jpeg);
|
||||
let (copy_width, copy_height) = pixels.dimensions();
|
||||
let copy = ImageCopy {
|
||||
width: copy_width,
|
||||
height: copy_height,
|
||||
of_width: width,
|
||||
of_height: height,
|
||||
of_bytes: bytes.len(),
|
||||
of_mime_type: format.to_mime_type(),
|
||||
};
|
||||
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
|
||||
fit.max_bytes as f64 / 1e6
|
||||
);
|
||||
Err(Unattached { key: "too_large", why })
|
||||
}
|
||||
@@ -302,12 +356,14 @@ mod tests {
|
||||
// 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();
|
||||
let sent = decode_inline_image(&wrapped, None, MODEL_FIT)
|
||||
.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;
|
||||
let page = decode_inline_image("PGh0bWw+", None, MODEL_FIT).await;
|
||||
assert!(matches!(page, Err(Unattached { key: "not_image", .. })));
|
||||
}
|
||||
|
||||
@@ -317,9 +373,11 @@ mod tests {
|
||||
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();
|
||||
let sent = image_from_bytes(sideways.clone(), None, MODEL_FIT)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sent.copy.as_deref(),
|
||||
sent.copy.as_ref().map(ToString::to_string).as_deref(),
|
||||
Some("a 3x2576 JPEG copy of the 10x9000 px file")
|
||||
);
|
||||
let copy = decoded(&sent);
|
||||
@@ -327,21 +385,47 @@ mod tests {
|
||||
(sent.image.mime_type, copy.width(), copy.height()),
|
||||
("image/jpeg", 3, 2576)
|
||||
);
|
||||
// A smaller fit gets a smaller copy.
|
||||
let fit = Fit { copy_side: 1600, ..MODEL_FIT };
|
||||
let drawn = decoded(&image_from_bytes(sideways, None, fit).await.unwrap());
|
||||
assert_eq!(drawn.height(), 1600);
|
||||
|
||||
// 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();
|
||||
let copy = decoded(&image_from_bytes(png, None, MODEL_FIT).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;
|
||||
let refused = image_from_bytes(gif.to_vec(), None, MODEL_FIT).await;
|
||||
assert!(matches!(refused, Err(Unattached { key: "too_large", .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_still_too_large_at_the_lowest_quality_is_made_smaller() {
|
||||
use image::codecs::jpeg::JpegEncoder;
|
||||
// Noise keeps a JPEG large at any quality.
|
||||
let noise = image::RgbImage::from_fn(400, 400, |x, y| {
|
||||
let v = (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503))
|
||||
.wrapping_mul(2_246_822_519);
|
||||
image::Rgb([(v >> 24) as u8, (v >> 16) as u8, (v >> 8) as u8])
|
||||
});
|
||||
let mut png = Vec::new();
|
||||
noise
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let mut full_size = Vec::new();
|
||||
JpegEncoder::new_with_quality(&mut full_size, 30)
|
||||
.encode_image(&noise)
|
||||
.unwrap();
|
||||
let fit = Fit { max_bytes: full_size.len() / 2, copy_side: 400 };
|
||||
let copy = decoded(&image_copy(&png, image::ImageFormat::Png, fit).unwrap());
|
||||
assert!(copy.width() < 400, "{}", copy.width());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_profile_past_the_metadata_limit_is_dropped() {
|
||||
use image::{ImageDecoder, ImageEncoder};
|
||||
@@ -371,10 +455,11 @@ mod tests {
|
||||
encoder
|
||||
.write_image(&[0; 6], 2, 1, image::ExtendedColorType::Rgb8)
|
||||
.unwrap();
|
||||
image_copy(&webp, image::ImageFormat::WebP)
|
||||
image_copy(&webp, image::ImageFormat::WebP, MODEL_FIT)
|
||||
.unwrap()
|
||||
.copy
|
||||
.unwrap()
|
||||
.to_string()
|
||||
};
|
||||
assert_eq!(copy(&exif), "a 1x2 JPEG copy of the 1x2 px file");
|
||||
exif.resize(MAX_METADATA_BYTES as usize + 1, 0);
|
||||
|
||||
@@ -857,7 +857,9 @@ pub(crate) struct ToolOutcome {
|
||||
|
||||
/// The card tools only MCP Apps clients draw; the chat draws its own cards.
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) use views::{allowed as view_allowed, definitions as view_definitions, LOAD_CARD};
|
||||
pub(crate) use views::{
|
||||
allowed as view_allowed, definitions as view_definitions, APP_ONLY, LOAD_FILE,
|
||||
};
|
||||
|
||||
pub(crate) async fn call_session_tool(
|
||||
ctx: &Ctx<'_>,
|
||||
|
||||
@@ -9,7 +9,7 @@ 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,
|
||||
Fit, ReadSlot, Unattached, MAX_IMAGE_BYTES, MAX_SOURCE_BYTES, MAX_SOURCE_CHARS, MODEL_FIT,
|
||||
};
|
||||
use super::workspace::{
|
||||
api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc,
|
||||
@@ -2399,10 +2399,29 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult {
|
||||
}
|
||||
}
|
||||
}
|
||||
match big_image_result(ctx, id, job, entries.first()).await {
|
||||
Some(image) => {
|
||||
let (mut whole, slot) = big_image_result(ctx, id, job, entries.first())
|
||||
.await
|
||||
.unzip();
|
||||
if whole.is_none() {
|
||||
whole = big_file_result(ctx, id, job, entries.first()).await;
|
||||
}
|
||||
if let Some(result) = whole.as_ref().or(job.get("result")) {
|
||||
if let Some(image) = read_card_image(ctx, result, slot.flatten()).await {
|
||||
details.insert("image".into(), image);
|
||||
}
|
||||
let files = result_files(result);
|
||||
if files.iter().any(ResultFile::downloadable) {
|
||||
details.insert("download".into(), true.into());
|
||||
}
|
||||
if result.is_array() && !files.is_empty() {
|
||||
details.insert("files".into(), card_files(ctx, &files).await.into());
|
||||
details.insert("files_total".into(), files.len().into());
|
||||
}
|
||||
}
|
||||
match whole {
|
||||
Some(whole) => {
|
||||
let mut job = job.clone();
|
||||
job["result"] = image;
|
||||
job["result"] = whole;
|
||||
report_run(ctx, id, Some(&job), details);
|
||||
}
|
||||
None => report_run(ctx, id, Some(job), details),
|
||||
@@ -2439,38 +2458,331 @@ fn too_big_image<'a>(result: Option<&Value>, root: Option<&'a Value>) -> Option<
|
||||
.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.
|
||||
/// The job read swaps a result past ~90 KB for a marker, so the card reads an image again
|
||||
/// by its one field. The step tree's head of the result says which it is.
|
||||
async fn big_image_result(
|
||||
ctx: &Ctx<'_>,
|
||||
id: &str,
|
||||
job: &Value,
|
||||
root: Option<&Value>,
|
||||
) -> Option<Value> {
|
||||
) -> Option<(Value, Option<ReadSlot>)> {
|
||||
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()
|
||||
// An SVG is drawn from its markup, never from a copy.
|
||||
let max = if kind == "svg" {
|
||||
CARD_IMAGE_CHARS
|
||||
} else {
|
||||
MAX_SOURCE_CHARS
|
||||
};
|
||||
read_whole_image(ctx, id, kind, length, max)
|
||||
.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.
|
||||
/// A PDF or file result the job read swapped for a marker, as the card names it and offers
|
||||
/// it to download: its shape, from its keys and its `filename` read on its own, with the
|
||||
/// payload left out. `load_file` reads the bytes when the user downloads it.
|
||||
async fn big_file_result(
|
||||
ctx: &Ctx<'_>,
|
||||
id: &str,
|
||||
job: &Value,
|
||||
root: Option<&Value>,
|
||||
) -> Option<Value> {
|
||||
if job.get("result")? != TOO_BIG {
|
||||
return None;
|
||||
}
|
||||
let root = root?;
|
||||
let prefix = root["result_prefix"].as_str()?;
|
||||
let readable = root["result_length"].as_u64()? <= MAX_FILE_RESULT_CHARS as u64;
|
||||
if !readable
|
||||
|| !["{\"pdf\": ", "{\"file\": "]
|
||||
.iter()
|
||||
.any(|p| prefix.starts_with(p))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let route = ctx.ws(&format!("jobs_u/completed/get_result_shape/{}", enc(id)));
|
||||
let shape = ctx.get(&route).await.ok()?;
|
||||
let keys: Vec<&str> = shape["keys"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
// The card names `{file, filename}` by its filename; `load_file` reads the name of any
|
||||
// file from the result itself.
|
||||
let name = match keys[..] {
|
||||
["file", "filename"] => {
|
||||
let route = ctx.ws(&format!(
|
||||
"jobs/completed/get_result/{}?json_path=filename",
|
||||
enc(id)
|
||||
));
|
||||
ctx.get(&route)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|n| n.as_str().map(str::to_string))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
file_stand_in(&keys, prefix.starts_with("{\"file\": {"), name.as_deref())
|
||||
}
|
||||
|
||||
/// The shape `big_file_result` hands the card for a file result with these top-level `keys`,
|
||||
/// `nested` when its `file` is an object: a payload that reads as base64 where the result's
|
||||
/// is, so the card names it and offers to download it as it does a small one.
|
||||
fn file_stand_in(keys: &[&str], nested: bool, name: Option<&str>) -> Option<Value> {
|
||||
const LEFT_OUT: &str = "AA==";
|
||||
Some(match (keys, nested, name) {
|
||||
(["pdf"], false, _) => json!({ "pdf": LEFT_OUT }),
|
||||
(["file"], false, _) => json!({ "file": LEFT_OUT }),
|
||||
(["file"], true, _) => json!({ "file": { "content": LEFT_OUT } }),
|
||||
(["file", "filename"], false, Some(name)) => json!({ "file": LEFT_OUT, "filename": name }),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The image the card draws for a result `card_image` leaves out: an inline image past the
|
||||
/// card's size, from a JPEG copy, and a file in object storage, read as the caller. `slot` is
|
||||
/// the one an inline image's read took. A copy names the file it stands for, which the card
|
||||
/// tells the user it is not showing.
|
||||
async fn read_card_image(ctx: &Ctx<'_>, result: &Value, slot: Option<ReadSlot>) -> Option<Value> {
|
||||
let read = match image_refs(result).as_slice() {
|
||||
[ImageRef::Inline { data, .. }] if data.len() > CARD_IMAGE_CHARS => {
|
||||
decode_inline_image(data, slot, CARD_FIT).await
|
||||
}
|
||||
// A list of files is named and linked: the card draws one image.
|
||||
[ImageRef::S3 { key, storage }] if !result.is_array() => {
|
||||
read_s3_image(ctx, key, *storage, CARD_FIT).await
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let Attachment { image, copy } = read.ok()?;
|
||||
let kind = image.mime_type.strip_prefix("image/")?;
|
||||
let mut drawn = json!({ "type": kind, "data": image.data });
|
||||
if let Some(copy) = copy {
|
||||
drawn["original"] = json!({
|
||||
"width": copy.of_width,
|
||||
"height": copy.of_height,
|
||||
"bytes": copy.of_bytes,
|
||||
"type": copy.of_mime_type.strip_prefix("image/"),
|
||||
});
|
||||
}
|
||||
Some(drawn)
|
||||
}
|
||||
|
||||
/// A file a run's result is, which the card's Download button hands the user.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum ResultFile<'a> {
|
||||
/// `disabled` by the file's `disable_download`, which hides the run page's download too.
|
||||
S3 { key: &'a str, storage: Option<&'a str>, disabled: bool },
|
||||
/// An image, PDF or other file as base64, or an SVG's markup, under the kind its key
|
||||
/// names, and the name a `file` gives itself.
|
||||
Inline { kind: &'a str, data: &'a str, name: Option<&'a str> },
|
||||
}
|
||||
|
||||
impl ResultFile<'_> {
|
||||
/// Object storage is read through Enterprise Edition's routes only.
|
||||
fn downloadable(&self) -> bool {
|
||||
match self {
|
||||
ResultFile::S3 { disabled, .. } => {
|
||||
!disabled && cfg!(all(feature = "private", feature = "parquet"))
|
||||
}
|
||||
ResultFile::Inline { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The files a result is, in the shapes the run page offers to download: a file in object
|
||||
/// storage or a list of them, whatever their extension, or a PNG, JPEG, GIF, PDF, SVG or
|
||||
/// named file inline.
|
||||
fn result_files(result: &Value) -> Vec<ResultFile<'_>> {
|
||||
if let Some(items) = result.as_array() {
|
||||
let files = items.iter().map(s3_object).collect::<Option<Vec<_>>>();
|
||||
return files.filter(|_| items.len() <= 100).unwrap_or_default();
|
||||
}
|
||||
s3_object(result)
|
||||
.or_else(|| inline_file(result))
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn s3_object(file: &Value) -> Option<ResultFile<'_>> {
|
||||
let (key, storage) = s3_file(file).filter(|_| file.is_object())?;
|
||||
let disabled = file.get("disable_download").and_then(Value::as_bool) == Some(true);
|
||||
Some(ResultFile::S3 { key, storage, disabled })
|
||||
}
|
||||
|
||||
fn inline_file(result: &Value) -> Option<ResultFile<'_>> {
|
||||
let named = result.get("filename").and_then(Value::as_str);
|
||||
let (kind, data, name) = match (result.get("file").and_then(Value::as_str), named) {
|
||||
(Some(data), Some(name)) => ("file", data, Some(name)),
|
||||
_ => {
|
||||
let (kind, data) = single_file(result)?;
|
||||
let name = result.pointer("/file/filename").and_then(Value::as_str);
|
||||
(kind, data, name)
|
||||
}
|
||||
};
|
||||
let inline = match kind {
|
||||
"png" | "jpeg" | "gif" | "pdf" | "file" => is_base64(data),
|
||||
"svg" => true,
|
||||
_ => false,
|
||||
};
|
||||
inline.then_some(ResultFile::Inline { kind, data, name })
|
||||
}
|
||||
|
||||
fn file_name(key: &str) -> &str {
|
||||
key.rsplit('/')
|
||||
.next()
|
||||
.filter(|n| !n.is_empty())
|
||||
.unwrap_or(key)
|
||||
}
|
||||
|
||||
/// The tiles of a list's card, each image drawn from a copy of at most 640 px on a side and
|
||||
/// 180 KB, so that together they stay within one image's `CARD_IMAGE_CHARS`. A longer list
|
||||
/// tiles one file fewer: its last tile counts the files left out.
|
||||
const CARD_FILES: usize = 4;
|
||||
const THUMB_FIT: Fit = Fit { max_bytes: 180_000, copy_side: 640 };
|
||||
|
||||
/// The first files of a list result as the card tiles them: each named, and an image drawn
|
||||
/// from a small copy. Read one at a time, as `get_run` reads a list. A read that waited its
|
||||
/// 5 s for a slot ends the reads, so a card waits that long once, not once per tile.
|
||||
async fn card_files(ctx: &Ctx<'_>, files: &[ResultFile<'_>]) -> Vec<Value> {
|
||||
let mut tiles = Vec::new();
|
||||
let mut busy = false;
|
||||
let shown = if files.len() > CARD_FILES {
|
||||
CARD_FILES - 1
|
||||
} else {
|
||||
CARD_FILES
|
||||
};
|
||||
for file in files.iter().take(shown) {
|
||||
let ResultFile::S3 { key, storage, .. } = *file else {
|
||||
continue;
|
||||
};
|
||||
let mut tile = json!({ "name": file_name(key), "download": file.downloadable() });
|
||||
if has_image_extension(key) && !busy {
|
||||
match read_s3_image(ctx, key, storage, THUMB_FIT).await {
|
||||
Ok(read) => {
|
||||
if let Some(kind) = read.image.mime_type.strip_prefix("image/") {
|
||||
tile["image"] = json!({ "type": kind, "data": read.image.data });
|
||||
}
|
||||
}
|
||||
Err(unattached) => busy = unattached.key == "busy",
|
||||
}
|
||||
}
|
||||
tiles.push(tile);
|
||||
}
|
||||
tiles
|
||||
}
|
||||
|
||||
/// The longest result `load_file` reads: a file's base64 within the 30 MB limit, and the
|
||||
/// JSON around it. The card offers to download a result past the job read's cut up to it.
|
||||
const MAX_FILE_RESULT_CHARS: usize = MAX_SOURCE_CHARS + 1024;
|
||||
|
||||
/// One file of a finished run's result, for the card's Download button: `index` picks one of
|
||||
/// a list. A file in object storage is read as the caller through the route the run page
|
||||
/// downloads it with, so the same storage permission rules apply. The whole result is read,
|
||||
/// past the job read's cut, holding a read slot.
|
||||
pub(super) async fn load_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
use base64::Engine;
|
||||
let id = str_arg(args, "id")?;
|
||||
let index = args.get("index").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let _slot = read_slot().await.map_err(|busy| busy.why)?;
|
||||
let route = ctx.ws(&format!("jobs/completed/get_result/{}", enc(id)));
|
||||
let result: Value = match ctx.get_bytes(&route, MAX_FILE_RESULT_CHARS).await? {
|
||||
Some(bytes) => serde_json::from_slice(&bytes)
|
||||
.map_err(|_| format!("Run {id}'s result cannot be read."))?,
|
||||
None => return Err(format!("Run {id}'s result is {}.", too_large().why)),
|
||||
};
|
||||
let files = result_files(&result);
|
||||
let file = files
|
||||
.get(index)
|
||||
.filter(|file| file.downloadable())
|
||||
.ok_or_else(|| format!("File {index} of run {id}'s result cannot be downloaded."))?;
|
||||
let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
let (name, mime_type, data) = match *file {
|
||||
ResultFile::S3 { key, storage, .. } => {
|
||||
let storage = storage
|
||||
.map(|s| format!("&storage={}", enc(s)))
|
||||
.unwrap_or_default();
|
||||
let route = ctx.ws(&format!(
|
||||
"job_helpers/download_s3_file?file_key={}{storage}",
|
||||
enc(key)
|
||||
));
|
||||
let bytes = ctx
|
||||
.get_bytes(&route, MAX_SOURCE_BYTES)
|
||||
.await?
|
||||
.ok_or_else(|| format!("{key} is {}.", too_large().why))?;
|
||||
let mime_type = mime_guess::from_path(key).first_or_octet_stream();
|
||||
(
|
||||
file_name(key).to_string(),
|
||||
mime_type.to_string(),
|
||||
encode(&bytes),
|
||||
)
|
||||
}
|
||||
ResultFile::Inline { kind, data, name } => {
|
||||
let (extension, mime_type) = match kind {
|
||||
"png" => ("png", "image/png"),
|
||||
"jpeg" => ("jpg", "image/jpeg"),
|
||||
"gif" => ("gif", "image/gif"),
|
||||
"svg" => ("svg", "image/svg+xml"),
|
||||
"pdf" => ("pdf", "application/pdf"),
|
||||
_ => ("bin", "application/octet-stream"),
|
||||
};
|
||||
let (name, mime_type) = match name {
|
||||
Some(name) => {
|
||||
let mime_type = mime_guess::from_path(name).first_or_octet_stream();
|
||||
(file_name(name).to_string(), mime_type.to_string())
|
||||
}
|
||||
None => {
|
||||
let stem = id.get(..8).unwrap_or(id);
|
||||
(format!("{stem}.{extension}"), mime_type.to_string())
|
||||
}
|
||||
};
|
||||
let data = match kind {
|
||||
"svg" => encode(data.as_bytes()),
|
||||
_ => data.chars().filter(|c| !matches!(c, '\n' | '\r')).collect(),
|
||||
};
|
||||
(name, mime_type, data)
|
||||
}
|
||||
};
|
||||
let text = format!("{name} ({mime_type}), {} base64 characters.", data.len());
|
||||
ctx.set_view(
|
||||
"windmill/file",
|
||||
json!({ "name": name, "mime_type": mime_type, "data": data }),
|
||||
);
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// A swapped result read again by its one field `kind` if its text, `length` characters, is
|
||||
/// within `max`: `None` when the result holds more than that field. A result past the card's
|
||||
/// size is read holding a read slot, handed on to be kept through the image's copy.
|
||||
async fn read_whole_image(
|
||||
ctx: &Ctx<'_>,
|
||||
id: &str,
|
||||
kind: &str,
|
||||
length: u64,
|
||||
) -> Result<Option<Value>, String> {
|
||||
max: usize,
|
||||
) -> Result<Option<(Value, Option<ReadSlot>)>, Unattached> {
|
||||
if length > max as u64 + 64 {
|
||||
return Err(too_large());
|
||||
}
|
||||
let slot = match length > CARD_IMAGE_CHARS as u64 + 64 {
|
||||
true => Some(read_slot().await?),
|
||||
false => None,
|
||||
};
|
||||
let route = ctx.ws(&format!(
|
||||
"jobs/completed/get_result/{}?json_path={kind}",
|
||||
enc(id)
|
||||
));
|
||||
let field = ctx.get(&route).await?;
|
||||
let field = ctx.get(&route).await.map_err(|error| {
|
||||
unreadable(format!(
|
||||
"its read failed: {}",
|
||||
js_head(api_message(&error), 300)
|
||||
))
|
||||
})?;
|
||||
// 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 });
|
||||
Ok((jsonb_text_len(&whole) == length).then_some(whole))
|
||||
Ok((jsonb_text_len(&whole) == length).then_some((whole, slot)))
|
||||
}
|
||||
|
||||
/// The length in characters of a value as PostgreSQL prints a jsonb: `", "` between items
|
||||
@@ -2553,11 +2865,12 @@ fn s3_file(value: &Value) -> Option<(&str, Option<&str>)> {
|
||||
|
||||
fn s3_image(value: &Value) -> Option<ImageRef<'_>> {
|
||||
let (key, storage) = s3_file(value)?;
|
||||
has_image_extension(key).then_some(ImageRef::S3 { key, storage })
|
||||
}
|
||||
|
||||
fn has_image_extension(key: &str) -> bool {
|
||||
let lower = key.to_ascii_lowercase();
|
||||
IMAGE_EXTENSIONS
|
||||
.iter()
|
||||
.any(|ext| lower.ends_with(ext))
|
||||
.then_some(ImageRef::S3 { key, storage })
|
||||
IMAGE_EXTENSIONS.iter().any(|ext| lower.ends_with(ext))
|
||||
}
|
||||
|
||||
/// A one-key result's value as text, bare or as a file's `content`: how a script returns
|
||||
@@ -2645,7 +2958,7 @@ async fn attach_result_images(
|
||||
}
|
||||
budget -= bytes;
|
||||
ctx.images.lock().unwrap().push(image);
|
||||
Ok(copy)
|
||||
Ok(copy.map(|copy| copy.to_string()))
|
||||
});
|
||||
// Only an object storage file is named, by its key.
|
||||
let source = if name.is_some() { "s3" } else { "inline" };
|
||||
@@ -2713,8 +3026,8 @@ fn image_note_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,
|
||||
ImageRef::Inline { data, .. } => decode_inline_image(data, None, MODEL_FIT).await,
|
||||
ImageRef::S3 { key, storage } => read_s3_image(ctx, key, storage, MODEL_FIT).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2726,22 +3039,12 @@ async fn read_swapped_image(
|
||||
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 {
|
||||
let (whole, slot) = match read_whole_image(ctx, job_id, kind, length, MAX_SOURCE_CHARS).await {
|
||||
Ok(whole) => whole?,
|
||||
Err(error) => {
|
||||
let why = format!("its read failed: {}", js_head(api_message(&error), 300));
|
||||
return Some(Err(unreadable(why)));
|
||||
}
|
||||
Err(skip) => return Some(Err(skip)),
|
||||
};
|
||||
Some(match inline_image(&whole) {
|
||||
Some(ImageRef::Inline { data, .. }) => decode_inline_image(data, Some(slot)).await,
|
||||
Some(ImageRef::Inline { data, .. }) => decode_inline_image(data, slot, MODEL_FIT).await,
|
||||
_ => Err(not_image("its content is not base64")),
|
||||
})
|
||||
}
|
||||
@@ -2752,6 +3055,7 @@ async fn read_s3_image(
|
||||
ctx: &Ctx<'_>,
|
||||
key: &str,
|
||||
storage: Option<&str>,
|
||||
fit: Fit,
|
||||
) -> Result<Attachment, Unattached> {
|
||||
if !cfg!(all(feature = "private", feature = "parquet")) {
|
||||
let why = "reading object storage needs Windmill Enterprise Edition";
|
||||
@@ -2766,7 +3070,7 @@ async fn read_s3_image(
|
||||
));
|
||||
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(Some(bytes)) => image_from_bytes(bytes.into(), Some(slot), fit).await,
|
||||
Ok(None) => Err(too_large()),
|
||||
Err(error) => Err(unreadable(format!(
|
||||
"object storage answered: {}",
|
||||
@@ -3042,9 +3346,10 @@ pub(super) async fn show_runs(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
|
||||
const CARD_RESULT_CHARS: usize = 1500;
|
||||
/// A loop's iterations the card lists, the latest ones: the rest are on the run page.
|
||||
const CARD_ITERATIONS: usize = 10;
|
||||
/// Past this an image result is named and linked rather than drawn: every refresh of the
|
||||
/// card carries it again.
|
||||
/// The most base64 the card draws an image from: every refresh of the card carries it
|
||||
/// again. A larger image is drawn from a JPEG copy, a larger SVG named and linked.
|
||||
const CARD_IMAGE_CHARS: usize = 1_000_000;
|
||||
const CARD_FIT: Fit = Fit { max_bytes: CARD_IMAGE_CHARS / 4 * 3, copy_side: 1600 };
|
||||
/// What the job read returns in place of a result too big to send.
|
||||
const TOO_BIG: &str = "WINDMILL_TOO_BIG";
|
||||
/// The card's `result` for a result too large to store.
|
||||
@@ -3986,6 +4291,80 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_result_is_downloadable_in_the_shapes_the_run_page_offers() {
|
||||
let s3 = |key, storage| ResultFile::S3 { key, storage, disabled: false };
|
||||
let inline = |kind, data, name| ResultFile::Inline { kind, data, name };
|
||||
assert_eq!(
|
||||
result_files(&json!({ "s3": "out/report.pdf" })),
|
||||
vec![s3("out/report.pdf", None)]
|
||||
);
|
||||
assert_eq!(
|
||||
result_files(&json!([{ "s3": "a.csv" }, { "s3": "b.png", "storage": "x" }])),
|
||||
vec![s3("a.csv", None), s3("b.png", Some("x"))]
|
||||
);
|
||||
let hidden = json!({ "s3": "a.csv", "disable_download": true });
|
||||
assert!(!result_files(&hidden)[0].downloadable());
|
||||
assert_eq!(
|
||||
result_files(&json!({ "file": "aGk=", "filename": "notes.txt" })),
|
||||
vec![inline("file", "aGk=", Some("notes.txt"))]
|
||||
);
|
||||
assert_eq!(
|
||||
result_files(&json!({ "file": { "content": "aGk=", "filename": "a.txt" } })),
|
||||
vec![inline("file", "aGk=", Some("a.txt"))]
|
||||
);
|
||||
assert_eq!(
|
||||
result_files(&json!({ "pdf": "JVBERi0=" })),
|
||||
vec![inline("pdf", "JVBERi0=", None)]
|
||||
);
|
||||
assert_eq!(
|
||||
result_files(&json!({ "svg": "<svg/>" })),
|
||||
vec![inline("svg", "<svg/>", None)]
|
||||
);
|
||||
for no_file in [
|
||||
json!("s3://bucket/a.csv"),
|
||||
json!([{ "s3": "a.csv" }, 1]),
|
||||
json!({ "html": "<p/>" }),
|
||||
json!({ "png": "not base64!" }),
|
||||
json!({ "rows": 1 }),
|
||||
] {
|
||||
assert!(result_files(&no_file).is_empty(), "{no_file}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file result past the job read's cut reaches the card as a stand-in: it must be named
|
||||
/// and offered to download as the result itself would be.
|
||||
#[test]
|
||||
fn a_big_file_stands_in_as_the_card_names_and_downloads_it() {
|
||||
for (keys, nested, name, label, file_name) in [
|
||||
(&["pdf"][..], false, None, "PDF document", None),
|
||||
(&["file"], false, None, "File", None),
|
||||
(&["file"], true, None, "File", None),
|
||||
(
|
||||
&["file", "filename"],
|
||||
false,
|
||||
Some("b.bin"),
|
||||
"File b.bin",
|
||||
Some("b.bin"),
|
||||
),
|
||||
] {
|
||||
let stand_in = file_stand_in(keys, nested, name).unwrap();
|
||||
assert_eq!(
|
||||
describe_result(&stand_in).as_deref(),
|
||||
Some(label),
|
||||
"{stand_in}"
|
||||
);
|
||||
let files = result_files(&stand_in);
|
||||
let [ResultFile::Inline { name, .. }] = &files[..] else {
|
||||
panic!("{stand_in}: {files:?}");
|
||||
};
|
||||
assert_eq!(*name, file_name, "{stand_in}");
|
||||
assert!(card_image(&stand_in).is_none(), "{stand_in}");
|
||||
}
|
||||
assert!(file_stand_in(&["file", "filename", "x"], false, Some("c")).is_none());
|
||||
assert!(file_stand_in(&["file", "filename"], false, None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attached_inline_image_reads_as_its_label() {
|
||||
let job =
|
||||
|
||||
@@ -15,6 +15,7 @@ pub(super) const TOOLS: &[&str] = &[
|
||||
"show_deploy_review",
|
||||
"show_item",
|
||||
LOAD_CARD,
|
||||
LOAD_FILE,
|
||||
];
|
||||
|
||||
/// The card's own read of what a show tool shows. Claude hands a card the result's
|
||||
@@ -23,6 +24,11 @@ pub(super) const TOOLS: &[&str] = &[
|
||||
/// every show call. So a show tool's `structuredContent` names only the call, and the card
|
||||
/// loads its data through this tool, which no host lists to the model (`visibility: ["app"]`).
|
||||
pub(crate) const LOAD_CARD: &str = "load_card";
|
||||
/// The bytes of a run's result file, which the card hands the host to save from its Download
|
||||
/// button. Hidden from the model as `load_card` is: a whole file would fill its context.
|
||||
pub(crate) const LOAD_FILE: &str = "load_file";
|
||||
/// The tools only the card calls.
|
||||
pub(crate) const APP_ONLY: [&str; 2] = [LOAD_CARD, LOAD_FILE];
|
||||
|
||||
/// The last line of each tool's text. The text is all a client that draws no card shows, and
|
||||
/// all the model reads in any client: the card's data rides in `_meta`, which neither reads.
|
||||
@@ -35,15 +41,16 @@ pub(crate) fn allowed(name: &str, access: SessionAccess) -> bool {
|
||||
}
|
||||
|
||||
pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult {
|
||||
if name != LOAD_CARD {
|
||||
return show(ctx, name, args).await;
|
||||
}
|
||||
match args.get("tool").and_then(Value::as_str) {
|
||||
Some(tool) if tool != LOAD_CARD && TOOLS.contains(&tool) => {
|
||||
let arguments = args.get("arguments").cloned().unwrap_or(Value::Null);
|
||||
show(ctx, tool, &arguments).await
|
||||
}
|
||||
_ => Err(format!("{LOAD_CARD} takes the name of a show tool.")),
|
||||
match name {
|
||||
LOAD_FILE => runs::load_file(ctx, args).await,
|
||||
LOAD_CARD => match args.get("tool").and_then(Value::as_str) {
|
||||
Some(tool) if !APP_ONLY.contains(&tool) && TOOLS.contains(&tool) => {
|
||||
let arguments = args.get("arguments").cloned().unwrap_or(Value::Null);
|
||||
show(ctx, tool, &arguments).await
|
||||
}
|
||||
_ => Err(format!("{LOAD_CARD} takes the name of a show tool.")),
|
||||
},
|
||||
_ => show(ctx, name, args).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,8 +72,21 @@ async fn show(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult {
|
||||
/// Each tool as `(name, description, input schema)`. All only read: the review card's
|
||||
/// Deploy button calls `deploy_workspace_item`, which the token's own access gates.
|
||||
#[cfg(feature = "mcp")]
|
||||
pub(crate) fn definitions() -> [(&'static str, &'static str, Value); 5] {
|
||||
pub(crate) fn definitions() -> [(&'static str, &'static str, Value); 6] {
|
||||
[
|
||||
(
|
||||
LOAD_FILE,
|
||||
"Load a file of a finished run's result, for the card's Download button. Only the card calls it.",
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": { "type": "string", "description": "The run (job) id." },
|
||||
"index": { "type": "integer", "minimum": 0, "description": "Which file of a result that lists files. Default 0." }
|
||||
},
|
||||
"required": ["id"],
|
||||
"additionalProperties": false
|
||||
}),
|
||||
),
|
||||
(
|
||||
LOAD_CARD,
|
||||
"Load the data a Windmill card shows. Only the card calls it.",
|
||||
|
||||
@@ -254,6 +254,15 @@
|
||||
.image-box img { max-width: 100%; height: auto; }
|
||||
.image-box.cut { cursor: zoom-in; }
|
||||
.image-box.cut img { max-height: 240px; }
|
||||
.files { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; }
|
||||
.file-tile { display: flex; flex-direction: column; gap: 4px; min-width: 0; padding: 8px; border-radius: var(--radius); background: var(--bg-2); }
|
||||
.file-tile .thumb { height: 120px; display: flex; align-items: center; justify-content: center; color: var(--fg-3); }
|
||||
.file-tile .thumb img { max-width: 100%; max-height: 100%; }
|
||||
.file-tile .name { display: flex; align-items: center; gap: 4px; min-width: 0; min-height: 28px; font-size: var(--t-sm); }
|
||||
.file-tile .name span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
button.file-tile { height: auto; padding: 7px; border: 1px solid transparent; font: inherit; color: var(--fg-2); text-align: left; }
|
||||
button.file-tile:hover { background: var(--bg-2); border-color: var(--line); color: var(--fg-em); }
|
||||
button.file-tile .thumb { font-size: calc(var(--t-md) * 2); font-weight: var(--w-medium); color: inherit; }
|
||||
.openable .corner { position: absolute; top: 4px; right: 4px; display: flex; gap: 2px; }
|
||||
.openable .corner button { min-height: 24px; width: 24px; border: 0; background: var(--bg-2); color: var(--fg-3); }
|
||||
.openable .corner button:hover { background: var(--bg); color: var(--fg-em); }
|
||||
@@ -358,6 +367,7 @@
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
let host = {};
|
||||
let hostCapabilities = {};
|
||||
let toolArgs = {};
|
||||
let view = null;
|
||||
let run = null;
|
||||
@@ -440,7 +450,9 @@
|
||||
loader: [['path', { d: 'M21 12a9 9 0 1 1-6.219-8.56' }]],
|
||||
save: [['path', { d: 'M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z' }], ['path', { d: 'M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7' }], ['path', { d: 'M7 3v4a1 1 0 0 0 1 1h7' }]],
|
||||
arrowUp: [['path', { d: 'm5 12 7-7 7 7' }], ['path', { d: 'M12 19V5' }]],
|
||||
arrowDown: [['path', { d: 'M12 5v14' }], ['path', { d: 'm19 12-7 7-7-7' }]]
|
||||
arrowDown: [['path', { d: 'M12 5v14' }], ['path', { d: 'm19 12-7 7-7-7' }]],
|
||||
download: [['path', { d: 'M12 15V3' }], ['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }], ['path', { d: 'm7 10 5 5 5-5' }]],
|
||||
file: [['path', { d: 'M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z' }], ['path', { d: 'M14 2v4a2 2 0 0 0 2 2h4' }]]
|
||||
};
|
||||
function icon(name) {
|
||||
const ns = 'http://www.w3.org/2000/svg';
|
||||
@@ -579,6 +591,69 @@
|
||||
return el('div', { class: 'image-box' }, el('img', { src, alt: of.result ?? 'Image result' }));
|
||||
}
|
||||
|
||||
// A sandboxed card cannot save a file itself: the host does, from the bytes `load_file`
|
||||
// reads as the user, on a host that says it can.
|
||||
const canDownload = (of) => !!(hostCapabilities.downloadFile && of?.download && of.id);
|
||||
function downloadButton(of, index, label = 'Download') {
|
||||
const button = el('button', { class: label ? 'more-line' : 'icon', type: 'button', title: 'Download', 'aria-label': 'Download' }, icon('download'), label);
|
||||
button.addEventListener('click', async (e) => {
|
||||
e.stopPropagation();
|
||||
setBusy(button, true, 'download');
|
||||
let saved = false;
|
||||
try {
|
||||
const loaded = await callTool('load_file', { workspace_id: of.workspace ?? run.workspace, id: of.id, index });
|
||||
const file = cardData(loaded)['windmill/file'];
|
||||
if (file) {
|
||||
const resource = { uri: `file:///${encodeURIComponent(file.name)}`, mimeType: file.mime_type, blob: file.data };
|
||||
const answer = await request('ui/download-file', { contents: [{ type: 'resource', resource }] });
|
||||
saved = !answer?.isError;
|
||||
}
|
||||
} catch {}
|
||||
setBusy(button, false, 'download');
|
||||
button.title = saved ? 'Download' : 'Not downloaded';
|
||||
});
|
||||
return button;
|
||||
}
|
||||
// A list of files: the first few as tiles, images drawn from small copies, and the rest as one
|
||||
// more tile that opens the run page.
|
||||
function fileTiles(of, url) {
|
||||
const tiles = of.files.map((file, index) => {
|
||||
const thumb = file.image
|
||||
? el('img', { src: `data:image/${file.image.type};base64,${file.image.data}`, alt: file.name })
|
||||
: icon('file');
|
||||
return el('div', { class: 'file-tile', title: file.name },
|
||||
el('div', { class: 'thumb' }, thumb),
|
||||
el('div', { class: 'name' }, el('span', {}, file.name), canDownload(of) && file.download ? downloadButton(of, index, '') : null));
|
||||
});
|
||||
const more = (of.files_total ?? 0) - of.files.length;
|
||||
if (more > 0) tiles.push(el('button', { class: 'file-tile', type: 'button', title: 'Open the run in Windmill', onclick: () => openLink(url) },
|
||||
el('div', { class: 'thumb' }, `+${more}`),
|
||||
el('div', { class: 'name' }, el('span', {}, plural(more, 'more file')), icon('external'))));
|
||||
return el('div', { class: 'files' }, ...tiles);
|
||||
}
|
||||
// An image drawn from a copy says what the file is: Download saves the file, not the copy.
|
||||
function copyNote({ width, height, bytes, type }) {
|
||||
const size = bytes >= 1e6 ? `${(bytes / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1e3))} KB`;
|
||||
const kind = type === 'webp' ? 'WebP' : String(type).toUpperCase();
|
||||
return `Smaller copy · original ${width} × ${height}, ${size} ${kind}`;
|
||||
}
|
||||
// Under a file result: its tiles, its name, the run page, and saving it.
|
||||
function fileParts(of, url) {
|
||||
const parts = [];
|
||||
const tiled = of.files?.length > 0;
|
||||
if (tiled) parts.push(fileTiles(of, url));
|
||||
if (!of.image) parts.push(el('div', { class: 'step' }, of.result));
|
||||
else if (of.image.original) parts.push(el('div', { class: 'step' }, copyNote(of.image.original)));
|
||||
// A drawn image opens on the run page from its own corner, and a list's other files from
|
||||
// their tile.
|
||||
const more = (of.files_total ?? 0) - (of.files?.length ?? 0);
|
||||
const named = (of.files_total ?? 1) > 1 ? 'Files in Windmill' : 'File in Windmill';
|
||||
const link = of.image || (tiled && more > 0) ? null : linkButton(more > 0 ? `${plural(more, 'more file')} in Windmill` : named, url);
|
||||
const save = canDownload(of) && !of.files?.length ? downloadButton(of, 0) : null;
|
||||
if (link || save) parts.push(el('div', { style: 'display: flex; align-items: center; gap: 12px' }, link, save));
|
||||
return parts;
|
||||
}
|
||||
|
||||
// A block's corner holds its copy control, as in Windmill, and when it is cut the control
|
||||
// that opens it whole. Text in it stays selectable unless a click on it opens it.
|
||||
function openable(block, cut, url, tabName = null, copy = null) {
|
||||
@@ -886,7 +961,8 @@
|
||||
more.replaceChildren();
|
||||
// A file, image, page or map is named here and shown on the run page.
|
||||
if (inline && run?.image && !running) more.append(openable(imageBox(run), true, run.url, 'result'));
|
||||
else if (inline && described && !running) more.append(el('div', { class: 'step' }, run.result), linkButton('File in Windmill', run.url, 'margin-top: 8px'));
|
||||
const files = inline && described && !running ? fileParts(run, run.url) : [];
|
||||
if (files.length) more.append(el('div', { class: 'section', style: run.image ? 'margin-top: 8px' : null }, ...files));
|
||||
// A flow waiting on an approval or another event is resumed or canceled on its page.
|
||||
if (inline && (status === 'suspended' || (running && run?.waiting))) more.append(...waitingView(run));
|
||||
// A saved agent says it once, on its steps line.
|
||||
@@ -1156,8 +1232,8 @@
|
||||
if (failed && stackBody(of)) parts.push(openable(el('pre', { class: 'stack' }, stackBody(of)), false, url, null, errorText(of)));
|
||||
if (failed && of.result_cut) parts.push(linkButton('Full error in Windmill', url));
|
||||
if (!failed && of.image) parts.push(imageBox(of));
|
||||
else if (!failed && of.result_kind === 'file') parts.push(el('div', { class: 'step' }, of.result), linkButton('File in Windmill', url));
|
||||
else if (!failed && of.result != null) {
|
||||
if (!failed && of.result_kind === 'file') parts.push(...fileParts(of, url));
|
||||
else if (!failed && of.result != null && !of.image) {
|
||||
const records = of.status === 'success' ? recordsTable(of.result) : null;
|
||||
parts.push(openable(records ?? el('pre', { class: 'result' }, of.result), false, url, null, of.result));
|
||||
if (of.result_cut) parts.push(linkButton('Full result in Windmill', url));
|
||||
@@ -1802,6 +1878,7 @@
|
||||
appInfo: { name: 'windmill-card', version: '1.0.0' },
|
||||
appCapabilities: { availableDisplayModes: ['inline', 'fullscreen'] }
|
||||
}).then((result) => {
|
||||
hostCapabilities = result?.hostCapabilities ?? {};
|
||||
applyContext(result?.hostContext);
|
||||
post({ method: 'ui/notifications/initialized', params: {} });
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -55,7 +55,7 @@ fn tool_title(name: &str) -> String {
|
||||
/// what the tool put in its result's `_meta` (`Ctx::view`), or loads it with `load_card`
|
||||
/// from the call named in `structuredContent`, and acts by calling tools. Hosts cache a
|
||||
/// view by its URI: bump the version when a change breaks what the deployed card reads.
|
||||
pub(super) const CARD_URI: &str = "ui://windmill/card-v2";
|
||||
pub(super) const CARD_URI: &str = "ui://windmill/card-v5";
|
||||
const CARD_HTML: &str = include_str!("card.html");
|
||||
|
||||
/// The `ui://` views the session's tools render in, as `(uri, html)`.
|
||||
@@ -89,7 +89,13 @@ pub(super) fn session_tools(session_access: SessionAccess) -> Vec<Tool> {
|
||||
.filter(|(name, ..)| tools::view_allowed(name, access))
|
||||
.map(|(name, description, schema)| {
|
||||
let mut meta = result_size_meta();
|
||||
let ui = if name == tools::LOAD_CARD {
|
||||
// A file's base64, which no model reads: up to 40M characters, and 53.3M
|
||||
// for an inline SVG, whose 40M characters of markup it encodes.
|
||||
if name == tools::LOAD_FILE {
|
||||
meta.0
|
||||
.insert("anthropic/maxResultSizeChars".into(), 60_000_000.into());
|
||||
}
|
||||
let ui = if tools::APP_ONLY.contains(&name) {
|
||||
json!({ "resourceUri": CARD_URI, "visibility": ["app"] })
|
||||
} else {
|
||||
json!({ "resourceUri": CARD_URI })
|
||||
@@ -145,15 +151,18 @@ pub(super) async fn call_session_tool(
|
||||
};
|
||||
if let Some((key, view)) = ctx.view.lock().unwrap().take() {
|
||||
result.structured_content = Some(structured_content(name, call, key, &view));
|
||||
result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)])));
|
||||
// A file's bytes, up to 53.3M characters, ride once.
|
||||
if name != tools::LOAD_FILE {
|
||||
result.meta = Some(MetaObject(Map::from_iter([(key.to_string(), view)])));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Codex's and ChatGPT's models read `structuredContent`, so a show tool's names only its
|
||||
/// call. `load_card`'s holds the card data: only the card calls it.
|
||||
/// call. An app-only tool's holds its data: only the card calls it.
|
||||
fn structured_content(name: &str, call: Value, key: &str, view: &Value) -> Value {
|
||||
if name == tools::LOAD_CARD {
|
||||
if tools::APP_ONLY.contains(&name) {
|
||||
json!({ key: view })
|
||||
} else {
|
||||
call
|
||||
@@ -181,10 +190,11 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The card loads its data through `load_card`; a model that could call it would read
|
||||
/// every card's data, which the show tools keep out of its context.
|
||||
/// The card loads its data through `load_card` and files through `load_file`; a model
|
||||
/// that could call them would read every card's data and whole files, which the show
|
||||
/// tools keep out of its context.
|
||||
#[test]
|
||||
fn only_load_card_is_hidden_from_the_model() {
|
||||
fn only_the_card_loaders_are_hidden_from_the_model() {
|
||||
let app_only: Vec<String> = session_tools(SessionAccess::Full)
|
||||
.into_iter()
|
||||
.filter(|tool| {
|
||||
@@ -193,11 +203,11 @@ mod tests {
|
||||
})
|
||||
.map(|tool| tool.name.to_string())
|
||||
.collect();
|
||||
assert_eq!(app_only, [tools::LOAD_CARD]);
|
||||
assert_eq!(app_only, ["load_file", "load_card"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_load_card_puts_card_data_in_structured_content() {
|
||||
fn only_the_card_loaders_put_their_data_in_structured_content() {
|
||||
let call = json!({ "tool": "show_run", "workspace_id": "w", "arguments": { "id": "1" } });
|
||||
let view = json!({ "status": "success", "logs": "tick" });
|
||||
assert_eq!(
|
||||
@@ -205,7 +215,7 @@ mod tests {
|
||||
call
|
||||
);
|
||||
assert_eq!(
|
||||
structured_content(tools::LOAD_CARD, call, "windmill/run", &view),
|
||||
structured_content("load_card", call, "windmill/run", &view),
|
||||
json!({ "windmill/run": view })
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user