feat: read and show S3 table files as the job result card does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-12-02 10:08:07 -08:00
co-authored by Claude Opus 5.5
parent 9474ddab97
commit d03dca74fe
6 changed files with 79 additions and 56 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, 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": {
@@ -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<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) {
fn fit_text(out: &mut Map<String, Value>, 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<String, Value>,
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<Value> = 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(),
@@ -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 @@
<div class="text-sm font-medium text-red-700 dark:text-red-400">Could not load asset</div>
<div class="text-2xs text-tertiary break-all">{loadError}</div>
</div>
{: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}
<S3ObjectTable s3object={{ s3: fileMetadata.fileKey, storage }} workspaceId={ws} fill />
{/key}
{:else if fileMetadata && isS3ImageKey(fileMetadata.fileKey)}
<div>
<ExpandableImage
src={`/api/w/${ws}/job_helpers/load_image_preview?file_key=${encodeURIComponent(
@@ -16,9 +16,11 @@
workspaceId?: string | undefined
/** Set in a deployed app: the file is read through the app-scoped `apps_u/*` routes. */
appPath?: string | undefined
/** Take the parent's height, as in a side panel, rather than one sized to the rows. */
fill?: boolean
}
let { s3object, workspaceId = undefined, appPath = undefined }: Props = $props()
let { s3object, workspaceId = undefined, appPath = undefined, fill = false }: Props = $props()
const operatingWorkspace = useOperatingWorkspace()
// DBTable loads no rows without an operating workspace, and a public app sets none.
@@ -111,7 +113,7 @@
})
</script>
<div class="flex flex-col gap-1 mt-2">
<div class="flex flex-col gap-1 {fill ? 'h-full min-h-0' : 'mt-2'}">
{#if isCsv || (isParquet && !s3object.disable_download)}
<div class="flex items-center justify-end gap-4 text-xs text-secondary">
{#if isCsv}
@@ -152,8 +154,8 @@
{/if}
<div
class="overflow-hidden border rounded-md"
style="height: {height}px"
class="overflow-hidden border rounded-md {fill ? 'flex-1 min-h-0' : ''}"
style={fill ? undefined : `height: ${height}px`}
bind:clientWidth={width}
data-interactive
>
@@ -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,
@@ -522,6 +522,7 @@
storage={slot.file.storage}
workspace={workspaceId || undefined}
showMetadata
table
/>
</div>
{:else if slot.kind === 'image' && mounted}