From d03dca74fe2ef60ee4c21c439f1c567d45b55012 Mon Sep 17 00:00:00 2001 From: Guilhem Lemouel Date: Wed, 2 Dec 2026 10:08:07 -0800 Subject: [PATCH] feat: read and show S3 table files as the job result card does Co-Authored-By: Claude Opus 5.5 --- .../src/ai_session_tools/gen/tools.json | 2 +- .../src/ai_session_tools/storage.rs | 93 ++++++++++--------- .../src/lib/components/S3FilePreview.svelte | 27 ++++-- .../common/fileDownload/S3ObjectTable.svelte | 10 +- .../components/copilot/chat/storageTools.ts | 2 +- .../components/sessions/PreviewTabHost.svelte | 1 + 6 files changed, 79 insertions(+), 56 deletions(-) diff --git a/backend/windmill-api/src/ai_session_tools/gen/tools.json b/backend/windmill-api/src/ai_session_tools/gen/tools.json index 9bb250253e..4a87f9bd9c 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/tools.json +++ b/backend/windmill-api/src/ai_session_tools/gen/tools.json @@ -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, the first rows of a Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files 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 or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only.", "parameters": { "type": "object", "properties": { diff --git a/backend/windmill-api/src/ai_session_tools/storage.rs b/backend/windmill-api/src/ai_session_tools/storage.rs index c2d18b96de..195f3b78df 100644 --- a/backend/windmill-api/src/ai_session_tools/storage.rs +++ b/backend/windmill-api/src/ai_session_tools/storage.rs @@ -42,9 +42,7 @@ const PREVIEW_BYTES: u64 = 32 * 1024; 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 TABLE_PREVIEW_ROWS: usize = 50; const MAX_CELL_CHARS: usize = 1000; /// Anthropic refuses an image whose base64 data passes 5 MB, and the server has no image /// library to downscale with. @@ -189,26 +187,40 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { out.insert("link".into(), link.into()); } - if key.to_lowercase().ends_with(".parquet") { + // A table file reads as the result card and the S3 file browser show it: rows parsed by + // the server, with typed columns. + if let Some(endpoint) = table_endpoint(key) { let preview = ctx .get(&with_query( - ctx.ws(&format!( - "job_helpers/load_parquet_preview/{}", - path_enc(key) - )), + ctx.ws(&format!("job_helpers/{endpoint}/{}", path_enc(key))), &[ - ("limit", Some(&PARQUET_PREVIEW_ROWS.to_string())), + ("limit", Some(&TABLE_PREVIEW_ROWS.to_string())), ("storage", storage), ], )) - .await?; - fit_parquet( - &mut out, - array(preview.get("columns")), - array(preview.get("column_types")), - array(preview.get("rows")), - ); - } else if is_image_key(key) { + .await; + match preview { + Ok(preview) => { + if let Some(separator) = preview.get("csv_separator").filter(|s| s.is_string()) { + out.insert("csv_separator".into(), separator.clone()); + } + fit_table( + &mut out, + array(preview.get("columns")), + array(preview.get("column_types")), + array(preview.get("rows")), + ); + return Ok(pretty(&Value::Object(out))); + } + // A CSV the table reader refuses, with ragged rows or a stray quote, still has + // text to show. + Err(e) if endpoint == "load_csv_preview" => { + out.insert("table".into(), format!("not read as a table: {e}").into()); + } + Err(e) => return Err(e), + } + } + if is_image_key(key) { if size > MAX_IMAGE_BYTES { out.insert("image".into(), "not attached: larger than 3.75 MB".into()); } else { @@ -247,9 +259,7 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { match preview["content"].as_str() { Some(content) => { out.insert("content_type".into(), preview["content_type"].clone()); - let csv_cut = - preview["content_type"] == "Csv" && content.lines().count() > CSV_PREVIEW_ROWS; - fit_text(&mut out, content, length < size, csv_cut); + fit_text(&mut out, content, length < size); } None => { // The endpoint's "Preview is not available" reads to a model as if the user @@ -291,6 +301,17 @@ async fn text_preview( .await } +/// The endpoint that reads a table file, by its extension. Both run DataFusion, which +/// filters, sorts and pages on the server; the CSV one sniffs the delimiter and reads +/// newline-delimited JSON by extension. +fn table_endpoint(key: &str) -> Option<&'static str> { + match key.rsplit_once('.')?.1.to_lowercase().as_str() { + "parquet" => Some("load_parquet_preview"), + "csv" | "tsv" | "jsonl" | "ndjson" => Some("load_csv_preview"), + _ => None, + } +} + fn is_image_key(key: &str) -> bool { key.rsplit_once('.') .is_some_and(|(_, ext)| IMAGE_EXTENSIONS.contains(&ext.to_lowercase().as_str())) @@ -338,25 +359,18 @@ fn room(out: &Map) -> usize { RESULT_BUDGET.saturating_sub(pretty_len(&Value::Object(out.clone()), 0) + NOTE_ROOM) } -fn fit_text(out: &mut Map, content: &str, file_cut: bool, csv_cut: bool) { +fn fit_text(out: &mut Map, content: &str, file_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()); + if file_cut || shown.len() < content.len() { + out.insert("note".into(), "Only the start of the file.".into()); } } -/// The schema and rows of a Parquet preview that fit the result. The schema takes at most +/// The schema and rows of a table preview that fit the result. The schema takes at most /// half the room, long strings are cut at any depth, and a first row too wide on its own /// keeps its leading columns. -fn fit_parquet( +fn fit_table( out: &mut Map, columns: &[Value], column_types: &[Value], @@ -430,7 +444,7 @@ fn fit_rows( } break; } - if rows.len() < returned.len() || returned.len() == PARQUET_PREVIEW_ROWS { + if rows.len() < returned.len() || returned.len() == TABLE_PREVIEW_ROWS { notes.push(match rows.len() { 1 => "The first row only.".to_string(), n => format!("The first {n} rows only."), @@ -546,12 +560,7 @@ mod tests { }; let mut out = file(); - fit_text( - &mut out, - &"\u{1}".repeat(PREVIEW_BYTES as usize), - false, - false, - ); + fit_text(&mut out, &"\u{1}".repeat(PREVIEW_BYTES as usize), false); let shown = fits(out); assert_eq!(shown["note"], "Only the start of the file."); @@ -561,7 +570,7 @@ mod tests { let names: Vec = wide.keys().map(|k| json!(k)).collect(); let types = vec![json!("Utf8"); 100]; let mut out = file(); - fit_parquet( + fit_table( &mut out, &names, &types, @@ -579,7 +588,7 @@ mod tests { .map(|n| (n.as_str().unwrap().to_string(), json!("v"))) .collect(); let mut out = file(); - fit_parquet(&mut out, &names, &types, &[Value::Object(row)]); + fit_table(&mut out, &names, &types, &[Value::Object(row)]); let shown = fits(out); assert!(shown["note"] .as_str() @@ -588,7 +597,7 @@ mod tests { let nested = json!({ "id": 1, "tags": ["y".repeat(1_000_000)] }); let mut out = file(); - fit_parquet(&mut out, &[json!("id"), json!("tags")], &[], &[nested]); + fit_table(&mut out, &[json!("id"), json!("tags")], &[], &[nested]); let shown = fits(out); assert_eq!( shown["rows"][0]["tags"][0].as_str().unwrap().len(), diff --git a/frontend/src/lib/components/S3FilePreview.svelte b/frontend/src/lib/components/S3FilePreview.svelte index 360b4e5940..b95da525af 100644 --- a/frontend/src/lib/components/S3FilePreview.svelte +++ b/frontend/src/lib/components/S3FilePreview.svelte @@ -18,9 +18,11 @@ type LoadFilePreviewData, type LoadFilePreviewResponse } from '$lib/gen' - import { displayDate, displaySize, emptyString } from '$lib/utils' + import { displayDate, displaySize, emptyString, isS3ImageKey } from '$lib/utils' import { twMerge } from 'tailwind-merge' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' + import S3ObjectTable from '$lib/components/common/fileDownload/S3ObjectTable.svelte' + import { serverTableFormat } from '$lib/components/s3TableOps' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -53,6 +55,9 @@ csvOptions?: { separator: string | undefined; hasHeader: boolean } /** Merged onto the preview body, below the metadata strip. */ bodyClass?: string + /** Show a CSV, TSV, NDJSON or Parquet file as the paged table a job's result shows, + * rather than its first bytes as text. Off for a caller that draws its own table. */ + table?: boolean // Bump this to force a re-fetch (metadata + preview). Used by the // asset detail pane after an upstream producer run completes — // without it, the "Asset not yet materialized" empty state stays @@ -71,9 +76,15 @@ class: className = '', bodyClass = '', csvOptions = undefined, + table = false, refreshKey }: Props = $props() + /** The table reads through the workspace's storage, not a resource the caller names. */ + function asTable(key: string | undefined): boolean { + return table && !s3ResourcePath && !!key && !!serverTableFormat(key) + } + let csvSeparatorChar: string = $state(',') let csvHasHeader: boolean = $state(true) @@ -168,7 +179,7 @@ lastModified: displayDate(meta.last_modified) } } - await reloadPreview(key, meta?.size_in_bytes, meta?.mime_type) + if (!asTable(key)) await reloadPreview(key, meta?.size_in_bytes, meta?.mime_type) } catch (err: any) { if (isNotFoundError(err)) { notFound = true @@ -203,11 +214,7 @@ filePreview = { fileKey: key, contentPreview: content, contentType: raw.content_type } if (fileMetadata) { fileMetadata.mimeType = - ((key.endsWith('.png') || - key.endsWith('.jpg') || - key.endsWith('.jpeg') || - key.endsWith('.webp')) && - 'Image') || + (isS3ImageKey(key) && 'Image') || (key.endsWith('.pdf') && 'PDF') || filePreview.contentType } @@ -283,7 +290,11 @@
Could not load asset
{loadError}
- {:else if fileMetadata?.fileKey.endsWith('.png') || fileMetadata?.fileKey.endsWith('.jpg') || fileMetadata?.fileKey.endsWith('.jpeg') || fileMetadata?.fileKey.endsWith('.webp')} + {:else if fileMetadata && asTable(fileMetadata.fileKey)} + {#key fileMetadata.fileKey} + + {/key} + {:else if fileMetadata && isS3ImageKey(fileMetadata.fileKey)}
-
+
{#if isCsv || (isParquet && !s3object.disable_download)}
{#if isCsv} @@ -152,8 +154,8 @@ {/if}
diff --git a/frontend/src/lib/components/copilot/chat/storageTools.ts b/frontend/src/lib/components/copilot/chat/storageTools.ts index 0e2f5c74c3..fbd47499d0 100644 --- a/frontend/src/lib/components/copilot/chat/storageTools.ts +++ b/frontend/src/lib/components/copilot/chat/storageTools.ts @@ -66,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, the first rows of a Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files 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 or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only." ) const deleteS3FileToolDef = createToolDef( deleteS3FileSchema, diff --git a/frontend/src/lib/components/sessions/PreviewTabHost.svelte b/frontend/src/lib/components/sessions/PreviewTabHost.svelte index ea561de25d..5151139baf 100644 --- a/frontend/src/lib/components/sessions/PreviewTabHost.svelte +++ b/frontend/src/lib/components/sessions/PreviewTabHost.svelte @@ -522,6 +522,7 @@ storage={slot.file.storage} workspace={workspaceId || undefined} showMetadata + table />
{:else if slot.kind === 'image' && mounted}