diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a0bcf96bc0..4b9f33b294 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.882.0" + ".": "1.883.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 867f120187..07e69fe192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,44 @@ # Changelog +## [1.883.0](https://github.com/windmill-labs/windmill/compare/v1.882.0...v1.883.0) (2026-11-24) + + +### Features + +* alert on same-tag wait deadlocks and fail the waiting parent ([#12613](https://github.com/windmill-labs/windmill/issues/12613)) ([304f912](https://github.com/windmill-labs/windmill/commit/304f9121835655c35091b3a98ddcb6b579548115)) +* **cli:** 30-day CLI login tokens with expiry picker and token roll ([#12621](https://github.com/windmill-labs/windmill/issues/12621)) ([e810cbb](https://github.com/windmill-labs/windmill/commit/e810cbb93a1847ba823cc5088bc3f88ed7552090)) +* fold consecutive test runs of one item in the ai chat ([#12599](https://github.com/windmill-labs/windmill/issues/12599)) ([924d9b7](https://github.com/windmill-labs/windmill/commit/924d9b7755485d59379f1ff745a051ad5da3b820)) +* keep mcp consent page open with a copyable callback for localhost clients ([#12619](https://github.com/windmill-labs/windmill/issues/12619)) ([3194184](https://github.com/windmill-labs/windmill/commit/3194184c521c2ad4a99529f6c7422c14af3ebb84)) +* let the workspace error handler skip jobs started from the UI ([#12624](https://github.com/windmill-labs/windmill/issues/12624)) ([ade2a55](https://github.com/windmill-labs/windmill/commit/ade2a55e862caa78dfca09646aac74670cbfd901)) +* **nsjail:** make rlimit_fsize configurable per worker (NSJAIL_RLIMIT_FSIZE_MB) ([#12609](https://github.com/windmill-labs/windmill/issues/12609)) ([e6d9ff8](https://github.com/windmill-labs/windmill/commit/e6d9ff8f9596f7529c899f9f8fd1d34a91698792)) +* pick how to connect a resource in a wizard, one row per provider ([#12418](https://github.com/windmill-labs/windmill/issues/12418)) ([2ca87ef](https://github.com/windmill-labs/windmill/commit/2ca87efdb8527d591865125db42d9f6f3b42bee3)) +* redesign the token scope picker and add a scope search ([#12595](https://github.com/windmill-labs/windmill/issues/12595)) ([344694a](https://github.com/windmill-labs/windmill/commit/344694ada73c857724cb8244e7e7f8188efa2611)) +* restore working in a new fork from the Home session composer ([#12559](https://github.com/windmill-labs/windmill/issues/12559)) ([1fb70c4](https://github.com/windmill-labs/windmill/commit/1fb70c4fab5379874c42d349120ed2e2db9a0806)) +* show who deployed each version in script and flow history ([#12587](https://github.com/windmill-labs/windmill/issues/12587)) ([ba0ef82](https://github.com/windmill-labs/windmill/commit/ba0ef82eedf97ce310967134b9200c4f93e7c3db)) +* store refreshed installation JWT for managed GitHub app git sync ([#12592](https://github.com/windmill-labs/windmill/issues/12592)) ([c3cb814](https://github.com/windmill-labs/windmill/commit/c3cb814e9e99c414a56fac9e1874f4eed5c1f42c)) + + +### Bug Fixes + +* apply a changed default value to the Time and Date Select app components ([#12581](https://github.com/windmill-labs/windmill/issues/12581)) ([17fe165](https://github.com/windmill-labs/windmill/commit/17fe165d605c6043afd53cdd83a88b63deae3d59)) +* **cli:** require the dot in .fetch.ts/.bun.ts/.deno.ts language suffixes ([#12583](https://github.com/windmill-labs/windmill/issues/12583)) ([ff8f2e0](https://github.com/windmill-labs/windmill/commit/ff8f2e05fb20cf4f5e931f7169856217c8088312)) +* derive chat lookup grouping from tool definitions ([#12596](https://github.com/windmill-labs/windmill/issues/12596)) ([3a720da](https://github.com/windmill-labs/windmill/commit/3a720da989416caabed08e9659b81f04cf510ac1)) +* generate branch predicates from the branch node ([#12623](https://github.com/windmill-labs/windmill/issues/12623)) ([f9ade48](https://github.com/windmill-labs/windmill/commit/f9ade481dae05bdbb0ef876939bcd3e5b7d02da4)) +* harden telemetry submission ([#12606](https://github.com/windmill-labs/windmill/issues/12606)) ([1d3fcb4](https://github.com/windmill-labs/windmill/commit/1d3fcb4a06c26f0007a95fbe40cc55761d4988f5)) +* let a Date & Time input become valid again once a later day is picked ([#12584](https://github.com/windmill-labs/windmill/issues/12584)) ([508b9f8](https://github.com/windmill-labs/windmill/commit/508b9f84f3a9ab80eb37db48c9a1e6c480d0ec55)) +* make schedule and trigger lists usable on small screens ([#12594](https://github.com/windmill-labs/windmill/issues/12594)) ([1fe3704](https://github.com/windmill-labs/windmill/commit/1fe370451576689215678e4da9098b4b342d1220)) +* raise windmill-worker macro recursion limit so main builds again ([#12612](https://github.com/windmill-labs/windmill/issues/12612)) ([db218c0](https://github.com/windmill-labs/windmill/commit/db218c0d3aff6476643fbf98188cf743a5c285ea)) +* serialize BigInt and non-finite elements of sql template arrays ([#12616](https://github.com/windmill-labs/windmill/issues/12616)) ([5044d02](https://github.com/windmill-labs/windmill/commit/5044d02325ff788bb5316e115fc52b377ef3c237)) +* steps inside expanded subflows on the flow detail and run pages ([#12591](https://github.com/windmill-labs/windmill/issues/12591)) ([a5c7dd4](https://github.com/windmill-labs/windmill/commit/a5c7dd4f699c85190eca5cc88717d85fcc28cfae)) +* stop AI sessions rewriting the tab's copy of the AI settings ([#12615](https://github.com/windmill-labs/windmill/issues/12615)) ([a87ab5d](https://github.com/windmill-labs/windmill/commit/a87ab5d6acfac1f175e4abac90e931de91ae4d50)) +* use the session's AI config in session editor tabs ([#12593](https://github.com/windmill-labs/windmill/issues/12593)) ([3ceff81](https://github.com/windmill-labs/windmill/commit/3ceff81e72541d63a29029fd8b296c318cd64b77)) +* **worker:** fall back to host RAM when cgroup v2 memory.max is max ([#12588](https://github.com/windmill-labs/windmill/issues/12588)) ([7d5a09a](https://github.com/windmill-labs/windmill/commit/7d5a09af83d611b06bff881d5c9d6dc57204b567)) + + +### Performance Improvements + +* **worker:** read cgroup and proc files directly instead of spawning cat ([#12614](https://github.com/windmill-labs/windmill/issues/12614)) ([3495d42](https://github.com/windmill-labs/windmill/commit/3495d42f78250572b913d15c0209cb9598f89646)) + ## [1.882.0](https://github.com/windmill-labs/windmill/compare/v1.881.1...v1.882.0) (2026-11-22) diff --git a/backend/.sqlx/query-0fc3318da2c8dd5304a0ba7a83f25cb2b7728ac069dcc29f9c7e76d915ea3076.json b/backend/.sqlx/query-0fc3318da2c8dd5304a0ba7a83f25cb2b7728ac069dcc29f9c7e76d915ea3076.json new file mode 100644 index 0000000000..e5aabe531d --- /dev/null +++ b/backend/.sqlx/query-0fc3318da2c8dd5304a0ba7a83f25cb2b7728ac069dcc29f9c7e76d915ea3076.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COALESCE((error_handler->>'muted_on_ui_runs')::boolean, false) AS \"muted!\"\n FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "muted!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "0fc3318da2c8dd5304a0ba7a83f25cb2b7728ac069dcc29f9c7e76d915ea3076" +} diff --git a/backend/.sqlx/query-4c7e47928b56f337a937013e512f24a1c2a22987d0dbd598ddc0560a140e0bef.json b/backend/.sqlx/query-4c7e47928b56f337a937013e512f24a1c2a22987d0dbd598ddc0560a140e0bef.json new file mode 100644 index 0000000000..dd01dfe7fe --- /dev/null +++ b/backend/.sqlx/query-4c7e47928b56f337a937013e512f24a1c2a22987d0dbd598ddc0560a140e0bef.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT q.tag, j.parent_job AS \"parent!\"\n FROM v2_job_queue q JOIN v2_job j ON j.id = q.id\n WHERE q.id = $1 AND j.parent_job = COALESCE($2, j.parent_job)\n AND NOT q.running AND q.suspend = 0\n AND q.scheduled_for <= now() - make_interval(secs => $3::bigint::double precision)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "tag", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "parent!", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "4c7e47928b56f337a937013e512f24a1c2a22987d0dbd598ddc0560a140e0bef" +} diff --git a/backend/.sqlx/query-636af7f63043d20752ef1ef0968efff600fcc5d453edcff05810220daa306bd1.json b/backend/.sqlx/query-636af7f63043d20752ef1ef0968efff600fcc5d453edcff05810220daa306bd1.json new file mode 100644 index 0000000000..bf211a0200 --- /dev/null +++ b/backend/.sqlx/query-636af7f63043d20752ef1ef0968efff600fcc5d453edcff05810220daa306bd1.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_queue SET extras = extras - 'waiting_on' WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "636af7f63043d20752ef1ef0968efff600fcc5d453edcff05810220daa306bd1" +} diff --git a/backend/.sqlx/query-9445708d7e6ba4ea9ad0dc4b50598d044b520fcaf84323890c0caf422cf7944a.json b/backend/.sqlx/query-9445708d7e6ba4ea9ad0dc4b50598d044b520fcaf84323890c0caf422cf7944a.json new file mode 100644 index 0000000000..0a1b54de1c --- /dev/null +++ b/backend/.sqlx/query-9445708d7e6ba4ea9ad0dc4b50598d044b520fcaf84323890c0caf422cf7944a.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT resource AS \"resource!\" FROM (\n SELECT DISTINCT ON (resource) resource, alert_type\n FROM alerts\n WHERE resource LIKE 'tag_deadlock:%' AND created_at > now() - interval '7 days'\n ORDER BY resource, created_at DESC, id DESC\n ) latest WHERE alert_type = 'critical_error'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "resource!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "9445708d7e6ba4ea9ad0dc4b50598d044b520fcaf84323890c0caf422cf7944a" +} diff --git a/backend/.sqlx/query-9a9766542a3ecc3b928557234298883554463eb6e5ec6ca47d453528c2175a24.json b/backend/.sqlx/query-9a9766542a3ecc3b928557234298883554463eb6e5ec6ca47d453528c2175a24.json new file mode 100644 index 0000000000..2d6bdb65d8 --- /dev/null +++ b/backend/.sqlx/query-9a9766542a3ecc3b928557234298883554463eb6e5ec6ca47d453528c2175a24.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_queue\n SET extras = jsonb_set(COALESCE(extras, '{}'::jsonb), '{waiting_on}',\n jsonb_build_object('child', $2::uuid, 'at', now()))\n WHERE id = $1 AND running\n AND (extras->'waiting_on'->>'child' IS DISTINCT FROM $2::uuid::text\n OR (extras->'waiting_on'->>'at')::timestamptz < now() - interval '5 seconds')", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "9a9766542a3ecc3b928557234298883554463eb6e5ec6ca47d453528c2175a24" +} diff --git a/backend/.sqlx/query-be2bf5ff24ee1daad674cabae2382a0d4d6ca268dbc734cb16b9405914029214.json b/backend/.sqlx/query-be2bf5ff24ee1daad674cabae2382a0d4d6ca268dbc734cb16b9405914029214.json new file mode 100644 index 0000000000..38fe0c7e47 --- /dev/null +++ b/backend/.sqlx/query-be2bf5ff24ee1daad674cabae2382a0d4d6ca268dbc734cb16b9405914029214.json @@ -0,0 +1,36 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH blocked AS (\n SELECT DISTINCT r.worker, c.tag, r.id AS parent\n FROM v2_job_queue r\n JOIN v2_job rj ON rj.id = r.id\n JOIN v2_job_queue c ON c.id = (r.extras->'waiting_on'->>'child')::uuid\n JOIN v2_job cj ON cj.id = c.id AND cj.parent_job = r.id\n WHERE r.running AND r.worker IS NOT NULL AND r.suspend = 0 AND r.started_at IS NOT NULL\n AND (r.extras->'waiting_on'->>'at')::timestamptz\n > now() - make_interval(secs => $3)\n AND rj.kind NOT IN ('flow', 'flowpreview', 'singlestepflow', 'flownode',\n 'unassigned_flow', 'unassigned_singlestepflow')\n AND NOT c.running AND c.suspend = 0\n AND c.scheduled_for <= now() - make_interval(secs => $2::bigint::double precision)\n AND ($1::text IS NULL OR c.tag = $1)\n ),\n live AS (\n SELECT worker, unnest(custom_tags) AS tag, native_mode\n FROM worker_ping\n WHERE ping_at > now() - interval '60 seconds' AND draining IS NOT TRUE\n )\n SELECT l.tag AS \"tag!\", count(*) AS \"workers!\",\n array_agg(b.parent) FILTER (WHERE b.parent IS NOT NULL) AS \"parents!\"\n FROM live l\n LEFT JOIN LATERAL (\n SELECT parent FROM blocked b WHERE b.worker = l.worker AND b.tag = l.tag LIMIT 1\n ) b ON true\n WHERE l.tag IN (SELECT tag FROM blocked)\n GROUP BY l.tag\n HAVING count(*) = count(b.parent) AND NOT bool_or(l.native_mode)\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "tag!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "workers!", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "parents!", + "type_info": "UuidArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8", + "Float8" + ] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "be2bf5ff24ee1daad674cabae2382a0d4d6ca268dbc734cb16b9405914029214" +} diff --git a/backend/.sqlx/query-c93530173f708742b68b268dc2e80e27ca4a83cb8a9893d88b4cd4101b5bae91.json b/backend/.sqlx/query-c93530173f708742b68b268dc2e80e27ca4a83cb8a9893d88b4cd4101b5bae91.json new file mode 100644 index 0000000000..46ddf84a8a --- /dev/null +++ b/backend/.sqlx/query-c93530173f708742b68b268dc2e80e27ca4a83cb8a9893d88b4cd4101b5bae91.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT pg_advisory_xact_lock(hashtext('tag_deadlock:' || $1::text))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "pg_advisory_xact_lock", + "type_info": "Void" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "c93530173f708742b68b268dc2e80e27ca4a83cb8a9893d88b4cd4101b5bae91" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index e21648e63b..d6f9e22136 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -66,9 +66,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +checksum = "ae442e79f0396cdfccee3e4380cc8d4a9fabbd23dc4a25e1bcc7f960693104ed" dependencies = [ "getrandom 0.2.17", "once_cell", @@ -77,14 +77,15 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.12" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38" dependencies = [ "cfg-if", "const-random", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", + "serde", "version_check", "zerocopy", ] @@ -228,9 +229,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" [[package]] name = "ar_archive_writer" @@ -324,7 +325,7 @@ version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70732f04d285d49054a48b72c54f791bb3424abae92d27aafdf776c98af161c8" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow-buffer", "arrow-data", "arrow-schema", @@ -468,7 +469,7 @@ version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd2b45757d6a2373faa3352d02ff5b54b098f5e21dccebc45a21806bc34501e5" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow-array", "arrow-buffer", "arrow-data", @@ -1414,7 +1415,7 @@ dependencies = [ "http 1.5.0", "http-body 0.4.6", "hyper 0.14.32", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.24.2", "hyper-rustls 0.27.10", "hyper-util", @@ -1581,7 +1582,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "itoa", "matchit 0.8.4", @@ -1960,7 +1961,7 @@ dependencies = [ "hex", "http 1.5.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-named-pipe", "hyper-util", "hyperlocal", @@ -2669,21 +2670,20 @@ checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "const-random" -version = "0.1.18" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +checksum = "d38d4bb3e79c716fd0330d8da84171b0135e59e01076e99f22b75a64c56e952c" dependencies = [ "const-random-macro", ] [[package]] name = "const-random-macro" -version = "0.1.16" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +checksum = "d66bb491e9fc48cb3fed9d57df886880a751d540d645ebc86b6d9d35b8fa8457" dependencies = [ - "getrandom 0.2.17", - "once_cell", + "getrandom 0.4.3", "tiny-keccak", ] @@ -2752,9 +2752,9 @@ checksum = "147be55d677052dabc6b22252d5dd0fd4c29c8c27aa4f2fbef0f94aa003b406f" [[package]] name = "cookie" -version = "0.18.2" +version = "0.18.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" dependencies = [ "percent-encoding", "time", @@ -2858,9 +2858,9 @@ checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" [[package]] name = "crc32fast" -version = "1.5.5" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ "cfg-if", ] @@ -3430,7 +3430,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0734015d81c8375eb5d4869b7f7ecccc2ee8d6cb81948ef737cd0e7b743bd69c" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow", "arrow-ipc", "base64 0.22.1", @@ -3670,7 +3670,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "408a05dafdc70d05a38a29005b8b15e21b0238734dab1e98483fcb58038c5aba" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow", "datafusion-common", "datafusion-doc", @@ -3691,7 +3691,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "756d21da2dd6c9bef97af1504970ff56cbf35d03fbd4ffd62827f02f4d2279d4" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow", "datafusion-common", "datafusion-expr-common", @@ -3798,7 +3798,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64c536062b0076f4e30084065d805f389f9fe38af0ca75bcbac86bc5e9fbab65" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow", "datafusion-common", "datafusion-expr", @@ -3820,7 +3820,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8a92b53b3193fac1916a1c5b8e3f4347c526f6822e56b71faa5fb372327a863" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow", "datafusion-common", "datafusion-expr-common", @@ -3853,7 +3853,7 @@ version = "47.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "690c615db468c2e5fe5085b232d8b1c088299a6c63d87fd960a354a71f7acb55" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow", "arrow-ord", "arrow-schema", @@ -4136,7 +4136,7 @@ dependencies = [ "hickory-resolver", "http 1.5.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.27.10", "hyper-util", "ipnet", @@ -4368,7 +4368,7 @@ dependencies = [ "deno_tls", "flate2", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.27.10", "hyper-util", "log", @@ -6054,9 +6054,9 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "globset" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d" +checksum = "71217a07f20b48b4938c14203b77b610f8a7fa6762c3f75394a10c5f31e5aee0" dependencies = [ "aho-corasick", "bstr", @@ -6283,7 +6283,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash 0.7.8", + "ahash 0.7.9", ] [[package]] @@ -6292,7 +6292,7 @@ version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "allocator-api2", ] @@ -6614,7 +6614,7 @@ dependencies = [ "futures", "http 1.5.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.26.0", "hyper-tls", "hyper-tungstenite", @@ -6675,9 +6675,9 @@ dependencies = [ [[package]] name = "hyper" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" dependencies = [ "atomic-waker", "bytes", @@ -6705,7 +6705,7 @@ dependencies = [ "futures-util", "headers", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.27.10", "hyper-util", "pin-project-lite", @@ -6721,7 +6721,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fab3637d6b04a8037af8a266fdf6cf92ea957e8c53981a2bf6136572531025bf" dependencies = [ "hex", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "pin-project-lite", "tokio", @@ -6752,7 +6752,7 @@ checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" dependencies = [ "futures-util", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "log", "rustls 0.22.4", @@ -6770,7 +6770,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "log", "rustls 0.23.40", @@ -6787,7 +6787,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "pin-project-lite", "tokio", @@ -6802,7 +6802,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "native-tls", "tokio", @@ -6817,7 +6817,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a343d17fe7885302ed7252767dc7bb83609a874b6ff581142241ec4b73957ad" dependencies = [ "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "pin-project-lite", "tokio", @@ -6838,7 +6838,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "httparse", - "hyper 1.12.0", + "hyper 1.13.0", "ipnet", "libc", "percent-encoding", @@ -6859,7 +6859,7 @@ checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7" dependencies = [ "hex", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-util", "pin-project-lite", "tokio", @@ -7598,7 +7598,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-http-proxy", "hyper-rustls 0.27.10", "hyper-timeout", @@ -7659,7 +7659,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f1326e946fadf6248febdf8a1c001809c3899ccf48cb9768cbc536b741040dc" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "async-broadcast", "async-stream", "backon", @@ -8931,7 +8931,7 @@ dependencies = [ "http-body-util", "httparse", "humantime", - "hyper 1.12.0", + "hyper 1.13.0", "itertools 0.14.0", "md-5 0.10.6", "parking_lot", @@ -9552,7 +9552,7 @@ version = "55.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b17da4150748086bd43352bc77372efa9b6e3dbd06a04831d2a98c041c225cfa" dependencies = [ - "ahash 0.8.12", + "ahash 0.8.13", "arrow-array", "arrow-buffer", "arrow-cast", @@ -11008,7 +11008,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.27.10", "hyper-tls", "hyper-util", @@ -11056,7 +11056,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-rustls 0.27.10", "hyper-util", "js-sys", @@ -11112,7 +11112,7 @@ dependencies = [ "futures", "getrandom 0.2.17", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "reqwest 0.13.5", "reqwest-middleware", "retry-policies", @@ -11790,9 +11790,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "ryu-js" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" +checksum = "1f232fd0249f55adbe7f15bee58bbbd3d40708000b84e6482066d2ba599e08a9" [[package]] name = "safetensors" @@ -14514,7 +14514,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-timeout", "hyper-util", "percent-encoding", @@ -14546,7 +14546,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.12.0", + "hyper 1.13.0", "hyper-timeout", "hyper-util", "percent-encoding", @@ -15654,7 +15654,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-nats", @@ -15744,7 +15744,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.882.0" +version = "1.883.0" dependencies = [ "async-stream", "async-trait", @@ -15779,7 +15779,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -15792,7 +15792,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "argon2", @@ -15821,7 +15821,7 @@ dependencies = [ "hex", "hmac 0.12.1", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "indexmap 2.14.2", "itertools 0.14.0", "jsonwebtoken 10.4.0", @@ -15934,12 +15934,12 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "lazy_static", "quick_cache", "serde", @@ -15958,7 +15958,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -15975,7 +15975,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", @@ -15986,6 +15986,7 @@ dependencies = [ "lazy_static", "quick_cache", "reqwest 0.13.5", + "semver", "serde", "serde_json", "sqlx", @@ -16001,7 +16002,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.882.0" +version = "1.883.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -16011,7 +16012,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16028,7 +16029,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "base64 0.22.1", @@ -16050,7 +16051,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", @@ -16073,7 +16074,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16089,11 +16090,11 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", - "hyper 1.12.0", + "hyper 1.13.0", "serde", "serde_json", "sql-builder", @@ -16111,7 +16112,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16133,7 +16134,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16147,7 +16148,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-nats", @@ -16183,14 +16184,14 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", "base64 0.22.1", "chrono", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "lazy_static", "serde", "serde_json", @@ -16209,7 +16210,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16237,7 +16238,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", @@ -16259,7 +16260,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16278,14 +16279,14 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", "chrono", "futures", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "itertools 0.14.0", "lazy_static", "prometheus", @@ -16320,7 +16321,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", @@ -16351,7 +16352,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.882.0" +version = "1.883.0" dependencies = [ "lazy_static", "serde", @@ -16363,13 +16364,13 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.882.0" +version = "1.883.0" dependencies = [ "argon2", "axum", "chrono", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "lazy_static", "serde", "serde_json", @@ -16387,7 +16388,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16402,7 +16403,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.882.0" +version = "1.883.0" dependencies = [ "axum", "chrono", @@ -16410,7 +16411,7 @@ dependencies = [ "futures", "hex", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "lazy_static", "magic-crypt", "regex", @@ -16441,7 +16442,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.882.0" +version = "1.883.0" dependencies = [ "chrono", "lazy_static", @@ -16456,7 +16457,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "axum", @@ -16475,7 +16476,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.882.0" +version = "1.883.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16513,7 +16514,7 @@ dependencies = [ "hkdf", "hmac 0.12.1", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "indexmap 2.14.2", "ipnet", "itertools 0.14.0", @@ -16594,7 +16595,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.882.0" +version = "1.883.0" dependencies = [ "chrono", "futures", @@ -16615,7 +16616,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.882.0" +version = "1.883.0" dependencies = [ "regex", "serde", @@ -16632,7 +16633,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16659,7 +16660,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "futures", @@ -16676,7 +16677,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.882.0" +version = "1.883.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16692,7 +16693,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -16714,7 +16715,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -16746,7 +16747,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "arc-swap", @@ -16771,7 +16772,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-stream", @@ -16807,7 +16808,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "futures", @@ -16826,7 +16827,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.882.0" +version = "1.883.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16835,7 +16836,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -16847,7 +16848,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde_json", @@ -16859,7 +16860,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "gosyn", @@ -16871,7 +16872,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -16883,7 +16884,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde_json", @@ -16895,7 +16896,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "nu-parser", @@ -16906,7 +16907,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16917,7 +16918,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16929,7 +16930,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16940,7 +16941,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-recursion", @@ -16963,7 +16964,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde_json", @@ -16975,7 +16976,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -16989,7 +16990,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -17006,7 +17007,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -17019,7 +17020,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde", @@ -17031,7 +17032,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -17049,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -17065,7 +17066,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -17082,7 +17083,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -17096,7 +17097,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-recursion", @@ -17134,7 +17135,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "const_format", @@ -17172,7 +17173,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.882.0" +version = "1.883.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17183,7 +17184,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-recursion", @@ -17194,7 +17195,7 @@ dependencies = [ "futures", "hex", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "lazy_static", "magic-crypt", "quick_cache", @@ -17218,7 +17219,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17242,14 +17243,14 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", "axum", "chrono", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "itertools 0.14.0", "lazy_static", "rand 0.9.5", @@ -17275,7 +17276,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17302,7 +17303,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17335,7 +17336,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17355,7 +17356,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17389,7 +17390,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17401,7 +17402,7 @@ dependencies = [ "hex", "hmac 0.12.1", "http 1.5.0", - "hyper 1.12.0", + "hyper 1.13.0", "itertools 0.14.0", "lazy_static", "matchit 0.7.3", @@ -17426,7 +17427,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17449,7 +17450,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17473,7 +17474,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-nats", @@ -17497,7 +17498,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17532,7 +17533,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17560,7 +17561,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-trait", @@ -17586,7 +17587,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17606,7 +17607,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-once-cell", @@ -17724,7 +17725,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.882.0" +version = "1.883.0" dependencies = [ "bytes", "fs4", @@ -18630,9 +18631,9 @@ dependencies = [ [[package]] name = "zlib-rs" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" [[package]] name = "zmij" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 4fde83d996..d8d7d4a124 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.882.0" +version = "1.883.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.882.0" +version = "1.883.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 771a86c39d..a1fc20442a 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -6c06d688fe435630e2827bc177f066d2646bb768 +a403f3ce12fd150dd649098e61562eda1e6a4d81 diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index ac8e8f90c8..d8bde1faa1 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.882.0" +version = "1.883.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.882.0" +version = "1.883.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.882.0" +version = "1.883.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.882.0" +version = "1.883.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 5e1435d913..998ffc1d4a 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.882.0" +version = "1.883.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 7359e74b40..6c70e666a8 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -4461,6 +4461,17 @@ pub async fn monitor_db( } }; + let tag_deadlock_alerts_f = async { + if server_mode && !initial_load { + if let Some(db) = conn.as_sql() { + if let Err(e) = windmill_common::tag_deadlock::recover_tag_deadlock_alerts(db).await + { + tracing::error!("Failed to check tag deadlock alerts for recovery: {e:#}"); + } + } + } + }; + let worker_groups_alerts_f = async { #[cfg(feature = "enterprise")] if server_mode && !initial_load { @@ -4806,6 +4817,7 @@ pub async fn monitor_db( enforce_offline_caps_f, worker_groups_alerts_f, jobs_waiting_alerts_f, + tag_deadlock_alerts_f, low_disk_alerts_f, apply_autoscaling_f, update_min_worker_version_f, diff --git a/backend/tests/worker.rs b/backend/tests/worker.rs index b655c96fd9..d53c4050fe 100644 --- a/backend/tests/worker.rs +++ b/backend/tests/worker.rs @@ -1240,9 +1240,16 @@ fn main(world: String) -> Result { Ok(()) } +/// The C# tests share the worker's C# cache as `DOTNET_CLI_HOME`, and .NET's first-run setup +/// there is not safe to run twice at once: on a fresh machine one of two concurrent first +/// builds can crash in it. +#[cfg(feature = "csharp")] +static CSHARP_FIRST_RUN: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + #[cfg(feature = "csharp")] #[sqlx::test(fixtures("base"))] async fn test_csharp_job(db: Pool) -> anyhow::Result<()> { + let _first_run = CSHARP_FIRST_RUN.lock().await; initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); @@ -1292,6 +1299,7 @@ class Script async fn test_csharp_job_omitted_args_take_declared_defaults( db: Pool, ) -> anyhow::Result<()> { + let _first_run = CSHARP_FIRST_RUN.lock().await; initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); diff --git a/backend/windmill-api-auth/Cargo.toml b/backend/windmill-api-auth/Cargo.toml index 1461e95237..c2cd3a1674 100644 --- a/backend/windmill-api-auth/Cargo.toml +++ b/backend/windmill-api-auth/Cargo.toml @@ -39,3 +39,6 @@ time.workspace = true anyhow.workspace = true jsonwebtoken = { workspace = true, optional = true } reqwest = { workspace = true, optional = true } + +[dev-dependencies] +semver.workspace = true diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index fdcff11ba6..389c43eb9c 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -140,15 +140,16 @@ impl ApiAuthed { /// reports for these routes. Derived from the token, never from the request, because the /// column is authority-bearing for other kinds (`app` marks a file as app-produced). /// - /// A browser session is left unstamped rather than marked [`JobTriggerKind::Ui`]: that label - /// is one a worker built before this release cannot decode, and it would strand the jobs - /// carrying it. `webhook` has always been decodable, so it is safe to write today. + /// A browser session is [`JobTriggerKind::Ui`], left unstamped until every worker can decode + /// that label: an older one would strand the jobs carrying it. pub fn trigger_or_fallback(&self, trigger: Option) -> Option { if trigger.is_some() { return trigger; } if self.is_session_token { - return None; + return windmill_common::min_version::MIN_VERSION_SUPPORTS_UI_TRIGGER_KIND + .met_conservatively() + .then(|| TriggerMetadata::new(None, JobTriggerKind::Ui)); } Some(TriggerMetadata::new(None, JobTriggerKind::Webhook)) } @@ -1648,11 +1649,11 @@ mod tests { ); } - /// A browser session is the one shape left unstamped, so the Runs page can say "a token - /// started this" without claiming the converse. Every other label — every shape a member - /// can pass to `create_token` — is `webhook`. + /// A browser session is the one shape stamped `ui`, and only once every worker can decode + /// it. Every other label — every shape a member can pass to `create_token` — is `webhook`. #[test] - fn only_a_browser_session_is_left_unstamped() { + fn only_a_browser_session_is_stamped_ui() { + use windmill_common::min_version::MIN_VERSION; let kind_of = |label: Option<&str>| { ApiAuthed { is_session_token: windmill_common::auth::is_session_label(label), @@ -1662,7 +1663,14 @@ mod tests { .map(|t| t.trigger_kind.to_string()) }; - assert_eq!(kind_of(Some("session")), None); + let before = MIN_VERSION.load_full(); + MIN_VERSION.store(std::sync::Arc::new(semver::Version::new(0, 0, 0))); + assert_eq!(kind_of(Some("session")), None, "unknown fleet"); + MIN_VERSION.store(std::sync::Arc::new(semver::Version::new(1, 775, 0))); + assert_eq!(kind_of(Some("session")), None, "a worker predates ui"); + MIN_VERSION.store(std::sync::Arc::new(semver::Version::new(1, 776, 0))); + assert_eq!(kind_of(Some("session")).as_deref(), Some("ui")); + MIN_VERSION.store(before); for label in [ Some("my-personal-token"), diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index e16d8b4c61..d362c91d78 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -512,6 +512,8 @@ pub struct WindmillCompositeResult { result: Option>, } +const DEADLOCK_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5); + pub async fn run_wait_result_internal( db: &DB, uuid: Uuid, @@ -542,6 +544,7 @@ pub async fn run_wait_result_internal( // Once we observe the early_return node failed with a failure_module configured, // its result is final — no need to re-query it on every poll. let mut early_return_failed_and_suppressed = false; + let mut last_deadlock_check = std::time::Instant::now(); loop { if let Some(node_id_for_empty_return) = node_id_for_empty_return @@ -603,6 +606,15 @@ pub async fn run_wait_result_internal( break; } + if last_deadlock_check.elapsed() >= DEADLOCK_CHECK_INTERVAL { + last_deadlock_check = std::time::Instant::now(); + match windmill_common::tag_deadlock::fail_fast_waiting_parent(db, uuid, None).await { + Ok(Some(e)) => return Err(e), + Ok(None) => (), + Err(e) => tracing::warn!("same-tag deadlock check for job {uuid} failed: {e}"), + } + } + let delay = if accumulated_delay <= fast_poll_duration { *WAIT_RESULT_FAST_POLL_INTERVAL_MS } else { diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 3c4b533565..97bcc82cff 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -680,6 +680,9 @@ pub struct EditErrorHandlerNew { pub muted_on_cancel: bool, #[serde(default)] pub muted_on_user_path: bool, + /// Skip runs whose `trigger_kind` is `ui`. `None` keeps the stored value, for the same + /// reason as `fallback_to_instance_alerts`. + pub muted_on_ui_runs: Option, /// Left as `None` by clients that predate the setting (the CLI among them), which must /// keep the stored value rather than silently reset it on every settings push. pub fallback_to_instance_alerts: Option, @@ -711,6 +714,7 @@ impl EditErrorHandler { extra_args: legacy.error_handler_extra_args, muted_on_cancel: legacy.error_handler_muted_on_cancel, muted_on_user_path: false, // Old format doesn't have this field + muted_on_ui_runs: None, fallback_to_instance_alerts: None, }, } @@ -6367,6 +6371,22 @@ async fn edit_error_handler( if let Some(extra_args) = &ee.extra_args { error_handler["extra_args"] = extra_args.clone(); } + // Written only when set, so the blob of every workspace that never turns it on, and + // its `settings.yaml`, stays as it was before the flag existed. + let muted_on_ui_runs = match ee.muted_on_ui_runs { + Some(muted) => muted, + None => sqlx::query_scalar!( + "SELECT COALESCE((error_handler->>'muted_on_ui_runs')::boolean, false) AS \"muted!\" + FROM workspace_settings WHERE workspace_id = $1", + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .unwrap_or(false), + }; + if muted_on_ui_runs { + error_handler["muted_on_ui_runs"] = serde_json::Value::Bool(true); + } sqlx::query!( "UPDATE workspace_settings SET error_handler = $1 WHERE workspace_id = $2", diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 3cc0878ce1..def62b1675 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.882.0 + version: 1.883.0 title: Windmill API contact: @@ -9182,13 +9182,21 @@ paths: type: string supports_client_credentials: type: boolean + supports_authorization_code: + type: boolean + description: The instance entry declares the authorization-code grant, so users can sign in with their own account when has_shared_credentials is also true. has_shared_credentials: type: boolean - description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account. Whether client credentials are shared is get_connect's client_credentials_configured. + description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account. + shares_client_credentials: + type: boolean + description: Users may connect as the instance entry's own app with its shared client credentials, with no sign-in. required: - name - supports_client_credentials + - supports_authorization_code - has_shared_credentials + - shares_client_credentials /oauth/get_connect/{client}: get: @@ -19485,6 +19493,15 @@ paths: - $ref: "#/components/parameters/WorkspaceId" - $ref: "#/components/parameters/JobId" - $ref: "#/components/parameters/GetStarted" + - name: wait_for_child + description: | + Set by a job's SDK wait helpers when the calling job is blocked until this job, its + child, completes. If every worker of the child's tag is held by such a waiting parent, + the child can never start, and the request fails with 409 instead of the wait hanging. + Leave unset for a plain status read. + in: query + schema: + type: boolean responses: "200": @@ -30855,6 +30872,10 @@ components: muted_on_user_path: type: boolean default: false + muted_on_ui_runs: + type: boolean + default: false + description: Skip jobs started from the UI, whose trigger kind is `ui`. Stored only when true. SuccessHandlerConfig: type: object @@ -30887,6 +30908,9 @@ components: muted_on_user_path: type: boolean default: false + muted_on_ui_runs: + type: boolean + description: Skip jobs started from the UI, whose trigger kind is `ui`. Omit to leave the stored value untouched. fallback_to_instance_alerts: type: boolean description: Report failed jobs to the instance critical alert channels when no workspace error handler is set. Omit to leave the stored value untouched. 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 bea0ff316f..c92a9b0104 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -317,7 +317,7 @@ "datatable.python3": "# 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## 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", "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? }`, `path` being `script/` or `flow/`. |\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`, `RequirePassingCiTests`. 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", + "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`, `RequirePassingCiTests`. 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", "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/ai_session_tools/gen/tools.json b/backend/windmill-api/src/ai_session_tools/gen/tools.json index a9247dfcee..4f1259bcfa 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/tools.json +++ b/backend/windmill-api/src/ai_session_tools/gen/tools.json @@ -79,7 +79,7 @@ "type": "string" }, "job_trigger_kind": { - "description": "Runs: filter by how the job was triggered — one of webhook, default_email, http, websocket, kafka, email, nats, mqtt, amqp, sqs, postgres, schedule, gcp, azure, google, github, asset, freshness, app. comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter). (e.g. '!schedule' to hide scheduled runs)", + "description": "Runs: filter by how the job was triggered — one of webhook, default_email, http, websocket, kafka, email, nats, mqtt, amqp, sqs, postgres, schedule, gcp, azure, google, github, asset, freshness, app, ui. comma-separate to match several values, or prefix each with ! to exclude them instead (never mix included and excluded values in one filter). (e.g. '!schedule' to hide scheduled runs)", "type": "string" }, "label": { diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 3e524344e8..fa57ed4b23 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -12650,6 +12650,28 @@ struct CompletedJobResult { #[derive(Deserialize)] struct GetCompletedJobQuery { get_started: Option, + /// The caller is blocked until this job completes (the SDK wait helpers). Only such polls + /// may be failed for a same-tag deadlock; a plain status read never is. + wait_for_child: Option, +} + +/// Why a job blocked on its own child's result should stop waiting: the child is stuck behind a +/// same-tag deadlock. A failed check answers `None`, so the poll carries on. +async fn waiting_parent_deadlock( + db: &DB, + child: Uuid, + authed: Option<&ApiAuthed>, + wait_for_child: Option, +) -> Option { + if wait_for_child != Some(true) { + return None; + } + let caller = authed?.job_id?; + windmill_common::tag_deadlock::fail_fast_waiting_parent(db, child, Some(caller)) + .await + .inspect_err(|e| tracing::warn!("same-tag deadlock check for job {child} failed: {e}")) + .ok() + .flatten() } async fn get_completed_job_result_maybe( @@ -12659,7 +12681,7 @@ async fn get_completed_job_result_maybe( Extension(db): Extension, Extension(user_db): Extension, Path((w_id, id)): Path<(String, Uuid)>, - Query(GetCompletedJobQuery { get_started }): Query, + Query(GetCompletedJobQuery { get_started, wait_for_child }): Query, ) -> error::Result { let tags = opt_authed .as_ref() @@ -12712,6 +12734,10 @@ async fn get_completed_job_result_maybe( is_skipped: Some(res.is_skipped), }) .into_response()) + } else if let Some(e) = + waiting_parent_deadlock(&db, id, opt_authed.as_ref(), wait_for_child).await + { + Err(e) } else if get_started.is_some_and(|x| x) { // No completed row yet — the job may be queued/running. Returning its // running-state still discloses information about a (possibly private) job, so diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index c817d314f3..25507b4119 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -71,7 +71,9 @@ pub struct WindmillBackend { /// `DisableDirectDeployment` holds a session to reading and running deployed items for /// everyone, admins and bypassers included: that workspace takes changes from its dev workspace /// or a fork, where drafts can go somewhere. Unreadable rules (`None`) hold it too. The in-app -/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. +/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. The +/// chat alone lets a bypasser opt one session into working there directly, behind a confirmation +/// an MCP client has no equivalent of, so a token stays held. fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess { let locked = rules.map_or(true, |rules| { rules diff --git a/backend/windmill-api/src/oauth2_oss.rs b/backend/windmill-api/src/oauth2_oss.rs index 845c989f9a..6f7a2c6daa 100644 --- a/backend/windmill-api/src/oauth2_oss.rs +++ b/backend/windmill-api/src/oauth2_oss.rs @@ -115,7 +115,9 @@ async fn list_logins() -> error::JsonResult { struct OAuthConnectListItem { name: String, supports_client_credentials: bool, + supports_authorization_code: bool, has_shared_credentials: bool, + shares_client_credentials: bool, } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index d793841e6c..0c78f4b947 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -1235,6 +1235,12 @@ fn plan_document( Value::is_boolean, "a boolean", ), + ( + "error_handler", + "muted_on_ui_runs", + Value::is_boolean, + "a boolean", + ), ( "variable_expiration_handler", "muted_on_user_path", @@ -1282,6 +1288,15 @@ fn plan_document( } } } + // ...but stores this one only when on, so an off one compares as absent. + if let Some(handler) = desired + .get_mut("error_handler") + .and_then(Value::as_object_mut) + { + if handler.get("muted_on_ui_runs") != Some(&Value::Bool(true)) { + handler.remove("muted_on_ui_runs"); + } + } for key in SECRET_KEYS { if let Some(v) = desired.remove(*key) { if let Some(v) = resolve_secret(key, v, mc, &mut warnings) { @@ -1429,6 +1444,7 @@ fn plan_document( "extra_args": handler.get("extra_args"), "muted_on_cancel": handler.get("muted_on_cancel").and_then(Value::as_bool).unwrap_or(false), "muted_on_user_path": handler.get("muted_on_user_path").and_then(Value::as_bool).unwrap_or(false), + "muted_on_ui_runs": handler.get("muted_on_ui_runs").and_then(Value::as_bool).unwrap_or(false), "fallback_to_instance_alerts": if fallback_changes { fallback.and_then(|f| f.as_bool()) } else { None }, }), ); @@ -2361,6 +2377,24 @@ mod tests { assert!(p.changes.is_empty(), "{:?}", keys(&p)); } + #[test] + fn muted_on_ui_runs_off_matches_a_blob_without_it() { + let mc = WorkspaceCrypt::new("k"); + let names = DatatableNames::default(); + let mut cur = current(); + cur.insert( + "error_handler".into(), + json!({ "path": "f/x", "muted_on_cancel": false, "muted_on_user_path": false }), + ); + let off = doc(json!({ "error_handler": { "path": "f/x", "muted_on_ui_runs": false } })); + let p = plan_document(cur.clone(), off, false, &mc, &names).unwrap(); + assert!(p.changes.is_empty(), "{:?}", keys(&p)); + + let on = doc(json!({ "error_handler": { "path": "f/x", "muted_on_ui_runs": true } })); + let p = plan_document(cur, on, false, &mc, &names).unwrap(); + assert_eq!(keys(&p), ["error_handler"]); + } + #[test] fn variable_expiration_handler_is_managed_only_when_stated() { let mc = WorkspaceCrypt::new("k"); diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 90710d0933..822b0fda31 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -145,6 +145,7 @@ pub mod ssrf; pub mod stats_ee; pub mod stats_oss; pub mod stream; +pub mod tag_deadlock; #[cfg(feature = "private")] pub mod teams_ee; pub mod teams_oss; diff --git a/backend/windmill-common/src/min_version.rs b/backend/windmill-common/src/min_version.rs index 63b3c7742a..76323620ac 100644 --- a/backend/windmill-common/src/min_version.rs +++ b/backend/windmill-common/src/min_version.rs @@ -48,6 +48,9 @@ pub const MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES: VC = vc(1, 872, 0, "Lease-fre // so a step the test mocks would run for real. Must name the release this ships in. pub const MIN_VERSION_SUPPORTS_FLOW_TEST_SUBFLOWS: VC = vc(1, 879, 0, "Overriding steps inside subflows in flow tests"); +// A worker before this release decodes `trigger_kind` strictly and cannot read `ui`, so a job +// stamped with it would fail on every pull of that worker. +pub const MIN_VERSION_SUPPORTS_UI_TRIGGER_KIND: VC = vc(1, 776, 0, "ui trigger kind"); pub const MIN_VERSION_SUPPORTS_NODE_DEBOUNCING: VC = vc(1, 658, 0, "Flow node debouncing"); pub const MIN_VERSION_SUPPORTS_TOKEN_HASH: VC = vc(1, 659, 0, "Token hash storage"); pub const MIN_VERSION_SUPPORTS_SYNC_JOBS_DEBOUNCING: VC = vc(1, 602, 0, "Sync jobs debouncing"); diff --git a/backend/windmill-common/src/tag_deadlock.rs b/backend/windmill-common/src/tag_deadlock.rs new file mode 100644 index 0000000000..0c89f24a53 --- /dev/null +++ b/backend/windmill-common/src/tag_deadlock.rs @@ -0,0 +1,455 @@ +//! Same-tag wait deadlocks: every live worker serving a tag is executing a job that has a child +//! queued on that same tag, so none of those children can start until a parent gives up. +//! +//! A parent that merely queued a child and carries on (fire-and-forget), or that reads its +//! child's status between other work, looks the same from the queue, and its worker frees up +//! once it finishes. So a holder counts only while it is provably blocked on that very child: +//! the SDK wait helpers say so on each poll (`wait_for_child`), as does a sync `run_wait_result`, +//! and each such check marks the parent's queue row with the child (`extras.waiting_on`). A tag +//! is deadlocked only when every holder is freshly marked as waiting on one of its stuck +//! children; a parent waiting on a child of another tag is not one. +//! +//! Everything here reads the queue across workspaces and writes instance-level alerts: it is +//! for the server's own maintenance and wait paths, never a workspace-facing query. + +use std::{ + collections::HashMap, + sync::Mutex, + time::{Duration, Instant}, +}; + +use uuid::Uuid; + +use crate::{error, DB}; + +lazy_static::lazy_static! { + /// How long a child must have been startable without starting before its tag can be called + /// deadlocked. It absorbs a worker that is between jobs or a parent that is about to finish. + pub static ref TAG_DEADLOCK_GRACE_SECS: i64 = std::env::var("TAG_DEADLOCK_GRACE_SECS") + .ok() + .and_then(|x| x.parse().ok()) + .unwrap_or(60); + + static ref CACHE: Mutex)>> = + Mutex::new(HashMap::new()); +} + +const CACHE_TTL: Duration = Duration::from_secs(5); +/// How long a parent's last wait check on its stuck child counts as it still waiting. Checks +/// mark at most every 5s, so this spans several of them. +const WAITING_MARK_TTL_SECS: f64 = 30.0; + +#[derive(Debug, Clone)] +pub struct TagDeadlock { + pub tag: String, + /// Live workers serving the tag, all of them held by a blocked parent. + pub workers: i64, + /// The jobs holding those workers. + pub parents: Vec, +} + +/// Every tag (or only `tag`) whose live workers are all held by a running job freshly marked as +/// waiting on its own child queued on that tag for longer than the grace period (see the module +/// doc). The child is reached through the mark rather than by walking the parent's children, +/// which on a backlog costs a lookup per queued child. +/// +/// Instance-wide and unauthorized: the parents it returns belong to any workspace, so they may +/// reach superadmin alerts but not a workspace caller. +/// +/// A worker's job is read from `v2_job_queue` (`running`, `worker`), not from +/// `worker_ping.current_job_id`, which keeps naming the last job after the worker went idle. +/// Flow jobs are excluded because they hold no worker while their steps run, and so are +/// parked jobs (a suspended workflow-as-code parent keeps `running` but released its slot). +/// Native-mode workers run several jobs at once, so a tag one of them serves is never reported. +pub async fn deadlocked_tags( + db: impl sqlx::PgExecutor<'_>, + tag: Option<&str>, +) -> error::Result> { + let rows = sqlx::query!( + r#" + WITH blocked AS ( + SELECT DISTINCT r.worker, c.tag, r.id AS parent + FROM v2_job_queue r + JOIN v2_job rj ON rj.id = r.id + JOIN v2_job_queue c ON c.id = (r.extras->'waiting_on'->>'child')::uuid + JOIN v2_job cj ON cj.id = c.id AND cj.parent_job = r.id + WHERE r.running AND r.worker IS NOT NULL AND r.suspend = 0 AND r.started_at IS NOT NULL + AND (r.extras->'waiting_on'->>'at')::timestamptz + > now() - make_interval(secs => $3) + AND rj.kind NOT IN ('flow', 'flowpreview', 'singlestepflow', 'flownode', + 'unassigned_flow', 'unassigned_singlestepflow') + AND NOT c.running AND c.suspend = 0 + AND c.scheduled_for <= now() - make_interval(secs => $2::bigint::double precision) + AND ($1::text IS NULL OR c.tag = $1) + ), + live AS ( + SELECT worker, unnest(custom_tags) AS tag, native_mode + FROM worker_ping + WHERE ping_at > now() - interval '60 seconds' AND draining IS NOT TRUE + ) + SELECT l.tag AS "tag!", count(*) AS "workers!", + array_agg(b.parent) FILTER (WHERE b.parent IS NOT NULL) AS "parents!" + FROM live l + LEFT JOIN LATERAL ( + SELECT parent FROM blocked b WHERE b.worker = l.worker AND b.tag = l.tag LIMIT 1 + ) b ON true + WHERE l.tag IN (SELECT tag FROM blocked) + GROUP BY l.tag + HAVING count(*) = count(b.parent) AND NOT bool_or(l.native_mode) + "#, + tag, + *TAG_DEADLOCK_GRACE_SECS, + WAITING_MARK_TTL_SECS, + ) + .fetch_all(db) + .await?; + + Ok(rows + .into_iter() + .map(|r| TagDeadlock { tag: r.tag, workers: r.workers, parents: r.parents }) + .collect()) +} + +/// The deadlock that the parent waiting on `child` is part of, if any: `child` has not started +/// past the grace period, and every worker of its tag, the parent's included, is held by a job +/// waiting on a child stuck on that tag. `waiter` is the job known to be waiting; `None` takes +/// the child's own `parent_job`, for a caller that created the child and is waiting on it. +/// Marks that parent as waiting on `child`, which is what lets the other holders' checks count it. +async fn deadlock_for_waiting_parent( + db: &DB, + child: Uuid, + waiter: Option, +) -> error::Result> { + let stuck = sqlx::query!( + r#"SELECT q.tag, j.parent_job AS "parent!" + FROM v2_job_queue q JOIN v2_job j ON j.id = q.id + WHERE q.id = $1 AND j.parent_job = COALESCE($2, j.parent_job) + AND NOT q.running AND q.suspend = 0 + AND q.scheduled_for <= now() - make_interval(secs => $3::bigint::double precision)"#, + child, + waiter, + *TAG_DEADLOCK_GRACE_SECS, + ) + .fetch_optional(db) + .await?; + let Some((tag, parent)) = stuck.map(|r| (r.tag, r.parent)) else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE v2_job_queue + SET extras = jsonb_set(COALESCE(extras, '{}'::jsonb), '{waiting_on}', + jsonb_build_object('child', $2::uuid, 'at', now())) + WHERE id = $1 AND running + AND (extras->'waiting_on'->>'child' IS DISTINCT FROM $2::uuid::text + OR (extras->'waiting_on'->>'at')::timestamptz < now() - interval '5 seconds')"#, + parent, + child, + ) + .execute(db) + .await?; + + let cached = CACHE + .lock() + .unwrap() + .get(&tag) + .filter(|(at, _)| at.elapsed() < CACHE_TTL) + .map(|(_, d)| d.clone()); + let deadlock = match cached { + Some(d) => d, + None => { + let d = deadlocked_tags(db, Some(&tag)) + .await? + .into_iter() + .next(); + let mut cache = CACHE.lock().unwrap(); + cache.retain(|_, (at, _)| at.elapsed() < CACHE_TTL); + cache.insert(tag, (Instant::now(), d.clone())); + d + } + }; + Ok(deadlock + .filter(|d| d.parents.contains(&parent)) + .map(|d| (d, parent))) +} + +/// The error to fail a parent's wait on `child` with when it is part of a same-tag deadlock +/// (see [`deadlock_for_waiting_parent`]), after raising the tag's alert. +/// +/// One failed parent is enough to start draining the tag: its worker takes a child, that child's +/// parent completes, and so on. So failing it also clears its waiting mark: until it exits it +/// still holds its worker, and every other parent of the tag would otherwise be failed in that +/// window too. Under the tag's advisory lock the deadlock is read again rather than from the +/// cache, so a check that follows one failure sees that parent no longer waiting. +/// +/// `waiter` must be the authenticated caller's own job, or `None` only when the caller created +/// `child` in this request: the check marks that parent as waiting and fails its wait. +pub async fn fail_fast_waiting_parent( + db: &DB, + child: Uuid, + waiter: Option, +) -> error::Result> { + let Some((d, parent)) = deadlock_for_waiting_parent(db, child, waiter).await? else { + return Ok(None); + }; + let mut tx = db.begin().await?; + sqlx::query!( + "SELECT pg_advisory_xact_lock(hashtext('tag_deadlock:' || $1::text))", + &d.tag + ) + .fetch_one(&mut *tx) + .await?; + let Some(d) = deadlocked_tags(&mut *tx, Some(&d.tag)) + .await? + .into_iter() + .find(|d| d.parents.contains(&parent)) + else { + return Ok(None); + }; + sqlx::query!( + "UPDATE v2_job_queue SET extras = extras - 'waiting_on' WHERE id = $1", + parent + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + alert_on_fail_fast(db, &d).await; + Ok(Some(deadlock_error(child, &d))) +} + +fn deadlock_error(child: Uuid, d: &TagDeadlock) -> error::Error { + error::Error::Generic( + hyper::StatusCode::CONFLICT, + format!( + "job {child} cannot start: every worker serving tag `{}` ({} worker{}) is running a job \ + that waits on a child queued on that same tag, this one included. Run the child on \ + another tag, add workers to `{}`, or use workflow-as-code so the parent releases its \ + worker while it waits.", + d.tag, + d.workers, + if d.workers == 1 { "" } else { "s" }, + d.tag, + ), + ) +} + +const ALERT_RESOURCE_PREFIX: &str = "tag_deadlock:"; + +/// Tag deadlock alerts still open: their latest row is the alert, not its recovery. Read from +/// `alerts` so every server agrees and a restart does not re-alert. +async fn open_alerts(db: &DB) -> error::Result> { + Ok(sqlx::query_scalar!( + r#"SELECT resource AS "resource!" FROM ( + SELECT DISTINCT ON (resource) resource, alert_type + FROM alerts + WHERE resource LIKE 'tag_deadlock:%' AND created_at > now() - interval '7 days' + ORDER BY resource, created_at DESC, id DESC + ) latest WHERE alert_type = 'critical_error'"# + ) + .fetch_all(db) + .await?) +} + +async fn alert_unless_open(db: &DB, d: &TagDeadlock, open: &[String]) { + let resource = format!("{ALERT_RESOURCE_PREFIX}{}", d.tag); + if open.contains(&resource) { + return; + } + crate::utils::report_critical_error( + format!( + "Tag `{}` is deadlocked: all {} of its workers are running a job waiting on a child \ + queued on `{}` for over {}s, which none of them can start. One waiting job is failed \ + to break it. Jobs holding the workers: {}", + d.tag, + d.workers, + d.tag, + *TAG_DEADLOCK_GRACE_SECS, + d.parents + .iter() + .map(|p| p.to_string()) + .collect::>() + .join(", "), + ), + db.clone(), + None, + Some(&resource), + ) + .await; +} + +/// Alerts on a deadlock a waiting parent is about to be failed for. This is the only place a tag +/// deadlock alert is raised: a deadlock counts only while its parents are polling with a fresh +/// waiting mark, and such a poll reaches this path within seconds. +async fn alert_on_fail_fast(db: &DB, d: &TagDeadlock) { + match open_alerts(db).await { + Ok(open) => alert_unless_open(db, d, &open).await, + Err(e) => tracing::warn!("could not read open tag deadlock alerts: {e}"), + } +} + +/// Raises a recovered alert for each tag with an open deadlock alert that is no longer +/// deadlocked. Instance maintenance, run by the server monitor. The queue is only read while an +/// alert is open, so the monitor costs one read of `alerts` the rest of the time. +pub async fn recover_tag_deadlock_alerts(db: &DB) -> error::Result<()> { + for resource in open_alerts(db).await? { + let tag = &resource[ALERT_RESOURCE_PREFIX.len()..]; + if deadlocked_tags(db, Some(tag)).await?.is_empty() { + crate::utils::report_recovered_critical_error( + format!("Tag `{tag}` is no longer deadlocked"), + db.clone(), + None, + Some(&resource), + ) + .await; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn live_worker(db: &DB, worker: &str) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO worker_ping (worker, worker_instance, ping_at, custom_tags) + VALUES ($1, 'test', now(), ARRAY['t1'])", + ) + .bind(worker) + .execute(db) + .await?; + Ok(()) + } + + /// A job of `kind` running on `worker`, with one child queued on `t1` for two minutes. + async fn parent_with_stuck_child( + db: &DB, + worker: &str, + kind: &str, + ) -> anyhow::Result<(Uuid, Uuid)> { + let (parent, child) = (Uuid::new_v4(), Uuid::new_v4()); + sqlx::query("INSERT INTO v2_job (id, workspace_id, kind, tag) VALUES ($1, 'admins', $2::job_kind, 't1')") + .bind(parent) + .bind(kind) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, started_at, worker, tag) + VALUES ($1, 'admins', now(), true, now(), $2, 't1')", + ) + .bind(parent) + .bind(worker) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, kind, tag, parent_job) VALUES ($1, 'admins', 'script', 't1', $2)", + ) + .bind(child) + .bind(parent) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, tag) + VALUES ($1, 'admins', now() - interval '2 minutes', false, 't1')", + ) + .bind(child) + .execute(db) + .await?; + Ok((parent, child)) + } + + async fn mark_waiting(db: &DB, parent: Uuid, child: Uuid) -> anyhow::Result<()> { + sqlx::query( + "UPDATE v2_job_queue SET extras = jsonb_build_object('waiting_on', + jsonb_build_object('child', $2::uuid, 'at', now())) WHERE id = $1", + ) + .bind(parent) + .bind(child) + .execute(db) + .await?; + Ok(()) + } + + #[sqlx::test(migrations = "../migrations")] + async fn a_tag_is_deadlocked_only_when_every_worker_holds_a_blocked_parent( + db: DB, + ) -> anyhow::Result<()> { + live_worker(&db, "w1").await?; + live_worker(&db, "w2").await?; + let (p1, c1) = parent_with_stuck_child(&db, "w1", "script").await?; + mark_waiting(&db, p1, c1).await?; + assert!(deadlocked_tags(&db, None).await?.is_empty(), "w2 is free"); + + // A flow holds no worker while its step waits, nor does a parked workflow-as-code parent. + let (p2, c2) = parent_with_stuck_child(&db, "w2", "flow").await?; + mark_waiting(&db, p2, c2).await?; + assert!(deadlocked_tags(&db, None).await?.is_empty()); + sqlx::query("UPDATE v2_job SET kind = 'script' WHERE id = $1") + .bind(p2) + .execute(&db) + .await?; + sqlx::query("UPDATE v2_job_queue SET suspend = 1, started_at = NULL WHERE id = $1") + .bind(p2) + .execute(&db) + .await?; + assert!(deadlocked_tags(&db, None).await?.is_empty()); + + sqlx::query("UPDATE v2_job_queue SET suspend = 0, started_at = now() WHERE id = $1") + .bind(p2) + .execute(&db) + .await?; + let d = deadlocked_tags(&db, Some("t1")).await?; + assert_eq!(d.len(), 1); + assert_eq!(d[0].workers, 2); + assert!(d[0].parents.contains(&p1) && d[0].parents.contains(&p2)); + sqlx::query("UPDATE v2_job_queue SET extras = extras - 'waiting_on'") + .execute(&db) + .await?; + + // p2 has not polled for its child, so it may be about to finish: no wait is failed yet. + assert!(deadlock_for_waiting_parent(&db, c1, Some(p1)) + .await? + .is_none()); + // Nor while p2 waits on a child of another tag: once that one runs, p2 frees its worker. + let other = Uuid::new_v4(); + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, kind, tag, parent_job) + VALUES ($1, 'admins', 'script', 't2', $2)", + ) + .bind(other) + .bind(p2) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, tag) + VALUES ($1, 'admins', now() - interval '2 minutes', false, 't2')", + ) + .bind(other) + .execute(&db) + .await?; + assert!(deadlock_for_waiting_parent(&db, other, Some(p2)) + .await? + .is_none()); + CACHE.lock().unwrap().clear(); + assert!(deadlock_for_waiting_parent(&db, c1, Some(p1)) + .await? + .is_none()); + CACHE.lock().unwrap().clear(); + // Once p2 waits too, the polling parent of a stuck child is part of the deadlock. + assert!(deadlock_for_waiting_parent(&db, c2, Some(p2)) + .await? + .is_some()); + assert!(deadlock_for_waiting_parent(&db, c1, None).await?.is_some()); + assert!( + deadlock_for_waiting_parent(&db, c1, Some(p2)) + .await? + .is_none(), + "not its child" + ); + + // One failed parent drains the tag. It stops counting as waiting, so the other holder + // is spared while the failed one still holds its worker, whichever process it polls. + assert!(fail_fast_waiting_parent(&db, c1, Some(p1)).await?.is_some()); + assert!(fail_fast_waiting_parent(&db, c2, Some(p2)).await?.is_none()); + Ok(()) + } +} diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index 9ac919fe6e..13292347f2 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -1236,18 +1236,8 @@ pub fn apply_custom_tags_setting(q: Option) { #[cfg(not(windows))] fn parse_file(path: &str) -> Option { - std::process::Command::new("cat") - .args([path]) - .output() - .ok() - .map(|o| { - String::from_utf8_lossy(&o.stdout) - .to_string() - .trim() - .parse::() - .ok() - }) - .flatten() + let bytes = fs::read(path).ok()?; + String::from_utf8_lossy(&bytes).trim().parse::().ok() } #[annotations("#")] @@ -1988,6 +1978,27 @@ fn get_memory_from_meminfo() -> Option { None } +#[cfg(not(windows))] +fn cgroup_v2_memory_limit(cgroup_root: &Path, cgroup_path: &Path) -> Option { + let mut min_limit: Option = None; + for dir in cgroup_path.ancestors() { + if !dir.starts_with(cgroup_root) { + break; + } + if let Ok(contents) = fs::read_to_string(dir.join("memory.max")) { + if let Ok(limit) = contents.trim().parse::() { + if limit >= 0 { + min_limit = Some(min_limit.map_or(limit, |m| m.min(limit))); + } + } + } + if dir == cgroup_root { + break; + } + } + min_limit +} + #[cfg(not(windows))] pub fn get_memory() -> Option { let memory_limit: Option = @@ -1995,21 +2006,16 @@ pub fn get_memory() -> Option { // cgroup v1 parse_file("/sys/fs/cgroup/memory/memory.limit_in_bytes") } else { - // cgroup v2 - let cgroup_path = get_cgroupv2_path()?; - let memory_max_path = format!("{cgroup_path}/memory.max"); - - parse_file(&memory_max_path) + // cgroup v2: walk up to the cgroup root for the tightest numeric limit; + // "max" means uncapped at that level + get_cgroupv2_path() + .and_then(|p| cgroup_v2_memory_limit(Path::new("/sys/fs/cgroup"), Path::new(&p))) }; - // if memory_max is super high, read machine total memory (meminfo) - if memory_limit - .as_ref() - .is_some_and(|x| x > &(1024 * 1024 * 1024 * 1024 * 1024)) - { - get_memory_from_meminfo() - } else { - memory_limit + // if uncapped ("max" on cgroup v2) or super high (cgroup v1), fall back to host RAM + match memory_limit { + Some(limit) if limit >= 0 && limit <= 1024 * 1024 * 1024 * 1024 * 1024 => Some(limit), + _ => get_memory_from_meminfo(), } } @@ -4442,4 +4448,45 @@ mod tests { let _ = std::fs::remove_dir_all(&base); } + + // Tests for cgroup v2 memory limit + #[cfg(not(windows))] + #[test] + fn test_cgroup_v2_memory_limit_walks_ancestors_and_handles_max() { + let root = std::env::temp_dir().join(format!("wm_cgv2_mem_{}", uuid::Uuid::new_v4())); + let slice = root.join("kubepods.slice/pod1"); + let leaf = slice.join("container1"); + std::fs::create_dir_all(&leaf).unwrap(); + + // All "max" -> None (caller falls back to /proc/meminfo) + std::fs::write(slice.join("memory.max"), "max\n").unwrap(); + std::fs::write(leaf.join("memory.max"), "max\n").unwrap(); + assert_eq!(cgroup_v2_memory_limit(&root, &leaf), None); + + // Leaf is "max" but parent slice has a 4 GiB limit -> inherits 4 GiB + std::fs::write(slice.join("memory.max"), "4294967296\n").unwrap(); + assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(4_294_967_296)); + + // Leaf has 8 GiB, parent has 4 GiB -> minimum effective limit (4 GiB) + std::fs::write(leaf.join("memory.max"), "8589934592\n").unwrap(); + assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(4_294_967_296)); + + // Leaf has 2 GiB, parent has 4 GiB -> leaf's tighter limit (2 GiB) + std::fs::write(leaf.join("memory.max"), "2147483648\n").unwrap(); + assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(2_147_483_648)); + + // Container cgroup namespace (`0::/` -> "/sys/fs/cgroup/") reads root/memory.max + std::fs::write(root.join("memory.max"), "1073741824\n").unwrap(); + let root_with_slash = PathBuf::from(format!("{}/", root.display())); + assert_eq!( + cgroup_v2_memory_limit(&root, &root_with_slash), + Some(1_073_741_824) + ); + + // An explicit limit of 0 is preserved (not treated as uncapped); downstream consumers currently treat 0 as no cap. + std::fs::write(leaf.join("memory.max"), "0\n").unwrap(); + assert_eq!(cgroup_v2_memory_limit(&root, &leaf), Some(0)); + + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/backend/windmill-oauth/src/lib.rs b/backend/windmill-oauth/src/lib.rs index e986fffa7d..524b72dfe5 100644 --- a/backend/windmill-oauth/src/lib.rs +++ b/backend/windmill-oauth/src/lib.rs @@ -74,9 +74,10 @@ pub struct ClientWithScopes { /// persist it on client-credentials accounts. pub token_url: String, /// Whether the instance entry carries shared credentials (non-empty id + - /// secret). Providers without them are bring-your-own only — the connect - /// dialog lists them under "Others", not "Instance-configured". + /// secret). Providers without them are bring-your-own only. pub has_shared_credentials: bool, + /// [`OAuthClient::shares_client_credentials`] resolved. + pub shares_client_credentials: bool, /// [`OAuthClient::pkce`] resolved; only the login flow reads it. pub pkce: bool, } diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index 855490935c..2a7c074dc9 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -1426,8 +1426,8 @@ lazy_static::lazy_static! { static ref RESTART_UNLESS_CANCELLED_CACHE: Cache<(i64, String), (bool, Option, Option>)> = Cache::new(10000); // Cache for workspace error handler settings with 60s TTL - // Key: workspace_id, Value: (error_handler, error_handler_extra_args, error_handler_muted_on_cancel, error_handler_muted_on_user_path, report_to_instance_alerts, expiry_timestamp) - static ref WORKSPACE_ERROR_HANDLER_CACHE: Cache, Option>>, bool, bool, bool, i64)> = Cache::new(1000); + // Key: workspace_id, Value: (settings, expiry_timestamp) + static ref WORKSPACE_ERROR_HANDLER_CACHE: Cache = Cache::new(1000); // Best-effort per-worker throttle for the instance-channel fallback: a flapping runnable // would otherwise turn every failure into outbound Slack/SMTP traffic on channels shared by @@ -2989,19 +2989,20 @@ pub async fn report_error_to_workspace_handler_or_critical_side_channel( } } +#[derive(Clone)] +struct WorkspaceErrorHandler { + path: Option, + extra_args: Option>>, + muted_on_cancel: bool, + muted_on_user_path: bool, + muted_on_ui_runs: bool, + report_to_instance_alerts: bool, +} + async fn fetch_error_handler_from_db( db: &Pool, w_id: &str, -) -> Result< - ( - Option, - Option>>, - bool, - bool, - bool, - ), - Error, -> { +) -> Result { sqlx::query_as::< _, ( @@ -3009,6 +3010,7 @@ async fn fetch_error_handler_from_db( Option>>, Option, Option, + Option, bool, ), >( @@ -3018,6 +3020,7 @@ async fn fetch_error_handler_from_db( (error_handler->'extra_args')::text::json, (error_handler->>'muted_on_cancel')::boolean, (error_handler->>'muted_on_user_path')::boolean, + (error_handler->>'muted_on_ui_runs')::boolean, ws.error_handler_fallback_to_instance_alerts AND w.parent_workspace_id IS NULL FROM workspace_settings ws JOIN workspace w ON w.id = ws.workspace_id @@ -3029,14 +3032,20 @@ async fn fetch_error_handler_from_db( .await .context("fetching error handler info from workspace_settings")? .map( - |(path, extra_args, muted_on_cancel, muted_on_user_path, report_to_instance_alerts)| { - ( - path, - extra_args, - muted_on_cancel.unwrap_or(false), - muted_on_user_path.unwrap_or(false), - report_to_instance_alerts, - ) + |( + path, + extra_args, + muted_on_cancel, + muted_on_user_path, + muted_on_ui_runs, + report_to_instance_alerts, + )| WorkspaceErrorHandler { + path, + extra_args, + muted_on_cancel: muted_on_cancel.unwrap_or(false), + muted_on_user_path: muted_on_user_path.unwrap_or(false), + muted_on_ui_runs: muted_on_ui_runs.unwrap_or(false), + report_to_instance_alerts, }, ) .ok_or_else(|| Error::internal_err(format!("no workspace settings for id {w_id}"))) @@ -3051,39 +3060,25 @@ pub async fn send_error_to_workspace_handler<'a, 'c, T: Serialize + Send + Sync> let w_id = &queued_job.workspace_id; let now = chrono::Utc::now().timestamp(); - let ( - error_handler, - error_handler_extra_args, - error_handler_muted_on_cancel, - error_handler_muted_on_user_path, - report_to_instance_alerts, - ) = if let Some(cached) = WORKSPACE_ERROR_HANDLER_CACHE.get(w_id) { - if cached.5 > now { - ( - cached.0.clone(), - cached.1.clone(), - cached.2, - cached.3, - cached.4, - ) - } else { - let row = fetch_error_handler_from_db(db, w_id).await?; - let expiry = now + WORKSPACE_HANDLER_CACHE_TTL_SECONDS; + let handler = match WORKSPACE_ERROR_HANDLER_CACHE.get(w_id) { + Some((handler, expiry)) if expiry > now => handler, + _ => { + let handler = fetch_error_handler_from_db(db, w_id).await?; WORKSPACE_ERROR_HANDLER_CACHE.insert( w_id.clone(), - (row.0.clone(), row.1.clone(), row.2, row.3, row.4, expiry), + (handler.clone(), now + WORKSPACE_HANDLER_CACHE_TTL_SECONDS), ); - row + handler } - } else { - let row = fetch_error_handler_from_db(db, w_id).await?; - let expiry = now + WORKSPACE_HANDLER_CACHE_TTL_SECONDS; - WORKSPACE_ERROR_HANDLER_CACHE.insert( - w_id.clone(), - (row.0.clone(), row.1.clone(), row.2, row.3, row.4, expiry), - ); - row }; + let WorkspaceErrorHandler { + path: error_handler, + extra_args: error_handler_extra_args, + muted_on_cancel, + muted_on_user_path, + muted_on_ui_runs, + report_to_instance_alerts, + } = handler; // Nothing to do for the vast majority of workspaces, and returning here keeps the // per-runnable mute lookup below off the path of every failed job. @@ -3091,12 +3086,12 @@ pub async fn send_error_to_workspace_handler<'a, 'c, T: Serialize + Send + Sync> return Ok(()); } - if is_canceled && error_handler_muted_on_cancel { + if is_canceled && muted_on_cancel { return Ok(()); } // Skip error handler for scripts/flows starting with u/ - if error_handler_muted_on_user_path { + if muted_on_user_path { if let Some(ref path) = queued_job.runnable_path { if path.starts_with("u/") { return Ok(()); @@ -3104,6 +3099,15 @@ pub async fn send_error_to_workspace_handler<'a, 'c, T: Serialize + Send + Sync> } } + if muted_on_ui_runs + && queued_job + .trigger_kind + .as_ref() + .is_some_and(|k| k.is(JobTriggerKind::Ui)) + { + return Ok(()); + } + let ws_error_handler_muted: Option = match queued_job.kind { JobKind::Script => { sqlx::query_scalar!( diff --git a/backend/windmill-queue/tests/workspace_error_handler_test.rs b/backend/windmill-queue/tests/workspace_error_handler_test.rs new file mode 100644 index 0000000000..b3ad9ba03f --- /dev/null +++ b/backend/windmill-queue/tests/workspace_error_handler_test.rs @@ -0,0 +1,76 @@ +// Alone in its binary: the worker caches a workspace's handler settings process-wide for 60s, +// keyed by workspace id, so a second test here would read the first one's settings. +mod workspace_error_handler { + use serde_json::json; + use sqlx::types::Json; + use sqlx::{Pool, Postgres}; + use uuid::Uuid; + + use windmill_common::jobs::{JobKind, JobTriggerKind}; + use windmill_common::scripts::{ScriptHash, ScriptLang}; + use windmill_common::users::username_to_permissioned_as; + use windmill_queue::jobs::{send_error_to_workspace_handler, MiniCompletedJob}; + + const WS: &str = "test-workspace"; + const SCRIPT: &str = "f/system/test_script"; + + fn failed(trigger_kind: JobTriggerKind) -> MiniCompletedJob { + MiniCompletedJob { + id: Uuid::new_v4(), + workspace_id: WS.to_string(), + runnable_id: Some(ScriptHash(100001)), + scheduled_for: chrono::Utc::now(), + parent_job: None, + flow_innermost_root_job: None, + runnable_path: Some(SCRIPT.to_string()), + kind: JobKind::Script, + started_at: Some(chrono::Utc::now()), + permissioned_as: username_to_permissioned_as("test-user"), + created_by: "test-user".to_string(), + script_lang: Some(ScriptLang::Deno), + permissioned_as_email: "test@windmill.dev".to_string(), + flow_step_id: None, + trigger_kind: Some(trigger_kind.into()), + trigger: None, + priority: None, + concurrent_limit: None, + tag: "deno".to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + runnable_settings_handle: None, + build_binary_only: false, + job_token_scopes: None, + } + } + + async fn handler_jobs(db: &Pool) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM v2_job WHERE workspace_id = $1") + .bind(WS) + .fetch_one(db) + .await + .unwrap() + } + + #[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))] + async fn muted_on_ui_runs_skips_only_ui_runs(db: Pool) -> anyhow::Result<()> { + sqlx::query("UPDATE workspace_settings SET error_handler = $1 WHERE workspace_id = $2") + .bind(json!({ "path": format!("script/{SCRIPT}"), "muted_on_ui_runs": true })) + .bind(WS) + .execute(&db) + .await?; + let error = json!({ "error": "boom" }); + + send_error_to_workspace_handler(&failed(JobTriggerKind::Ui), false, &db, Json(&error)) + .await?; + assert_eq!( + handler_jobs(&db).await, + 0, + "a ui run must not reach the handler" + ); + + send_error_to_workspace_handler(&failed(JobTriggerKind::Webhook), false, &db, Json(&error)) + .await?; + assert_eq!(handler_jobs(&db).await, 1, "any other run still does"); + Ok(()) + } +} diff --git a/backend/windmill-types/src/jobs.rs b/backend/windmill-types/src/jobs.rs index ae7e83b697..4a3fe6bdbb 100644 --- a/backend/windmill-types/src/jobs.rs +++ b/backend/windmill-types/src/jobs.rs @@ -56,10 +56,9 @@ pub enum JobTriggerKind { // produced from files a viewer forged by running a declared runnable directly. App, // A run started from the browser (the `/jobs/run*` request carried the session token - // minted at login). Nothing writes this yet — it exists so every binary from this release - // can decode it, which is what a later release needs before it can start stamping it. - // When that happens: attribution, not authority, unlike `App` — a member can have a - // session token minted for a script (`/users/refresh_token`), so nothing may gate on it. + // minted at login), stamped only once every worker decodes it (`trigger_or_fallback`). + // Attribution, not authority, unlike `App` — a member can have a session token minted for + // a script (`/users/refresh_token`), so no access decision may gate on it. Ui, } diff --git a/backend/windmill-worker/nsjail/run.ansible.config.proto b/backend/windmill-worker/nsjail/run.ansible.config.proto index ce5dab1dff..a778861bbd 100644 --- a/backend/windmill-worker/nsjail/run.ansible.config.proto +++ b/backend/windmill-worker/nsjail/run.ansible.config.proto @@ -7,7 +7,7 @@ time_limit: {TIMEOUT} {RLIMIT_AS} rlimit_cpu: 1000 -rlimit_fsize: 1000 +{RLIMIT_FSIZE} rlimit_nofile: 10000 cwd: "/tmp" diff --git a/backend/windmill-worker/nsjail/run.dbt.config.proto b/backend/windmill-worker/nsjail/run.dbt.config.proto index 192a12b3a5..aaca98df63 100644 --- a/backend/windmill-worker/nsjail/run.dbt.config.proto +++ b/backend/windmill-worker/nsjail/run.dbt.config.proto @@ -7,7 +7,7 @@ time_limit: {TIMEOUT} {RLIMIT_AS} rlimit_cpu: 1000 -rlimit_fsize: 1000 +{RLIMIT_FSIZE} rlimit_nofile: 10000 cwd: "{PROJECT_DIR}" diff --git a/backend/windmill-worker/nsjail/run.python3.config.proto b/backend/windmill-worker/nsjail/run.python3.config.proto index 6b18f6d7fa..ba55d16290 100644 --- a/backend/windmill-worker/nsjail/run.python3.config.proto +++ b/backend/windmill-worker/nsjail/run.python3.config.proto @@ -7,7 +7,7 @@ time_limit: {TIMEOUT} {RLIMIT_AS} rlimit_cpu: 1000 -rlimit_fsize: 1000 +{RLIMIT_FSIZE} rlimit_nofile: 10000 cwd: "/tmp" diff --git a/backend/windmill-worker/src/ansible_executor.rs b/backend/windmill-worker/src/ansible_executor.rs index ac1f48196e..c3f9913d39 100644 --- a/backend/windmill-worker/src/ansible_executor.rs +++ b/backend/windmill-worker/src/ansible_executor.rs @@ -35,14 +35,14 @@ use crate::{ common::{ build_command_with_isolation, check_executor_binary_exists, get_reserved_variables, interpolate_template, read_and_check_result, render_nsjail_rlimit_as, - resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, start_child_process, - transform_json, validate_relative_path, OccupancyMetrics, + render_nsjail_rlimit_fsize, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, + start_child_process, transform_json, validate_relative_path, OccupancyMetrics, }, handle_child::{handle_child, run_future_with_polling_update_job_poller}, is_sandboxing_enabled, python_executor::{create_dependencies_dir, handle_python_reqs, uv_pip_compile}, - PyV, DISABLE_NUSER, GIT_PATH, HOME_ENV, NSJAIL_ANSIBLE_RLIMIT_AS_MB, NSJAIL_PATH, PATH_ENV, - PROXY_ENVS, PY_INSTALL_DIR, TZ_ENV, + PyV, DISABLE_NUSER, GIT_PATH, HOME_ENV, NSJAIL_ANSIBLE_RLIMIT_AS_MB, NSJAIL_PATH, + NSJAIL_RLIMIT_FSIZE_MB, PATH_ENV, PROXY_ENVS, PY_INSTALL_DIR, TZ_ENV, }; use windmill_common::client::AuthedClient; @@ -2163,6 +2163,10 @@ mount {{ "{RLIMIT_AS}", &render_nsjail_rlimit_as(NSJAIL_ANSIBLE_RLIMIT_AS_MB.as_deref(), 4096), ) + .replace( + "{RLIMIT_FSIZE}", + &render_nsjail_rlimit_fsize(NSJAIL_RLIMIT_FSIZE_MB.as_deref(), 1000), + ) .replace("{PY_INSTALL_DIR}", &*PY_INSTALL_DIR) .replace("{JOB_DIR}", job_dir) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs index 132eda4e8c..eb0853a5c8 100644 --- a/backend/windmill-worker/src/common.rs +++ b/backend/windmill-worker/src/common.rs @@ -1457,23 +1457,37 @@ pub async fn resolve_nsjail_timeout( /// - `unlimited`/`none`/`inf`/`0` -> `rlimit_as_type: INF` (address space uncapped) /// - a positive integer (MiB) -> `rlimit_as: {n}` pub fn render_nsjail_rlimit_as(env_override: Option<&str>, default_mb: u32) -> String { + render_nsjail_rlimit("rlimit_as", env_override, default_mb) +} + +/// Render the `rlimit_fsize` line (largest single file a jailed job may write, in +/// MiB) for the nsjail run configs that set one (python3, ansible, dbt), honoring +/// the `NSJAIL_RLIMIT_FSIZE_MB` env var. Same value grammar as +/// [`render_nsjail_rlimit_as`]. The total space a job can fill is bounded +/// separately by its `/tmp` (tmpfs size or, when disk-backed, the worker's disk), +/// so operators who move `/tmp` to disk usually want to raise or lift this too. +pub fn render_nsjail_rlimit_fsize(env_override: Option<&str>, default_mb: u32) -> String { + render_nsjail_rlimit("rlimit_fsize", env_override, default_mb) +} + +fn render_nsjail_rlimit(field: &str, env_override: Option<&str>, default_mb: u32) -> String { match env_override.map(str::trim) { - None | Some("") => format!("rlimit_as: {default_mb}"), + None | Some("") => format!("{field}: {default_mb}"), Some(v) if v.eq_ignore_ascii_case("unlimited") || v.eq_ignore_ascii_case("none") || v.eq_ignore_ascii_case("inf") || v == "0" => { - "rlimit_as_type: INF".to_string() + format!("{field}_type: INF") } Some(v) => match v.parse::() { - Ok(mb) => format!("rlimit_as: {mb}"), + Ok(mb) => format!("{field}: {mb}"), Err(_) => { tracing::warn!( - "Invalid nsjail rlimit_as override {v:?}, using default {default_mb}MiB" + "Invalid nsjail {field} override {v:?}, using default {default_mb}MiB" ); - format!("rlimit_as: {default_mb}") + format!("{field}: {default_mb}") } }, } @@ -1668,7 +1682,7 @@ pub(crate) async fn resolve_nsjail_tmp_mount_block(job_dir: &str) -> String { #[cfg(test)] mod nsjail_rlimit_as_tests { - use super::render_nsjail_rlimit_as; + use super::{render_nsjail_rlimit_as, render_nsjail_rlimit_fsize}; #[test] fn unset_uses_default() { @@ -1707,6 +1721,23 @@ mod nsjail_rlimit_as_tests { ); assert_eq!(render_nsjail_rlimit_as(Some("-1"), 4096), "rlimit_as: 4096"); } + + #[test] + fn fsize_uses_its_own_field() { + assert_eq!(render_nsjail_rlimit_fsize(None, 1000), "rlimit_fsize: 1000"); + assert_eq!( + render_nsjail_rlimit_fsize(Some("20000"), 1000), + "rlimit_fsize: 20000" + ); + assert_eq!( + render_nsjail_rlimit_fsize(Some("unlimited"), 1000), + "rlimit_fsize_type: INF" + ); + assert_eq!( + render_nsjail_rlimit_fsize(Some("abc"), 1000), + "rlimit_fsize: 1000" + ); + } } #[cfg(test)] diff --git a/backend/windmill-worker/src/csharp_executor.rs b/backend/windmill-worker/src/csharp_executor.rs index 293401a508..1f9d902616 100644 --- a/backend/windmill-worker/src/csharp_executor.rs +++ b/backend/windmill-worker/src/csharp_executor.rs @@ -143,6 +143,10 @@ pub async fn generate_nuget_lockfile( .env("NUGET_PACKAGES", format!("{}/nuget", *CSHARP_CACHE_DIR)) .env("DOTNET_CLI_TELEMETRY_OPTOUT", "true") .env("DOTNET_NOLOGO", "true") + // The SDK's first run otherwise generates an HTTPS dev certificate and puts the global + // tools directory on PATH, in a home every worker sharing the cache may enter at once. + .env("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false") + .env("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false") .env("MSBUILDDISABLENODEREUSE", "1") .env("DOTNET_ROOT", DOTNET_ROOT.as_str()) .args(vec!["restore", "--use-lock-file"]) @@ -495,6 +499,8 @@ async fn build_cs_proj( .env("NUGET_PACKAGES", format!("{}/nuget", *CSHARP_CACHE_DIR)) .env("DOTNET_CLI_TELEMETRY_OPTOUT", "true") .env("DOTNET_NOLOGO", "true") + .env("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false") + .env("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false") .env("MSBUILDDISABLENODEREUSE", "1") .env("DOTNET_ROOT", DOTNET_ROOT.as_str()) .envs(PROXY_ENVS.clone()) @@ -514,6 +520,8 @@ async fn build_cs_proj( .env("NUGET_PACKAGES", format!("{}/nuget", *CSHARP_CACHE_DIR)) .env("DOTNET_CLI_TELEMETRY_OPTOUT", "true") .env("DOTNET_NOLOGO", "true") + .env("DOTNET_GENERATE_ASPNET_CERTIFICATE", "false") + .env("DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false") .env("MSBUILDDISABLENODEREUSE", "1") .env("DOTNET_ROOT", DOTNET_ROOT.as_str()) .args(publish_args.clone()) diff --git a/backend/windmill-worker/src/dbt_executor.rs b/backend/windmill-worker/src/dbt_executor.rs index 4db8201e9b..cfe1cbef4f 100644 --- a/backend/windmill-worker/src/dbt_executor.rs +++ b/backend/windmill-worker/src/dbt_executor.rs @@ -31,7 +31,8 @@ use windmill_parser_yaml::{ use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; use crate::common::{ - render_envars, render_nsjail_rlimit_as, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, + render_envars, render_nsjail_rlimit_as, render_nsjail_rlimit_fsize, resolve_nsjail_timeout, + resolve_nsjail_tmp_mount_block, }; use crate::common::{start_child_process, OccupancyMetrics}; use crate::dbt_engine::{provision_engine, ProvisionedEngine, DBT_CACHE_DIR}; @@ -46,8 +47,8 @@ use crate::handle_child::{ }; use crate::worker::write_module_files; use crate::{ - is_sandboxing_enabled, GIT_PATH, NSJAIL_DBT_RLIMIT_AS_MB, NSJAIL_PATH, PATH_ENV, PROXY_ENVS, - TZ_ENV, + is_sandboxing_enabled, GIT_PATH, NSJAIL_DBT_RLIMIT_AS_MB, NSJAIL_PATH, NSJAIL_RLIMIT_FSIZE_MB, + PATH_ENV, PROXY_ENVS, TZ_ENV, }; /// The profile name Windmill renders into `profiles.yml`. dbt takes the profile @@ -1372,6 +1373,10 @@ pub(crate) async fn prepare_project( "{RLIMIT_AS}", &render_nsjail_rlimit_as(NSJAIL_DBT_RLIMIT_AS_MB.as_deref(), 4096), ) + .replace( + "{RLIMIT_FSIZE}", + &render_nsjail_rlimit_fsize(NSJAIL_RLIMIT_FSIZE_MB.as_deref(), 1000), + ) .replace("{JOB_DIR}", &escape_textproto(job_dir)) .replace( "{PROJECT_DIR}", diff --git a/backend/windmill-worker/src/lib.rs b/backend/windmill-worker/src/lib.rs index 1945d16346..c571e9510c 100644 --- a/backend/windmill-worker/src/lib.rs +++ b/backend/windmill-worker/src/lib.rs @@ -1,3 +1,4 @@ +#![recursion_limit = "256"] #[cfg(feature = "bigquery")] mod bigquery_executor; #[cfg(all(feature = "enterprise", feature = "mssql"))] diff --git a/backend/windmill-worker/src/python_executor.rs b/backend/windmill-worker/src/python_executor.rs index b573a20313..f8ab6de7d5 100644 --- a/backend/windmill-worker/src/python_executor.rs +++ b/backend/windmill-worker/src/python_executor.rs @@ -153,18 +153,18 @@ use windmill_object_store::get_cache_object_store; use crate::{ check_no_network_jailed, common::{ - build_command_with_isolation, create_args_and_out_file, get_reserved_variables, read_file, - read_result, render_nsjail_rlimit_as, resolve_nsjail_timeout, - proto_str, resolve_nsjail_tmp_mount_block, start_child_process, OccupancyMetrics, - StreamNotifier, DEV_CONF_NSJAIL, + build_command_with_isolation, create_args_and_out_file, get_reserved_variables, proto_str, + read_file, read_result, render_nsjail_rlimit_as, render_nsjail_rlimit_fsize, + resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, start_child_process, + OccupancyMetrics, StreamNotifier, DEV_CONF_NSJAIL, }, get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::handle_child, is_sandboxing_enabled, nsjail_clone_newnet, read_ee_registry, worker_utils::ping_job_status, PyV, DISABLE_NUSER, HOME_ENV, INDEX_CERT, NATIVE_CERT, NSJAIL_AVAILABLE, NSJAIL_PATH, - NSJAIL_PY_RLIMIT_AS_MB, PATH_ENV, PIP_EXTRA_INDEX_URL, PIP_INDEX_URL, PROXY_ENVS, - PY_INSTALL_DIR, TRACING_PROXY_CA_CERT_PATH, TRUSTED_HOST, TZ_ENV, UV_CACHE_DIR, + NSJAIL_PY_RLIMIT_AS_MB, NSJAIL_RLIMIT_FSIZE_MB, PATH_ENV, PIP_EXTRA_INDEX_URL, PIP_INDEX_URL, + PROXY_ENVS, PY_INSTALL_DIR, TRACING_PROXY_CA_CERT_PATH, TRUSTED_HOST, TZ_ENV, UV_CACHE_DIR, UV_EXCLUDE_NEWER, UV_HTTP_TIMEOUT, UV_INDEX_STRATEGY, UV_PYTHON_INSTALL_MIRROR, }; use windmill_common::client::AuthedClient; @@ -1173,6 +1173,10 @@ mount {{ "{RLIMIT_AS}", &render_nsjail_rlimit_as(NSJAIL_PY_RLIMIT_AS_MB.as_deref(), 4096), ) + .replace( + "{RLIMIT_FSIZE}", + &render_nsjail_rlimit_fsize(NSJAIL_RLIMIT_FSIZE_MB.as_deref(), 1000), + ) .replace("{JOB_DIR}", job_dir) .replace("{PY_INSTALL_DIR}", &*PY_INSTALL_DIR) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index 6007928242..4c9f8d9704 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -397,6 +397,12 @@ lazy_static::lazy_static! { pub static ref NSJAIL_DBT_RLIMIT_AS_MB: Option = std::env::var("NSJAIL_DBT_RLIMIT_AS_MB").ok(); + /// Override for the nsjail `rlimit_fsize` cap (largest single file a jailed + /// python3/ansible/dbt job may write). MiB, or `unlimited`/`none`/`inf`/`0` to + /// uncap. Unset keeps the historical 1000 MiB. See `render_nsjail_rlimit_fsize`. + pub static ref NSJAIL_RLIMIT_FSIZE_MB: Option = + std::env::var("NSJAIL_RLIMIT_FSIZE_MB").ok(); + // pub static ref DISABLE_NSJAIL: bool = false; pub static ref DISABLE_NSJAIL: bool = std::env::var("DISABLE_NSJAIL") .ok() diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 74e93c01d4..7bf5cb141c 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.882.0"; +export const VERSION = "v1.883.0"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 41f0959aaf..f092d431ee 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.882.0", + "version": "1.883.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.882.0", + "version": "1.883.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 501d117204..5722b7b285 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.882.0", + "version": "1.883.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/commands/workspace/workspace.ts b/cli/src/commands/workspace/workspace.ts index 49462155e1..8c8b90cc24 100644 --- a/cli/src/commands/workspace/workspace.ts +++ b/cli/src/commands/workspace/workspace.ts @@ -551,6 +551,106 @@ async function remove(_opts: GlobalOptions, name: string) { await removeWorkspace(name, false, _opts); } +const CLI_LOGIN_TOKEN_LABEL_PREFIX = "cli-login:"; + +// Only a token the CLI's own browser login minted is revoked: a token pasted into the profile may +// also be used elsewhere (CI, another machine), so deleting it could break more than this profile. +async function revokeCliLoginToken(token: string): Promise { + const prefix = token.substring(0, 10); + const perPage = 100; + for (let page = 1; page <= 50; page++) { + const tokens = await wmill.listTokens({ excludeEphemeral: true, page, perPage }); + const match = tokens.find((t) => t.token_prefix === prefix); + if (match) { + if (!match.label?.startsWith(CLI_LOGIN_TOKEN_LABEL_PREFIX)) { + return false; + } + await wmill.deleteToken({ tokenPrefix: prefix }); + return true; + } + if (tokens.length < perPage) { + return false; + } + } + return false; +} + +async function login(opts: GlobalOptions, workspaceName?: string) { + const workspace = workspaceName + ? await getWorkspaceByName(workspaceName, opts.configDir) + : await getActiveWorkspace(opts); + if (!workspace) { + log.info( + colors.red.bold( + workspaceName + ? `! Workspace profile ${workspaceName} does not exist locally` + : "! No active workspace profile. Add one with 'wmill workspace add'." + ) + ); + return process.exit(1); + } + if ( + opts.baseUrl && + new URL(opts.baseUrl).toString() !== new URL(workspace.remote).toString() + ) { + log.info( + colors.red.bold( + `! --base-url ${opts.baseUrl} does not match profile ${workspace.name} (${workspace.remote}). Use 'wmill workspace add' for another instance.` + ) + ); + return process.exit(1); + } + + let token = await tryGetLoginInfo(opts); + if (!token) { + if (!(process.stdin.isTTY ?? false)) { + log.info("Not a TTY, can't login interactively. Pass the token in --token"); + return process.exit(1); + } + log.info( + `Signing in again to ${workspace.workspaceId} on ${workspace.remote} for profile ${workspace.name}` + ); + token = await loginInteractive(workspace.remote); + } + if (!token) { + log.info(colors.red.bold("! Login failed, the profile was left unchanged.")); + return process.exit(1); + } + + const remote = workspace.remote.substring(0, workspace.remote.length - 1); + setClient(token, remote); + try { + await wmill.whoami({ workspace: workspace.workspaceId }); + } catch (e) { + log.info( + colors.red.bold( + `! The new token cannot access workspace ${workspace.workspaceId}, the profile was left unchanged.` + ) + ); + throw e; + } + + const oldToken = workspace.token; + await addWorkspace({ ...workspace, token }, opts); + + // `wmill instance pull --include-workspaces` copies one token into the instance profile and + // every workspace profile it creates: revoking it would sign all the others out. + const { allInstances } = await import("../instance/instance.ts"); + const stillReferenced = + (await allWorkspaces(opts.configDir)).some((w) => w.token === oldToken) || + (await allInstances()).some((i) => i.token === oldToken); + if (oldToken && oldToken !== token && !stillReferenced) { + try { + if (await revokeCliLoginToken(oldToken)) { + log.info("Revoked the profile's previous token."); + } + } catch { + // Already expired or deleted, or owned by another user: nothing left to revoke. + } + } + log.info(colors.green.underline(`Successfully signed in again for profile ${workspace.name}`)); +} + async function whoami(_opts: GlobalOptions) { const whoamiInfo = await requireLogin(_opts); log.info(JSON.stringify(whoamiInfo, null, 2)); @@ -937,6 +1037,13 @@ const command = new Command() .description("Remove a workspace") .arguments("") .action(remove as any) + .command("login") + .complete("workspace", async () => (await allWorkspaces()).map((x) => x.name)) + .description( + "Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it." + ) + .arguments("[workspace_name:string:workspace]") + .action(login as any) .command("whoami") .description("Show the currently active user") .action(whoami as any) diff --git a/cli/src/core/auth.ts b/cli/src/core/auth.ts index bee70aef28..4ce903e875 100644 --- a/cli/src/core/auth.ts +++ b/cli/src/core/auth.ts @@ -122,19 +122,27 @@ export async function requireLogin( return process.exit(1); } - log.infoStderr( - "! Could not reach API given existing credentials. Attempting to reauth..." - ); + const isUnauthorized = error && typeof error === "object" && + "name" in error && (error as { name: unknown }).name === "ApiError" && + (error as { status?: number }).status === 401; + log.infoStderr(colors.yellow( + isUnauthorized + ? `! The token of workspace profile '${workspace.name}' has expired or was revoked. Sign in again to continue.` + : "! Could not reach API given existing credentials. Attempting to reauth..." + )); const newToken = await loginInteractive(workspace.remote); if (!newToken) { - throw new Error("Unauthorized: Could not authenticate with the provided credentials"); + throw new Error( + `Unauthorized: Could not authenticate with the provided credentials. Run 'wmill workspace login ${workspace.name}' in a terminal to sign in again.` + ); } - // Update workspace token + // Removed silently first: `addWorkspace` logs the update to stdout, which would land in the + // output of the command being run (e.g. `wmill variable get … > file`). const { removeWorkspace, addWorkspace } = await import("../commands/workspace/workspace.ts"); - removeWorkspace(workspace.name, false, opts); + await removeWorkspace(workspace.name, true, opts); workspace.token = newToken; - addWorkspace(workspace, opts); + await addWorkspace(workspace, opts); setClient( newToken, diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 1e7067ffb8..3f59ecfcbd 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.882.0"; +export const VERSION = "1.883.0"; diff --git a/cli/src/core/login.ts b/cli/src/core/login.ts index e6a06e8383..94a9ce11b8 100644 --- a/cli/src/core/login.ts +++ b/cli/src/core/login.ts @@ -97,7 +97,7 @@ export async function browserLogin( // Start the server server.listen(port, () => { - console.log(`Listening on port ${port}`); + log.infoStderr(`Listening on port ${port}`); }); }); } diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index ec0035de79..719de7a96d 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -27,6 +27,7 @@ export interface ErrorHandlerConfig { extra_args?: any; muted_on_cancel?: boolean; muted_on_user_path?: boolean; + muted_on_ui_runs?: boolean; } export interface SuccessHandlerConfig { @@ -254,6 +255,9 @@ export async function pushWorkspaceSettings( for (const key of SETTINGS_MANAGED_ONLY_WHEN_PRESENT) { delete (localSettings as any)[key]; } + // Such a server reads an error handler body carrying this key as the legacy format, which + // clears the handler. + delete localSettings.error_handler?.muted_on_ui_runs; const webhookUnreadable = unreadableSecret(localSettings.webhook); if (webhookUnreadable) { log.warn( diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 60b3230684..65b9100420 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8651,7 +8651,7 @@ write a secret you were not given: keep the placeholder. | Key | Value | |---|---| | \`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. | -| \`error_handler\` / \`success_handler\` | \`{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }\`, \`path\` being \`script/\` or \`flow/\`. | +| \`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. | | \`error_handler_fallback_to_instance_alerts\` | Report failures to the instance critical alert channels when no error handler is set. | | \`webhook\` | URL POSTed a JSON event on every change to the workspace's items. | | \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. | @@ -9703,6 +9703,7 @@ workspace related commands - \`--create-workspace-name \` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id. - \`--create-username \` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance. - \`workspace remove \` - Remove a workspace +- \`workspace login [workspace_name:string:workspace]\` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it. - \`workspace whoami\` - Show the currently active user - \`workspace list\` - List local workspace profiles - \`workspace list-remote\` - List workspaces on the remote server that you have access to diff --git a/cli/src/utils/script_common.ts b/cli/src/utils/script_common.ts index e3deabb6a7..9f55fe9f78 100644 --- a/cli/src/utils/script_common.ts +++ b/cli/src/utils/script_common.ts @@ -284,11 +284,11 @@ export function inferContentTypeFromFilePath( ): ScriptLanguage { if (contentPath.endsWith(".py")) { return "python3"; - } else if (contentPath.endsWith("fetch.ts")) { + } else if (contentPath.endsWith(".fetch.ts")) { return "nativets"; - } else if (contentPath.endsWith("bun.ts")) { + } else if (contentPath.endsWith(".bun.ts")) { return "bun"; - } else if (contentPath.endsWith("deno.ts")) { + } else if (contentPath.endsWith(".deno.ts")) { return "deno"; } else if (contentPath.endsWith(".ts")) { return defaultTs ?? "bun"; diff --git a/cli/test/utils_unit.test.ts b/cli/test/utils_unit.test.ts index daba8c776e..a0ba7fe3e1 100644 --- a/cli/test/utils_unit.test.ts +++ b/cli/test/utils_unit.test.ts @@ -391,6 +391,13 @@ describe("inferContentTypeFromFilePath", () => { expect(inferContentTypeFromFilePath("script.fetch.ts", "bun")).toBe("nativets"); }); + test("language suffix needs its dot", () => { + expect(inferContentTypeFromFilePath("f/a/a_fetch.ts", "bun")).toBe("bun"); + expect(inferContentTypeFromFilePath("f/a/afetch.ts", "bun")).toBe("bun"); + expect(inferContentTypeFromFilePath("f/a/a_bun.ts", "deno")).toBe("deno"); + expect(inferContentTypeFromFilePath("f/a/a_deno.ts", "bun")).toBe("bun"); + }); + test("detects SQL variants", () => { expect(inferContentTypeFromFilePath("query.pg.sql", undefined)).toBe("postgresql"); expect(inferContentTypeFromFilePath("query.my.sql", undefined)).toBe("mysql"); diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 0b7b7e9827..90157c4a31 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -37,11 +37,14 @@ Symbols, not line numbers, are cited: they drift less. so until `whoami` answers that browser still renders as its own last user. - **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie. - **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by - shortening the stored expiration (`cap_token_expiration`), never by refusing: the CLI - authorization page, `wmill user create-token` and the editor's language-server token all pick a - lifetime without reading the setting, and CLIs already installed never will. The CLI signs in - again on its own when its token expires, which is why the authorization page labels it - `cli-login:`, reserved in `is_user_token` so its expiry does not email the user. A token + shortening the stored expiration (`cap_token_expiration`), never by refusing: `wmill user + create-token` and the editor's language-server token pick a lifetime without reading the + setting, and CLIs already installed never will. The CLI authorization page (`/user/cli`) reads + it only to offer the lifetimes that would be kept (30 days by default). The CLI signs in again + on its own when its token expires, which is why the authorization page labels it + `cli-login:`, reserved in `is_user_token` so its expiry does not email the user. + `wmill workspace login` replaces a profile's token before it expires, and revokes the previous + one only when that label shows the browser login minted it. A token owned by a service account is exempt: one in the workspace the token names, or in any workspace for a workspace-less token (for `tokens/impersonate`, the impersonated account). Any workspace admin can therefore create and impersonate a service account to hold an uncapped token, so the diff --git a/frontend/package-lock.json b/frontend/package-lock.json index efd7bdab39..77b635953b 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.882.0", + "version": "1.883.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.882.0", + "version": "1.883.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index c175c40d4b..8c34f1676f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.882.0", + "version": "1.883.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/frontend/src/lib/aiStore.test.ts b/frontend/src/lib/aiStore.test.ts index 74785105fb..c8f62e04b0 100644 --- a/frontend/src/lib/aiStore.test.ts +++ b/frontend/src/lib/aiStore.test.ts @@ -23,11 +23,13 @@ import { isWebSearchEnabledForProvider, setCopilotInfo, copilotInfo, + copilotSessionModel, copilotWorkspace, getWorkspaceCopilotInfo, invalidateWorkspaceCopilotInfo, loadWorkspaceCopilotInfo, applySavedWorkspaceCopilotInfo, + tryResolveModelFor, workspaceCopilotInfoFailed } from './aiStore' @@ -157,3 +159,13 @@ describe('setCopilotInfo legacy /thinking migration', () => { expect(isWebSearchEnabledForProvider('anthropic')).toBe(true) }) }) + +it("keeps a model pick the tab's workspace does not offer, without sending it there", () => { + const pick = { provider: 'anthropic', model: 'fork-only' } as const + copilotSessionModel.set(pick) + setCopilotInfo(withModel('parent')) + + expect(get(copilotSessionModel)).toEqual(pick) + expect(tryResolveModelFor(get(copilotInfo))?.model).toBe('parent') + copilotSessionModel.set(undefined) +}) diff --git a/frontend/src/lib/aiStore.ts b/frontend/src/lib/aiStore.ts index ac8dc5e9e5..d931f52145 100644 --- a/frontend/src/lib/aiStore.ts +++ b/frontend/src/lib/aiStore.ts @@ -2,6 +2,7 @@ // client (`components/copilot/lib`) or anything under `components/copilot/chat` — those // import aiStore back, and such a cycle crashes the app once the bundler splits it across // chunks (docs/frontend-import-cycles.md; the build fails on the chunk cycle, not on this). +import { untrack } from 'svelte' import { writable, get } from 'svelte/store' import { SvelteMap, SvelteSet } from 'svelte/reactivity' import { @@ -125,9 +126,8 @@ function dedupeModels(models: AIProviderModel[]): AIProviderModel[] { }) } -// The workspace copilotInfo currently reflects. A session send awaits this -// matching its committed workspace so getCurrentModel() can't read the previous -// workspace's provider/model while the scoped load is still in flight. +// The workspace copilotInfo currently reflects: the page's, which an AI session's may not be. +// Session code must not point them at its own workspace. export const copilotWorkspace = writable(undefined) function buildCopilotInfo(aiConfig: AIConfig, userDisabled: boolean): CopilotInfo { @@ -240,12 +240,20 @@ export function workspaceCopilotInfoFailed(workspace: string): boolean { return failedWorkspaceCopilotInfos.has(workspace) } -/** `workspace`'s AI config for a request made on its behalf, without touching the tab's. +// The tab's copy follows only when it describes this workspace: a session's may be another. +function keepWorkspaceCopilotInfo(workspace: string, info: CopilotInfo) { + workspaceCopilotInfos.set(workspace, info) + failedWorkspaceCopilotInfos.delete(workspace) + if (get(copilotWorkspace) === workspace) copilotInfo.set(info) +} + +/** `workspace`'s AI config for a request made on its behalf, whatever workspace the tab's is. * Fetched once and kept until invalidated. `fresh` refetches a config that may have changed * elsewhere: unlike after a save, the one held stays readable until the new one lands, so what * shows it does not blank meanwhile, and a load already in flight is as fresh and is shared. */ export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Promise { - const known = workspaceCopilotInfos.get(workspace) + // Untracked: an effect that refreshes would otherwise rerun on its own refresh, forever. + const known = untrack(() => workspaceCopilotInfos.get(workspace)) if (known && !fresh) return Promise.resolve(known) let load = workspaceLoads.get(workspace) if (!load) { @@ -256,8 +264,7 @@ export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Prom .then((config) => { if (version !== versionOf(workspace)) return loadWorkspaceCopilotInfo(workspace) const info = buildCopilotInfo(config, get(aiUserDisabled)) - workspaceCopilotInfos.set(workspace, info) - failedWorkspaceCopilotInfos.delete(workspace) + keepWorkspaceCopilotInfo(workspace, info) return info }) .catch((e) => { @@ -271,14 +278,11 @@ export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Prom /** After a save of `workspace`'s AI config, with the effective config the save returned: what * shows it keeps a config throughout, where invalidating would blank it until the refetch. A load - * started before the save still refetches. Also updates the tab's copy, but only when the tab is - * on `workspace`: it belongs to the workspace on screen, which a session's may not be. */ + * started before the save still refetches. */ export function applySavedWorkspaceCopilotInfo(workspace: string, aiConfig: AIConfig) { const info = buildCopilotInfo(aiConfig, get(aiUserDisabled)) workspaceVersions.set(workspace, (workspaceVersions.get(workspace) ?? 0) + 1) - workspaceCopilotInfos.set(workspace, info) - failedWorkspaceCopilotInfos.delete(workspace) - if (get(copilotWorkspace) === workspace) applyCopilotInfo(info) + keepWorkspaceCopilotInfo(workspace, info) } /** After a save of `workspace`'s AI config, or with none of a config every workspace inherits @@ -293,13 +297,10 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) { } } +// Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may +// offer a model this one does not. export function setCopilotInfo(aiConfig: AIConfig) { - applyCopilotInfo(buildCopilotInfo(aiConfig, get(aiUserDisabled))) -} - -export function applyCopilotInfo(info: CopilotInfo) { - copilotSessionModel.update((model) => (model && isOffered(info, model) ? model : undefined)) - copilotInfo.set(info) + copilotInfo.set(buildCopilotInfo(aiConfig, get(aiUserDisabled))) } function isOffered(info: CopilotInfo, model: AIProviderModel): boolean { diff --git a/frontend/src/lib/components/ApiConnectForm.svelte b/frontend/src/lib/components/ApiConnectForm.svelte index dc5a5436a1..e2f5ebd4c0 100644 --- a/frontend/src/lib/components/ApiConnectForm.svelte +++ b/frontend/src/lib/components/ApiConnectForm.svelte @@ -7,7 +7,7 @@ import TestConnection from './TestConnection.svelte' import TestAiKey from './copilot/TestAIKey.svelte' import { aiResourceProvider } from './copilot/aiResourceProvider' - import { copilotInfo } from '$lib/aiStore' + import { getAiChatManager } from './copilot/chat/aiChatManagerContext' import Popover from './meltComponents/Popover.svelte' import Button from './common/button/Button.svelte' import { Loader2 } from 'lucide-svelte' @@ -60,6 +60,8 @@ onSynced = undefined }: Props = $props() + const aiChat = getAiChatManager() + let aiProvider = $derived(aiResourceProvider(resourceType, args)) let schema = $state(emptySchema()) @@ -225,7 +227,7 @@ {aiProvider} workspace={workspace ?? $operatingWorkspace} resourceValue={args} - model={$copilotInfo.aiModels.find((m) => m.provider === aiProvider)?.model} + model={aiChat.aiInfo?.aiModels.find((m) => m.provider === aiProvider)?.model} /> {/if} {#if resourceType == 'postgresql'} diff --git a/frontend/src/lib/components/AppConnectDrawer.svelte b/frontend/src/lib/components/AppConnectDrawer.svelte index ca6cb05300..9e5f1a05b1 100644 --- a/frontend/src/lib/components/AppConnectDrawer.svelte +++ b/frontend/src/lib/components/AppConnectDrawer.svelte @@ -29,6 +29,8 @@ let disabled = $state(false) let isGoogleSignin = $state(false) let manual = $state(true) + let actionLabel: string | undefined = $state(undefined) + let canGoBack: boolean | undefined = $state(undefined) let appConnectInner: AppConnectInner | undefined = $state(undefined) @@ -96,6 +98,8 @@ bind:isGoogleSignin bind:disabled bind:manual + bind:actionLabel + bind:canGoBack on:close={drawer?.closeDrawer} on:refresh express={expressOAuthSetup} @@ -105,9 +109,7 @@ /> {#snippet actions()}
- - {#if step > 1 && !rtToLoad} + {#if canGoBack} @@ -121,13 +123,7 @@ {disabled} onClick={() => appConnectInner?.next()} > - {#if (step == 2 && !manual) || native} - Connect - {:else if step == 1} - Next - {:else} - Save - {/if} + {actionLabel ?? 'Next'} {/if}
diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index b584815a7f..1e879593e8 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -8,7 +8,6 @@ addResourceTypeDisplayName, isCustomResourceTypeName, resourceTypeDisplayName, - resourceTypeMatchRank, resourceTypeSearchText, setResourceTypeDisplayNames, sortResourceTypesByMatch @@ -26,6 +25,7 @@ import { createEventDispatcher, onDestroy, tick } from 'svelte' import Path from './Path.svelte' import { Badge, ListRow, RadioCard, Skeleton } from './common' + import Stepper from './common/stepper/Stepper.svelte' import { useListHighlight } from './common/listRow/listHighlight.svelte' import ApiConnectForm from './ApiConnectForm.svelte' import SearchItems from './SearchItems.svelte' @@ -47,7 +47,8 @@ byPopularity, hubResourceTypePicks, localResourceTypeCounts, - recordHubResourceTypePick + recordHubResourceTypePick, + type PopularityCounts } from './pickerPopularity' import Label from './Label.svelte' import ResourcePathHint from './ResourcePathHint.svelte' @@ -80,6 +81,10 @@ * popup through the trigger service's OAuth app, whose callback saves the connection. */ native?: NativeConnect + /** What the caller's primary button does on the current step. */ + actionLabel?: string + /** Whether the caller should offer Back on the current step. */ + canGoBack?: boolean } let { @@ -91,9 +96,21 @@ express = false, workspace = undefined, fillPath = undefined, - native = undefined + native = undefined, + actionLabel = $bindable(), + canGoBack = $bindable() }: Props = $props() + /** + * Steps: 1 resource type, 2 authentication method (skipped when only one is offered), + * 3 the method's inputs (a manual resource is saved here), 4 waiting on the OAuth + * exchange, 5 path and save of an OAuth resource. + */ + type ConnectMethod = 'auth_code' | 'auth_code_user' | 'cc_shared' | 'cc_byo' | 'manual' + let method: ConnectMethod | undefined = $state(undefined) + /** Opened on one resource type: the type list was never shown, so there is no going back to it. */ + let openedOnType = $state(false) + let effectiveWorkspace = $derived(workspace ?? $operatingWorkspace!) let isValid = $state(true) @@ -118,12 +135,16 @@ /** Per-provider instance-entry metadata, keyed by provider name. */ let connectsInfo: Record< string, - { supports_client_credentials: boolean; has_shared_credentials: boolean } + { + supports_client_credentials: boolean + supports_authorization_code: boolean + has_shared_credentials: boolean + shares_client_credentials: boolean + } > = $state({}) - /** An instance entry with shared credentials (admin id+secret): connect with - * no input. Shown under "Instance-configured"; bring-your-own-only providers - * (no shared creds) are shown under "Others" instead. */ + /** An instance entry with shared credentials (instance id+secret), which the browser + * sign-in needs. Bring-your-own-only entries (no shared creds) are not one. */ function isSharedConnect(key: string): boolean { return connectsInfo[key]?.has_shared_credentials ?? false } @@ -233,13 +254,6 @@ } } - function selectUserToken(user: boolean) { - if (user !== useUserToken) { - scopes = user ? (registryEntry()?.user_scopes ?? []) : instanceScopes - } - useUserToken = user - } - /** * Client credentials for resource-level OAuth */ @@ -331,39 +345,110 @@ * doesn't enter their own — the exchange runs server-side with those creds */ let ccInstanceConfigured = $state(false) - /** The user wants their own credentials (picked the provider from the "Others" - * section) — overrides the shared instance credentials for this connection */ - let ccBringYourOwn = $state(false) - /** Connect with the shared instance credentials (no form) rather than the * bring-your-own form */ - let useSharedInstanceCreds = $derived(ccInstanceConfigured && !ccBringYourOwn) + let useSharedInstanceCreds = $derived(method === 'cc_shared') - /** Connectable via client credentials only: registry-declared provider with - * no instance OAuth client, or instance provider without an authorize URL */ - let ccOnly = $derived.by( - () => - authCodeUnavailable || - (registryCcCapable() && connectClient != '' && !(connects?.includes(connectClient) ?? false)) - ) + /** The ways in this provider offers, read once `getScopesAndParams` has run. A browser + * sign-in the registry declares but the instance holds no client for is listed disabled, + * so the user learns it exists and who can turn it on. */ + let methodOptions = $derived.by(() => { + const signIn = isSharedConnect(connectClient) && !authCodeUnavailable + const opts: { method: ConnectMethod; disabled: boolean }[] = [] + if (signIn || (registryEntry()?.grant_types?.includes('authorization_code') ?? false)) { + opts.push({ method: 'auth_code', disabled: !signIn }) + if (registryEntry()?.user_scopes) { + opts.push({ method: 'auth_code_user', disabled: !signIn }) + } + } + if (ccInstanceConfigured) opts.push({ method: 'cc_shared', disabled: false }) + if (supportsClientCredentials) opts.push({ method: 'cc_byo', disabled: false }) + opts.push({ method: 'manual', disabled: false }) + return opts + }) + let enabledMethods = $derived(methodOptions.filter((o) => !o.disabled).map((o) => o.method)) + let methodStepShown = $derived(enabledMethods.length > 1) - /** The provider also has a browser sign-in, unavailable here only because the - * instance holds no OAuth client for it */ - let signInNeedsInstanceClient = $derived.by( - () => - (registryEntry()?.grant_types?.includes('authorization_code') ?? false) && - connectClient != '' && - !(connects?.includes(connectClient) ?? false) - ) + function methodCopy( + m: ConnectMethod, + disabled: boolean + ): { label: string; description: string; grant: string } { + const browser = disabled + ? `Needs an OAuth client for ${providerName} in the instance settings.` + : 'Opens a browser window to authorize.' + switch (m) { + case 'auth_code': + return registryEntry()?.user_scopes + ? { + label: 'Install the app (bot token)', + description: `${browser} Acts as the app's bot user, in the channels it is added to.`, + grant: 'Authorization code' + } + : { + label: `Log in with your ${providerName} account`, + description: `${browser} The connection acts as you.`, + grant: 'Authorization code' + } + case 'auth_code_user': + return { + label: `Log in with your ${providerName} account (user token)`, + description: `${browser} Acts as you, with access to what you can see: history, DMs and search.`, + grant: 'Authorization code' + } + case 'cc_shared': + return { + label: "Connect as this instance's app", + description: + 'Uses the app configured in the instance settings. No input needed. The connection acts as that app, not as you.', + grant: 'Client credentials' + } + case 'cc_byo': + return { + label: 'Connect as your own app', + description: `Enter the client ID and secret of an app registered in ${providerName}. The connection acts as that app, not as you.`, + grant: 'Client credentials' + } + case 'manual': + return { + label: 'Enter credentials manually', + description: "Fill in the resource's fields yourself, such as an API key or a token.", + grant: '' + } + } + } + + function selectMethod(m: ConnectMethod) { + // Re-picking the current method after Back keeps the scopes the user edited. + if (m === method) return + method = m + manual = m === 'manual' + useClientCredentials = m === 'cc_shared' || m === 'cc_byo' + useUserToken = m === 'auth_code_user' + // Each grant starts from its own defaults: most providers reject authorization-code + // scopes in a 2-legged request, and Slack's user token takes `user_scope`. + scopes = useClientCredentials + ? defaultCcScopes() + : useUserToken + ? (registryEntry()?.user_scopes ?? []) + : instanceScopes + } + + function backTarget(s: number): number { + return s >= 4 ? 3 : s == 3 ? (methodStepShown ? 2 : 1) : s == 2 ? 1 : 0 + } + function canBackFrom(s: number): boolean { + const t = backTarget(s) + return !native && !express && t > 0 && (t > 1 || !openedOnType) + } /** Clear CC inputs and scopes so a previous selection never leaks into a new one */ function resetClientCredentialsState() { + method = undefined supportsClientCredentials = false useClientCredentials = false useUserToken = false authCodeUnavailable = false ccInstanceConfigured = false - ccBringYourOwn = false clientId = '' clientSecret = '' ccInstance = '' @@ -385,62 +470,21 @@ return entry ? (entry.cc_scopes ?? []) : instanceScopes } - function enableClientCredentials() { - manual = false - supportsClientCredentials = true - if (!useClientCredentials) { - // Switching into client-credentials: default to the CC scopes (never the - // authorization-code scopes — most providers reject member/consent scopes - // in a 2-legged request). Only reset on the transition so edits made while - // already in CC mode are preserved. - scopes = defaultCcScopes() - } - useClientCredentials = true + /** Only an instance OAuth client is a `_sandbox` alias of its parent type; a resource + * type's own name may end in `_sandbox` too. */ + function typeOfKey(key: string): string { + return connects?.includes(key) ? stripSandboxSuffix(key) : key } - /** Switch to the browser sign-in (authorization-code) grant, restoring its - * default scopes when coming from the client-credentials grant. */ - function selectAuthCodeGrant() { - if (useClientCredentials) { - scopes = instanceScopes - } - useClientCredentials = false - } - - /** Static registry declares client-credentials support for `key`. */ - function isCcCapable(key: string): boolean { - return registryCcCapableFor(key) - } - - /** Step-1 "Others" selection: CC-capable resource types open the client- - * credentials form with the user's own credentials — even when the instance - * has shared ones (the "Instance-configured OAuth APIs" section is the entry - * point for those). Every other type opens the raw manual form. */ - function connectOauth(key: string) { - manual = false + function selectType(key: string) { connectClient = key - resourceType = stripSandboxSuffix(key) + resourceType = typeOfKey(key) + // The path form names it after the type, so one generated for another type must go. + path = '' resetClientCredentialsState() next() } - function selectFromOthers(key: string) { - connectClient = key - resourceType = key - resetClientCredentialsState() - // Registry CC providers and instance-configured providers that declare the - // client-credentials grant (incl. custom providers set up with only a token - // URL and no shared creds) open the bring-your-own form. Everything else is - // a manual resource. - if (isCcCapable(key) || (connectsInfo[key]?.supports_client_credentials ?? false)) { - ccBringYourOwn = true - enableClientCredentials() - } else { - manual = true - } - next() - } - let pathError = $state('') export async function open(rt?: string) { @@ -448,9 +492,10 @@ resourceType = rt ?? '' manual = false path = '' - step = 4 + step = 5 return } + openedOnType = !!rt if (!rt) { loadResourceTypes() loadPopularity() @@ -464,38 +509,32 @@ wsSpecific = false const rawRt = rt ?? '' connectClient = rawRt - resourceType = stripSandboxSuffix(rawRt) valueToken = undefined resetClientCredentialsState() await loadConnects() - const inConnects = connects?.includes(connectClient) ?? false - // Registry-declared client-credentials providers are connectable even - // without an instance OAuth client - manual = !inConnects && !(rt && registryCcCapable()) - if (manual && express) { - dispatch('error', 'Express OAuth setup is not available for non OAuth resource types') - return - } - if (!inConnects && !manual && express) { - // Client-credentials connections need interactive credential entry - dispatch('error', 'Express OAuth setup is not available for client credentials providers') - return - } - if (!inConnects && !manual) { - enableClientCredentials() - } - if (rt) { - if (!manual && express) { - await getScopesAndParams() - if (authCodeUnavailable) { - // No popup flow to drive express setup with - dispatch('error', 'Express OAuth setup is not available for client credentials providers') - return - } - step = 2 + resourceType = typeOfKey(rawRt) + if (express) { + // Express drives the browser sign-in with no input, so it needs the instance's client. + if (!(connects?.includes(connectClient) ?? false)) { + dispatch( + 'error', + registryCcCapable() + ? 'Express OAuth setup is not available for client credentials providers' + : 'Express OAuth setup is not available for non OAuth resource types' + ) + return } + await getScopesAndParams() + if (authCodeUnavailable) { + dispatch('error', 'Express OAuth setup is not available for client credentials providers') + return + } + selectMethod('auth_code') + step = 3 + next() + } else if (rt) { next() } } @@ -503,18 +542,27 @@ /** * Orders the browse list: the types this workspace already has resources of lead, ranked * among themselves by the hub's pick counts, then everything else on the same counts. - * `byPopularity` carries the full rule. Both signals are fetched, so the rows render - * alphabetically and re-sort when this lands. + * `byPopularity` carries the full rule. The list waits on it, so it renders once and in + * order rather than re-sorting under the pointer; the hub is the slow signal, so it gets + * `HUB_PICKS_WAIT_MS` and is left out past that, never holding the list. */ let popularity: (a: string, b: string) => number = $state(alphabetical) + let popularityReady = $state(false) + const HUB_PICKS_WAIT_MS = 1500 async function loadPopularity() { - if (!effectiveWorkspace) return - const [hub, local] = await Promise.all([ - hubResourceTypePicks(effectiveWorkspace), - localResourceTypeCounts(effectiveWorkspace) - ]) - popularity = byPopularity(hub, local) + if (effectiveWorkspace) { + const none: PopularityCounts = {} + const [hub, local] = await Promise.all([ + Promise.race([ + hubResourceTypePicks(effectiveWorkspace).catch(() => none), + new Promise((r) => setTimeout(() => r(none), HUB_PICKS_WAIT_MS)) + ]), + localResourceTypeCounts(effectiveWorkspace).catch(() => none) + ]) + popularity = byPopularity(hub, local) + } + popularityReady = true } async function loadConnects() { @@ -534,13 +582,15 @@ } // Google's terms require its own button on the control that starts the sign-in, which is - // the step-2 Connect: step 1 only picks a type, and a manual step 2 saves a resource - // without ever reaching Google. Every registry provider that signs in through Google's - // authorize endpoint counts; `google` itself is a login provider, not a registry entry. + // the step-3 Connect of a browser sign-in: the earlier steps only pick, and a manual or + // client-credentials step 3 never reaches Google's sign-in. Every registry provider that + // signs in through Google's authorize endpoint counts; `google` itself is a login + // provider, not a registry entry. run(() => { isGoogleSignin = - (step == 2 || (!!native && step == 4)) && + (step == 3 || (!!native && step == 5)) && !manual && + !useClientCredentials && (resourceType == 'google' || (registryEntryFor(resourceType)?.auth_url?.startsWith('https://accounts.google.com/') ?? false)) @@ -549,7 +599,8 @@ run(() => { disabled = (step == 1 && resourceType == '') || - (step == 2 && + (step == 2 && !method) || + (step == 3 && (manual ? value == '' && args && @@ -563,9 +614,15 @@ (clientId.trim() == '' || clientSecret.trim() == '' || (!!ccInstanceMeta && ccInstance.trim() == '')))) || - step == 3 || - (step == 4 && (pathError != '' || (!!native && !path))) || - !isValid + step == 4 || + (step == 5 && (pathError != '' || (!!native && !path))) || + // The manual form's own validity: it must not hold Next once the form is left. + (step == 3 && manual && !isValid) + }) + + run(() => { + canGoBack = canBackFrom(step) + actionLabel = native || (step == 3 && !manual) ? 'Connect' : step <= 2 ? 'Next' : 'Save' }) export async function loadResourceTypes() { @@ -601,10 +658,6 @@ }) .catch(() => {}) - // "Others" lists every resource type — including instance-configured OAuth - // providers — so any of them can also be connected with the user's own - // credentials or manually, not only via the shared instance setup (same as - // the authorization-code behavior). connectsManual = availableRts.map( (x) => ({ @@ -684,7 +737,7 @@ console.log('Processing oauth popup data') if (data.type === 'error') { sendUserToast(data.error, true) - step = 2 + step = 3 } else if (data.type === 'success') { connectClient = data.resource_type resourceType = stripSandboxSuffix(connectClient) @@ -692,7 +745,7 @@ valueToken = data.res Object.assign(args, data.res.resource_fields ?? {}) fillGeneratedDescription() - step = 4 + step = 5 // `fillPath` decides the path as surely as express does, so neither stops here. if (fillPath || express) { path = fillPath ?? `u/${$userStore?.username}/${defaultName}_${new Date().getTime()}` @@ -701,13 +754,11 @@ } } + /** Reads what the provider offers; `selectMethod` then sets the grant and its scopes. */ async function getScopesAndParams() { - useUserToken = false if (!connects?.includes(connectClient)) { - // No instance OAuth client (registry-declared CC-only provider): - // defaults come from the static registry instead. + // No instance OAuth client: defaults come from the static registry instead. instanceScopes = registryEntry()?.scopes ?? [] - scopes = useClientCredentials ? defaultCcScopes() : instanceScopes extra_params = [] supportsClientCredentials = registryCcCapable() return @@ -728,14 +779,6 @@ // Custom provider configured with only a token URL: no popup flow possible authCodeUnavailable = supportsClientCredentials && !(connect.grant_types?.includes('authorization_code') ?? true) - if (authCodeUnavailable) { - useClientCredentials = true - } - // Default scopes to the active grant: client-credentials uses the registry's - // cc_scopes (auth-code scopes are invalid in a 2-legged request), every other - // path keeps the instance entry's scopes. Applies to shared instance creds, - // not just bring-your-own. Switching grants resets to these defaults. - scopes = useClientCredentials ? defaultCcScopes() : instanceScopes } async function getResourceTypeInfo() { @@ -762,30 +805,28 @@ } export async function next() { if (native) { - step = 3 + step = 4 try { await native.connect(path) dispatch('close') } catch { - step = 4 + step = 5 } return } if (step == 1) { linkedSecrets = [] - // Both branches: the OAuth one fills `resourceFields` into the same map, and fields - // typed into another type's form before Back would otherwise ride along. + // The OAuth path fills `resourceFields` into the same map, and fields typed into + // another type's form before Back would otherwise ride along. args = {} - if (manual) { - getResourceTypeInfo() - } else { - getResourceTypeInfo() - // Awaited: the popup is built from `scopes`, so advancing before this - // resolves sends the user to an authorize url with no scope at all. - await getScopesAndParams() - } - step += 1 - } else if (step == 2 && !manual) { + getResourceTypeInfo() + // Awaited: the methods offered, and the scopes the popup is built from, come from it. + await getScopesAndParams() + selectMethod(enabledMethods[0]) + step = methodStepShown ? 2 : 3 + } else if (step == 2) { + step = 3 + } else if (step == 3 && !manual) { if (useClientCredentials) { /** * Client credentials flow: Direct API call to backend @@ -844,7 +885,7 @@ grant_type: 'client_credentials' // Mark this token as client_credentials } fillGeneratedDescription() - step = 4 + step = 5 if (fillPath || express) { path = fillPath ?? `u/${$userStore?.username}/${defaultName}_${new Date().getTime()}` next() @@ -878,7 +919,7 @@ } } else { if (!path) { - if (step == 2) return + if (step == 3) return throw Error('Path is not set') } // Check if variable paths already exist @@ -958,7 +999,8 @@ if (connectTemplate?.resource_mapping) { const instanceKey = connectTemplate.extra_params_key ?? 'instance' let instanceValue = extra_params.find(([key, _]) => key === instanceKey)?.[1] ?? '' - if (ccInstance.trim()) { + // Only the bring-your-own exchange used it: one typed before switching method is stale. + if (method === 'cc_byo' && ccInstance.trim()) { const stripSuffix = connectTemplate.strip_suffix as string | undefined let v = ccInstance .trim() @@ -1129,12 +1171,9 @@ } } - export async function back() { - if (step == 4) { - step -= 2 - } else if (step > 1) { - step -= 1 - } + export function back() { + if (!canBackFrom(step)) return + step = backTarget(step) if (step == 1) { loadConnects() loadResourceTypes() @@ -1144,9 +1183,18 @@ } } + /** Stepper index of each step: waiting on the exchange still reads as "Connect". */ + let stepIndex = $derived(step <= 3 ? step - 1 : step == 4 ? 2 : 3) + const STEP_OF_INDEX = [1, 2, 3, 5] + + function goToStep(index: number) { + const target = STEP_OF_INDEX[index] + if ((target == 2 && !methodStepShown) || (target == 1 && openedOnType)) return + while (step > target && canBackFrom(step)) back() + } + const dispatch = createEventDispatcher<{ error: string; refresh: string; close: void }>() - let filteredConnects: { key: string }[] = $state([]) let filteredConnectsManual: { key: string; img?: string; instructions: string[] }[] = $state([]) let searching = $derived(filter.trim() !== '') @@ -1173,70 +1221,55 @@ popularity(stripSandboxSuffix(a.key), stripSandboxSuffix(b.key)) || a.key.localeCompare(b.key) )) - let rankedConnects = $derived(rank(filteredConnects)) let rankedConnectsManual = $derived( rank(filteredConnectsManual) as typeof filteredConnectsManual | undefined ) - // Browsing, the "Others" list leads with the native database types. Searching, that - // grouping would outrank the search itself — `ms_sql_server` sorting under `mysql` on - // "sql" — so the ranked order stands on its own. - let manualOrderedKeys = $derived( - !searching - ? [ - ...(rankedConnectsManual ?? []) - .filter((x) => nativeLanguagesCategory.includes(x.key)) - .map((x) => x.key), - ...(rankedConnectsManual ?? []) - .filter((x) => !nativeLanguagesCategory.includes(x.key)) - .map((x) => x.key) - ] - : (rankedConnectsManual ?? []).map((x) => x.key) + /** One row per provider: every resource type, plus the instance OAuth clients no type is + * named after (a `_sandbox` client, a custom provider). How to connect is picked after. */ + let typeItems = $derived.by(() => { + const types = connectsManual + const clients: string[] | undefined = connects + if (!types || !clients) return undefined + return [ + ...types, + ...clients + .filter((k) => isSharedConnect(k) && !types.some((x) => x.key == k)) + .map((key) => ({ key, instructions: [] as string[] })) + ] + }) + + // Browsing, the list leads with the workspace's custom types, then the providers the + // instance has an OAuth client for, then the native database types. Searching, that + // grouping would outrank the search itself (`ms_sql_server` sorting under `mysql` on "sql"), + // so the ranked order stands on its own. + const browseGroup = (key: string) => + customResourceTypes.has(key) + ? 0 + : isSharedConnect(key) + ? 1 + : nativeLanguagesCategory.includes(key) + ? 2 + : 3 + let navItems = $derived( + (searching + ? (rankedConnectsManual ?? []) + : [...(rankedConnectsManual ?? [])].sort((a, b) => browseGroup(a.key) - browseGroup(b.key)) + ).map((x) => x.key) ) - let customKeys = $derived(manualOrderedKeys.filter((key) => customResourceTypes.has(key))) - let otherKeys = $derived(manualOrderedKeys.filter((key) => !customResourceTypes.has(key))) - - // Every row in the order it is rendered, so arrow keys walk the sections as one list. - // A provider appears in more than one, so rows are addressed by index, not by name. - let navItems = $derived([ - ...customKeys.map((key) => ({ key, oauth: false })), - ...(rankedConnects ?? []).map((x) => ({ key: x.key, oauth: true })), - ...otherKeys.map((key) => ({ key, oauth: false })) - ]) - // Both lists start undefined and render skeletons; "nothing found" only means something - // once they have landed. - let listsLoaded = $derived(rankedConnectsManual !== undefined && rankedConnects !== undefined) + // The list starts undefined and renders skeletons; "nothing found" only means something + // once it has landed. + let listsLoaded = $derived(rankedConnectsManual !== undefined && popularityReady) const rowDomId = (index: number) => `resource-type-row-${index}` - const oauthRowOffset = $derived(customKeys.length) - const otherRowOffset = $derived(customKeys.length + (rankedConnects?.length ?? 0)) - - // Sections are rendered in a fixed order, so the best match is not necessarily the first - // row: rank the rows against the query to find it. - function bestMatchIndex(): number { - let best = navItems.length > 0 ? 0 : -1 - let bestRank = Infinity - navItems.forEach((item, index) => { - const rank = resourceTypeMatchRank(item.key, resourceTypeDescriptions[item.key], filter) - if (rank < bestRank) { - bestRank = rank - best = index - } - }) - return best - } - const highlight = useListHighlight({ count: () => navItems.length, rowId: rowDomId, - // Sections are rendered in a fixed order, so the best match is not necessarily the - // first row; Enter should still take the top hit. - restingIndex: () => (searching ? bestMatchIndex() : -1), + restingIndex: () => (searching && navItems.length > 0 ? 0 : -1), onActivate: (index) => { - const item = navItems[index] - if (!item) return - item.oauth ? connectOauth(item.key) : selectFromOthers(item.key) + const key = navItems[index] + if (key) selectType(key) }, activateEnterFrom: [SEARCH_INPUT_ID] }) @@ -1250,20 +1283,28 @@ {#if !express} ({ - key - })) - : undefined} - bind:filteredItems={filteredConnects} - f={(x) => resourceTypeSearchText(x.key, resourceTypeDescriptions[x.key])} - /> - resourceTypeSearchText(x.key, resourceTypeDescriptions[x.key])} /> + + {#snippet wizardSteps()} + {#if !native && methodStepShown} +
+ goToStep(e.detail.index)} + /> +
+ {/if} + {/snippet} {#if step == 1} highlight.hovered(index)} - onClick={() => (oauth ? connectOauth(key) : selectFromOthers(key))} + onClick={() => selectType(key)} /> {/snippet} @@ -1329,70 +1374,21 @@ {:else} - -
- {#if customKeys.length > 0} -
- {@render sectionHeading('Custom resource types', customKeys.length)} -
- {#each customKeys as key, i} - {@render resourceButton(key, i, false)} - {/each} -
-
- {/if} + {#if !searching && connectsManual && connectsManual?.length < 10} +
+ Resource types have not been synced with the hub +
+ {/if} - {#if !searching || (rankedConnects?.length ?? 0) > 0} -
- {@render sectionHeading( - 'Instance-configured OAuth APIs', - rankedConnects?.length ?? 0 - )} -
- {#if rankedConnects} - {#each rankedConnects as { key }, i} - {@render resourceButton(key, oauthRowOffset + i, true)} - {/each} - {:else} - {#each new Array(3) as _} - - {/each} - {/if} -
- {#if !searching && connects && connects.filter(isSharedConnect).length == 0} -
No OAuth APIs have been set up on this instance. To add OAuth APIs, first sync - the resource types with the hub, then add OAuth configuration. See documentation -
- {/if} -
- {/if} - - {#if !searching || otherKeys.length > 0} -
- {@render sectionHeading('Others', otherKeys.length)} - - {#if !searching && connectsManual && connectsManual?.length < 10} -
- Resource types have not been synced with the hub -
- {/if} - -
- {#if rankedConnectsManual} - {#each otherKeys as key, i} - {@render resourceButton(key, otherRowOffset + i, false)} - {/each} - {:else} - {#each new Array(9) as _} - - {/each} - {/if} -
-
+
+ {#if listsLoaded} + {#each navItems as key, i} + {@render resourceButton(key, i)} + {/each} + {:else} + {#each new Array(9) as _} + + {/each} {/if}
{/if} @@ -1408,7 +1404,30 @@ />
- {:else if step == 2 && manual} + {:else if step == 2} + {@render wizardSteps()} +
+

How do you want to connect?

+ {#each methodOptions as opt (opt.method)} + {@const copy = methodCopy(opt.method, opt.disabled)} + {#snippet methodBadge()} + {copy.grant} + {#if opt.disabled} + Instance setup needed + {/if} + {/snippet} + selectMethod(opt.method)} + disabled={opt.disabled} + badge={copy.grant || opt.disabled ? methodBadge : undefined} + /> + {/each} +
+ {:else if step == 3 && manual} + {@render wizardSteps()}
{#if !emptyString(resourceTypeInfo?.description)} @@ -1418,7 +1437,7 @@ @@ -1488,14 +1507,6 @@
{/if} - {#if registryCcCapable()} - - {/if} {#if resourceTypeAlternative} - - {#if useClientCredentials && !useSharedInstanceCreds} - - - - {#if ccInstanceMeta} - - {:else} - - {/if} - - {/if} - - {/if} - - {#if registryEntry()?.user_scopes && !useClientCredentials} -
-

Connect as

-
- selectUserToken(false)} - /> - selectUserToken(true)} - /> -
-
+ {/if}
@@ -1705,13 +1626,15 @@
{/if} - {:else if step == 3 && !manual && !express} + {:else if step == 4 && !manual && !express} + {@render wizardSteps()} {#if useClientCredentials} Connecting with client credentials... {:else} Finish connection in popup window {/if} {:else} + {@render wizardSteps()}