diff --git a/backend/.sqlx/query-8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d.json b/backend/.sqlx/query-8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d.json new file mode 100644 index 0000000000..216c54a3f4 --- /dev/null +++ b/backend/.sqlx/query-8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d.json @@ -0,0 +1,57 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH v AS (\n SELECT c.result #> $3 AS r, created_by\n FROM v2_job_completed c JOIN v2_job USING (id)\n WHERE c.id = $1 AND c.workspace_id = $2 AND ($4::text[] IS NULL OR tag = ANY($4))\n )\n SELECT\n created_by AS \"created_by!\",\n jsonb_typeof(r) AS \"type\",\n length(r::text) AS \"length\",\n CASE WHEN jsonb_typeof(r) = 'object' THEN\n ARRAY(SELECT jsonb_object_keys(r) LIMIT $6)\n END AS \"keys\",\n CASE WHEN jsonb_typeof(r) = 'array' THEN jsonb_array_length(r) END AS \"item_count\",\n CASE WHEN jsonb_typeof(r) = 'array' THEN (\n SELECT jsonb_agg(jsonb_build_object(\n 'length', length(e::text),\n 'keys', CASE WHEN jsonb_typeof(e) = 'object' THEN\n to_jsonb(ARRAY(SELECT jsonb_object_keys(e) LIMIT $6))\n END\n ) ORDER BY i)\n FROM jsonb_array_elements(r) WITH ORDINALITY AS t(e, i)\n WHERE i <= $5\n ) END AS \"items: sqlx::types::Json>\"\n FROM v", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "created_by!", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "type", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "length", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "keys", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "item_count", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "items: sqlx::types::Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "TextArray", + "TextArray", + "Int8", + "Int8" + ] + }, + "nullable": [ + false, + null, + null, + null, + null, + null + ] + }, + "hash": "8b088d35a98d695c35d0ffe3ee3d104d2e4275bd1e9562927d591650382d510d" +} diff --git a/backend/tests/jobs_read_auth.rs b/backend/tests/jobs_read_auth.rs index bffacfbaf0..e52530d63c 100644 --- a/backend/tests/jobs_read_auth.rs +++ b/backend/tests/jobs_read_auth.rs @@ -139,6 +139,10 @@ async fn test_single_job_read_authorization(db: Pool) -> anyhow::Resul "completed/get_result_maybe", format!("completed/get_result_maybe/{VICTIM}"), ), + ( + "completed/get_result_shape", + format!("completed/get_result_shape/{VICTIM}"), + ), ("get_args", format!("get_args/{VICTIM}")), ("get_logs", format!("get_logs/{VICTIM}")), ( @@ -1226,3 +1230,80 @@ async fn test_single_job_read_authorization(db: Pool) -> anyhow::Resul Ok(()) } + +/// `get_result_shape` outlines a result too large to send inline: the viewer draws one row per +/// listed element and reads each one through `get_result?json_path=.`, so the cap, +/// the element order and the path handling are what it relies on. +#[sqlx::test(fixtures("base"))] +async fn test_result_shape(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let job = "99999999-9999-9999-9999-999999999999"; + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email, + kind, script_lang, tag) + VALUES ($1::uuid, 'test-workspace', 'test-user', 'u/test-user', 'test@windmill.dev', + 'script', 'bun', 'bun')", + ) + .bind(job) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status, result) + SELECT $1::uuid, 'test-workspace', 1, 'success'::job_status, jsonb_build_object( + 'render_all', + (SELECT jsonb_agg(CASE WHEN i = 1 THEN jsonb_build_object('png', 'aGVsbG8=') + ELSE jsonb_build_object('n', i) END ORDER BY i) + FROM generate_series(1, 105) AS i))", + ) + .bind(job) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace/jobs_u/completed/get_result_shape/{job}", + server.addr.port() + ); + let shape = |query: &'static str| { + let url = format!("{base}{query}"); + async move { + let resp = client() + .get(url) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await + .expect("request"); + (resp.status(), resp.text().await.expect("body")) + } + }; + + let (status, body) = shape("").await; + assert_eq!(status, 200, "{body}"); + let root: serde_json::Value = serde_json::from_str(&body)?; + assert_eq!(root["type"], "object"); + assert_eq!(root["keys"], serde_json::json!(["render_all"])); + assert!(root.get("items").is_none(), "{body}"); + + let (status, body) = shape("?json_path=render_all").await; + assert_eq!(status, 200, "{body}"); + let list: serde_json::Value = serde_json::from_str(&body)?; + assert_eq!(list["type"], "array"); + assert_eq!(list["item_count"], 105); + let items = list["items"].as_array().expect("items"); + assert_eq!(items.len(), 100); + assert_eq!(items[0]["keys"], serde_json::json!(["png"])); + assert_eq!(items[0]["length"], r#"{"png": "aGVsbG8="}"#.len()); + assert_eq!(items[1]["keys"], serde_json::json!(["n"])); + + let (status, body) = shape("?json_path=render_all.0").await; + assert_eq!(status, 200, "{body}"); + assert_eq!( + serde_json::from_str::(&body)?["keys"], + serde_json::json!(["png"]) + ); + + let (status, body) = shape("?json_path=missing").await; + assert_eq!(status, 404, "{body}"); + + Ok(()) +} diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index b5910f776d..b475e98b03 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -367,7 +367,7 @@ fn extract_domain_from_route( /// exports) and credential minting (`job_view_token`) are deliberately absent — those are /// `jobs:read`. Keep by-id read routes here in sync as they are added, or a run token /// loses the ability to follow its own run through them. -const RUN_WHITELISTED_GET_PATHS: [&'static str; 34] = [ +const RUN_WHITELISTED_GET_PATHS: [&'static str; 35] = [ "jobs_u/get_flow/", "jobs_u/get_root_job_id/", "jobs_u/get/", @@ -381,6 +381,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 34] = [ "jobs_u/completed/get/", "jobs_u/completed/get_result/", "jobs_u/completed/get_result_maybe/", + "jobs_u/completed/get_result_shape/", "jobs_u/completed/get_timing/", "jobs_u/dispatch_events/", "jobs_u/getupdate/", @@ -554,7 +555,7 @@ fn app_embed_job_route_allowed(suffix: &str) -> bool { // `get_root_job_id` is intentionally absent: its handler has no access check at // all (returns any job's root id by id) and the app never calls it, so denying // it costs nothing and avoids leaking a foreign job's flow lineage. - const ALLOWED: [&str; 15] = [ + const ALLOWED: [&str; 16] = [ "jobs_u/get/", "jobs_u/getupdate/", "jobs_u/getupdate_sse/", @@ -568,6 +569,7 @@ fn app_embed_job_route_allowed(suffix: &str) -> bool { "jobs_u/completed/get/", "jobs_u/completed/get_result/", "jobs_u/completed/get_result_maybe/", + "jobs_u/completed/get_result_shape/", "jobs_u/completed/get_timing/", "jobs_u/queue/cancel/", ]; @@ -595,7 +597,7 @@ fn resource_metadata_route_allowed(suffix: &str) -> bool { /// a direct `require_job_within_read_scope`. `jobs/result_by_id/` is absent because it /// resolves a node up through the enclosing flows, past the job the check admitted. /// A route added here without that check serves a path-scoped token every job. -const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 27] = [ +const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 28] = [ "jobs_u/get/", "jobs_u/get_logs/", "jobs_u/get_completed_logs_tail/", @@ -607,6 +609,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 27] = [ "jobs_u/completed/get/", "jobs_u/completed/get_result/", "jobs_u/completed/get_result_maybe/", + "jobs_u/completed/get_result_shape/", "jobs_u/completed/get_timing/", "jobs_u/dispatch_events/", "jobs_u/getupdate/", @@ -1364,13 +1367,17 @@ mod tests { #[test] fn jobs_run_reads_are_limited_to_the_by_id_poll_routes() { let job = "/api/w/test/jobs_u/completed/get_result/019ff012-6b1e-0d6b-fc0d-0c85d34d9cec"; + let shape = + "/api/w/test/jobs_u/completed/get_result_shape/019ff012-6b1e-0d6b-fc0d-0c85d34d9cec"; let list = "/api/w/test/jobs/list"; for scope in ["jobs:run", "jobs:run:scripts:u/admin/script"] { // Following the run it started stays available... - assert!( - check_route_access(&[scope.to_string()], job, "GET").is_ok(), - "{scope} must reach the by-id job poll routes" - ); + for route in [job, shape] { + assert!( + check_route_access(&[scope.to_string()], route, "GET").is_ok(), + "{scope} must reach the by-id job poll route {route}" + ); + } // ...but a run grant is not a licence to enumerate the workspace's jobs. assert!( check_route_access(&[scope.to_string()], list, "GET").is_err(), @@ -1468,6 +1475,7 @@ mod tests { for route in [ format!("jobs_u/get/{id}"), format!("jobs_u/completed/get_result/{id}"), + format!("jobs_u/completed/get_result_shape/{id}"), format!("jobs_u/getupdate_sse/{id}"), format!("jobs_u/flow/approval_info/{id}"), "jobs/list".to_string(), diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 44dff55639..4704016ffc 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -20267,6 +20267,64 @@ paths: application/json: schema: {} + /w/{workspace}/jobs_u/completed/get_result_shape/{id}: + get: + summary: get the outline of a completed job's result + description: | + The JSON length and keys of a completed job's result, or of the value at `json_path` + in it, and the same for each of the first 100 elements of a list. Lets a viewer offer + the parts of a result too large to send inline without reading all of it. + operationId: getCompletedJobResultShape + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/JobId" + - name: json_path + description: dot-separated path into the result, as for getCompletedJobResult + in: query + schema: + type: string + responses: + "200": + description: result outline + content: + application/json: + schema: + type: object + properties: + type: + type: string + description: the JSON type of the value (object, array, string, ...) + length: + type: integer + description: characters in the value's JSON text + keys: + type: array + description: up to 20 of the keys, for an object + items: + type: string + item_count: + type: integer + description: the number of elements, for a list + items: + type: array + description: the first 100 elements, for a list + items: + type: object + properties: + length: + type: integer + keys: + type: array + items: + type: string + required: + - length + required: + - type + - length + /w/{workspace}/jobs_u/completed/get_result_maybe/{id}: get: summary: get completed job result if job is completed diff --git a/backend/windmill-api/src/ai_session_tools/gen/instructions.json b/backend/windmill-api/src/ai_session_tools/gen/instructions.json index 3175fce392..e0dd1ee8b8 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -318,7 +318,7 @@ "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch(\n params?: FetchParams // The union is for auto-completion\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit, \"resultCollection\">\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit, \"resultCollection\">\n ): Promise;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n (strings: TemplateStringsArray, ...values: any[]): SqlStatement;\n query(sql: string, ...params: any[]): SqlStatement;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake:///` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO
SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/
`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"\")` targets a non-default catalog; `wmill.datatable(\"\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on ` — declares an execution-DAG **input** (what triggers/feeds this node). `` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $ (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize `.\n- Optional badges: `// partitioned `, `// freshness ` (e.g. `1h`), `// tag `, `// retry [delay]`, `// data_test ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure = [where ]` and `// dimension = ` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3:///` (**double** slash, non-empty first segment) = a **named secondary** storage called `` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"\"), data)` (or the import-free dict `{\"s3\": \"\"}`), TS `wmill.writeS3File({ s3: \"\" }, data)`. That records the default-storage asset `/`, which a downstream `s3:///` reader connects to (same key both sides). A bare `write_s3_file(\"\", ...)` records **no** asset and produces **no** edge. Add `storage=\"\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake:///
`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes.\n\nA managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.)\n\nA target that names no table — `// materialize`, `// materialize ducklake://`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read.\n\nWrite strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize append` → INSERT-append rows (incremental);\n- `// materialize key=` → merge/upsert on ``.\n\n`// materialize manual ` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned ` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition() = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure = [where ]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension = ` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as ` FILTER (WHERE )`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f//`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there.\n6. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nATTACH 'ducklake://main' AS lake;\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM lake.orders GROUP BY 1\n```\n\nA node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://' AS lake;`, then `lake.
`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.
` does not resolve.\n", "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/` or `flow/`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ : { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", - "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"\" }`: a PDF.\n- `{ \"file\": \"\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", + "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"\" }`: a PDF.\n- `{ \"file\": \"\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Large results\n\nA result stored above about 90 KB is not sent with the run: the run page and the editors offer it\nas a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of\nits elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a\nclick, write the content to the workspace storage and return `{ \"s3\": \"path/to/key\" }`, which is\npreviewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only\nneeds to be looked at.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", "code_mode": "# Solving a task with code\n\nWhen the user asks for something done against the systems their workspace connects to (look\nsomething up in an API, move data, check a status), answer it with a Windmill script run as a\npreview: it executes on the workspace's workers, with its resources. A script that worked can be\nsaved and run as is the next time.\n\n1. **Look for a saved script first**, by the user's words and by the system the task touches. If\n one fits, run it rather than writing new code; if one nearly fits, offer to change it rather\n than writing a near-duplicate.\n2. **Otherwise write one script and run it as a preview.** Do the fetching, filtering and\n combining in the code, and return only what answers the task, not raw API payloads. Take\n credentials as a resource-typed `main` parameter, passed as `$res:` when running, never\n as a token in the code. Give `main` typed parameters for whatever would change between runs,\n so the script is reusable.\n3. **Offer to save it** when the task is likely to come back, without saving it unasked. Saving\n makes a draft, deployed only when the user asks; from then on it is an ordinary script.\n\nFor a third-party API, look up its hub integration for its resource type and how to call it.\n\n" } } diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 67bc2f1f5f..5b99c044a1 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -291,7 +291,10 @@ pub fn workspaced_service() -> Router { ) .route("/add_batch_jobs/{n}", post(add_batch_jobs)) .route("/run/preview_flow", post(run_preview_flow_job)) - .route("/run/flow_test/{*path}", post(crate::flow_test::run_flow_test)) + .route( + "/run/flow_test/{*path}", + post(crate::flow_test::run_flow_test), + ) .route("/run/agent/{*path}", post(crate::agent_runs::run_agent)) .route( "/run_wait_result/preview_flow", @@ -476,6 +479,10 @@ pub fn workspace_unauthed_service() -> Router { .route("/get_flow_debug_info/{id}", get(get_flow_job_debug_info)) .route("/completed/get/{id}", get(get_completed_job)) .route("/completed/get_result/{id}", get(get_completed_job_result)) + .route( + "/completed/get_result_shape/{id}", + get(get_completed_job_result_shape), + ) .route( "/completed/get_result_maybe/{id}", get(get_completed_job_result_maybe), @@ -11428,7 +11435,8 @@ pub(crate) async fn push_preview_flow_job( "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2) WHERE id = $1", uuid, - sqlx::types::Json(test_subflows) as sqlx::types::Json> + sqlx::types::Json(test_subflows) + as sqlx::types::Json> ) .execute(&mut *tx) .await?; @@ -13067,6 +13075,127 @@ async fn get_completed_job_result( Ok(Json(raw_result.result).into_response()) } +/// Elements listed by `get_result_shape`; the rest of a longer list is counted only. +const RESULT_SHAPE_MAX_ITEMS: i64 = 100; +/// Keys listed per object by `get_result_shape`. +const RESULT_SHAPE_MAX_KEYS: i64 = 20; + +#[derive(Deserialize)] +struct ResultShapeQuery { + json_path: Option, +} + +#[derive(Serialize, Deserialize, Debug)] +struct ResultShapeItem { + length: i32, + #[serde(skip_serializing_if = "Option::is_none")] + keys: Option>, +} + +#[derive(Serialize)] +struct ResultShape { + #[serde(rename = "type")] + type_: String, + length: i32, + #[serde(skip_serializing_if = "Option::is_none")] + keys: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + item_count: Option, + #[serde(skip_serializing_if = "Option::is_none")] + items: Option>, +} + +/// The outline of a result too large to send inline: its JSON length, its keys, and the same +/// for each element of a list, so a viewer can offer each part without reading the whole. +async fn get_completed_job_result_shape( + OptViewToken(view_token): OptViewToken, + OptAuthed(opt_authed): OptAuthed, + opt_tokened: OptTokened, + Extension(db): Extension, + Extension(user_db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, + Query(ResultShapeQuery { json_path }): Query, +) -> JsonResult { + let tags = opt_authed + .as_ref() + .map(|authed| get_scope_tags(authed)) + .flatten(); + let path: Vec<&str> = json_path + .as_deref() + .filter(|p| !p.is_empty()) + .map(|p| p.split('.').collect()) + .unwrap_or_default(); + let row = sqlx::query!( + r#"WITH v AS ( + SELECT c.result #> $3 AS r, created_by + FROM v2_job_completed c JOIN v2_job USING (id) + WHERE c.id = $1 AND c.workspace_id = $2 AND ($4::text[] IS NULL OR tag = ANY($4)) + ) + SELECT + created_by AS "created_by!", + jsonb_typeof(r) AS "type", + length(r::text) AS "length", + CASE WHEN jsonb_typeof(r) = 'object' THEN + ARRAY(SELECT jsonb_object_keys(r) LIMIT $6) + END AS "keys", + CASE WHEN jsonb_typeof(r) = 'array' THEN jsonb_array_length(r) END AS "item_count", + CASE WHEN jsonb_typeof(r) = 'array' THEN ( + SELECT jsonb_agg(jsonb_build_object( + 'length', length(e::text), + 'keys', CASE WHEN jsonb_typeof(e) = 'object' THEN + to_jsonb(ARRAY(SELECT jsonb_object_keys(e) LIMIT $6)) + END + ) ORDER BY i) + FROM jsonb_array_elements(r) WITH ORDINALITY AS t(e, i) + WHERE i <= $5 + ) END AS "items: sqlx::types::Json>" + FROM v"#, + id, + &w_id, + &path as &[&str], + tags.as_ref().map(|v| v.as_slice()) as Option<&[&str]>, + RESULT_SHAPE_MAX_ITEMS, + RESULT_SHAPE_MAX_KEYS, + ) + .fetch_optional(&db) + .await?; + let row = not_found_if_none(row, "Completed Job", id.to_string())?; + + require_opt_authed_job_read_access( + &db, + &user_db, + &opt_authed, + &w_id, + &id, + &row.created_by, + view_token.as_deref(), + ) + .await?; + + let Some(type_) = row.r#type else { + return Err(Error::NotFound(format!( + "no value at {} in the result of job {id}", + json_path.unwrap_or_default() + ))); + }; + log_job_view( + &db, + opt_authed.as_ref(), + opt_tokened.token.as_deref(), + &w_id, + &id, + ) + .await?; + + Ok(Json(ResultShape { + type_, + length: row.length.unwrap_or(0), + keys: row.keys, + item_count: row.item_count, + items: row.items.map(|items| items.0), + })) +} + #[derive(Deserialize)] struct CountByTagQuery { horizon_secs: Option, diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index d1005c4026..ca220a6abe 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8763,6 +8763,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for \`s3\`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A \`render_all\` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return \`{ "s3": "path/to/key" }\`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index 33d986c0e9..42026c81f8 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -30,11 +30,17 @@ PanelRightOpen, Table2, Braces, + Brackets, Highlighter, ArrowDownFromLine, Database, + Eye, + FileImage, + FileText, Loader2 } from 'lucide-svelte' + import Tooltip from './Tooltip.svelte' + import MeltTooltip from './meltComponents/Tooltip.svelte' import DataTestsResult from './DataTestsResult.svelte' import Portal from '$lib/components/Portal.svelte' import DisplayResultControlBar from './DisplayResultControlBar.svelte' @@ -61,9 +67,7 @@ import MapResult from './MapResult.svelte' import ChartResult from './display/ChartResult.svelte' import { isChartResult } from './display/displayCatalog' - import DownloadCsv from './table/DownloadCsv.svelte' import { convertJsonToCsv } from './table/tableUtils' - import Tooltip from './Tooltip.svelte' import HighlightTheme from './HighlightTheme.svelte' import type { DisplayResultUi } from './custom_ui' import { getContext, hasContext, createEventDispatcher, onDestroy, untrack } from 'svelte' @@ -298,8 +302,12 @@ } $effect(() => { tooBigFilename = undefined + tooBigInfo = undefined const apiPath = result === 'WINDMILL_TOO_BIG' ? resultApiPath : undefined if (!apiPath) return + // The placeholder is drawn again (the view showed another result, then this one), so the + // elements loaded before are no longer shown: Load starts over from the first. + if (!untrack(() => tooBigLoaded.loading)) tooBigLoaded = { values: [], loading: false } let stale = false fetchResultAt(apiPath, 'file.filename').then( (name) => { @@ -307,19 +315,173 @@ }, () => {} ) + // `nodeId` reads a flow step's collected results, which have no row of their own. + if (workspaceId && jobId && !nodeId) { + readTooBigShape(workspaceId, jobId).then( + (shape) => { + if (!stale && shape) tooBigInfo = { apiPath, ...shape } + }, + () => {} + ) + } return () => (stale = true) }) + type ResultShape = { + type: string + length: number + keys?: string[] + item_count?: number + items?: { length: number; keys?: string[] }[] + } + /** A part of a large result: the image of an image result (read under its key and wrapped + * back), or an element of a `render_all`. */ + type TooBigPart = { + path: string + index?: number + length: number + imageKind?: string + wrap?: string + } + /** `render_all` elements read per click, and listed before the rest are counted */ + const TOO_BIG_PAGE_SIZE = 10 + const TOO_BIG_LISTED = 5 + type TooBigShape = { + length: number + /** The image of an image result, or the `render_all` elements the shape lists (the first 100) */ + parts: TooBigPart[] + /** Element count, when the result is a list or a `render_all` */ + itemCount?: number + renderAll?: boolean + } + let tooBigInfo = $state<({ apiPath: string } & TooBigShape) | undefined>(undefined) + // Read only on a click: a view is mounted for every loop iteration stepped through and every + // run card of a chat, and each would download the result. Tied to the result it was read + // from, so a new result never shows the previous one's elements. + type TooBigLoaded = { + apiPath?: string + shape?: TooBigShape + /** The `render_all` elements read so far */ + values: unknown[] + loading: boolean + } + let tooBigLoaded = $state({ values: [], loading: false }) + function imageKindOf(keys: string[] | undefined): string | undefined { + return keys?.length === 1 && IMG_KINDS.includes(keys[0]) ? keys[0] : undefined + } + async function fetchResultShape( + workspace: string, + id: string, + jsonPath?: string + ): Promise { + const query = jsonPath ? `?json_path=${jsonPath}` : '' + const r = await fetchViaClient( + appendViewToken(`/w/${workspace}/jobs_u/completed/get_result_shape/${id}${query}`) + ) + return r.ok ? r.json() : undefined + } + async function readTooBigShape(workspace: string, id: string): Promise { + const root = await fetchResultShape(workspace, id) + if (!root) return + const rootImage = imageKindOf(root.keys) + if (rootImage) { + return { + length: root.length, + parts: [{ path: rootImage, length: root.length, imageKind: rootImage, wrap: rootImage }] + } + } + // Only a `render_all` is split into its elements, as it is drawn element by element when + // small. A bare list is drawn as a table, which needs every row, so it loads whole. + if (!(root.keys?.length === 1 && root.keys[0] === 'render_all')) { + return { + length: root.length, + parts: [], + itemCount: root.type === 'array' ? root.item_count : undefined + } + } + const list = await fetchResultShape(workspace, id, 'render_all') + // A `render_all` that is not a list, or a list whose shape could not be read, loads whole + if (list?.type !== 'array' || list.item_count === undefined) { + return { length: root.length, parts: [] } + } + const items = list.items ?? [] + return { + length: root.length, + itemCount: list.item_count, + renderAll: true, + parts: items.map((item, index) => ({ + path: `render_all.${index}`, + index, + length: item.length, + imageKind: imageKindOf(item.keys) + })) + } + } + function formatSize(chars: number): string { + return chars >= 1_000_000 + ? `${(chars / 1_000_000).toFixed(1)} MB` + : `${Math.max(1, Math.round(chars / 1000))} KB` + } + /** Size of the `render_all` elements `from` to `to`, when the shape lists them all */ + function tooBigPageSize(shape: TooBigShape, from: number, to: number): number | undefined { + if (shape.parts.length < to) return undefined + return shape.parts.slice(from, to).reduce((n, p) => n + p.length, 0) + } + /** Reads the whole result, its image, or the next page of its `render_all`, and draws what was + * read in place of the placeholder, as a result under the limit is drawn (Pretty/JSON toggle + * included). A new result from the parent wins. */ + async function loadTooBig(apiPath: string, shape: TooBigShape | undefined) { + const current: TooBigLoaded = + tooBigLoaded.apiPath === apiPath + ? tooBigLoaded + : { apiPath, shape, values: [], loading: false } + if (current.loading) return + tooBigLoaded = { ...current, loading: true } + try { + let next: unknown + let values = current.values + if (shape?.renderAll && shape.itemCount !== undefined) { + const from = values.length + const to = Math.min(shape.itemCount, from + TOO_BIG_PAGE_SIZE) + const page = await Promise.all( + Array.from({ length: to - from }, (_, i) => + fetchResultAt(apiPath, `render_all.${from + i}`) + ) + ) + values = [...values, ...page] + next = { render_all: values } + } else { + const part = shape?.parts[0] + const value = part + ? await fetchResultAt(apiPath, part.path) + : await fetchViaClient(apiPath).then((r) => { + if (!r.ok) throw new Error(`${r.status} ${r.statusText}`) + return r.json() + }) + next = part?.wrap ? { [part.wrap]: value } : value + } + if (resultApiPath !== apiPath || tooBigLoaded.apiPath !== apiPath) return + tooBigLoaded = { ...tooBigLoaded, values } + result = next + } catch (e) { + sendUserToast(`Could not load the result: ${e instanceof Error ? e.message : e}`, true) + } finally { + if (tooBigLoaded.apiPath === apiPath) tooBigLoaded = { ...tooBigLoaded, loading: false } + } + } + function base64ToBytes(content: string): Uint8Array { + const bin = atob(content) + // Filled byte by byte: a per-character array is several times the file's size + const bytes = new Uint8Array(bin.length) + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) + return bytes + } async function downloadTooBigFile(apiPath: string, name: string) { downloadingTooBigFile = true try { const content = await fetchResultAt(apiPath, 'file.content') if (typeof content !== 'string' || !content) throw new Error('the result has no file content') - const bin = atob(content) - // Filled byte by byte: a per-character array is several times the file's size - const bytes = new Uint8Array(bin.length) - for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) // A blob, not a data: URL, which browsers cap well below a large file's size - downloadBlob(new Blob([bytes]), name) + downloadBlob(new Blob([base64ToBytes(content)]), name) } catch (e) { sendUserToast(`Download failed: ${e instanceof Error ? e.message : e}`, true) } finally { @@ -354,8 +516,14 @@ let showMaterializedPreview = $state(true) let is_render_all = $state(false) + /** `roughSizeOfObject` of the result: UTF-16 bytes, two per character. */ + let loadedResultBytes = $state(0) let download_as_csv = $state(false) function inferResultKind(result: any) { + // Reset first: the same view is reused across results (the runs page's preview), and the + // early returns below would keep a previous `render_all` or table's flags. + is_render_all = false + download_as_csv = false if (typeof result === 'string' && result.match(/s3:\/\/[^/]*\/.+/)) { largeObject = true return 's3object' @@ -393,7 +561,8 @@ // same too-big handling as any other oversized result. if (parseAgentResult(result)) { is_render_all = false - largeObject = roughSizeOfObject(result) > DISPLAY_MAX_SIZE + loadedResultBytes = roughSizeOfObject(result) + largeObject = loadedResultBytes > DISPLAY_MAX_SIZE return 'aiagent' } @@ -401,10 +570,15 @@ keys.length == 1 && keys.includes('render_all') && Array.isArray(result['render_all']) let size = roughSizeOfObject(result) + loadedResultBytes = size console.debug('size of object', size) // Otherwise, check if the result is too large (10kb) for json - if (size > TABLE_MAX_SIZE) { + // An image, file, pdf or html result is drawn whatever its size + if ( + size > TABLE_MAX_SIZE && + !(keys.length === 1 && NO_SIZE_LIMIT_KINDS.includes(keys[0])) + ) { largeObject = true if (Array.isArray(result) && isTableRowObject(result)) { download_as_csv = true @@ -888,37 +1062,79 @@ {:else if is_render_all}
{#if !noControls} -
- { - globalForceJson = ev.detail === 'json' - }} - > - {#snippet children({ item })} - - - {/snippet} - -
- {/if} -
- {#each result['render_all'] as res, i} - +
+
+ { + globalForceJson = ev.detail === 'json' + }} + > + {#snippet children({ item })} + + + {/snippet} + +
+ openDrawer()} /> +
+ {/if} + +
+ {#each result['render_all'] as res, i} + +
+ +
{/each} + {#if tooBigLoaded.apiPath === resultApiPath && tooBigLoaded.shape?.itemCount !== undefined && tooBigLoaded.values.length < tooBigLoaded.shape.itemCount} + {@const shape = tooBigLoaded.shape} + {@const done = tooBigLoaded.values.length} + {@const next = Math.min(shape.itemCount ?? 0, done + TOO_BIG_PAGE_SIZE)} + {@const nextSize = tooBigPageSize(shape, done, next)} +
+ {done} of {shape.itemCount} loaded + +
+ {/if}
{:else if resultKind === 'nondisplayable'} @@ -1445,50 +1661,206 @@ >
{:else} - {#if tooBigFilename && resultApiPath} -
- -
- {/if} {#if largeObject} -
{#if resultApiPath && shouldDownloadViaClient()} - + {@const notSent = result === 'WINDMILL_TOO_BIG'} + {@const info = tooBigInfo?.apiPath === resultApiPath ? tooBigInfo : undefined} + {@const loaded = tooBigLoaded.apiPath === resultApiPath ? tooBigLoaded : undefined} + {@const size = notSent ? info?.length : loadedResultBytes / 2} + + {@const toolbarDownloads = + toolbarLocation === 'self' && customUi?.disableDownload !== true} + {#snippet downloadJson(variant: 'default' | 'subtle')} + {#if resultApiPath && shouldDownloadViaClient()} + {:else} - - Download {filename ? '' : 'as JSON'} - + {/if} - {#if download_as_csv} - convertJsonToCsv(result)} - customText="Download as CSV" - /> - {/if} -
- -
- -
+ {/snippet} + {#if notSent} + + {@const parts = info?.parts ?? []} + {@const count = info?.renderAll ? (info.itemCount ?? 0) : 0} + {@const firstPage = Math.min(count, TOO_BIG_PAGE_SIZE)} + {@const loadSize = info?.renderAll ? tooBigPageSize(info, 0, firstPage) : size} +
+ {#snippet partRows(rows: TooBigPart[])} + {#each rows as part (part.path)} + {@const Icon = part.imageKind ? FileImage : Braces} +
  • + + {part.imageKind ? `${part.imageKind.toUpperCase()} image` : 'JSON'} + {formatSize(part.length)} +
  • + {/each} + {/snippet} +
      + {#if parts.length} + {@render partRows(parts.slice(0, TOO_BIG_LISTED))} + {#if Math.max(parts.length, count) > TOO_BIG_LISTED} + {@const rest = parts.slice(TOO_BIG_LISTED)} + {@const images = rest.filter((p) => p.imageKind).length} + {@const json = rest.length - images} + + {@const unlisted = Math.max( + 0, + count - Math.max(parts.length, TOO_BIG_LISTED) + )} +
    • + + + +{[ + images ? `${images} ${images === 1 ? 'image' : 'images'}` : '', + json ? `${json} JSON` : '', + unlisted ? `${unlisted} more` : '' + ] + .filter(Boolean) + .join(', ')} + {#snippet text()} +
        + {@render partRows(rest)} +
      + {/snippet} +
      +
    • + {/if} + {:else} + {@const Icon = tooBigFilename + ? FileText + : info?.itemCount !== undefined + ? Brackets + : Braces} +
    • + + {tooBigFilename ?? + (info?.itemCount !== undefined + ? `List of ${info.itemCount} ${info.itemCount === 1 ? 'item' : 'items'}` + : 'JSON')} + {#if size} + {formatSize(size)} + {/if} +
    • + {/if} +
    +
    + + {#if tooBigFilename && resultApiPath} + + {/if} + {#if !toolbarDownloads} + {@render downloadJson('subtle')} + {/if} +
    + + Over the 90 KB display limit + + Results over 90 KB are kept with the job but not loaded with it, so they + appear here only after you click Load. +

    + For large outputs such as images, files or big tables, we recommend workspace object + storage (S3): write the file there and return + {'{ "s3": "path/to/key" }'}. The job then stores only the path, + and the file is previewed right away, by type, with no Load step. +
    +
    +
    + {:else} + +
    + Shown as JSON: over 50,000 characters + + Results over 50,000 characters are shown as JSON rather than as a table, chart + or document. +

    + For large outputs, we recommend workspace object storage (S3): write the file there + and return {'{ "s3": "path/to/key" }'}, and the file is previewed + by type. +
    +
    + {/if} + {#if !notSent && (download_as_csv || !toolbarDownloads)} +
    + {#if download_as_csv} + + {/if} + {#if !toolbarDownloads} + {@render downloadJson('subtle')} + {/if} +
    + {/if} {/if} {#if result && result != 'WINDMILL_TOO_BIG'} - + {/if} {/if} {:else if typeof result === 'string' && result.length > 0} @@ -1527,63 +1899,64 @@
    No result: {toJsonStr(result)}
    {/if} +{/if} - {#if !disableExpand && !noControls} - - - {#snippet actions()} - {#if customUi?.disableDownload !== true} - {#if resultApiPath && shouldDownloadViaClient()} - - {:else} - - {/if} + +{#if !disableExpand && !noControls} + + + {#snippet actions()} + {#if customUi?.disableDownload !== true} + {#if resultApiPath && shouldDownloadViaClient()} + + {:else} + {/if} - - {/snippet} - - - + {/if} + + {/snippet} + + + - - - - {/if} + + + {/if} diff --git a/frontend/src/lib/components/DisplayResultControlBar.svelte b/frontend/src/lib/components/DisplayResultControlBar.svelte index 6af502a1b8..e9b6e415f9 100644 --- a/frontend/src/lib/components/DisplayResultControlBar.svelte +++ b/frontend/src/lib/components/DisplayResultControlBar.svelte @@ -16,6 +16,7 @@ nodeId?: string | undefined result: any disableTooltips?: boolean + disableExpand?: boolean } let { @@ -25,7 +26,8 @@ jobId = undefined, nodeId = undefined, result, - disableTooltips = false + disableTooltips = false, + disableExpand = false }: Props = $props() const dispatch = createEventDispatcher() @@ -86,7 +88,9 @@ - + {#if !disableExpand} + + {/if} diff --git a/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte b/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte index d9684430c5..1102ea7165 100644 --- a/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte +++ b/frontend/src/lib/components/propertyPicker/ObjectViewer.svelte @@ -51,6 +51,10 @@ connecting?: boolean metaData?: Snippet<[any]> editKey?: Snippet<[any]> + /** Keep each value on its key's line and widen the tree to its widest row, scrolling + * sideways. Off, a long value wraps, which narrow panels (the flow pickers) rely on to + * avoid a horizontal scrollbar. */ + wideRows?: boolean } let { @@ -67,7 +71,8 @@ expandedEvenOnLevel0 = undefined, connecting = false, metaData, - editKey + editKey, + wideRows = false }: Props = $props() let jsonFiltered = $state(untrack(() => json)) @@ -281,7 +286,7 @@ {/if} {#if level == 0} -
    + {#snippet searchControl()} {#if searchOpen}
    {/if} -
    + {/snippet} + {#if wideRows} + + + {:else} +
    + {@render searchControl()} +
    + {/if} {/if} {#if keys.length > 0} @@ -475,7 +494,15 @@ {#if level === 0} - {@render viewerContent()} + {#if wideRows} + +
    + {@render viewerContent()} +
    + {:else} + {@render viewerContent()} + {/if}
    {:else} {@render viewerContent()} diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index b5031e9c25..8bc8b7e1da 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1911,6 +1911,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for \`s3\`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A \`render_all\` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return \`{ "s3": "path/to/key" }\`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories diff --git a/system_prompts/auto-generated/skills/rich-results/SKILL.md b/system_prompts/auto-generated/skills/rich-results/SKILL.md index ec49550773..8c73970720 100644 --- a/system_prompts/auto-generated/skills/rich-results/SKILL.md +++ b/system_prompts/auto-generated/skills/rich-results/SKILL.md @@ -30,6 +30,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus `filename` for a file, and an optional `storage` for `s3`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return `{ "s3": "path/to/key" }`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories diff --git a/system_prompts/base/display-results.md b/system_prompts/base/display-results.md index 17f0c5b864..aa82751ddb 100644 --- a/system_prompts/base/display-results.md +++ b/system_prompts/base/display-results.md @@ -25,6 +25,15 @@ of the shapes below is shown as JSON. Each shape is an object with that one key (plus `filename` for a file, and an optional `storage` for `s3`). A result carrying any other key beside it is shown as JSON. +## Large results + +A result stored above about 90 KB is not sent with the run: the run page and the editors offer it +as a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of +its elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a +click, write the content to the workspace storage and return `{ "s3": "path/to/key" }`, which is +previewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only +needs to be looked at. + ## Choosing one A chart answers a question at a glance: a trend over time (line), a comparison across categories