feat: show S3 images to the model and open S3 files in the session preview

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-26 06:41:04 -08:00
co-authored by Claude Opus 5.5
parent 6553dfda4a
commit c96cfb74a1
18 changed files with 471 additions and 107 deletions
@@ -2707,7 +2707,7 @@
},
{
"name": "read_s3_file",
"description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, or the first rows of a Parquet file. Other files, such as images, return their metadata only.",
"description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, the first rows of a Parquet file, or the image itself for a png, jpeg, gif or webp of up to 5 MB, which you then see. Other files return their metadata only.",
"parameters": {
"type": "object",
"properties": {
@@ -2718,6 +2718,10 @@
"storage": {
"description": "Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage.",
"type": "string"
},
"open_in_preview": {
"description": "Also open the file in the side panel next to the chat. Only when the user asks to open or display the file itself: reading it to answer a question about it does not. Only Windmill's own chat has that panel; elsewhere the result's `link` opens the file.",
"type": "boolean"
}
},
"required": [
@@ -283,6 +283,16 @@ 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)>>,
/// Images the model sees beside the text: MCP sends them as image content, the chat
/// attaches them to the conversation.
pub images: std::sync::Mutex<Vec<ToolImage>>,
}
/// An image a tool returns, base64-encoded.
#[derive(Serialize)]
pub(crate) struct ToolImage {
pub mime_type: String,
pub data: String,
}
impl<'a> Ctx<'a> {
@@ -303,6 +313,7 @@ impl<'a> Ctx<'a> {
effects: Default::default(),
jwt: Default::default(),
view: Default::default(),
images: Default::default(),
}
}
@@ -323,6 +334,15 @@ impl Ctx<'_> {
*self.view.lock().unwrap() = Some((key, value));
}
/// Return an image to the model with the call's text.
pub fn push_image(&self, mime_type: &str, bytes: &[u8]) {
use base64::Engine;
self.images.lock().unwrap().push(ToolImage {
mime_type: mime_type.to_string(),
data: base64::engine::general_purpose::STANDARD.encode(bytes),
});
}
/// Call the API as the caller. `path` follows `/api`; a non-2xx answer is the error.
pub async fn request(&self, method: &str, path: &str, body: Option<Value>) -> ToolResult {
self.request_within(method, path, body, REQUEST_TIMEOUT)
@@ -339,6 +359,22 @@ impl Ctx<'_> {
body: Option<Value>,
timeout: std::time::Duration,
) -> ToolResult {
let bytes = self.request_bytes(method, path, body, timeout).await?;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
/// `GET` a route that answers with bytes, such as a file's content.
pub async fn get_bytes(&self, path: &str) -> Result<Vec<u8>, String> {
self.request_bytes("GET", path, None, REQUEST_TIMEOUT).await
}
async fn request_bytes(
&self,
method: &str,
path: &str,
body: Option<Value>,
timeout: std::time::Duration,
) -> Result<Vec<u8>, 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
@@ -357,7 +393,7 @@ impl Ctx<'_> {
.unwrap()
.get(self.base_internal_url)
.cloned();
let (status, text) = match router {
let (status, bytes) = match router {
Some(router) => {
self.call_router(router, method, &url, body, scopes, timeout)
.await?
@@ -365,8 +401,10 @@ impl Ctx<'_> {
None => self.call_http(method, &url, body, scopes, timeout).await?,
};
if status.is_success() {
Ok(text)
} else if text.trim().is_empty() {
return Ok(bytes);
}
let text = String::from_utf8_lossy(&bytes);
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()))
@@ -385,7 +423,7 @@ impl Ctx<'_> {
body: Option<Value>,
scopes: Option<Vec<String>>,
timeout: std::time::Duration,
) -> Result<(http::StatusCode, String), String> {
) -> Result<(http::StatusCode, Vec<u8>), 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.
@@ -418,7 +456,7 @@ impl Ctx<'_> {
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()))
Ok((status, bytes.to_vec()))
})
.await
.map_err(|_| format!("Failed to execute request: {method} {url} timed out"))?
@@ -432,7 +470,7 @@ impl Ctx<'_> {
body: Option<Value>,
scopes: Option<Vec<String>>,
timeout: std::time::Duration,
) -> Result<(http::StatusCode, String), String> {
) -> Result<(http::StatusCode, Vec<u8>), String> {
let method = http::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?;
let token = self
.jwt
@@ -451,7 +489,8 @@ 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())?))
let bytes = response.bytes().await.map_err(|e| e.to_string())?;
Ok((status, bytes.to_vec()))
}
pub async fn get(&self, path: &str) -> Result<Value, String> {
@@ -738,6 +777,8 @@ pub(crate) enum CallRefused {
pub(crate) struct ToolOutcome {
pub text: String,
pub is_error: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub images: Vec<ToolImage>,
}
/// The card tools only MCP Apps clients draw; the chat draws its own cards.
@@ -753,7 +794,11 @@ pub(crate) async fn call_session_tool(
return Ok(outcome(views::call(ctx, name, &args).await));
}
let result = call_generated_tool(ctx, name, &args).await?;
Ok(outcome(result))
let mut outcome = outcome(result);
if !outcome.is_error {
outcome.images = std::mem::take(&mut *ctx.images.lock().unwrap());
}
Ok(outcome)
}
/// A generated session tool, refused when the caller's access does not cover it.
@@ -781,12 +826,12 @@ async fn call_generated_tool(
fn outcome(result: ToolResult) -> ToolOutcome {
match result {
Ok(text) => ToolOutcome { text, is_error: false },
Ok(text) => ToolOutcome { text, is_error: false, images: vec![] },
// Without the status code `Ctx` prefixes an API failure with, as the session reads it.
Err(message) => {
let body = workspace::api_message(&message);
let text = if body.is_empty() { &message } else { body };
ToolOutcome { text: text.to_string(), is_error: true }
ToolOutcome { text: text.to_string(), is_error: true, images: vec![] }
}
}
}
@@ -35,10 +35,27 @@ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult
const DEFAULT_MAX_KEYS: u64 = 100;
const MAX_KEYS: u64 = 500;
/// Bytes of a text file handed to the model, under the MCP runner's result limit.
/// Bytes of a text file the preview endpoint is asked for.
const PREVIEW_BYTES: u64 = 32 * 1024;
/// A `read_s3_file` result as the model reads it, under the MCP runner's cap
/// (`MAX_TOOL_RESULT_BYTES`), which cuts a longer one mid-JSON.
const RESULT_BUDGET: usize = 48 * 1024;
/// Kept free for the note a preview adds once it is cut.
const NOTE_ROOM: usize = 2048;
const PARQUET_PREVIEW_ROWS: usize = 50;
/// The CSV preview endpoint parses at most this many rows, whatever length it is asked.
const CSV_PREVIEW_ROWS: usize = 20;
const MAX_CELL_CHARS: usize = 1000;
/// Anthropic's limit for one image; the server has no image library to downscale with.
const MAX_IMAGE_BYTES: u64 = 5 * 1024 * 1024;
/// What the S3 file browser shows as an image.
const IMAGE_TYPES: &[(&str, &str)] = &[
("png", "image/png"),
("jpg", "image/jpeg"),
("jpeg", "image/jpeg"),
("gif", "image/gif"),
("webp", "image/webp"),
];
/// `None` for the primary storage, however it was named.
fn storage_arg(args: &Value) -> Option<&str> {
@@ -162,6 +179,13 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let mut out = s3_object(&key.into(), storage);
out.insert("size".into(), meta["size_in_bytes"].clone());
out.insert("last_modified".into(), meta["last_modified"].clone());
let download = with_query(
ctx.ws("job_helpers/download_s3_file"),
&[("file_key", Some(key)), ("storage", storage)],
);
if let Some(link) = ctx.link(&format!("/api{download}")) {
out.insert("link".into(), link.into());
}
if key.to_lowercase().ends_with(".parquet") {
let preview = ctx
@@ -176,22 +200,24 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
],
))
.await?;
let returned = array(preview.get("rows"));
let (rows, cut_cells) = bounded_rows(returned);
out.insert("columns".into(), preview["columns"].clone());
out.insert("column_types".into(), preview["column_types"].clone());
let mut notes = vec![];
if rows.len() < returned.len() || returned.len() == PARQUET_PREVIEW_ROWS {
notes.push(format!("The first {} rows only.", rows.len()));
}
if cut_cells {
notes.push(format!(
"Text cells longer than {MAX_CELL_CHARS} characters are cut."
));
}
out.insert("rows".into(), rows.into());
if !notes.is_empty() {
out.insert("note".into(), notes.join(" ").into());
fit_rows(&mut out, array(preview.get("rows")));
} else if let Some(mime_type) = image_type(key) {
if size > MAX_IMAGE_BYTES {
out.insert(
"image".into(),
format!("not attached: larger than {} MB", MAX_IMAGE_BYTES >> 20).into(),
);
} else {
let bytes = ctx
.get_bytes(&with_query(
ctx.ws("job_helpers/load_image_preview"),
&[("file_key", Some(key)), ("storage", storage)],
))
.await?;
ctx.push_image(mime_type, &bytes);
out.insert("image".into(), "attached".into());
}
} else {
let mut length = size.min(PREVIEW_BYTES);
@@ -209,13 +235,10 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
}
match preview["content"].as_str() {
Some(content) => {
// A CSV preview is the endpoint's parsed rows, whatever length was asked.
let shown = cut_utf8(content, PREVIEW_BYTES as usize);
out.insert("content_type".into(), preview["content_type"].clone());
out.insert("preview".into(), shown.into());
if shown.len() < content.len() || length < size {
out.insert("note".into(), "Only the start of the file.".into());
}
let csv_cut =
preview["content_type"] == "Csv" && content.lines().count() > CSV_PREVIEW_ROWS;
fit_text(&mut out, content, length < size, csv_cut);
}
None => {
out.insert("preview_unavailable".into(), preview["msg"].clone());
@@ -245,42 +268,132 @@ async fn text_preview(
.await
}
fn cut_utf8(text: &str, max_bytes: usize) -> &str {
if text.len() <= max_bytes {
return text;
}
let mut end = max_bytes;
while !text.is_char_boundary(end) {
end -= 1;
}
&text[..end]
fn image_type(key: &str) -> Option<&'static str> {
let ext = key.rsplit_once('.')?.1.to_lowercase();
IMAGE_TYPES
.iter()
.find(|(e, _)| *e == ext)
.map(|(_, mime_type)| *mime_type)
}
/// Parquet rows within the preview budget, with long text cells cut; also whether a cell was.
fn bounded_rows(rows: &[Value]) -> (Vec<Value>, bool) {
let mut kept = vec![];
/// Bytes of `value` once pretty-printed `depth` levels deep in the result.
fn pretty_len(value: &Value, depth: usize) -> usize {
let s = pretty(value);
s.len() + s.matches('\n').count() * 2 * depth
}
/// The longest prefix of `text` whose JSON-escaped form fits in `max` bytes: a control
/// byte escapes to six.
fn cut_escaped(text: &str, max: usize) -> &str {
let mut used = 0;
for (i, c) in text.char_indices() {
used += match c {
'"' | '\\' | '\n' | '\r' | '\t' | '\u{8}' | '\u{c}' => 2,
c if (c as u32) < 0x20 => 6,
c => c.len_utf8(),
};
if used > max {
return &text[..i];
}
}
text
}
/// Room left in the result for one more field, its key and the note included.
fn room(out: &Map<String, Value>) -> usize {
RESULT_BUDGET.saturating_sub(pretty_len(&Value::Object(out.clone()), 0) + NOTE_ROOM)
}
fn fit_text(out: &mut Map<String, Value>, content: &str, file_cut: bool, csv_cut: bool) {
let shown = cut_escaped(content, room(out));
let mut notes = vec![];
if csv_cut {
notes.push(format!("The first {CSV_PREVIEW_ROWS} rows only."));
}
if file_cut || shown.len() < content.len() {
notes.push("Only the start of the file.".to_string());
}
out.insert("preview".into(), shown.into());
if !notes.is_empty() {
out.insert("note".into(), notes.join(" ").into());
}
}
/// The Parquet rows that fit the result, with long strings cut at any depth; a first row
/// too wide on its own keeps its leading columns.
fn fit_rows(out: &mut Map<String, Value>, returned: &[Value]) {
let mut room = room(out);
let mut cut_cells = false;
// the array's brackets, then each row and its separator
let mut bytes = 2;
for row in rows {
let mut rows = vec![];
let mut left_out = vec![];
for row in returned {
let mut row = row.clone();
if let Value::Object(cells) = &mut row {
for cell in cells.values_mut() {
if let Value::String(s) = cell {
if let Some((end, _)) = s.char_indices().nth(MAX_CELL_CHARS) {
s.truncate(end);
cut_cells = true;
cut_cells |= cut_strings(&mut row);
// An array element sits two levels deep, behind its indent and separator.
let cost = pretty_len(&row, 2) + 6;
if cost <= room {
room -= cost;
rows.push(row);
continue;
}
if rows.is_empty() {
if let Value::Object(cells) = row {
let mut kept = Map::new();
for (column, cell) in cells {
let cost = column.len() + pretty_len(&cell, 3) + 12;
if left_out.is_empty() && cost <= room {
room -= cost;
kept.insert(column, cell);
} else {
left_out.push(column);
}
}
rows.push(Value::Object(kept));
}
}
bytes += row.to_string().len() + 1;
if bytes > PREVIEW_BYTES as usize && !kept.is_empty() {
break;
}
kept.push(row);
break;
}
let mut notes = vec![];
if rows.len() < returned.len() || returned.len() == PARQUET_PREVIEW_ROWS {
notes.push(match rows.len() {
1 => "The first row only.".to_string(),
n => format!("The first {n} rows only."),
});
}
if cut_cells {
notes.push(format!(
"Text longer than {MAX_CELL_CHARS} characters is cut."
));
}
if !left_out.is_empty() {
notes.push(format!(
"{} columns left out of the row: {}.",
left_out.len(),
left_out.join(", ")
));
}
out.insert("rows".into(), rows.into());
if !notes.is_empty() {
out.insert("note".into(), notes.join(" ").into());
}
}
/// Cut every string in `value` to `MAX_CELL_CHARS`; whether one was.
fn cut_strings(value: &mut Value) -> bool {
match value {
Value::String(s) => match s.char_indices().nth(MAX_CELL_CHARS) {
Some((end, _)) => {
s.truncate(end);
true
}
None => false,
},
Value::Array(items) => items.iter_mut().fold(false, |cut, v| cut_strings(v) | cut),
Value::Object(fields) => fields
.values_mut()
.fold(false, |cut, v| cut_strings(v) | cut),
_ => false,
}
(kept, cut_cells)
}
fn in_storage(storage: Option<&str>) -> String {
@@ -348,17 +461,46 @@ mod tests {
assert_eq!(folder_prefix(Some("/")), "");
}
/// The endpoints return whole rows whatever size was asked, so the tool must bound them.
/// The preview endpoints return whole rows whatever length was asked, and escaping
/// grows text: what bounds the result is its serialized size, which the MCP runner cuts.
#[test]
fn previews_stay_within_the_byte_budget() {
let long = "é".repeat(PREVIEW_BYTES as usize);
let cut = cut_utf8(&long, PREVIEW_BYTES as usize + 1);
assert_eq!(cut.len(), PREVIEW_BYTES as usize);
fn previews_stay_within_the_result_budget() {
let file = || s3_object(&json!("big/file"), None);
let fits = |out: Map<String, Value>| {
let text = pretty(&Value::Object(out));
assert!(text.len() <= RESULT_BUDGET, "{} bytes", text.len());
serde_json::from_str::<Value>(&text).unwrap()
};
let rows: Vec<Value> = (0..50).map(|i| json!({ "id": i, "text": long })).collect();
let (kept, cut_cells) = bounded_rows(&rows);
assert!(cut_cells);
assert!(kept.len() < rows.len());
assert!(Value::from(kept).to_string().len() <= PREVIEW_BYTES as usize);
let mut out = file();
fit_text(
&mut out,
&"\u{1}".repeat(PREVIEW_BYTES as usize),
false,
false,
);
let shown = fits(out);
assert_eq!(shown["note"], "Only the start of the file.");
let wide: Map<String, Value> = (0..100)
.map(|i| (format!("c{i}"), json!("x".repeat(1000))))
.collect();
let mut out = file();
fit_rows(
&mut out,
&[Value::Object(wide.clone()), Value::Object(wide)],
);
let shown = fits(out);
assert_eq!(shown["rows"].as_array().unwrap().len(), 1);
assert!(shown["note"].as_str().unwrap().contains("columns left out"));
let nested = json!({ "id": 1, "tags": ["y".repeat(1_000_000)] });
let mut out = file();
fit_rows(&mut out, &[nested]);
let shown = fits(out);
assert_eq!(
shown["rows"][0]["tags"][0].as_str().unwrap().len(),
MAX_CELL_CHARS
);
}
}
+7 -1
View File
@@ -124,7 +124,13 @@ 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)];
content.extend(
outcome
.images
.into_iter()
.map(|image| ContentBlock::image(image.data, image.mime_type)),
);
let mut result = if outcome.is_error {
CallToolResult::error(content)
} else {
@@ -217,7 +217,7 @@ import { scopedKey, onUserChange, migrateLegacyLocalStorage } from '$lib/userSco
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
import { AttachedFilesStore } from './files/attachedFiles.svelte'
import { SessionArtifactsStore } from './artifacts/artifactsState.svelte'
import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRouter'
import type { ArtifactVersionTarget, S3FileRef } from '$lib/components/sessions/previewRouter'
import { appendAttachedFilesRoster } from './files/fileTools'
import { ENTER_PLAN_MODE_TOOL, EXIT_PLAN_MODE_TOOL } from './planMode'
import { PlanModeController, type PlanModeHost } from './planModeController.svelte'
@@ -692,6 +692,7 @@ export class AIChatManager implements ChatViewHost {
isRunFormTabOpen?: (toolCallId: string) => boolean
openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void
closeArtifact?: (artifactId: string) => void
openS3File?: (file: S3FileRef) => void
#loading = $state<boolean>(false)
get loading(): boolean {
return this.#loading
@@ -3198,7 +3199,8 @@ export class AIChatManager implements ChatViewHost {
artifacts: this.artifacts,
access: this.#toolAccess,
getChatId: () => this.historyManager.getCurrentChatId(),
openArtifact: this.openArtifact
openArtifact: this.openArtifact,
openS3File: this.openS3File
}
: {}),
testActiveFlow: async (storagePath: string, args?: Record<string, any>, memoryId?: string) =>
@@ -10,7 +10,8 @@
PanelRight,
Lock,
ExternalLink,
BookOpen
BookOpen,
Eye
} from 'lucide-svelte'
import { truncateRev } from '$lib/utils'
import {
@@ -354,6 +355,22 @@
{/if}
{/snippet}
{#snippet s3FileChip()}
{#if message.s3File && chatHost.openS3File}
{@const file = message.s3File}
<Button
variant="default"
unifiedSize="2xs"
title="Open {file.s3} in the side panel"
onClick={() => chatHost.openS3File?.(file)}
endIcon={{ icon: Eye }}
wrapperClasses="shrink-0"
>
{file.s3.split('/').pop()}
</Button>
{/if}
{/snippet}
{#snippet jobLink()}
<a
href="/run/{message.jobId}?workspace={chatHost.operatingWorkspace}"
@@ -394,7 +411,13 @@
headerClass={message.needsConfirmation || pendingOutOfScope ? 'opacity-80' : ''}
labelClass="truncate"
contentClass="space-y-3"
headerRight={showPreviewChip ? previewChip : message.jobId ? jobLink : undefined}
headerRight={showPreviewChip
? previewChip
: message.s3File && chatHost.openS3File && !message.isLoading && !message.error
? s3FileChip
: message.jobId
? jobLink
: undefined}
headerLeft={mcpServer?.workspace ? serverMark : undefined}
>
<!-- Image a tool produced (e.g. take_screenshot) — shown inline, not gated on expand. -->
@@ -14,7 +14,7 @@ import type { ScopeDecision } from './workingScope'
import type { GroupingTools } from './toolGroups'
import type { AttachedFilesStore } from './files/attachedFiles.svelte'
import type { SessionArtifactsStore } from './artifacts/artifactsState.svelte'
import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRouter'
import type { ArtifactVersionTarget, S3FileRef } from '$lib/components/sessions/previewRouter'
import type { FlowAIChatHelpers } from './flow/core'
import type { AppAIChatHelpers } from './app/core'
import type AIChatInput from './AIChatInput.svelte'
@@ -205,6 +205,9 @@ export interface ChatViewHost {
attachedFiles: AttachedFilesStore
artifacts: SessionArtifactsStore
openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void
/** Opens a file of the workspace's object storage in the session's side panel; only a
* session has one. */
openS3File?: (file: S3FileRef) => void
flowAiChatHelpers?: FlowAIChatHelpers
appAiChatHelpers?: AppAIChatHelpers
}
@@ -49,6 +49,8 @@ export type SessionToolResponse = {
text: string
is_error: boolean
effects: SessionToolEffect[]
/** Images the model sees beside the text, base64-encoded. */
images?: { mime_type: string; data: string }[]
}
/** What the browser holds that a tool reads: the editor open on each draft kind, and
@@ -20,7 +20,11 @@ import {
WorkspaceService
} from '$lib/gen'
import { deepEqual } from 'fast-equals'
import { promptSafe, type ArtifactVersionTarget } from '$lib/components/sessions/previewRouter'
import {
promptSafe,
type ArtifactVersionTarget,
type S3FileRef
} from '$lib/components/sessions/previewRouter'
import { canDraftItem, roleCanDraft } from '$lib/editRights'
import { renderPromptTemplate } from './promptTemplate'
import { $ScriptLang } from '$lib/gen/schemas.gen'
@@ -4948,6 +4952,7 @@ export type GlobalToolHelpers = SessionToolHelpers & {
artifacts?: SessionArtifactsStore
getChatId?: () => string | undefined
openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void
openS3File?: (file: S3FileRef) => void
}
function sessionIdFromCtx(ctx: { helpers?: unknown }): string | undefined {
@@ -4,10 +4,8 @@ import { createToolDef } from '../shared'
import { NONE, type SessionTool } from '../sessionCapabilities'
import { enabledMcpPaths } from '$lib/components/mcp/enabledServers'
import { isOwnOrSharedMcpPath, MCP_LIST_PER_PAGE, mcpViewer } from '$lib/components/mcp/ownServers'
import { MAX_ATTACHED_IMAGES, normalizeImageDataUrl, type AttachedImage } from '../imageUtils'
import { modelSupportsVision } from '../../modelConfig'
import { tryGetCurrentModel } from '$lib/aiStore'
import type { GlobalToolHelpers } from './core'
import { MAX_ATTACHED_IMAGES, type AttachedImage } from '../imageUtils'
import { chatModelSeesImages, toolImagesFor } from './toolImages'
/**
* Access to the MCP servers the user has connected (resources of type `mcp`)
@@ -313,20 +311,12 @@ async function executeTool(
return { result, images: [] }
}
const images: AttachedImage[] = []
for (const image of rawImages) {
const name = describeImage(image.index, image.mimeType)
// A text-only model would reject the follow-up image message and fail the turn.
if (!canSeeImages) {
omitted.push(`${name}: the current model cannot read images`)
continue
}
try {
images.push(await normalizeImageDataUrl(`data:${image.mimeType};base64,${image.data}`))
} catch {
omitted.push(`${name}: could not be decoded`)
}
}
const decoded = await toolImagesFor(
rawImages.map((i) => ({ ...i, name: describeImage(i.index, i.mimeType) })),
canSeeImages
)
const images = decoded.images
omitted.push(...decoded.omitted)
const note = imagesNote(images.length, omitted)
return { result: bounded({ success: true, data, ...(note ? { images: note } : {}) }), images }
}
@@ -484,16 +474,13 @@ function createCallTool(servers: McpServer[], mode: 'read' | 'write'): SessionTo
return bounded({ success: false, error })
}
toolCallbacks.setToolStatus(toolId, { content: `Calling ${parsed.tool}...` })
// Re-read per call: the session's model can change between turns.
const sessionAi = (helpers as GlobalToolHelpers | undefined)?.sessionAi
const model = sessionAi ? sessionAi().model : tryGetCurrentModel()
const { result, images } = await executeTool(
workspace,
resolved.server,
resolved.tool,
parsed.arguments ?? {},
isRead,
!model || modelSupportsVision(model.provider, model.model)
chatModelSeesImages(helpers)
)
const caption = `Image(s) returned by ${parsed.tool} on ${resolved.server.path}:`
for (const image of images) toolCallbacks.attachToolImage?.(toolId, { image, caption })
@@ -0,0 +1,34 @@
import { normalizeImageDataUrl, type AttachedImage } from '../imageUtils'
import { modelSupportsVision } from '../../modelConfig'
import { tryGetCurrentModel } from '$lib/aiStore'
import type { GlobalToolHelpers } from './core'
/** Whether the chat's model reads images. Re-read per call: a session's model can change
* between turns, and a text-only model rejects the image message, failing the turn. */
export function chatModelSeesImages(helpers: unknown): boolean {
const sessionAi = (helpers as GlobalToolHelpers | undefined)?.sessionAi
const model = sessionAi ? sessionAi().model : tryGetCurrentModel()
return !model || modelSupportsVision(model.provider, model.model)
}
/** A tool's base64 images, decoded and downscaled for the model; each one it cannot be shown
* is named in `omitted`, for the tool's text to say so. */
export async function toolImagesFor(
raw: { name: string; mimeType: string; data: string }[],
canSeeImages: boolean
): Promise<{ images: AttachedImage[]; omitted: string[] }> {
const images: AttachedImage[] = []
const omitted: string[] = []
for (const image of raw) {
if (!canSeeImages) {
omitted.push(`${image.name}: the current model cannot read images`)
continue
}
try {
images.push(await normalizeImageDataUrl(`data:${image.mimeType};base64,${image.data}`))
} catch {
omitted.push(`${image.name}: could not be decoded`)
}
}
return { images, omitted }
}
@@ -800,6 +800,9 @@ export type ToolDisplayMessage = {
* always-visible card that opens (or focuses) the item's preview in the
* session side panel. Set only for session chats — the side panel is their surface. */
previewCard?: { kind: PreviewCardKind | 'agent'; path: string }
/** A file of the workspace's object storage this tool read, which the row offers to open in
* the session side panel. */
s3File?: { s3: string; storage?: string }
/** Whole text on both sides of an edit this call saved. Kept in full rather than as a
* reference: drafts are overwritten in place, so the sides cannot be fetched back later. */
codeDiff?: ToolCodeDiff
@@ -2,6 +2,8 @@ import { z } from 'zod'
import { createToolDef } from './shared'
import { NONE, type SessionTool } from './sessionCapabilities'
import { runOnServer } from './global/backendSessionTools'
import { chatModelSeesImages, toolImagesFor } from './global/toolImages'
import type { GlobalToolHelpers } from './global/core'
/**
* The workspace's object storage (its large file storage and secondary storages), through the
@@ -39,7 +41,16 @@ const s3KeyArg = z
.string()
.describe('Key of the file, as list_s3_files returns it in `s3`, e.g. `charts/sales.csv`.')
const readS3FileSchema = z.object({ s3: s3KeyArg, storage: storageArg })
const readS3FileSchema = z.object({
s3: s3KeyArg,
storage: storageArg,
open_in_preview: z
.boolean()
.optional()
.describe(
"Also open the file in the side panel next to the chat. Only when the user asks to open or display the file itself: reading it to answer a question about it does not. Only Windmill's own chat has that panel; elsewhere the result's `link` opens the file."
)
})
const deleteS3FileSchema = z.object({ s3: s3KeyArg, storage: storageArg })
const moveS3FileSchema = z.object({
s3: s3KeyArg,
@@ -55,7 +66,7 @@ const listS3FilesToolDef = createToolDef(
const readS3FileToolDef = createToolDef(
readS3FileSchema,
'read_s3_file',
"Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, or the first rows of a Parquet file. Other files, such as images, return their metadata only."
"Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, the first rows of a Parquet file, or the image itself for a png, jpeg, gif or webp of up to 5 MB, which you then see. Other files return their metadata only."
)
const deleteS3FileToolDef = createToolDef(
deleteS3FileSchema,
@@ -100,15 +111,34 @@ export function getStorageTools(): SessionTool<{}>[] {
planModeSafe: true,
lookup: true,
showDetails: true,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
const { s3, storage } = readS3FileSchema.parse(args)
fn: async ({ args, workspace, toolId, toolCallbacks, helpers }) => {
const parsed = readS3FileSchema.parse(args)
const s3 = parsed.s3
const storage = parsed.storage === '_default_' ? undefined : parsed.storage || undefined
toolCallbacks.setToolStatus(toolId, { content: `Reading ${s3}${storageLabel(storage)}...` })
const { text } = await runOnServer('read_s3_file', workspace, args)
const response = await runOnServer('read_s3_file', workspace, args)
const result = JSON.parse(response.text)
const { images, omitted } = await toolImagesFor(
(response.images ?? []).map((i) => ({ name: s3, mimeType: i.mime_type, data: i.data })),
chatModelSeesImages(helpers)
)
const caption = `${s3}${storageLabel(storage)}, as read_s3_file returned it:`
for (const image of images) toolCallbacks.attachToolImage?.(toolId, { image, caption })
if (images.length > 0) result.image = 'attached in the following message'
else if (omitted.length > 0) result.image = `not shown: ${omitted.join('; ')}`
const file = { s3, ...(storage ? { storage } : {}) }
const openS3File = (helpers as GlobalToolHelpers | undefined)?.openS3File
if (parsed.open_in_preview) {
if (openS3File) openS3File(file)
result.side_panel = openS3File ? 'opened' : 'this chat has no side panel'
}
toolCallbacks.setToolStatus(toolId, {
content: `Read ${s3}${storageLabel(storage)}`,
result: JSON.parse(text)
result,
s3File: file,
...(images.length > 0 ? { imageUrl: images[0].dataUrl } : {})
})
return text
return JSON.stringify(result, null, 2)
}
},
{
@@ -21,6 +21,7 @@
import { useSessionPermissions } from './sessionPermissions.svelte'
import ArtifactViewer from '../copilot/chat/artifacts/ArtifactViewer.svelte'
import RunFormPreviewSlot from './RunFormPreviewSlot.svelte'
import S3FilePreview from '../S3FilePreview.svelte'
import { setOverlayHost } from '../common/overlayHost.svelte'
import { setReadOnlyWorkspace } from '../operatingWorkspace.svelte'
@@ -505,6 +506,19 @@
<div class="p-4 text-sm text-tertiary">This artifact is no longer available.</div>
{/if}
</div>
{:else if slot.kind === 's3file' && mounted}
<div
class="absolute inset-0 flex flex-col min-h-0 bg-surface {visibility}"
aria-hidden={!active}
{inert}
>
<S3FilePreview
fileKey={slot.file.s3}
storage={slot.file.storage}
workspace={workspaceId || undefined}
showMetadata
/>
</div>
{:else if slot.kind === 'runform' && mounted}
<div
bind:this={overlayHostEl}
@@ -8,6 +8,8 @@ import {
itemDisplayName,
matchReusablePage,
parseArtifactRoute,
parseS3FileRoute,
s3FileUrl,
parsePreviewItemRoute,
parsePreviewSelectedId,
parseRunFormRoute,
@@ -455,6 +457,20 @@ describe('parsePreviewSelectedId', () => {
})
})
describe('s3 file route', () => {
it('round-trips a key and its storage, and the primary storage as no storage', () => {
for (const file of [
{ s3: 'charts/q1 report#2.csv', storage: 'archive' },
{ s3: 'a/b/c.png' }
]) {
const url = s3FileUrl(file)
expect(parseS3FileRoute(url)).toEqual(file)
expect(resolvePreviewTab(url)).toEqual({ kind: 's3file', file })
expect(workspacePageHref(url)).toBeUndefined()
}
})
})
describe('artifact route', () => {
it('round-trips id and name through artifactUrl → parseArtifactRoute, including special chars', () => {
for (const [id, name] of [
@@ -105,6 +105,11 @@ export type PreviewTarget =
| { type: 'artifact'; id: string; name: string; version?: ArtifactVersionTarget }
| { type: 'runform'; toolCallId: string; label: string }
| { type: 'pageitem'; ref: PageItemRef }
| { type: 's3file'; file: S3FileRef }
/** A file in the workspace's object storage: its key, in the storage it names (the primary
* one when none). */
export type S3FileRef = { s3: string; storage?: string }
/**
* Which side of an item to open when the opener is showing the reader something
@@ -214,7 +219,13 @@ const INJECTED_PARAMS = ['nomenubar', 'workspace'] as const
export function canonicalizeObservedLoc(loc: string): string {
// An artifact or a run form is a scheme, not a path — `new URL` would happily parse it
// and hand back a pathname with the scheme gone.
if (parseArtifactRoute(loc) || parseRunFormRoute(loc) || parsePageItemRoute(loc)) return loc
if (
parseArtifactRoute(loc) ||
parseRunFormRoute(loc) ||
parsePageItemRoute(loc) ||
parseS3FileRoute(loc)
)
return loc
try {
const u = new URL(loc, 'http://_')
for (const p of INJECTED_PARAMS) u.searchParams.delete(p)
@@ -296,6 +307,8 @@ export function describeLocation(loc: string): PreviewLocation {
if (runForm) return { identity: `runform:${runForm.toolCallId}`, view: '', anchor: '' }
const pageItem = parsePageItemRoute(loc)
if (pageItem) return { identity: pageItemUrl(pageItem), view: '', anchor: '' }
const s3File = parseS3FileRoute(loc)
if (s3File) return { identity: s3FileUrl(s3File), view: '', anchor: '' }
// Keyed by its hash: as a bare path it would claim the live editor's tab on the same script.
const historical = parseHistoricalScriptEdit(loc)
if (historical) {
@@ -479,6 +492,8 @@ export function previewLocationLabel(url: string): string {
if (artifact) return artifact.name || 'Artifact'
const runForm = parseRunFormRoute(url)
if (runForm) return runForm.label || 'Run form'
const s3File = parseS3FileRoute(url)
if (s3File) return s3File.s3.split('/').pop() || s3File.s3
const pageItem = parsePageItemRoute(url)
if (pageItem) return pageItem.path.split('/').pop() || pageItem.path
const page = matchReusablePage(url)
@@ -607,6 +622,26 @@ export function parseRunRoute(
}
}
// A file in the workspace's object storage. A scheme for the same reason as artifacts: the tab
// mounts a viewer, there is no page to frame. `_default_` stands for the primary storage, as
// the storage endpoints name it.
export function parseS3FileRoute(url: string): S3FileRef | null {
const m = url.match(/^s3file:([^/?#]+)\/([^?#]+)$/)
if (!m) return null
try {
const storage = decodeURIComponent(m[1])
const s3 = m[2].split('/').map(decodeURIComponent).join('/')
return storage === '_default_' ? { s3 } : { s3, storage }
} catch {
return null
}
}
export function s3FileUrl(file: S3FileRef): string {
const key = file.s3.split('/').map(encodeURIComponent).join('/')
return `s3file:${encodeURIComponent(file.storage || '_default_')}/${key}`
}
export function runFormUrl(toolCallId: string, label: string): string {
return `runform:${encodeURIComponent(toolCallId)}#${encodeURIComponent(label)}`
}
@@ -640,6 +675,7 @@ export type PreviewSlot =
| { kind: 'viewer'; viewerKind: SessionTargetKind | 'agent'; path: string }
| { kind: 'artifact'; id: string; version?: number }
| { kind: 'runform'; toolCallId: string }
| { kind: 's3file'; file: S3FileRef }
| { kind: 'pageitem'; ref: PageItemRef }
| { kind: 'pagelist'; path: string }
| { kind: 'run'; jobId: string; workspace?: string }
@@ -662,6 +698,8 @@ export function resolvePreviewTab(url: string): PreviewSlot {
if (artifact) return { kind: 'artifact', id: artifact.id, version: artifact.version }
const runForm = parseRunFormRoute(url)
if (runForm) return { kind: 'runform', toolCallId: runForm.toolCallId }
const s3File = parseS3FileRoute(url)
if (s3File) return { kind: 's3file', file: s3File }
const pageItem = parsePageItemRoute(url)
if (pageItem) return { kind: 'pageitem', ref: pageItem }
const route = barePath(url)
@@ -702,6 +740,7 @@ export function workspacePageHref(location: string): string | undefined {
switch (slot.kind) {
case 'artifact':
case 'runform':
case 's3file':
return undefined
case 'pageitem':
return pageItemPageHref(slot.ref)
@@ -19,6 +19,8 @@ import {
previewLocationLabel,
resolvePreviewTab,
runFormUrl,
s3FileUrl,
parseS3FileRoute,
barePath,
type ArtifactVersionTarget,
type PreviewItemMode,
@@ -109,6 +111,7 @@ function targetUrl(target: PreviewTarget, onto?: SessionPreviewTab): string {
return artifactUrl(target.id, target.name, keptVersion(target, onto))
}
if (target.type === 'runform') return runFormUrl(target.toolCallId, target.label)
if (target.type === 's3file') return s3FileUrl(target.file)
// A re-point with no mode keeps the side the tab is already on, so an AI write to
// an item the user left on View does not yank them back to the editor.
const mode = target.mode ?? (onto ? (parsePreviewItemRoute(onto.url)?.mode ?? 'edit') : 'edit')
@@ -849,6 +852,7 @@ export function describePreview(
const where = whereIs(t)
const artifact = parseArtifactRoute(where)
const pageItem = parsePageItemRoute(where)
const s3File = parseS3FileRoute(where)
const page = matchPreviewPage(where)
const pipelineFolder = parsePipelineRoute(where)
const route = parsePreviewItemRoute(where)
@@ -856,7 +860,9 @@ export function describePreview(
? // A pinned tab is not showing what the assistant last wrote, and nothing else in this
// summary would tell it so.
`artifact "${artifact.name || 'Artifact'}"${artifact.version ? ` (pinned to v${artifact.version})` : ''}`
: pageItem
: s3File
? `object storage file "${s3File.s3}"${s3File.storage ? ` in storage "${s3File.storage}"` : ''}`
: pageItem
? `${pageItemKindLabel(pageItem).toLowerCase()} "${pageItem.path}"`
: page
? `page "${page.label}"${previewLocationDetail(where)}`
@@ -754,6 +754,9 @@ function createRuntime(session: Session): SessionRuntime {
previewTabs.open({ type: 'artifact', id, name, version })
}
manager.closeArtifact = (id) => previewTabs.closeArtifact(id)
manager.openS3File = (file) => {
previewTabs.open({ type: 's3file', file })
}
// Key the store before any configureGlobalMode runs, so a new session's first create shows at once.
void manager.artifacts.setSession(session.id)