diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ebb4b7f4d0..3c7beb2306 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.866.0" + ".": "1.867.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index e893e893fa..f0be69063a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## [1.867.0](https://github.com/windmill-labs/windmill/compare/v1.866.0...v1.867.0) (2026-11-10) + + +### Features + +* fold sidebar AI chats and sessions inactive for over a week ([#12314](https://github.com/windmill-labs/windmill/issues/12314)) ([466885f](https://github.com/windmill-labs/windmill/commit/466885fd26b74bd20de67ee0ef0e55a47826cd47)) +* gate public apps on cloud plans and unpublish them on archive ([#12321](https://github.com/windmill-labs/windmill/issues/12321)) ([a9f5a9c](https://github.com/windmill-labs/windmill/commit/a9f5a9caa0bce2162a34bca1cfd0438893945d6e)) +* reveal the failed call from a tool group's failed badge ([#12320](https://github.com/windmill-labs/windmill/issues/12320)) ([0e1464e](https://github.com/windmill-labs/windmill/commit/0e1464e877dcfabdffc8901d2a0735e04b73772e)) + + +### Bug Fixes + +* build Azure block upload URLs from the account endpoint ([#12333](https://github.com/windmill-labs/windmill/issues/12333)) ([38e7463](https://github.com/windmill-labs/windmill/commit/38e7463dd4e93c36f28fefb102bc5d0d3060cdf3)) +* cut long item summaries in the session composer placeholder ([#12312](https://github.com/windmill-labs/windmill/issues/12312)) ([abfa6b1](https://github.com/windmill-labs/windmill/commit/abfa6b1a6743d99858b6923f40a76deb9e6ff063)) +* drop renamed and deleted items from Home recent list ([#12317](https://github.com/windmill-labs/windmill/issues/12317)) ([c144738](https://github.com/windmill-labs/windmill/commit/c1447389e546022f1fb6cd2a18c88480e27ce792)) +* explain why a fork folder deploy can leave a lasting conflict ([#12323](https://github.com/windmill-labs/windmill/issues/12323)) ([6a11d30](https://github.com/windmill-labs/windmill/commit/6a11d3033ad329a730848698d9fa8ddd2cb5563e)) +* keep siblings in place when editing an EditableInput ([#12318](https://github.com/windmill-labs/windmill/issues/12318)) ([5e89ba1](https://github.com/windmill-labs/windmill/commit/5e89ba180e57922a107d840e9fe2b8c00fb2340a)) +* keep the sessions sidebar icons stable until the workspace list loads ([#12322](https://github.com/windmill-labs/windmill/issues/12322)) ([9d7adef](https://github.com/windmill-labs/windmill/commit/9d7adefe23f130168e7e9d77ce4a52c4c4f2223f)) +* load mermaid diagrams without source flashes or layout jumps ([#12319](https://github.com/windmill-labs/windmill/issues/12319)) ([fecc8a6](https://github.com/windmill-labs/windmill/commit/fecc8a6bfd01dacea90bee6d9864527d26cf1714)) +* mark delete and discard tool confirmations as destructive ([#12324](https://github.com/windmill-labs/windmill/issues/12324)) ([949ef23](https://github.com/windmill-labs/windmill/commit/949ef234a841dd18eca661addbf2369329dbc9a3)) +* name agents in session chat tool call labels ([#12313](https://github.com/windmill-labs/windmill/issues/12313)) ([80e2be5](https://github.com/windmill-labs/windmill/commit/80e2be56ddd21cd7f5ea778989e83e09e87b08f5)) +* **python:** give folder modules an empty __path__ so relative imports resolve to workspace scripts ([#12307](https://github.com/windmill-labs/windmill/issues/12307)) ([0323310](https://github.com/windmill-labs/windmill/commit/0323310d6455c361eef2ca857883cdfd888c43ce)) +* read dedicated worker entries with the runnable parser ([#12326](https://github.com/windmill-labs/windmill/issues/12326)) ([df6a61c](https://github.com/windmill-labs/windmill/commit/df6a61c07eabb9845b7ba5a3ef7284df52517445)) +* send AI session requests with their own workspace's AI config ([#12330](https://github.com/windmill-labs/windmill/issues/12330)) ([e8d48b1](https://github.com/windmill-labs/windmill/commit/e8d48b1348893e9396734d0ed4fc4d33049fb0ed)) +* stop forcing the structured output tool for Claude AI agents ([#12331](https://github.com/windmill-labs/windmill/issues/12331)) ([5b4f918](https://github.com/windmill-labs/windmill/commit/5b4f918e0d7742bf09629f0cfe8f90b3038f965e)) +* stream logs of a selected step nested in a subflow or loop ([#12334](https://github.com/windmill-labs/windmill/issues/12334)) ([841cc3e](https://github.com/windmill-labs/windmill/commit/841cc3ecbad7e599086bdb2902fa8c2d4c48e7a6)) +* tighten forwarded http trigger headers and route resolution ([#12298](https://github.com/windmill-labs/windmill/issues/12298)) ([c3adae1](https://github.com/windmill-labs/windmill/commit/c3adae14017cb81cf15549c3f2000eba65e424c0)) +* **worker:** wait up to 3 min for migrations before exiting ([#12316](https://github.com/windmill-labs/windmill/issues/12316)) ([a2685ef](https://github.com/windmill-labs/windmill/commit/a2685ef71880aa9d9745709e5b57f29ff76a85e0)) + + +### Performance Improvements + +* cut release CI wall time and build windmill-extra on its own release ([#12329](https://github.com/windmill-labs/windmill/issues/12329)) ([7ec64ab](https://github.com/windmill-labs/windmill/commit/7ec64ab33acc56870975c05f24a983bdcd146ee2)) + ## [1.866.0](https://github.com/windmill-labs/windmill/compare/v1.865.0...v1.866.0) (2026-11-10) diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 75c2466a93..b42124841a 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2663,9 +2663,9 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "const-oid" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "const-random" @@ -4507,7 +4507,7 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ - "const-oid 0.10.2", + "const-oid 0.10.3", "pem-rfc7468 1.0.0", "zeroize", ] @@ -4744,7 +4744,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid 0.10.2", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", ] @@ -6778,7 +6778,7 @@ dependencies = [ "tokio", "tokio-rustls 0.26.6", "tower-service", - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", ] [[package]] @@ -10986,7 +10986,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", ] [[package]] @@ -11643,9 +11643,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -15483,9 +15483,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -15496,14 +15496,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", ] [[package]] name = "webpki-roots" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -15601,7 +15601,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-nats", @@ -15691,7 +15691,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.866.0" +version = "1.867.0" dependencies = [ "async-stream", "async-trait", @@ -15726,7 +15726,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -15739,7 +15739,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "argon2", @@ -15881,7 +15881,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -15905,7 +15905,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -15922,7 +15922,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -15948,7 +15948,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.866.0" +version = "1.867.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15958,7 +15958,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -15975,7 +15975,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "base64 0.22.1", @@ -15997,7 +15997,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -16020,7 +16020,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16036,7 +16036,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16058,7 +16058,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16080,7 +16080,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16094,7 +16094,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-nats", @@ -16130,7 +16130,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -16156,7 +16156,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16184,7 +16184,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -16206,7 +16206,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16225,7 +16225,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -16267,7 +16267,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -16297,7 +16297,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.866.0" +version = "1.867.0" dependencies = [ "lazy_static", "serde", @@ -16309,7 +16309,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.866.0" +version = "1.867.0" dependencies = [ "argon2", "axum", @@ -16333,7 +16333,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16348,7 +16348,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.866.0" +version = "1.867.0" dependencies = [ "axum", "chrono", @@ -16387,7 +16387,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.866.0" +version = "1.867.0" dependencies = [ "chrono", "lazy_static", @@ -16402,7 +16402,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "axum", @@ -16421,7 +16421,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.866.0" +version = "1.867.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16528,7 +16528,7 @@ dependencies = [ "url", "urlencoding", "uuid", - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", "windmill-macros", "windmill-parser", "windmill-parser-py", @@ -16540,7 +16540,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.866.0" +version = "1.867.0" dependencies = [ "chrono", "futures", @@ -16560,7 +16560,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.866.0" +version = "1.867.0" dependencies = [ "regex", "serde", @@ -16577,7 +16577,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16604,7 +16604,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "futures", @@ -16621,7 +16621,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.866.0" +version = "1.867.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16637,7 +16637,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -16659,7 +16659,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -16691,7 +16691,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "arc-swap", @@ -16716,7 +16716,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-stream", @@ -16752,7 +16752,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "futures", @@ -16771,7 +16771,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.866.0" +version = "1.867.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16780,7 +16780,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -16792,7 +16792,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde_json", @@ -16804,7 +16804,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "gosyn", @@ -16816,7 +16816,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -16828,7 +16828,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde_json", @@ -16840,7 +16840,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "nu-parser", @@ -16851,7 +16851,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16862,7 +16862,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16874,7 +16874,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16885,7 +16885,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-recursion", @@ -16908,7 +16908,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde_json", @@ -16920,7 +16920,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -16934,7 +16934,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16951,7 +16951,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -16964,7 +16964,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde", @@ -16976,7 +16976,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -16994,7 +16994,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -17010,7 +17010,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -17027,7 +17027,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -17041,7 +17041,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-recursion", @@ -17079,7 +17079,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "const_format", @@ -17117,7 +17117,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.866.0" +version = "1.867.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17128,7 +17128,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-recursion", @@ -17163,7 +17163,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17187,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17220,7 +17220,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17247,7 +17247,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17280,7 +17280,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17300,7 +17300,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17334,7 +17334,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17371,7 +17371,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17394,7 +17394,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17418,7 +17418,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-nats", @@ -17442,7 +17442,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17477,7 +17477,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17505,7 +17505,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-trait", @@ -17531,7 +17531,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17550,7 +17550,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-once-cell", @@ -17668,7 +17668,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.866.0" +version = "1.867.0" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 6b84a24949..da3918da69 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.866.0" +version = "1.867.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.866.0" +version = "1.867.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 7fe20e438b..515798aed6 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -d7d509d0955c52f83afd0bf8b61a0e811162c16f +1b1071ad69624a79e6eb9ceeb5d0f63c29de8167 diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index b62513aef0..00a399dab0 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.866.0" +version = "1.867.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.866.0" +version = "1.867.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.866.0" +version = "1.867.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.866.0" +version = "1.867.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 750721fa8c..fc0d18b1db 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.866.0" +version = "1.867.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/tests/fixtures/relative_python.sql b/backend/tests/fixtures/relative_python.sql index 7a70e06d20..40fbedfc34 100644 --- a/backend/tests/fixtures/relative_python.sql +++ b/backend/tests/fixtures/relative_python.sql @@ -38,3 +38,24 @@ def main(): '', '', 'f/system_relative/nested_script', 12348, 'python3', ''); + +-- Named after files in the job dir (loader.py) and after the running script's folder (f/system/). +INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( +'test-workspace', +'test-user', +'from .different_folder_script import main +', +'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', +'', +'', +'f/system_relative/loader', 12349, 'python3', ''); + +INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( +'test-workspace', +'test-user', +'from .different_folder_script import main +', +'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', +'', +'', +'f/system_relative/system', 12350, 'python3', ''); diff --git a/backend/tests/python_jobs.rs b/backend/tests/python_jobs.rs index 4236599aba..599f5c5f33 100644 --- a/backend/tests/python_jobs.rs +++ b/backend/tests/python_jobs.rs @@ -1141,9 +1141,9 @@ async fn test_relative_imports_python(db: Pool) -> anyhow::Result<()> let content = r#" from f.system.same_folder_script import main as test1 from .same_folder_script import main as test2 -from f.system_relative.different_folder_script import main as test3 -from ..system_relative.different_folder_script import main as test4 - +from f.system_relative.system import main as test3 +from ..system_relative.loader import main as test4 + def main(): return [test1(), test2(), test3(), test4()] "# diff --git a/backend/tests/runnables_list_paths.rs b/backend/tests/runnables_list_paths.rs new file mode 100644 index 0000000000..abbd34e5f7 --- /dev/null +++ b/backend/tests/runnables_list_paths.rs @@ -0,0 +1,78 @@ +//! `GET /w/{workspace}/runnables/list?paths=`: only rows at the given paths, each kind on its +//! own at a shared path, archived rows left out. + +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +async fn insert_script( + db: &Pool, + hash: i64, + path: &str, + archived: bool, +) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by, language, archived) + VALUES ('test-workspace', $1, $2, '', '', 'x', 'test-user', 'deno', $3)", + ) + .bind(hash) + .bind(path) + .bind(archived) + .execute(db) + .await?; + Ok(()) +} + +async fn insert_flow(db: &Pool, path: &str, archived: bool) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO flow (workspace_id, path, summary, description, value, edited_by, schema, archived) + VALUES ('test-workspace', $1, '', '', '{}'::jsonb, 'test-user', '{}'::json, $2)", + ) + .bind(path) + .bind(archived) + .execute(db) + .await?; + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +async fn test_list_runnables_by_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + // A renamed script leaves its archived versions behind; a flow can then take the path. + insert_script(&db, 9100001, "u/test-user/moved", true).await?; + insert_flow(&db, "u/test-user/moved", false).await?; + insert_script(&db, 9100002, "u/test-user/live", false).await?; + insert_flow(&db, "u/test-user/archived_flow", true).await?; + insert_script(&db, 9100003, "u/test-user/not_asked", false).await?; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let body: serde_json::Value = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/w/test-workspace/runnables/list\ + ?paths=u/test-user/moved,u/test-user/live,u/test-user/archived_flow,u/test-user/gone" + )) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await? + .error_for_status()? + .json() + .await?; + let mut found: Vec = body["items"] + .as_array() + .unwrap() + .iter() + .map(|x| { + format!( + "{}:{}", + x["type"].as_str().unwrap(), + x["path"].as_str().unwrap() + ) + }) + .collect(); + found.sort(); + assert_eq!(found, ["flow:u/test-user/moved", "script:u/test-user/live"]); + + Ok(()) +} diff --git a/backend/windmill-ai/src/providers/anthropic.rs b/backend/windmill-ai/src/providers/anthropic.rs index 2a3417bc62..519b1ffe74 100644 --- a/backend/windmill-ai/src/providers/anthropic.rs +++ b/backend/windmill-ai/src/providers/anthropic.rs @@ -10,7 +10,7 @@ use crate::{ query_builder::{BuildRequestArgs, ParsedResponse, QueryBuilder, StreamEventSink}, sse::{AnthropicSSEParser, SSEParser}, types::*, - utils::{collect_system_prompt, extract_text_content, should_use_structured_output_tool}, + utils::{collect_system_prompt, extract_text_content}, }; use async_trait::async_trait; use http::Method; @@ -73,19 +73,6 @@ pub enum AnthropicTool { WebSearch(AnthropicWebSearchTool), } -/// Tool choice for Anthropic API to force tool usage -#[derive(Serialize, Debug)] -pub struct AnthropicToolChoice { - pub r#type: String, -} - -impl AnthropicToolChoice { - /// Create a tool_choice that forces the model to use any tool - pub fn any() -> Self { - Self { r#type: "any".to_string() } - } -} - /// Content block for Anthropic messages (for serialization to API) #[derive(Serialize, Debug)] #[serde(tag = "type")] @@ -206,8 +193,6 @@ pub struct AnthropicRequest<'a> { #[serde(skip_serializing_if = "Option::is_none")] pub tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] - pub tool_choice: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub temperature: Option, #[serde(skip_serializing_if = "Option::is_none")] pub thinking: Option, @@ -231,8 +216,6 @@ pub struct AnthropicVertexRequest { #[serde(skip_serializing_if = "Option::is_none")] pub tools: Option>, #[serde(skip_serializing_if = "Option::is_none")] - pub tool_choice: Option, - #[serde(skip_serializing_if = "Option::is_none")] pub temperature: Option, #[serde(skip_serializing_if = "Option::is_none")] pub thinking: Option, @@ -643,23 +626,6 @@ impl AnthropicQueryBuilder { }] }); - // Check if we need to force tool usage for structured output - let has_output_properties = args - .output_schema - .and_then(|schema| schema.properties.as_ref()) - .map(|props| !props.is_empty()) - .unwrap_or(false); - - let should_use_structured_output = - should_use_structured_output_tool(&self.provider_kind, args.model); - - // Force tool usage when structured output is needed - let tool_choice = if should_use_structured_output && has_output_properties { - Some(AnthropicToolChoice::any()) - } else { - None - }; - let mut tools_option = if tools.is_empty() { None } else { Some(tools) }; let max_tokens = Some(args.max_tokens.unwrap_or(64000)); @@ -700,7 +666,6 @@ impl AnthropicQueryBuilder { system, messages: anthropic_messages, tools: tools_option, - tool_choice, temperature, thinking, output_config, @@ -716,7 +681,6 @@ impl AnthropicQueryBuilder { system, messages: anthropic_messages, tools: tools_option, - tool_choice, temperature, thinking, output_config, @@ -1314,7 +1278,6 @@ mod tests { system: None, messages: vec![], tools: None, - tool_choice: None, temperature: None, thinking: Some(AnthropicThinking::adaptive()), output_config: Some(AnthropicOutputConfig { effort: "high".to_string() }), @@ -1390,7 +1353,6 @@ mod tests { system: None, messages: vec![], tools: None, - tool_choice: None, temperature, thinking, output_config, @@ -1415,7 +1377,6 @@ mod tests { system: None, messages: vec![], tools: None, - tool_choice: None, temperature: Some(0.5), thinking: None, output_config: None, diff --git a/backend/windmill-ai/src/providers/bedrock.rs b/backend/windmill-ai/src/providers/bedrock.rs index 5aa142a127..383d93ea6b 100644 --- a/backend/windmill-ai/src/providers/bedrock.rs +++ b/backend/windmill-ai/src/providers/bedrock.rs @@ -1004,10 +1004,11 @@ impl BedrockQueryBuilder { // Build inference configuration using shared helper let inference_config = create_inference_config(temperature, max_tokens.map(|t| t as i32)); - // Build tool configuration with optional ToolChoice + // Claude rejects a forced tool alongside thinking, and the newest models reject it + // outright, so there the structured output tool is only described as the last call. let tool_config = build_tool_config( tools, - structured_output_tool_name.is_some(), + structured_output_tool_name.is_some() && !model.to_lowercase().contains("claude"), enable_prompt_caching, )?; diff --git a/backend/windmill-ai/src/providers/other.rs b/backend/windmill-ai/src/providers/other.rs index fea8edbdac..2f6d931abc 100644 --- a/backend/windmill-ai/src/providers/other.rs +++ b/backend/windmill-ai/src/providers/other.rs @@ -13,14 +13,6 @@ use serde::Serialize; use serde_json; use windmill_common::{client::AuthedClient, error::Error}; -#[derive(Serialize, Debug, Clone)] -#[serde(rename_all = "lowercase")] -pub enum ToolChoice { - #[allow(dead_code)] - Auto, - Required, -} - /// Stream options for OpenAI API to include usage in streaming responses #[derive(Serialize)] pub struct StreamOptions { @@ -45,8 +37,6 @@ pub struct OpenAICompletionRequest<'a> { pub max_completion_tokens: Option, #[serde(skip_serializing_if = "Option::is_none")] pub response_format: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub tool_choice: Option, pub stream: bool, #[serde(skip_serializing_if = "Option::is_none")] pub stream_options: Option, @@ -135,13 +125,6 @@ impl OtherQueryBuilder { None }; - // Force usage of structured output tool for Claude models when structured output is provided - let tool_choice = if should_use_structured_output_tool && has_output_properties { - Some(ToolChoice::Required) - } else { - None - }; - let (reasoning_effort, thinking, temperature) = provider_reasoning_fields(&self.provider_kind, args.reasoning_effort, args.temperature); // With tools, gpt-5.5+ only run here with reasoning off: turn it off where the model @@ -164,7 +147,6 @@ impl OtherQueryBuilder { thinking: thinking.clone(), max_completion_tokens: args.max_tokens, response_format: response_format.clone(), - tool_choice: tool_choice.clone(), stream: true, stream_options: Some(StreamOptions { include_usage: true }), }; @@ -179,7 +161,6 @@ impl OtherQueryBuilder { thinking, max_completion_tokens: args.max_tokens, response_format, - tool_choice, stream: true, stream_options: None, }; diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index 35682c60ca..aef171ff49 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -3048,13 +3048,15 @@ async fn create_script_internal<'c>( // Its dependency job is tagged for a dedicated worker. One taking it through a // `dedicated_workers` pattern only listens to the scripts it found at its last config // load: re-saving the group's config reloads it, unless the live version it replaces - // was served already (a version adopted from a deleted path was not). + // was served already (a version adopted from a deleted path was not). An entry's one + // leading `/` is dropped first, as `WorkspacedPath::dedicated` reads it for the worker. sqlx::query( "UPDATE config SET config = config WHERE name LIKE 'worker\\_\\_%' AND jsonb_typeof(config->'dedicated_workers') = 'array' AND EXISTS ( - SELECT 1 FROM jsonb_array_elements_text(config->'dedicated_workers') e + SELECT 1 FROM jsonb_array_elements_text(config->'dedicated_workers') raw, + regexp_replace(raw, '^([^:]*):/(?!/)', '\\1:') e WHERE right(e, 2) = '/*' AND starts_with($1 || ':' || $2, left(e, -1))) AND NOT EXISTS ( SELECT 1 FROM script WHERE workspace_id = $1 AND hash = $3 AND path = $2 diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index bb910f28df..18c73376d8 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.866.0 + version: 1.867.0 title: Windmill API contact: @@ -13144,6 +13144,11 @@ paths: description: restrict to paths under this prefix schema: type: string + - name: paths + in: query + description: comma-separated exact paths, to list only the rows at one of them + schema: + type: string - name: label in: query schema: diff --git a/backend/windmill-api/src/args.rs b/backend/windmill-api/src/args.rs index 6c1c9824bd..569df56ece 100644 --- a/backend/windmill-api/src/args.rs +++ b/backend/windmill-api/src/args.rs @@ -7,14 +7,16 @@ use axum::{ }; use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _}; use bytes::Bytes; -use http::header::CONTENT_TYPE; +use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE}; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use sqlx::types::JsonRawValue; +use tower_cookies::Cookie; use windmill_common::{ error::Error, jobs::WM_TRACEPARENT, triggers::{RunnableFormat, RunnableFormatVersion, TriggerKind}, + users::COOKIE_NAME, worker::to_raw_value, DB, OTEL_TRACING_ENABLED, }; @@ -363,16 +365,19 @@ impl WebhookArgs { // don't get a stray `_wm_traceparent` arg key. let trace_context = inbound_traceparent(&self.metadata.headers); + // Webhooks are authenticated by Windmill (a webhook capture stands in for one). let headers = build_headers( &self.metadata.headers, self.metadata.query_include_header, runnable_format.has_preprocessor, + true, ); let query = build_query( self.metadata.query.as_deref(), self.metadata.query_include_query, runnable_format.has_preprocessor, + true, ); let mut push_args = match runnable_format { @@ -614,19 +619,50 @@ fn inbound_traceparent(headers: &HeaderMap) -> Option { .map(|s| s.to_string()) } +/// A header's value as a runnable or a capture sees it, `None` to withhold it. +/// +/// Windmill's session cookie is never forwarded: browsers attach it on their own, so it would hand +/// the visitor's session to whoever wrote the runnable. Other cookies are kept. When the request +/// was authenticated by Windmill (`windmill_authed`), its bearer token is withheld as well. +fn forwarded_header_value( + name: &str, + value: &http::HeaderValue, + windmill_authed: bool, +) -> Option { + let value = value.to_str().unwrap_or(""); + if name.eq_ignore_ascii_case(COOKIE.as_str()) { + // Parsed the way `extract_token` reads it, so an encoded name is caught too. + let other_cookies = value + .split(';') + .filter(|c| !Cookie::parse_encoded(*c).is_ok_and(|c| c.name() == COOKIE_NAME)) + .map(str::trim) + .collect::>(); + return (!other_cookies.is_empty()).then(|| other_cookies.join("; ")); + } + if windmill_authed + && name.eq_ignore_ascii_case(AUTHORIZATION.as_str()) + && value.starts_with("Bearer ") + { + return None; + } + Some(value.to_string()) +} + +/// `windmill_authed`: the caller was authenticated by Windmill, so `Authorization: Bearer` carries +/// their Windmill token. See `forwarded_header_value`. pub fn build_headers( headers: &HeaderMap, include_header: Option, include_all_headers: bool, + windmill_authed: bool, ) -> HashMap> { let mut selected_headers = HashMap::new(); if include_all_headers { for (k, v) in headers.iter() { - selected_headers.insert( - k.to_string(), - to_raw_value(&v.to_str().unwrap_or("").to_string()), - ); + if let Some(v) = forwarded_header_value(k.as_str(), v, windmill_authed) { + selected_headers.insert(k.to_string(), to_raw_value(&v)); + } } } else { let whitelist = include_header @@ -636,10 +672,13 @@ pub fn build_headers( .iter() .chain(INCLUDE_HEADERS.iter()) .for_each(|h| { - if let Some(v) = headers.get(h) { + if let Some(v) = headers + .get(h) + .and_then(|v| forwarded_header_value(h, v, windmill_authed)) + { selected_headers.insert( h.to_string().to_lowercase().replace('-', "_"), - to_raw_value(&v.to_str().unwrap_or("").to_string()), + to_raw_value(&v), ); } }); @@ -651,16 +690,20 @@ pub fn build_query( query: Option<&str>, include_query: Option, include_all_query: bool, + windmill_authed: bool, ) -> HashMap> { let Some(query) = query else { return HashMap::new(); }; + // `?token=` is a Windmill credential when Windmill authenticated the request. + let withheld = |k: &str| windmill_authed && k == "token"; if include_all_query { let queries = serde_urlencoded::from_str::>(&query).unwrap_or_default(); queries .into_iter() + .filter(|(k, _)| !withheld(k)) .map(|(k, v)| (k, to_raw_value(&v))) .collect() } else { @@ -671,11 +714,14 @@ pub fn build_query( if !parse_query_args.is_empty() { let queries = serde_urlencoded::from_str::>(&query).unwrap_or_default(); - parse_query_args.iter().for_each(|h| { - if let Some(v) = queries.get(h) { - args.insert(h.to_string(), to_raw_value(v)); - } - }); + parse_query_args + .iter() + .filter(|h| !withheld(h)) + .for_each(|h| { + if let Some(v) = queries.get(h) { + args.insert(h.to_string(), to_raw_value(v)); + } + }); } args } @@ -755,6 +801,47 @@ mod tests { use super::*; + #[test] + fn test_build_headers_withholds_windmill_credentials() { + let headers = HeaderMap::from_iter([ + (COOKIE, "a=1; token=s; %74oken=s; b=2".parse().unwrap()), + (AUTHORIZATION, "Bearer s".parse().unwrap()), + ]); + let get = + |h: &HashMap>, k: &str| h.get(k).map(|v| v.get().to_string()); + + for windmill_authed in [false, true] { + let auth = (!windmill_authed).then(|| r#""Bearer s""#.to_string()); + let all = build_headers(&headers, None, true, windmill_authed); + assert_eq!(get(&all, "cookie").as_deref(), Some(r#""a=1; b=2""#)); + assert_eq!(get(&all, "authorization"), auth); + + let listed = build_headers( + &headers, + Some("cookie,authorization".into()), + false, + windmill_authed, + ); + assert_eq!(get(&listed, "cookie").as_deref(), Some(r#""a=1; b=2""#)); + assert_eq!(get(&listed, "authorization"), auth); + + let query = build_query(Some("token=s&a=1"), None, true, windmill_authed); + assert_eq!(query.contains_key("token"), !windmill_authed); + assert!(query.contains_key("a")); + let listed = build_query( + Some("token=s&a=1"), + Some("token,a".into()), + false, + windmill_authed, + ); + assert_eq!(listed.contains_key("token"), !windmill_authed); + assert!(listed.contains_key("a")); + } + + let only_session = HeaderMap::from_iter([(COOKIE, "token=s".parse().unwrap())]); + assert!(build_headers(&only_session, None, true, false).is_empty()); + } + #[tokio::test] async fn test_bodyless_request_with_json_content_type() { let request = Request::builder() diff --git a/backend/windmill-api/src/capture.rs b/backend/windmill-api/src/capture.rs index 8e9fb4a823..7dbb464a57 100644 --- a/backend/windmill-api/src/capture.rs +++ b/backend/windmill-api/src/capture.rs @@ -1250,8 +1250,8 @@ async fn http_payload( .map(|(k, v)| (k.to_string(), v.to_string())) .collect(); - let headers = build_headers(&args.0.metadata.headers, None, true); - let query = build_query(args.0.metadata.query.as_deref(), None, true); + let headers = build_headers(&args.0.metadata.headers, None, true, false); + let query = build_query(args.0.metadata.query.as_deref(), None, true, false); let preprocessor_args = args .clone() diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index e4245c32aa..72ed0ca03e 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -768,16 +768,16 @@ struct McpPreprocessorEvent<'a> { /// Headers withheld from a preprocessor because they authenticate the connection. /// -/// Not a security boundary: a webhook preprocessor receives all three. Withheld -/// because nothing needs them yet, and releasing one later is additive while -/// withdrawing one after runnables read it is not. +/// `build_headers` already withholds Windmill's own credentials. The rest is +/// withheld because nothing needs it yet, and releasing one later is additive +/// while withdrawing one after runnables read it is not. const WITHHELD_FROM_PREPROCESSOR: &[&str] = &["authorization", "cookie", "proxy-authorization"]; /// Every header a preprocessor may see. fn preprocessor_headers( headers: &http::HeaderMap, ) -> HashMap> { - let mut selected = build_headers(headers, None, true); + let mut selected = build_headers(headers, None, true, true); selected.retain(|name, _| { !WITHHELD_FROM_PREPROCESSOR .iter() diff --git a/backend/windmill-api/src/runnables.rs b/backend/windmill-api/src/runnables.rs index 0037a37042..ae5e7da787 100644 --- a/backend/windmill-api/src/runnables.rs +++ b/backend/windmill-api/src/runnables.rs @@ -60,6 +60,8 @@ struct ListRunnablesQuery { include_without_main: Option, /// Restrict to paths under this prefix (owner/folder filter). path_start: Option, + /// Comma-separated exact paths: list only the rows at one of them. + paths: Option, /// Comma-separated labels; a row matches if it (or its folder) carries all. label: Option, /// Case-insensitive fuzzy match on `summary (path)`, mirroring how the homepage @@ -519,6 +521,13 @@ async fn list_runnables( // `u//draft_` it is parked at. draft_common.push(format!("COALESCE(o.draft_path, o.path) LIKE {}", p)); } + if let Some(ps) = q.paths.as_ref().filter(|s| !s.is_empty()) { + let p = add_bind(&mut binds, ps.clone()); + common.push(format!("o.path = ANY(string_to_array({p}, ','))")); + draft_common.push(format!( + "COALESCE(o.draft_path, o.path) = ANY(string_to_array({p}, ','))" + )); + } if let Some(search) = q.search.as_ref().filter(|s| !s.is_empty()) { let terms = search_terms(search); if terms.is_empty() { diff --git a/backend/windmill-api/src/triggers/http/handler.rs b/backend/windmill-api/src/triggers/http/handler.rs index daff81249f..ed7a61d986 100644 --- a/backend/windmill-api/src/triggers/http/handler.rs +++ b/backend/windmill-api/src/triggers/http/handler.rs @@ -759,6 +759,10 @@ async fn route_job( ¶ms, runnable_format, trigger.wrap_body, + matches!( + trigger.authentication_method, + AuthenticationMethod::Windmill + ), ) .map(windmill_queue::PushArgsOwned::omit_untrusted_interpolation) .map_err(|e| e.into_response())?; diff --git a/backend/windmill-api/src/triggers/http/http_trigger_args.rs b/backend/windmill-api/src/triggers/http/http_trigger_args.rs index f8460f42e2..2dacbdb50d 100644 --- a/backend/windmill-api/src/triggers/http/http_trigger_args.rs +++ b/backend/windmill-api/src/triggers/http/http_trigger_args.rs @@ -121,9 +121,15 @@ impl HttpTriggerArgs { params: &HashMap, format: RunnableFormat, wrap_body: bool, + windmill_authed: bool, ) -> Result { - let headers = build_headers(&self.0.metadata.headers, None, true); - let query = build_query(self.0.metadata.query.as_deref(), None, true); + let headers = build_headers(&self.0.metadata.headers, None, true, windmill_authed); + let query = build_query( + self.0.metadata.query.as_deref(), + None, + true, + windmill_authed, + ); match format { RunnableFormat { has_preprocessor: true, version: RunnableFormatVersion::V2 } => { // we don't care about wrap_body in v2 diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index c1c1e9f582..99f3860247 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -33,6 +33,7 @@ use crate::{ external_ip::UNKNOWN_IP, global_settings::CUSTOM_TAGS_SETTING, indexer::TantivyIndexerSettings, + runnable_ref::RunnableRef, server::Smtp, utils::{merge_nested_raw_values_to_array, merge_raw_values_to_array}, KillpillSender, DB, @@ -2713,12 +2714,7 @@ pub async fn load_worker_config( "Invalid dedicated_worker format. Got {x}, expects :" )); } else { - let workspace = splitted[0]; - let script_path = splitted[1]; - Ok(WorkspacedPath { - workspace_id: workspace.to_string(), - path: script_path.to_string(), - }) + Ok(WorkspacedPath::dedicated(splitted[0], splitted[1])) } }) .transpose()?; @@ -2736,12 +2732,7 @@ pub async fn load_worker_config( "Invalid dedicated_workers format. Got {x}, expects :" )); } - let workspace = splitted[0]; - let script_path = splitted[1]; - Ok(WorkspacedPath { - workspace_id: workspace.to_string(), - path: script_path.to_string(), - }) + Ok(WorkspacedPath::dedicated(splitted[0], splitted[1])) }) .collect::, _>>() }) @@ -3103,6 +3094,26 @@ pub struct WorkspacedPath { pub path: String, } +impl WorkspacedPath { + /// A dedicated worker setting's ``, a flow written `flow/`, read the way job + /// resolution reads it: the result is the path its jobs' dedicated tag is built from. A path + /// that does not parse is kept as written: its tag matches no job, and refusing it would stop + /// the worker serving the other entries of its group. + pub fn dedicated(workspace_id: &str, path: &str) -> Self { + let runnable = if path.starts_with("flow/") { + RunnableRef::from_prefixed(path) + } else { + RunnableRef::from_path(path, false) + }; + let path = match runnable { + Ok(r) if r.is_flow() => format!("flow/{}", r.path()), + Ok(r) => r.path().to_string(), + Err(_) => path.to_string(), + }; + Self { workspace_id: workspace_id.to_string(), path } + } +} + #[derive(Serialize, Deserialize, Debug)] pub struct WorkerConfigOpt { pub worker_tags: Option>, @@ -3372,6 +3383,16 @@ mod tests { use super::*; use std::collections::HashMap; + #[test] + fn dedicated_path_is_read_like_a_job_path() { + let path = |p: &str| WorkspacedPath::dedicated("ws", p).path; + assert_eq!(path("/u/me/x"), "u/me/x"); + assert_eq!(path("flow//f/a/b"), "flow/f/a/b"); + assert_eq!(path("u/me/x"), "u/me/x"); + assert_eq!(path("//u/me/x"), "//u/me/x"); + assert_eq!(path("/f/dw/*"), "f/dw/*"); + } + #[test] fn whitelist_env_secret_heuristic() { let cases = [ diff --git a/backend/windmill-queue/src/tags.rs b/backend/windmill-queue/src/tags.rs index 6a9cfc1200..1c30146491 100644 --- a/backend/windmill-queue/src/tags.rs +++ b/backend/windmill-queue/src/tags.rs @@ -209,8 +209,7 @@ async fn is_dedicated_worker_tag_of( .await?; let of_workspace = |entry: &serde_json::Value| { let (ws, path) = entry.as_str()?.split_once(':')?; - (ws == workspace_id) - .then(|| WorkspacedPath { workspace_id: ws.to_string(), path: path.to_string() }) + (ws == workspace_id).then(|| WorkspacedPath::dedicated(ws, path)) }; let mut single = vec![]; let mut many = vec![]; diff --git a/backend/windmill-trigger-http/src/lib.rs b/backend/windmill-trigger-http/src/lib.rs index e9dfbd405a..e39828dfd8 100644 --- a/backend/windmill-trigger-http/src/lib.rs +++ b/backend/windmill-trigger-http/src/lib.rs @@ -58,8 +58,47 @@ pub struct TriggerRoute { pub mode: TriggerMode, } +/// The routes of one HTTP method. Workspaced routes are looked up first, so a route a workspace +/// serves under its own `/{workspace_id}/` prefix is never answered by an instance-wide route, +/// whatever their patterns, and a conflict between the two cannot drop either. +pub struct MethodRouter { + workspaced: matchit::Router, + instance_wide: matchit::Router, +} + +impl Default for MethodRouter { + fn default() -> Self { + Self { workspaced: matchit::Router::new(), instance_wide: matchit::Router::new() } + } +} + +impl MethodRouter { + pub fn insert( + &mut self, + workspaced: bool, + path: String, + value: T, + ) -> std::result::Result<(), matchit::InsertError> { + if workspaced { + &mut self.workspaced + } else { + &mut self.instance_wide + } + .insert(path, value) + } + + pub fn at<'m, 'p>( + &'m self, + path: &'p str, + ) -> std::result::Result, matchit::MatchError> { + self.workspaced + .at(path) + .or_else(|_| self.instance_wide.at(path)) + } +} + pub struct RoutersCache { - pub routers: HashMap>, + pub routers: HashMap>, pub version: i64, /// `HTTP_ROUTERS_INVALIDATIONS` as of the moment these rows were read. A rebuild that /// started before an invalidation publishes a count behind the current one, which is what @@ -343,21 +382,25 @@ pub async fn refresh_routers( .fetch_all(db) .await?; - let mut router = matchit::Router::new(); + let mut router = MethodRouter::default(); let http_route_workspaced = HTTP_ROUTE_WORKSPACED_ROUTE.load(std::sync::atomic::Ordering::Relaxed); for trigger in triggers { - let full_path = - if trigger.workspaced_route || *CLOUD_HOSTED || http_route_workspaced { - format!("/{}/{}", trigger.workspace_id, trigger.route_path) - } else { - format!("/{}", trigger.route_path) - }; + let workspaced = trigger.workspaced_route || *CLOUD_HOSTED || http_route_workspaced; + let full_path = if workspaced { + format!("/{}/{}", trigger.workspace_id, trigger.route_path) + } else { + format!("/{}", trigger.route_path) + }; if trigger.is_static_website { router - .insert(format!("{}/*wm_subpath", full_path), trigger.clone()) + .insert( + workspaced, + format!("{}/*wm_subpath", full_path), + trigger.clone(), + ) .unwrap_or_else(|e| { tracing::warn!( "Failed to consider HTTP route {}/*wm_subpath: {:?}", @@ -367,7 +410,7 @@ pub async fn refresh_routers( }); } router - .insert(full_path.clone(), trigger.clone()) + .insert(workspaced, full_path.clone(), trigger.clone()) .unwrap_or_else(|e| { tracing::warn!("Failed to consider HTTP route {}: {:?}", full_path, e,); }); @@ -492,6 +535,33 @@ mod tests { validate_allowed_origins, MAX_ALLOWED_ORIGINS, MAX_ALLOWED_ORIGIN_LEN, }; + #[test] + fn test_workspaced_route_takes_precedence_over_instance_wide() { + let mut router = MethodRouter::default(); + router + .insert(false, "/ws/gh/myrepo".to_string(), "instance") + .unwrap(); + router + .insert(false, "/ws/hooks/*rest".to_string(), "instance") + .unwrap(); + router + .insert(true, "/ws/gh/:repo".to_string(), "ws") + .unwrap(); + router + .insert(true, "/ws/hooks/:id".to_string(), "ws") + .unwrap(); + router + .insert(false, "/other/:id".to_string(), "instance") + .unwrap(); + + let at = |path| router.at(path).map(|m| *m.value).ok(); + assert_eq!(at("/ws/gh/myrepo"), Some("ws")); + assert_eq!(at("/ws/hooks/abc"), Some("ws")); + assert_eq!(at("/ws/hooks/abc/def"), Some("instance")); + assert_eq!(at("/other/1"), Some("instance")); + assert_eq!(at("/nothing"), None); + } + #[test] fn test_request_type_backward_compatibility() { // Test with new request_type field diff --git a/backend/windmill-worker/loader.py b/backend/windmill-worker/loader.py index bf67266d87..fd9d2b1376 100644 --- a/backend/windmill-worker/loader.py +++ b/backend/windmill-worker/loader.py @@ -11,14 +11,14 @@ import time TEMP_SCRIPT_REFS = TEMP_SCRIPT_REFS_PLACEHOLDER class WindmillLoader(Loader): - def __init__(self, path): - self.path = path - def create_module(self, spec): return None def exec_module(self, module): - module.__path__ = self.path + # Must stay empty: PathFinder runs before WindmillFinder and would resolve + # submodules against any entry here (relative to the job dir, which holds + # loader.py, wrapper.py and the running script's f//). + module.__path__ = [] return None @@ -31,7 +31,7 @@ class WindmillFinder(MetaPathFinder): return None l = len(splitted) # noqa: E741 if l <= 2: - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) elif l > 2: script_path = "/".join(splitted) @@ -68,7 +68,7 @@ class WindmillFinder(MetaPathFinder): os.makedirs(folder, exist_ok=True) r = response.read().decode("utf-8") if r == "WINDMILL_IS_FOLDER": - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) # Python parses .py as UTF-8 regardless of locale, so the # file has to be written as UTF-8. Without this the ANSI # code page on a Windows worker re-encodes every @@ -80,7 +80,7 @@ class WindmillFinder(MetaPathFinder): duration = time.time() - req_start if e.code != 404: print(f"Error fetching script {script_path}: HTTP {e.code} - {e.reason} - {duration}s") - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) except Exception as e: duration = time.time() - req_start # Check if this is errno 104 (Connection reset by peer) and we have retries left @@ -89,7 +89,7 @@ class WindmillFinder(MetaPathFinder): time.sleep(3) continue print(f"Error fetching script {script_path}: {e} - {duration}s") - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) diff --git a/backend/windmill-worker/src/ai_executor.rs b/backend/windmill-worker/src/ai_executor.rs index 385f88685c..5e8bb1d921 100644 --- a/backend/windmill-worker/src/ai_executor.rs +++ b/backend/windmill-worker/src/ai_executor.rs @@ -1715,7 +1715,7 @@ pub async fn run_agent( function: ToolDefFunction { name: unique_tool_name, description: Some( - "This tool MUST be used last to return a structured JSON object as the final output." + "Return the final answer. Always finish by calling this tool exactly once with the answer as its input, instead of replying in plain text." .to_string(), ), parameters: to_raw_value(&schema), diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 851a59e987..199e26a1a4 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.866.0"; +export const VERSION = "v1.867.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 69c3fa2b56..93db1e4dab 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.866.0", + "version": "1.867.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.866.0", + "version": "1.867.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 be58d54c45..c9174c6c32 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.866.0", + "version": "1.867.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/bun.lock b/cli/bun.lock index 5c39e7e9df..f4aee7d364 100644 --- a/cli/bun.lock +++ b/cli/bun.lock @@ -14,7 +14,7 @@ "esbuild": "0.28.2", "get-port": "7.1.0", "jszip": "3.8.0", - "minimatch": "^10.0.0", + "minimatch": "^11.0.1", "open": "^10.0.0", "pg-gateway": "0.3.0-beta.4", "svelte": "^5.56.8", @@ -35,7 +35,7 @@ "windmill-parser-wasm-yaml": "1.770.0", "windmill-yaml-validator": "1.1.1", "ws": "8.21.3", - "yaml": "^2.7.0", + "yaml": "^2.9.1", }, "devDependencies": { "@types/bun": "^1.3.9", @@ -109,6 +109,8 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + "@isaacs/nonrecursive-glob-match": ["@isaacs/nonrecursive-glob-match@1.1.0", "", {}, "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw=="], + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], @@ -191,7 +193,7 @@ "bare-events": ["bare-events@2.8.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ=="], - "brace-expansion": ["brace-expansion@5.0.2", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw=="], + "brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], "bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="], @@ -223,7 +225,7 @@ "fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="], - "fast-uri": ["fast-uri@3.1.4", "", {}, "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw=="], + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], "get-port": ["get-port@7.1.0", "", {}, "sha512-QB9NKEeDg3xxVwCCwJQ9+xycaz6pBB6iQ76wiWMl1927n0Kir6alPiP+yuiICLLU4jpMe08dXfpebuQppFA2zw=="], @@ -251,7 +253,7 @@ "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - "minimatch": ["minimatch@10.2.2", "", { "dependencies": { "brace-expansion": "^5.0.2" } }, "sha512-+G4CpNBxa5MprY+04MbgOw1v7So6n5JY166pFi9KfYwT78fxScCeSNQSNzp6dpPSW2rONOps6Ocam1wFhCgoVw=="], + "minimatch": ["minimatch@11.0.7", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" } }, "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg=="], "open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], @@ -325,7 +327,7 @@ "wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - "yaml": ["yaml@2.8.2", "", { "bin": "bin.mjs" }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], "zimmerframe": ["zimmerframe@1.1.4", "", {}, "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ=="], } diff --git a/cli/package.json b/cli/package.json index 47dc820f9a..a6f152daac 100644 --- a/cli/package.json +++ b/cli/package.json @@ -27,7 +27,7 @@ "esbuild": "0.28.2", "get-port": "7.1.0", "jszip": "3.8.0", - "minimatch": "^10.0.0", + "minimatch": "^11.0.1", "open": "^10.0.0", "pg-gateway": "0.3.0-beta.4", "svelte": "^5.56.8", @@ -48,7 +48,7 @@ "windmill-parser-wasm-yaml": "1.770.0", "windmill-yaml-validator": "1.1.1", "ws": "8.21.3", - "yaml": "^2.7.0" + "yaml": "^2.9.1" }, "devDependencies": { "@types/bun": "^1.3.9", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index a431495b12..264767060e 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.866.0"; +export const VERSION = "1.867.0"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f5d0e7fe90..c865ebff73 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.866.0", + "version": "1.867.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.866.0", + "version": "1.867.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index aa2892911b..b824b787f8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.866.0", + "version": "1.867.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 be8980e93a..22c841c91a 100644 --- a/frontend/src/lib/aiStore.test.ts +++ b/frontend/src/lib/aiStore.test.ts @@ -1,16 +1,53 @@ import { describe, expect, it, vi } from 'vitest' import { get } from 'svelte/store' -// aiStore pulls in the (heavy) copilot lib for workspaceAIClients and the gen -// client for WorkspaceService; neither is exercised by setCopilotInfo. +let requests: { workspace: string; resolve: (config: any) => void }[] = [] + +// aiStore pulls in the (heavy) copilot lib for workspaceAIClients; setCopilotInfo does not +// exercise it. vi.mock('./components/copilot/lib', () => ({ workspaceAIClients: { init: () => {} } })) vi.mock('./gen', () => ({ - WorkspaceService: { getCopilotInfo: async () => ({}) } + WorkspaceService: { + getCopilotInfo: ({ workspace }: { workspace: string }) => + new Promise((resolve) => requests.push({ workspace, resolve })) + } })) -import { isWebSearchEnabledForProvider, setCopilotInfo, copilotInfo } from './aiStore' +import { + isWebSearchEnabledForProvider, + setCopilotInfo, + copilotInfo, + getWorkspaceCopilotInfo, + invalidateWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo +} from './aiStore' + +const withModel = (model: string) => ({ + providers: { anthropic: { resource_path: 'u/admin/anthropic', models: [model] } } +}) +const modelOf = (info: { aiModels: { model: string }[] } | undefined) => info?.aiModels[0]?.model + +// A config saved, or one every workspace inherits, while a session's load is in flight: the load +// read the config from before the save and must not keep it. +describe.each([ + ['its workspace', () => invalidateWorkspaceCopilotInfo('ws')], + ['every workspace', () => invalidateWorkspaceCopilotInfo()] +])('loadWorkspaceCopilotInfo invalidated for %s mid-fetch', (_, invalidate) => { + it('refetches instead of keeping the outdated config', async () => { + requests = [] + invalidateWorkspaceCopilotInfo() + const load = loadWorkspaceCopilotInfo('ws') + invalidate() + requests[0].resolve(withModel('before-save')) + await vi.waitFor(() => expect(requests).toHaveLength(2)) + requests[1].resolve(withModel('saved')) + + expect(modelOf(await load)).toBe('saved') + expect(modelOf(getWorkspaceCopilotInfo('ws'))).toBe('saved') + }) +}) describe('setCopilotInfo legacy /thinking migration', () => { it('strips the /thinking suffix from configured model slots', () => { diff --git a/frontend/src/lib/aiStore.ts b/frontend/src/lib/aiStore.ts index ac9320f8a3..246fd0a1f0 100644 --- a/frontend/src/lib/aiStore.ts +++ b/frontend/src/lib/aiStore.ts @@ -3,13 +3,15 @@ // 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 { writable, get } from 'svelte/store' +import { SvelteMap } from 'svelte/reactivity' import { type AIProviderModel, type AIProvider, type AIConfig, type AIWebSearchConfig, type FreeTierInfo, - type ModelPriceOverride + type ModelPriceOverride, + WorkspaceService } from './gen' import { aiUserDisabled, @@ -40,7 +42,7 @@ export const copilotSessionModel = writable( : undefined ) -export const copilotInfo = writable<{ +export type CopilotInfo = { enabled: boolean // The workspace hid the assistant (`ai_config.copilot_disabled`). `enabled` is then false // whatever the providers say, and the AI entry points that nudge "configure AI" when @@ -64,7 +66,9 @@ export const copilotInfo = writable<{ // Windmill's free tier. `exhausted` means the grant is spent: there is no model, but // that is a different state from "never configured" and the UI must say so. freeTier?: FreeTierInfo -}>({ +} + +export const copilotInfo = writable({ enabled: false, workspaceDisabled: false, codeCompletionModel: undefined, @@ -78,13 +82,27 @@ export const copilotInfo = writable<{ webSearchEnabledProviders: {} }) +// Each workspace's AI config, read by AI sessions, which send with their own workspace's config +// rather than the tab's. Only `loadWorkspaceCopilotInfo` fills it: a save invalidates instead. +const workspaceCopilotInfos = new SvelteMap() +const workspaceLoads = new Map>() +// Bumped by invalidation: a load started before it refetches instead of keeping its answer. +let allWorkspacesVersion = 0 +const workspaceVersions = new Map() +const versionOf = (workspace: string) => + `${allWorkspacesVersion}:${workspaceVersions.get(workspace) ?? 0}` + // Apply the per-user opt-out live: toggling it flips `enabled` without re-fetching. // Only enable when providers exist (aiModels is populated whenever the config has any). aiUserDisabled.subscribe((disabled) => { - copilotInfo.update((info) => ({ + const withOptOut = (info: CopilotInfo): CopilotInfo => ({ ...info, enabled: info.aiModels.length > 0 && !disabled && !info.workspaceDisabled - })) + }) + copilotInfo.update(withOptOut) + for (const [workspace, info] of workspaceCopilotInfos) { + workspaceCopilotInfos.set(workspace, withOptOut(info)) + } }) /** Strip the deprecated /thinking suffix from a configured model slot, if present. */ @@ -110,7 +128,7 @@ function dedupeModels(models: AIProviderModel[]): AIProviderModel[] { // workspace's provider/model while the scoped load is still in flight. export const copilotWorkspace = writable(undefined) -export function setCopilotInfo(aiConfig: AIConfig) { +function buildCopilotInfo(aiConfig: AIConfig, userDisabled: boolean): CopilotInfo { if (Object.keys(aiConfig.providers ?? {}).length > 0) { const aiModels = dedupeModels( Object.entries(aiConfig.providers ?? {}).flatMap(([provider, providerConfig]) => @@ -128,20 +146,10 @@ export function setCopilotInfo(aiConfig: AIConfig) { ]) ) as Partial> - copilotSessionModel.update((model) => { - if ( - model && - !aiModels.some((m) => m.model === model.model && m.provider === model.provider) - ) { - return undefined - } - return model - }) - const workspaceDisabled = aiConfig.copilot_disabled === true - copilotInfo.set({ + return { // Providers are configured; only the workspace or per-user opt-outs can gate it off. - enabled: !workspaceDisabled && !get(aiUserDisabled), + enabled: !workspaceDisabled && !userDisabled, workspaceDisabled, // Strip the deprecated /thinking suffix from the configured model slots too, // otherwise a workspace whose default still carries it sends an invalid model id. @@ -156,11 +164,9 @@ export function setCopilotInfo(aiConfig: AIConfig) { webSearchBackend: aiConfig.web_search?.provider, modelPricing: aiConfig.model_pricing ?? {}, freeTier: aiConfig.free_tier - }) + } } else { - copilotSessionModel.set(undefined) - - copilotInfo.set({ + return { enabled: false, workspaceDisabled: aiConfig.copilot_disabled === true, codeCompletionModel: undefined, @@ -175,20 +181,26 @@ export function setCopilotInfo(aiConfig: AIConfig) { // An exhausted free grant lands here — no providers, but the reason AI is off // is "you used it up", not "you never set it up". freeTier: aiConfig.free_tier - }) + } } } -export function isWebSearchEnabledForProvider(provider: AIProvider | undefined): boolean { +export function isWebSearchEnabledForProvider( + provider: AIProvider | undefined, + info: CopilotInfo = get(copilotInfo) +): boolean { if (!provider) { return false } - return get(copilotInfo).webSearchEnabledProviders?.[provider] ?? true + return info.webSearchEnabledProviders?.[provider] ?? true } export function getCurrentModel(): ReasoningProviderModel { - const model = - get(copilotSessionModel) ?? get(copilotInfo).defaultModel ?? get(copilotInfo).aiModels[0] + return resolveModelFor(get(copilotInfo)) +} + +export function resolveModelFor(info: CopilotInfo): ReasoningProviderModel { + const model = tryResolveModelFor(info) if (!model) { throw new Error('No model selected') } @@ -196,7 +208,10 @@ export function getCurrentModel(): ReasoningProviderModel { } export function getMetadataModel(): AIProviderModel { - const info = get(copilotInfo) + return resolveMetadataModelFor(get(copilotInfo)) +} + +export function resolveMetadataModelFor(info: CopilotInfo): AIProviderModel { const model = info.metadataModel ?? info.defaultModel ?? info.aiModels[0] if (!model) { throw new Error('No model selected') @@ -205,9 +220,85 @@ export function getMetadataModel(): AIProviderModel { } export function tryGetCurrentModel(): ReasoningProviderModel | undefined { - return get(copilotSessionModel) ?? get(copilotInfo).defaultModel ?? get(copilotInfo).aiModels[0] + return tryResolveModelFor(get(copilotInfo)) } +/** `workspace`'s AI config if loaded; otherwise starts loading it and returns undefined. */ +export function getWorkspaceCopilotInfo(workspace: string): CopilotInfo | undefined { + const info = workspaceCopilotInfos.get(workspace) + if (!info) { + loadWorkspaceCopilotInfo(workspace).catch((e) => + console.error(`Failed to load the AI config of workspace ${workspace}`, e) + ) + } + return info +} + +/** `workspace`'s AI config for a request made on its behalf, without touching the tab's. + * 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) + if (known && !fresh) return Promise.resolve(known) + let load = workspaceLoads.get(workspace) + if (!load) { + const version = versionOf(workspace) + load = WorkspaceService.getCopilotInfo({ workspace }) + // Settled before the retry below, which would otherwise be handed this same load. + .finally(() => workspaceLoads.delete(workspace)) + .then((config) => { + if (version !== versionOf(workspace)) return loadWorkspaceCopilotInfo(workspace) + const info = buildCopilotInfo(config, get(aiUserDisabled)) + workspaceCopilotInfos.set(workspace, info) + return info + }) + workspaceLoads.set(workspace, load) + } + return load +} + +/** After a save of `workspace`'s AI config, or with none of a config every workspace inherits + * (the instance's): the next request refetches. */ +export function invalidateWorkspaceCopilotInfo(workspace?: string) { + if (workspace) { + workspaceVersions.set(workspace, (workspaceVersions.get(workspace) ?? 0) + 1) + workspaceCopilotInfos.delete(workspace) + } else { + allWorkspacesVersion++ + workspaceCopilotInfos.clear() + } +} + +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) +} + +function isOffered(info: CopilotInfo, model: AIProviderModel): boolean { + return info.aiModels.some((m) => m.model === model.model && m.provider === model.provider) +} + +/** The model a request for `info`'s workspace sends: the shared pick when that workspace offers + * it, else its default, else its first model. Never one the workspace does not offer. */ +export function tryResolveModelFor(info: CopilotInfo): ReasoningProviderModel | undefined { + const picked = get(copilotSessionModel) + if (picked && isOffered(info, picked)) return picked + return info.defaultModel ?? info.aiModels[0] +} + +/** A workspace a request is made for and that workspace's AI config, kept together so a request + * never pairs one workspace's credentials with another's settings. */ +export type AiTarget = { workspace: string; info: CopilotInfo } + +/** What an AI session sends with, for code that otherwise reads the tab's model and config. + * Both are undefined while the session's config is loading. */ +export type SessionAi = { model: ReasoningProviderModel | undefined; info: CopilotInfo | undefined } + export function getUserCustomPrompts(): Record { const stored = getLocalSetting(USER_CUSTOM_PROMPTS_KEY) if (stored) { @@ -242,8 +333,11 @@ export function getCombinedCustomPrompt(mode: string): string | undefined { // Like getCombinedCustomPrompt but keeps the workspace and user slices separate so the // Global system prompt can label them distinctly — only the user slice is editable by the // update_user_instructions tool. -export function getCustomPromptParts(mode: string): { workspace?: string; user?: string } { - const workspace = get(copilotInfo).customPrompts?.[mode]?.trim() || undefined +export function getCustomPromptParts( + mode: string, + customPrompts: Record | undefined = get(copilotInfo).customPrompts +): { workspace?: string; user?: string } { + const workspace = customPrompts?.[mode]?.trim() || undefined const user = getUserCustomPrompts()[mode]?.trim() || undefined return { workspace, user } } diff --git a/frontend/src/lib/components/DedicatedWorkersSelector.svelte b/frontend/src/lib/components/DedicatedWorkersSelector.svelte index c355f1cf50..6bcdbd3eb7 100644 --- a/frontend/src/lib/components/DedicatedWorkersSelector.svelte +++ b/frontend/src/lib/components/DedicatedWorkersSelector.svelte @@ -26,7 +26,7 @@ import { SvelteMap } from 'svelte/reactivity' import { untrack } from 'svelte' import BarsStaggered from './icons/BarsStaggered.svelte' - import { isDedicatedPattern, parseTag } from './dedicated_worker' + import { canonicalTag, isDedicatedPattern, parseTag } from './dedicated_worker' import Tooltip from './Tooltip.svelte' // A "Runnable" is a script or flow with dedicated_worker=true @@ -481,7 +481,7 @@ language: script.language ?? 'unknown', type: 'script', path: script.path, - selected: selectedTags.includes(tag), + selected: isSelected(tag), workspaceDeps: depsMap.get(script.path) }) } @@ -496,7 +496,7 @@ language: 'flow', type: 'flow', path: flow.path, - selected: selectedTags.includes(tag), + selected: isSelected(tag), runners: undefined, loadingRunners: false, expanded: false @@ -541,17 +541,22 @@ function updateSelectedTags() { // Keep tags from other workspaces, update only the currently visible ones const visibleTags = new Set(runnables.map((r) => r.tag)) - const otherTags = selectedTags.filter((t) => !visibleTags.has(t)) + const otherTags = selectedTags.filter((t) => !visibleTags.has(canonicalTag(t))) for (const r of runnables) if (coveringPattern(r)) r.selected = false const newVisibleTags = runnables.filter((r) => r.selected).map((r) => r.tag) selectedTags = [...otherTags, ...newVisibleTags] onchange?.(selectedTags) } + // `tag` is canonical; a saved entry may be spelled with a leading `/` + function isSelected(tag: string): boolean { + return selectedTags.some((t) => canonicalTag(t) === tag) + } + let patternInput = $state('') let patternTag = $derived( selectedWorkspace && isDedicatedPattern(patternInput.trim()) - ? `${selectedWorkspace}:${patternInput.trim()}` + ? canonicalTag(`${selectedWorkspace}:${patternInput.trim()}`) : undefined ) @@ -569,7 +574,7 @@ } function addPattern() { - if (!patternTag || selectedTags.includes(patternTag)) return + if (!patternTag || isSelected(patternTag)) return selectedTags = [...selectedTags, patternTag] patternInput = '' updateSelectedTags() @@ -578,7 +583,7 @@ function removeTag(tag: string) { selectedTags = selectedTags.filter((t) => t !== tag) // Also update runnable state if visible - const runnable = runnables.find((r) => r.tag === tag) + const runnable = runnables.find((r) => r.tag === canonicalTag(tag)) if (runnable) { runnable.selected = false } @@ -912,7 +917,7 @@ > {#if via} via {via.substring(via.indexOf(':') + 1)}via {parseTag(via)?.path} {/if} {#if runnable.type === 'flow' && runnable.runners} diff --git a/frontend/src/lib/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index b103e7ddf8..7e9b192578 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -276,6 +276,10 @@ // rather than via getAiChatManager(), which collapses "no session" into the // singleton — the distinction is what tells ⌘L whether a pane exists to open. const sessionScopedChatManager = getContext('aiChatManager') + // Autocomplete in a session's editor follows the session's workspace, not the tab's. + const completionInfo = $derived( + sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo + ) // let graphqlService: MonacoGraphQLAPI | undefined = undefined let fetchedDbSchema: DBSchema | undefined = $state(undefined) @@ -1008,7 +1012,11 @@ if (autocompletor) { autocompletor.dispose() } - autocompletor = new Autocompletor(editor, scriptLang, { workflowAsCode }) + const session = sessionScopedChatManager + autocompletor = new Autocompletor(editor, scriptLang, { + workflowAsCode, + sessionTarget: session ? () => session.loadedSessionAiTarget : undefined + }) } const outputChannel = { @@ -2082,9 +2090,9 @@ }) $effect(() => { const currentWorkflowAsCode = workflowAsCode - $copilotInfo.enabled && + completionInfo?.enabled && $codeCompletionSessionEnabled && - Autocompletor.isProviderModelSupported($copilotInfo.codeCompletionModel) && + Autocompletor.isProviderModelSupported(completionInfo.codeCompletionModel) && initialized && editor && scriptLang && @@ -2094,7 +2102,7 @@ $copilotInfo.enabled && initialized && editor && untrack(() => editor && addChatHandler(editor)) }) $effect(() => { - ;(!$codeCompletionSessionEnabled || !$copilotInfo.enabled) && autocompletor?.dispose() + ;(!$codeCompletionSessionEnabled || !completionInfo?.enabled) && autocompletor?.dispose() }) $effect(() => { if (yContent && awareness && model && editor) { diff --git a/frontend/src/lib/components/FlowStatusViewerInner.svelte b/frontend/src/lib/components/FlowStatusViewerInner.svelte index 308092c1c4..1b1334bbcc 100644 --- a/frontend/src/lib/components/FlowStatusViewerInner.svelte +++ b/frontend/src/lib/components/FlowStatusViewerInner.svelte @@ -108,6 +108,10 @@ innerModule?: FlowModuleValue | undefined render?: boolean selectedNode?: string | undefined + /** Job of the node selected in the root viewer's graph. Nested viewers have no + * selectedNode of their own, so this is how a step inside a subflow, loop or retry + * knows it is selected and must stream its logs. */ + selectedJobId?: string | undefined globalModuleStates: Record[] globalDurationStatuses?: Record[] isSelectedBranch?: boolean @@ -169,6 +173,7 @@ innerModule = undefined, render = true, selectedNode = $bindable(undefined), + selectedJobId = undefined, globalModuleStates, globalDurationStatuses = [], updateRecursiveRefreshFn = undefined, @@ -1407,6 +1412,11 @@ let noLogs = $derived(graphTabOpen && !isNodeSelected) + // The root viewer's module states hold every nested step, prefixed for subflows. + let effectiveSelectedJobId = $derived( + selectedJobId ?? localModuleStates?.[selectedNode ?? '']?.job_id + ) + /** * Returns a string like "forloopmodid1-{iter1}-forloopmodid2-{iter2}-forloopmodid3-{iter3}-" * that can be used to prefix tool call store keys for nested tool calls. @@ -1668,6 +1678,7 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={forloop_selected == loopJobId} toolCallStore={{ getStoredToolCallJob: (storeKey: string) => @@ -1765,6 +1776,7 @@ jobId={failedRetry} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={retry_selected == failedRetry} /> @@ -1801,6 +1813,7 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={false} /> {:else if mod.flow_jobs?.length == 0 && mod.job == '00000000-0000-0000-0000-000000000000'} @@ -1842,7 +1855,8 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} - isNodeSelected={localModuleStates?.[selectedNode ?? '']?.job_id == mod.job} + selectedJobId={effectiveSelectedJobId} + isNodeSelected={effectiveSelectedJobId == mod.job} {toolCallStore} showLogsWithResult={['script', 'rawscript'].includes( job.raw_flow?.modules[i]?.value?.type ?? '' @@ -2085,7 +2099,11 @@ wrapperClass={closableDetails ? 'grow min-w-0' : 'shrink-0'} > {#if !hideTimeline} - + {/if} .input-sizer::after { - content: attr(data-value) ' '; + /* Must measure exactly as wide as the idle button, or siblings move on toggle. */ + content: attr(data-value); visibility: hidden; white-space: pre; + overflow: hidden; grid-area: 1 / 1; font: inherit; padding: 2px; diff --git a/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts b/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts index 5c9519ba1e..ce1f9bc3f2 100644 --- a/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts +++ b/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts @@ -9,7 +9,7 @@ import { setGlobalCSS } from '../shared' import { supportsAutocomplete } from '../utils' import { get } from 'svelte/store' import type { MonacoLanguageClient } from 'monaco-languageclient' -import { copilotInfo } from '$lib/aiStore' +import { copilotInfo, type AiTarget } from '$lib/aiStore' import { getTypeScriptWorker } from '@codingame/monaco-vscode-standalone-typescript-language-features' // max ratio of completions to context window @@ -72,15 +72,21 @@ export class Autocompletor { #completionDisposable: IDisposable #cursorDisposable: IDisposable #lastCompletions: string[] = [] - #contextWindow: number = 0 + #sessionTarget: (() => AiTarget | undefined) | undefined #shouldShowDeletionCue = false #languageClient: MonacoLanguageClient | undefined = undefined constructor( editor: meditor.IStandaloneCodeEditor, scriptLang: ScriptLang | 'bunnative' | 'jsx' | 'tsx' | 'json', - options: { workflowAsCode?: boolean } = {} + options: { + workflowAsCode?: boolean + /** Set in an AI session's editor: completions go to the session's workspace with its + * AI config. Undefined while that config is loading. */ + sessionTarget?: () => AiTarget | undefined + } = {} ) { + this.#sessionTarget = options.sessionTarget setGlobalCSS( 'ai-chat-autocomplete', ` @@ -94,15 +100,6 @@ export class Autocompletor { const deletionsCues = editor.createDecorationsCollection() - const { codeCompletionModel: completionModel, contextWindowPerModel } = get(copilotInfo) - this.#contextWindow = completionModel - ? getEffectiveModelContextWindow( - completionModel.provider, - completionModel.model, - contextWindowPerModel - ) - : ASSUMED_CONTEXT_WINDOW - this.#completionDisposable = languages.registerInlineCompletionsProvider( { pattern: '**' }, { @@ -520,9 +517,22 @@ export class Autocompletor { const markers = meditor.getModelMarkers({ resource: model.uri }) const markersAtCursor = this.#markersAtCursor(position, markers) + const target = this.#sessionTarget?.() + // A session's editor completes only once its own workspace's config is known. + if (this.#sessionTarget && !target) { + return + } + const { codeCompletionModel, contextWindowPerModel } = target?.info ?? get(copilotInfo) + const contextWindow = codeCompletionModel + ? getEffectiveModelContextWindow( + codeCompletionModel.provider, + codeCompletionModel.model, + contextWindowPerModel + ) + : ASSUMED_CONTEXT_WINDOW const librariesCompletions: string = completions .join('\n') - .slice(0, Math.floor(this.#contextWindow * COMPLETIONS_MAX_RATIO)) + .slice(0, Math.floor(contextWindow * COMPLETIONS_MAX_RATIO)) const completion = await autocompleteRequest( { @@ -533,7 +543,8 @@ export class Autocompletor { libraries: librariesCompletions, workflowAsCode: this.#workflowAsCode }, - this.#abortController + this.#abortController, + target ) if (!completion) { diff --git a/frontend/src/lib/components/copilot/autocomplete/request.ts b/frontend/src/lib/components/copilot/autocomplete/request.ts index cc3987ebe5..651b212ec2 100644 --- a/frontend/src/lib/components/copilot/autocomplete/request.ts +++ b/frontend/src/lib/components/copilot/autocomplete/request.ts @@ -4,7 +4,7 @@ import { getLangContext } from '../chat/script/core' import { type ScriptLang } from '$lib/gen/types.gen' import type { editor } from 'monaco-editor' import { getCommentSymbol } from '../utils' -import { copilotInfo } from '$lib/aiStore' +import { copilotInfo, type AiTarget } from '$lib/aiStore' function comment(commentSymbol: string, text: string) { return text @@ -22,9 +22,10 @@ export async function autocompleteRequest( libraries: string workflowAsCode?: boolean }, - abortController: AbortController + abortController: AbortController, + target?: AiTarget ) { - const providerModel = get(copilotInfo).codeCompletionModel + const providerModel = (target?.info ?? get(copilotInfo)).codeCompletionModel if (!providerModel) { throw new Error('No code completion model selected') @@ -56,7 +57,8 @@ export async function autocompleteRequest( context.prefix, context.suffix, providerModel, - abortController + abortController, + target?.workspace ) return completion diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index f3b49d680b..f3dd73bc46 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -44,7 +44,6 @@ type AttachedImage } from './imageUtils' import { modelSupportsVision } from '../modelConfig' - import { tryGetCurrentModel } from '$lib/aiStore' import { createLongHash } from '$lib/editorLangUtils' import { fileToAttachedTextFile, @@ -334,11 +333,9 @@ if (imageFiles.length === 0) return // The vision check is about the model this composer's own turn will hit, so it // only applies to a host that picks that model. Elsewhere the model is chosen - // in the flow and tryGetCurrentModel would answer for the wrong one. + // in the flow and the host's model would answer for the wrong one. if (chatHost.supportsModelSettings) { - // tryGetCurrentModel returns undefined instead of throwing: this runs from a - // drop/paste handler that can't surface a rejection. - const model = tryGetCurrentModel() + const model = chatHost.currentModel // Only known text-only models fail this, so attaching would certainly 400 the // next turn — refuse rather than warn and send it anyway. if (model && !modelSupportsVision(model.provider, model.model)) { diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 6c8142fa72..9910bb1e87 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -98,7 +98,17 @@ import { fromStore, get } from 'svelte/store' import type { ProviderToolSummary } from './agentContext' import { BROWSER } from 'esm-env' import { roleCapabilities, workspaceStore, type DBSchemas } from '$lib/stores' -import { copilotInfo, copilotSessionModel } from '$lib/aiStore' +import { + copilotInfo, + copilotSessionModel, + getWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo, + resolveModelFor, + tryResolveModelFor, + type AiTarget, + type CopilotInfo +} from '$lib/aiStore' +import type { ReasoningProviderModel } from '../reasoningRegistry' import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot' import { askTools, prepareAskSystemMessage, prepareAskUserMessage } from './ask/core' import { readDocsPageTool, searchDocsTool } from './docs/core' @@ -707,8 +717,11 @@ export class AIChatManager implements ChatViewHost { if (this.reasoningSummaryUnavailableFor.length === 0) { return undefined } - const provider = getCurrentModel().provider - if (!this.reasoningSummaryUnavailableFor.includes(this.reasoningSummaryKey(provider))) { + const provider = this.currentModel?.provider + if ( + !provider || + !this.reasoningSummaryUnavailableFor.includes(this.reasoningSummaryKey(provider)) + ) { return undefined } return `Thinking (hidden, ${providerDisplayName(provider)} org not verified)` @@ -860,16 +873,12 @@ export class AIChatManager implements ChatViewHost { #copilotInfo = fromStore(copilotInfo) #sessionModel = fromStore(copilotSessionModel) /** Capabilities the provider runs on its own servers, attached by the adapter at send - * time. Never part of `tools`: the request path would try to dispatch them. The two - * `void` reads only subscribe: the model helpers read through `get()`, which tracks - * nothing, so a change of model or of the workspace's AI config would otherwise not - * re-derive. A workspace switch re-derives through the AI config it loads. */ + * time. Never part of `tools`: the request path would try to dispatch them. */ get providerTools(): ProviderToolSummary[] { - void this.#copilotInfo.current - void this.#sessionModel.current - const model = tryGetCurrentModel() - if (!model || (model.provider === 'openai' && this.skipResponsesApi)) return [] - const enabled = isWebSearchEnabledForProvider(model.provider) + const model = this.currentModel + const info = this.aiInfo + if (!model || !info || (model.provider === 'openai' && this.skipResponsesApi)) return [] + const enabled = isWebSearchEnabledForProvider(model.provider, info) return sendsWebSearch(this.operatingWorkspace ?? '', model, enabled) ? [ { @@ -1061,6 +1070,37 @@ export class AIChatManager implements ChatViewHost { return this.workspaceResolver?.() ?? get(workspaceStore) } + /** The AI config this chat sends with. A session's is its own workspace's, never the tab's, + * which belongs to whatever workspace is on screen; other chats use the tab's. Undefined while + * a session's is still loading, and reading it starts the load. */ + get aiInfo(): CopilotInfo | undefined { + if (!this.isSessionChat) return this.#copilotInfo.current + const workspace = this.operatingWorkspace + return workspace ? getWorkspaceCopilotInfo(workspace) : undefined + } + + /** The session's workspace and loaded config, for code that cannot wait for the load. */ + get loadedSessionAiTarget(): AiTarget | undefined { + const info = this.isSessionChat ? this.aiInfo : undefined + const workspace = this.operatingWorkspace + return info && workspace ? { workspace, info } : undefined + } + + get currentModel(): ReasoningProviderModel | undefined { + // Subscribes only: the model helpers read through `get()`, which tracks nothing. + void this.#sessionModel.current + const info = this.aiInfo + return info && tryResolveModelFor(info) + } + + /** Resolved at each request, after any fork commit. Undefined for other chats, whose requests + * use the tab's. */ + sessionAiTarget = async (): Promise => { + if (!this.isSessionChat) return undefined + const workspace = this.operatingWorkspace ?? '' + return { workspace, info: await loadWorkspaceCopilotInfo(workspace) } + } + // Fired whenever the active chat id changes away from the one the consumer // knows (a "/clear" rotation or a history switch). Session runtimes wire this // to keep the session record's chatId aligned — the compare-page handoff @@ -1792,6 +1832,7 @@ export class AIChatManager implements ChatViewHost { ): Promise<'ok' | 'empty' | 'aborted' | 'error'> => { this.compacting = true try { + const target = await this.sessionAiTarget() // Cap the summarizer's output at the budget already reserved for the // summary: without a cap the model's default max_tokens applies. const raw = await getStreamedCompletionText( @@ -1802,7 +1843,7 @@ export class AIChatManager implements ChatViewHost { { role: 'user', content: getCompactionSummaryPrompt() } ], abortController, - { maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS } + { maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS, ...target } ) const formatted = formatCompactSummary(raw) if (!formatted) { @@ -1991,12 +2032,9 @@ export class AIChatManager implements ChatViewHost { model: ChatLoopConfig['modelProvider'] | undefined, inFlightTokens = 0 ): Promise => { + const info = (await this.sessionAiTarget())?.info ?? get(copilotInfo) const contextWindow = model - ? getEffectiveModelContextWindow( - model.provider, - model.model, - get(copilotInfo).contextWindowPerModel - ) + ? getEffectiveModelContextWindow(model.provider, model.model, info.contextWindowPerModel) : undefined if (contextWindow === undefined || projectedTokens < contextWindow * COMPACTION_TRIGGER_RATIO) { return false @@ -2893,6 +2931,7 @@ export class AIChatManager implements ChatViewHost { ? { sessionId: this.sessionId, operatingWorkspace: this.operatingWorkspace, + sessionAi: () => ({ model: this.currentModel, info: this.aiInfo }), artifacts: this.artifacts, access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), @@ -2923,7 +2962,10 @@ export class AIChatManager implements ChatViewHost { ensurePipeline: this.#ensurePipeline } : baseHelpers - this.systemMessage = assembleGlobalSystemMessage(getCustomPromptParts(AIMode.GLOBAL), opts) + this.systemMessage = assembleGlobalSystemMessage( + getCustomPromptParts(AIMode.GLOBAL, this.aiInfo?.customPrompts ?? {}), + opts + ) this.syncArtifactsSession() } @@ -3103,7 +3145,7 @@ export class AIChatManager implements ChatViewHost { return } this.systemMessage = assembleGlobalSystemMessage( - getCustomPromptParts(AIMode.GLOBAL), + getCustomPromptParts(AIMode.GLOBAL, this.aiInfo?.customPrompts ?? {}), this.globalAssemblyOpts() ) } @@ -3435,7 +3477,8 @@ export class AIChatManager implements ChatViewHost { } private notifyReasoningSummaryUnavailable = () => { - const provider = getCurrentModel().provider + const provider = this.currentModel?.provider + if (!provider) return const key = this.reasoningSummaryKey(provider) if (!this.reasoningSummaryUnavailableFor.includes(key)) { this.reasoningSummaryUnavailableFor = [...this.reasoningSummaryUnavailableFor, key] @@ -3482,6 +3525,8 @@ export class AIChatManager implements ChatViewHost { // while a response streams would bill it to the workspace the user landed // on rather than the one whose credentials and proxy served it. const usageWorkspace = this.operatingWorkspace + const target = await this.sessionAiTarget() + const info = target?.info const result = await runChatLoop({ messages, addedMessages, @@ -3502,7 +3547,7 @@ export class AIChatManager implements ChatViewHost { get tools() { return withWebSearchFallback( self.tools, - !!get(copilotInfo).webSearchBackend, + !!(info ?? get(copilotInfo)).webSearchBackend, self.providerTools.length > 0 ) }, @@ -3512,10 +3557,10 @@ export class AIChatManager implements ChatViewHost { abortController, callbacks, get modelProvider() { - return getCurrentModel() + return info ? resolveModelFor(info) : getCurrentModel() }, get webSearch() { - return isWebSearchEnabledForProvider(getCurrentModel().provider) + return isWebSearchEnabledForProvider(this.modelProvider.provider, info) }, // Build the proxy clients against the operating workspace, not the global // singleton: a session deliberately leaves workspaceStore untouched, so the @@ -3523,13 +3568,14 @@ export class AIChatManager implements ChatViewHost { // request through the navigation workspace's /ai/proxy instead of the // session's — sending it to the wrong workspace's AI credentials. get clients() { - const ws = self.operatingWorkspace ?? '' + const ws = target?.workspace ?? self.operatingWorkspace ?? '' return { openai: workspaceAIClients.createOpenaiClient(ws), anthropic: workspaceAIClients.createAnthropicClient(ws) } }, - workspace: this.operatingWorkspace ?? '', + workspace: target?.workspace ?? this.operatingWorkspace ?? '', + info, skipResponsesApi: this.skipResponsesApi, onSkipResponsesApi: () => { this.skipResponsesApi = true @@ -3973,7 +4019,7 @@ export class AIChatManager implements ChatViewHost { // only edit/retry of a pre-id transcript can arrive without one, and the // hash is deterministic, so hydration reproduces the original id. const files = withAttachedTextFileIds(options.files ?? []) - const sendModel = tryGetCurrentModel() + const sendModel = this.currentModel const modelIsBlind = !!sendModel && !modelSupportsVision(sendModel.provider, sendModel.model) if (requestedImages.length > 0 && modelIsBlind) { // An image-only message has nothing left once the images are dropped — @@ -4111,8 +4157,13 @@ export class AIChatManager implements ChatViewHost { this.refreshSessionAccess(this.operatingWorkspace ?? ''), resolveResourceTypeSync(this.operatingWorkspace ?? '', this.messages).then((sync) => { this.resourceTypeSync = sync - }) + }), + // Its workspace prompt goes into the system prompt rebuilt below. + this.sessionAiTarget().catch(() => {}) ]) + if (this.isSessionChat) { + this.rebuildGlobalSystemMessage() + } } // Stop/Escape during the beforeSend pre-flight aborted this send before any // request went out. Mirror the main "cancelled before usable output" recovery: @@ -4268,7 +4319,7 @@ export class AIChatManager implements ChatViewHost { // loading + abortController were set optimistically before beforeSend, above. this.#automaticScroll = true - const model = tryGetCurrentModel() + const model = this.currentModel if (model) { const chatId = this.historyManager.getCurrentChatId() logFeatureUsage('ai_chat', 'message', { @@ -4792,15 +4843,11 @@ export class AIChatManager implements ChatViewHost { if ( requestCarriedImages && messagesHaveImageParts(this.messages) && - isImageRejection(err, [ - sendModel?.model, - tryGetCurrentModel()?.model, - failingModel?.model - ]) + isImageRejection(err, [sendModel?.model, this.currentModel?.model, failingModel?.model]) ) { this.messages = stripImagePartsFromMessages(this.messages) sendUserToast( - `${tryGetCurrentModel()?.model ?? 'The model'} could not read the attached image(s), so they were removed from the conversation. Your message was kept.`, + `${this.currentModel?.model ?? 'The model'} could not read the attached image(s), so they were removed from the conversation. Your message was kept.`, true ) } diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 9f6179a538..ff64eb07fc 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -141,6 +141,11 @@ vi.mock('$lib/aiStore', () => ({ copilotSessionModel: writable(undefined), getCurrentModel: mocks.getCurrentModel, tryGetCurrentModel: mocks.tryGetCurrentModel, + // A session reads its own workspace's config; here every workspace has the same one. + getWorkspaceCopilotInfo: () => ({ enabled: true, workspaceDisabled: false, aiModels: [] }), + loadWorkspaceCopilotInfo: async () => ({ enabled: true, workspaceDisabled: false, aiModels: [] }), + resolveModelFor: mocks.getCurrentModel, + tryResolveModelFor: mocks.tryGetCurrentModel, getCombinedCustomPrompt: () => '', getCustomPromptParts: () => ({}), getUserCustomPrompts: () => ({}), diff --git a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte index 5f4b4a5040..fb65460f2c 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte @@ -17,6 +17,7 @@ copilotInfo, copilotSessionModel, getUserCustomPrompts, + invalidateWorkspaceCopilotInfo, setCopilotInfo, setUserCustomPrompts } from '$lib/aiStore' @@ -192,6 +193,7 @@ requestBody: { ...config, custom_prompts } }) setCopilotInfo(response.effective_ai_config) + invalidateWorkspaceCopilotInfo(workspace) initialPrompt = value customPrompts = { [activeMode]: value } sendUserToast('Workspace AI prompt saved') diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 547940bde9..ebea3dbb6a 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -23,6 +23,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio import { copilotInfo, getUserCustomPrompts, + invalidateWorkspaceCopilotInfo, setCopilotInfo, setUserCustomPrompts } from '$lib/aiStore' @@ -596,6 +597,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio requestBody: { ...config, custom_prompts } }) setCopilotInfo(response.effective_ai_config) + invalidateWorkspaceCopilotInfo(target) workspaceSaved = value workspaceDraft = value sendUserToast('Workspace instructions were saved') diff --git a/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte b/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte index e5a9989365..ac8127dd50 100644 --- a/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte +++ b/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte @@ -17,6 +17,8 @@ labelMore?: string[] expanded: boolean onToggle: () => void + /** Called once the body has finished opening, when its contents have their final position. */ + onContentShown?: () => void // A card with nothing to reveal keeps the header inert (no chevron, no // hover affordance implying a toggle). toggleable?: boolean @@ -49,6 +51,7 @@ labelMore, expanded, onToggle, + onContentShown, toggleable = true, shimmer = false, settleLabel = false, @@ -161,6 +164,7 @@ {#if expanded && children}
{@render children()} diff --git a/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte b/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte index faf0395bc3..5e3d4048dc 100644 --- a/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte @@ -12,6 +12,7 @@ confirmLabel: string /** Omit for a label-only confirm button. */ confirmIcon?: any + confirmDestructive?: boolean class?: string } @@ -22,6 +23,7 @@ rejectDestructive = false, confirmLabel, confirmIcon, + confirmDestructive = false, class: className }: Props = $props() @@ -48,6 +50,7 @@ {/if} {#if previewCard} @@ -72,7 +106,16 @@ label={header.label} labelMore={header.more} {expanded} - onToggle={() => (expanded = !expanded)} + onToggle={() => { + scrollOnceOpen = false + expanded = !expanded + }} + onContentShown={() => { + if (scrollOnceOpen) { + scrollOnceOpen = false + scrollToFailedCall() + } + }} shimmer={running} settleLabel {liveLine} @@ -83,6 +126,8 @@ contentClass="border-0 border-l rounded-none bg-transparent p-0 pl-2 ml-1.5 mt-0.5" > {#each group.entries as { message, index } (index)} - {@render entry(message, index)} +
+ {@render entry(message, index)} +
{/each} diff --git a/frontend/src/lib/components/copilot/chat/anthropic.ts b/frontend/src/lib/components/copilot/chat/anthropic.ts index ce11b0dade..937fe47ed4 100644 --- a/frontend/src/lib/components/copilot/chat/anthropic.ts +++ b/frontend/src/lib/components/copilot/chat/anthropic.ts @@ -14,6 +14,7 @@ import type { } from '@anthropic-ai/sdk/resources' import type { MessageStream } from '@anthropic-ai/sdk/lib/MessageStream' import type { AIProviderModel } from '$lib/gen' +import type { CopilotInfo } from '$lib/aiStore' import { getProviderAndCompletionConfig, workspaceAIClients } from '../lib' import { applyReasoningToConfig } from '../reasoningRegistry' import { @@ -137,13 +138,15 @@ export async function getAnthropicCompletion( anthropicClient?: Anthropic webSearch?: boolean reasoningEffort?: string + info?: CopilotInfo } ): Promise { const { provider, config } = getProviderAndCompletionConfig({ messages, stream: true, forceModelProvider: options?.forceModelProvider, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages) let anthropicTools = convertOpenAIToolsToAnthropic(tools) diff --git a/frontend/src/lib/components/copilot/chat/chatLoop.ts b/frontend/src/lib/components/copilot/chat/chatLoop.ts index 14de05cd74..e6b9e5c060 100644 --- a/frontend/src/lib/components/copilot/chat/chatLoop.ts +++ b/frontend/src/lib/components/copilot/chat/chatLoop.ts @@ -14,6 +14,7 @@ import { type ReasoningProviderModel } from '../reasoningRegistry' import { getAnthropicCompletion, parseAnthropicCompletion } from './anthropic' +import type { CopilotInfo } from '$lib/aiStore' import { modelSupportsVision, usesAnthropicMessagesApi } from '../modelConfig' import { boundImagePartBytes, stripImagePartsFromMessages } from './imageUtils' import { @@ -49,6 +50,8 @@ export interface ChatLoopConfig { modelProvider: ReasoningProviderModel clients: ChatClients workspace: string + /** `workspace`'s AI config when it is not the tab's (an AI session). */ + info?: CopilotInfo /** * Enable provider-native web search. Defaults to true for compatible providers * and is re-read each iteration so model/provider changes take effect. Explicit @@ -371,6 +374,7 @@ export async function runChatLoop(config: ChatLoopConfig): Promise[] = [ // A known text-only model would reject the follow-up image message and fail // the turn, so refuse before capturing rather than buffer an image it can // never read. The model is re-read here because it can change between turns. - const model = tryGetCurrentModel() + const sessionAi = (ctx.helpers as GlobalToolHelpers | undefined)?.sessionAi + const model = sessionAi ? sessionAi().model : tryGetCurrentModel() if (model && !modelSupportsVision(model.provider, model.model)) { const cannotSee = `${model.model} cannot read images, so a screenshot would be discarded. Ask the user to describe what looks wrong, or to switch to a model that supports images.` ctx.toolCallbacks.setToolStatus(ctx.toolId, { @@ -4694,6 +4695,8 @@ export type GlobalToolHelpers = SessionToolHelpers & { // (possibly forked) workspace while $workspaceStore stays on the navigation workspace, // so permission gating (open_page) must read this, not the global store. operatingWorkspace?: string + // The session's model and its workspace's AI config, rather than the tab's. + sessionAi?: () => SessionAi // Wired only for session chats (see AIChatManager): the artifact tools are session-gated. artifacts?: SessionArtifactsStore getChatId?: () => string | undefined diff --git a/frontend/src/lib/components/copilot/chat/openai-responses.ts b/frontend/src/lib/components/copilot/chat/openai-responses.ts index 2071ff0d74..eccda3bc1a 100644 --- a/frontend/src/lib/components/copilot/chat/openai-responses.ts +++ b/frontend/src/lib/components/copilot/chat/openai-responses.ts @@ -28,6 +28,7 @@ import { OutputTokenLimitError } from './outputTokenLimit' import { buildAssistantToolCallMessage } from './openaiReasoning' import type { ResponseStream } from 'openai/lib/responses/ResponseStream.mjs' import type { AIProviderModel } from '$lib/gen' +import type { CopilotInfo } from '$lib/aiStore' import { openAIResponsesUsageToChatTokenUsage, type ChatTokenUsage } from './tokenUsage' interface ParsedCompletionResult { @@ -308,6 +309,7 @@ export async function getOpenAIResponsesCompletion( reasoningEffort?: string reasoningSummary?: boolean promptCacheKey?: string + info?: CopilotInfo } ) { const { provider, config } = getProviderAndCompletionConfig({ @@ -315,7 +317,8 @@ export async function getOpenAIResponsesCompletion( stream: true, tools, forceModelProvider: options?.forceModelProvider, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { instructions, input } = convertMessagesToResponsesInput(messages, provider === 'deepseek') const responsesConfig = applyReasoningToConfig( @@ -379,6 +382,7 @@ export async function* getOpenAIResponsesCompletionStream( openaiClient?: OpenAI reasoningEffort?: string maxTokensCap?: number + info?: CopilotInfo } ): AsyncGenerator { const { provider, config } = getProviderAndCompletionConfig({ @@ -387,7 +391,8 @@ export async function* getOpenAIResponsesCompletionStream( tools, forceModelProvider: options?.forceModelProvider, maxTokensCap: options?.maxTokensCap, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { instructions, input } = convertMessagesToResponsesInput(messages) // No prompt cache key here: a rejected key has to be retried without it, and this is @@ -717,13 +722,15 @@ export async function getNonStreamingOpenAIResponsesCompletion( resourceValue?: Record forceModelProvider?: AIProviderModel maxTokensCap?: number + info?: CopilotInfo } ): Promise { const { provider, config } = getProviderAndCompletionConfig({ messages, stream: false, forceModelProvider: options?.forceModelProvider, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + info: options?.info }) const { instructions, input } = convertMessagesToResponsesInput(messages) diff --git a/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte b/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte index d39ab52bf7..6635774248 100644 --- a/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/script/MermaidDisplay.svelte @@ -1,27 +1,60 @@ - + + -{#if showSvg} -
+{#if showSource} +
{code}
+{:else if svg === undefined} + +
+ +
+{:else} +
-{:else} - -
{code}
{/if} diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index e7053ce141..79f8621e40 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -26,7 +26,7 @@ import { createWorkspaceMutationTools } from '../workspaceTools' import { setupTypeAcquisition, type DepsToGet } from '$lib/ata' import { getEffectiveModelContextWindow } from '../../modelConfig' import type { ReviewChangesOpts } from '../monaco-adapter' -import { copilotInfo, getCurrentModel } from '$lib/aiStore' +import { copilotInfo, getCurrentModel, type SessionAi } from '$lib/aiStore' import { get } from 'svelte/store' import { getDbSchemas } from '$lib/components/apps/components/display/dbtable/metadata' import { scriptLangToEditorLang } from '$lib/scripts' @@ -604,7 +604,10 @@ type PackageSearchResult = { } const packagesSearchCache = new Map() -export async function searchExternalIntegrationResources(args: { query: string }): Promise { +export async function searchExternalIntegrationResources( + args: { query: string }, + sessionAi?: SessionAi +): Promise { try { if (packagesSearchCache.has(args.query)) { return JSON.stringify(packagesSearchCache.get(args.query)) @@ -619,11 +622,14 @@ export async function searchExternalIntegrationResources(args: { query: string } (r: PackageSearchQuery) => r.searchScore >= best * NPM_RUNNER_UP_SHARE ) - const model = getCurrentModel() + const model = sessionAi ? sessionAi.model : getCurrentModel() + if (!model) { + throw new Error('No model selected') + } const modelContextWindow = getEffectiveModelContextWindow( model.provider, model.model, - get(copilotInfo).contextWindowPerModel + (sessionAi ? sessionAi.info : get(copilotInfo))?.contextWindowPerModel ) const results: PackageSearchResult[] = await Promise.all( filtered.map(async (r: PackageSearchQuery) => { @@ -684,9 +690,10 @@ export const searchNpmPackagesTool: SessionTool<{}> = { requires: NONE, def: SEARCH_NPM_PACKAGES_TOOL, planModeSafe: true, - fn: async ({ args, toolId, toolCallbacks }) => { + fn: async ({ args, toolId, toolCallbacks, helpers }) => { toolCallbacks.setToolStatus(toolId, { content: 'Searching for relevant packages...' }) - const result = await searchExternalIntegrationResources(args) + const sessionAi = (helpers as { sessionAi?: () => SessionAi } | undefined)?.sessionAi + const result = await searchExternalIntegrationResources(args, sessionAi?.()) toolCallbacks.setToolStatus(toolId, { content: 'Retrieved relevant packages' }) return result } diff --git a/frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts b/frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts new file mode 100644 index 0000000000..afe3dc773a --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/sessionAiConfig.test.ts @@ -0,0 +1,145 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AIConfig } from '$lib/gen' +import { copilotSessionModel, setCopilotInfo } from '$lib/aiStore' +import { workspaceStore } from '$lib/stores' +import { workspaceAIClients } from '../lib' +import { AIChatManager } from './AIChatManager.svelte' +import { generateSessionSummary } from '$lib/components/sessions/sessionTitle' + +vi.mock('$app/navigation', () => ({ + goto: vi.fn(), + afterNavigate: vi.fn(), + beforeNavigate: vi.fn() +})) +vi.mock('monaco-editor', () => ({ Selection: class Selection {} })) +vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() })) + +// The session works in `staging` while the tab shows `prod`: every request the session +// makes must carry staging's proxy, model and limits. +const CONFIGS: Record = { + staging: { + providers: { mistral: { resource_path: 'u/admin/mistral', models: ['staging-model'] } }, + default_model: { provider: 'mistral', model: 'staging-model' }, + max_tokens_per_model: { 'mistral:staging-model': 3000 }, + context_window_per_model: { 'mistral:staging-model': 30000 } + }, + prod: { + providers: { deepseek: { resource_path: 'u/admin/deepseek', models: ['prod-model'] } }, + default_model: { provider: 'deepseek', model: 'prod-model' } + } +} + +vi.mock('$lib/gen', async (importOriginal) => ({ + ...(await importOriginal()), + WorkspaceService: { + getCopilotInfo: async ({ workspace }: { workspace: string }) => CONFIGS[workspace] + } +})) + +type SentRequest = { url: string; body: any } +let sent: SentRequest[] = [] + +function completionResponse(body: any): Response { + const text = 'Earlier work' + if (!body.stream) { + return Response.json({ + id: 'c', + object: 'chat.completion', + created: 0, + model: body.model, + choices: [ + { + index: 0, + message: { role: 'assistant', content: 'Staging title' }, + finish_reason: 'stop' + } + ] + }) + } + const chunk = (delta: object, finish_reason: string | null) => + `data: ${JSON.stringify({ + id: 'c', + object: 'chat.completion.chunk', + created: 0, + model: body.model, + choices: [{ index: 0, delta, finish_reason }] + })}\n\n` + return new Response(chunk({ content: text }, null) + chunk({}, 'stop') + 'data: [DONE]\n\n', { + headers: { 'content-type': 'text/event-stream' } + }) +} + +function sessionManager(): AIChatManager { + const manager = new AIChatManager() + manager.isSessionChat = true + manager.workspaceResolver = () => 'staging' + manager.messages = [ + { role: 'user', content: 'q1' }, + { role: 'assistant', content: 'a1' }, + { role: 'user', content: 'q2' }, + { role: 'assistant', content: 'a2' }, + { role: 'user', content: 'q3' } + ] + manager.displayMessages = [ + { role: 'user', content: 'q1', index: 0 }, + { role: 'assistant', content: 'a1' }, + { role: 'user', content: 'q2', index: 2 }, + { role: 'assistant', content: 'a2' }, + { role: 'user', content: 'q3', index: 4 } + ] as AIChatManager['displayMessages'] + return manager +} + +function expectSentForStaging(request: SentRequest | undefined) { + expect(request?.url).toContain('/w/staging/ai/proxy/') + expect(request?.body.model).toBe('staging-model') + expect(request?.body.max_tokens).toBe(3000) +} + +beforeEach(() => { + sent = [] + vi.stubGlobal('location', { origin: 'http://localhost' }) + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input) + const body = JSON.parse( + String(init?.body ?? (input instanceof Request ? await input.text() : '{}')) + ) + sent.push({ url, body }) + return completionResponse(body) + }) + // The tab is on prod, with prod's model picked. + workspaceStore.set('prod') + workspaceAIClients.init('prod') + setCopilotInfo(CONFIGS.prod) + copilotSessionModel.set({ provider: 'deepseek', model: 'prod-model' }) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('an AI session in another workspace than the tab', () => { + it('names the session with its own workspace', async () => { + expect(await generateSessionSummary(sessionManager())).toBe('Staging title') + expect(sent).toHaveLength(1) + expectSentForStaging(sent[0]) + }) + + it('summarizes for compaction with its own workspace', async () => { + const manager = sessionManager() + await manager.compactManually() + expect(sent).toHaveLength(1) + expectSentForStaging(sent[0]) + }) + + it("compacts at its own workspace's context window", async () => { + const manager = sessionManager() + manager.abortController = new AbortController() + // 80% of staging's 30k window; far below the window prod's model would get. + const compacted = await (manager as any).compactIfOverTrigger(25000, { + provider: 'mistral', + model: 'staging-model' + }) + expect(compacted).toBe(true) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts b/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts index 52f5d546e8..2894c1f49c 100644 --- a/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts +++ b/frontend/src/lib/components/copilot/chat/toolConfirmAction.ts @@ -1,13 +1,16 @@ import { Check, Play, Plus, Save, Trash2, Undo2 } from 'lucide-svelte' import type { ToolConfirmAction } from './shared' -export const TOOL_CONFIRM_ACTIONS: Record = { +export const TOOL_CONFIRM_ACTIONS: Record< + ToolConfirmAction, + { label: string; icon: any; destructive?: boolean } +> = { run: { label: 'Run', icon: Play }, deploy: { label: 'Deploy', icon: Save }, create: { label: 'Create', icon: Plus }, apply: { label: 'Apply', icon: Check }, - delete: { label: 'Delete', icon: Trash2 }, - discard: { label: 'Discard', icon: Trash2 }, + delete: { label: 'Delete', icon: Trash2, destructive: true }, + discard: { label: 'Discard', icon: Trash2, destructive: true }, rollback: { label: 'Roll back', icon: Undo2 }, confirm: { label: 'Confirm', icon: Check } } diff --git a/frontend/src/lib/components/copilot/lib.ts b/frontend/src/lib/components/copilot/lib.ts index d2eae56bcd..5975fc3546 100644 --- a/frontend/src/lib/components/copilot/lib.ts +++ b/frontend/src/lib/components/copilot/lib.ts @@ -47,7 +47,15 @@ import { import { convertOpenAIToAnthropicMessages } from './chat/anthropic' import type { Stream } from 'openai/core/streaming.mjs' import { generateRandomString } from '$lib/utils' -import { copilotInfo, getCurrentModel, getMetadataModel } from '$lib/aiStore' +import { + copilotInfo, + getCurrentModel, + getMetadataModel, + resolveMetadataModelFor, + resolveModelFor, + type AiTarget, + type CopilotInfo +} from '$lib/aiStore' import { emptyChatTokenUsage, openAICompletionsUsageToChatTokenUsage, @@ -279,7 +287,8 @@ export function getModelMaxTokens( function resolveMaxTokens( modelProvider: AIProviderModel, cap?: number, - reasoningEffort?: ReasoningEffort + reasoningEffort?: ReasoningEffort, + info?: CopilotInfo ): number { const defaultMaxTokens = getModelMaxTokens( modelProvider.provider, @@ -289,7 +298,7 @@ function resolveMaxTokens( const modelKey = `${modelProvider.provider}:${modelProvider.model}` let customMaxTokensStore: Record | undefined try { - customMaxTokensStore = get(copilotInfo)?.maxTokensPerModel + customMaxTokensStore = (info ?? get(copilotInfo))?.maxTokensPerModel } catch { // copilotInfo store may not be initialized in vitest } @@ -308,9 +317,10 @@ function getModelSpecificConfig( modelProvider: AIProviderModel, tools?: OpenAI.Chat.Completions.ChatCompletionTool[], maxTokensCap?: number, - reasoningEffort?: ReasoningEffort + reasoningEffort?: ReasoningEffort, + info?: CopilotInfo ) { - const maxTokens = resolveMaxTokens(modelProvider, maxTokensCap, reasoningEffort) + const maxTokens = resolveMaxTokens(modelProvider, maxTokensCap, reasoningEffort, info) if ( (modelProvider.provider === 'openai' || modelProvider.provider === 'azure_openai' || @@ -594,6 +604,7 @@ interface AnthropicCompletionParams { resourcePath?: string resourceValue?: Record maxTokensCap?: number + info?: CopilotInfo } function buildAnthropicProxyRequest({ @@ -603,7 +614,8 @@ function buildAnthropicProxyRequest({ workspace, resourcePath, resourceValue, - maxTokensCap + maxTokensCap, + info }: Omit) { const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages) @@ -623,7 +635,7 @@ function buildAnthropicProxyRequest({ const body = { model: modelProvider.model, - max_tokens: resolveMaxTokens(modelProvider, maxTokensCap), + max_tokens: resolveMaxTokens(modelProvider, maxTokensCap, undefined, info), messages: anthropicMessages, ...(system && { system }) } @@ -887,6 +899,11 @@ export function modelSupportsWebSearch(provider: AIProvider | undefined, model: return providerSupportsWebSearch(provider) } +/** The model a request sends: for `info`'s workspace when given, else the tab's. */ +function modelFor(info: CopilotInfo | undefined): AIProviderModel { + return info ? resolveModelFor(info) : getCurrentModel() +} + export function getProviderAndCompletionConfig({ messages, stream, @@ -894,7 +911,8 @@ export function getProviderAndCompletionConfig({ forceModelProvider, maxTokensCap, promptCaching, - reasoningEffort + reasoningEffort, + info }: { messages: ChatCompletionMessageParam[] stream: K @@ -907,13 +925,15 @@ export function getProviderAndCompletionConfig({ // The effort the caller will add with `applyReasoningToConfig`. Only sizes the // output budget here: a request that reasons needs room for the thinking. reasoningEffort?: ReasoningEffort + // The AI config of the workspace the request is made for, when it is not the tab's. + info?: CopilotInfo }): { provider: AIProvider config: K extends true ? ChatCompletionCreateParamsStreaming : ChatCompletionCreateParamsNonStreaming } { - const modelProvider = forceModelProvider ?? getCurrentModel() + const modelProvider = forceModelProvider ?? modelFor(info) const providerConfig = PROVIDER_COMPLETION_CONFIG_MAP[modelProvider.provider] const processedMessages = prepareMessages(modelProvider.provider, messages, { model: modelProvider.model, @@ -923,7 +943,7 @@ export function getProviderAndCompletionConfig({ provider: modelProvider.provider, config: { ...providerConfig, - ...getModelSpecificConfig(modelProvider, tools, maxTokensCap, reasoningEffort), + ...getModelSpecificConfig(modelProvider, tools, maxTokensCap, reasoningEffort, info), messages: processedMessages, stream } as any @@ -940,9 +960,10 @@ export async function getNonStreamingCompletion( workspace?: string // use a specific workspace proxy when testing a workspace resource forceModelProvider?: AIProviderModel maxTokensCap?: number // hard ceiling on output tokens (see METADATA_MAX_TOKENS) + info?: CopilotInfo // the AI config of `workspace`, when it is not the tab's } ) { - const modelProvider = options?.forceModelProvider ?? getCurrentModel() + const modelProvider = options?.forceModelProvider ?? modelFor(options?.info) if (usesAnthropicMessagesApi(modelProvider.provider, modelProvider.model)) { return getAnthropicNonStreamingCompletion({ @@ -953,7 +974,8 @@ export async function getNonStreamingCompletion( workspace: options?.workspace, resourcePath: options?.resourcePath, resourceValue: options?.resourceValue, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + info: options?.info }) } @@ -961,18 +983,18 @@ export async function getNonStreamingCompletion( const { provider, config } = getProviderAndCompletionConfig({ messages, stream: false, - forceModelProvider: options?.forceModelProvider, - maxTokensCap: options?.maxTokensCap + forceModelProvider: modelProvider, + maxTokensCap: options?.maxTokensCap, + info: options?.info }) // Use Responses API for OpenAI and Azure OpenAI if (provider === 'openai' || provider === 'azure_openai') { try { - const response = await getNonStreamingOpenAIResponsesCompletion( - messages, - abortController, - options - ) + const response = await getNonStreamingOpenAIResponsesCompletion(messages, abortController, { + ...options, + forceModelProvider: modelProvider + }) return response } catch (error) { console.error('Error using Responses API:', error) @@ -1003,13 +1025,17 @@ export async function getNonStreamingCompletion( return response } +/** `target` sends it for that workspace with its config; without one it uses the tab's. */ export async function getNonStreamingMetadataCompletion( messages: ChatCompletionMessageParam[], - abortController: AbortController + abortController: AbortController, + target?: AiTarget ) { return getNonStreamingCompletion(messages, abortController, { - forceModelProvider: getMetadataModel(), - maxTokensCap: METADATA_MAX_TOKENS + forceModelProvider: target ? resolveMetadataModelFor(target.info) : getMetadataModel(), + maxTokensCap: METADATA_MAX_TOKENS, + workspace: target?.workspace, + info: target?.info }) } @@ -1019,7 +1045,8 @@ export async function getFimCompletion( prompt: string, suffix: string, providerModel: AIProviderModel, - abortController: AbortController + abortController: AbortController, + workspace: string = get(workspaceStore)! ): Promise { // The Anthropic Messages API has no fill-in-the-middle endpoint, and Foundry // Claude deployments don't expose the OpenAI-compatible completions surface the @@ -1039,8 +1066,6 @@ export async function getFimCompletion( } } - const workspace = get(workspaceStore) - const response = await fetch( `${location.origin}${OpenAPI.BASE}/w/${workspace}/ai/proxy/fim/completions`, { @@ -1108,36 +1133,46 @@ export async function getCompletion( reasoningEffort?: string promptCaching?: boolean maxTokensCap?: number + // Send for this workspace, with its AI config, rather than the tab's. + workspace?: string + info?: CopilotInfo } ): Promise> { - const modelProvider = options?.forceModelProvider ?? getCurrentModel() + const modelProvider = options?.forceModelProvider ?? modelFor(options?.info) if (usesAnthropicMessagesApi(modelProvider.provider, modelProvider.model)) { return getAnthropicStreamingCompletion({ messages, modelProvider, abortController, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + workspace: options?.workspace, + info: options?.info }) } + const openaiClient = + options?.openaiClient ?? + (options?.workspace ? workspaceAIClients.createOpenaiClient(options.workspace) : undefined) const { provider, config } = getProviderAndCompletionConfig({ messages, stream: true, tools, - forceModelProvider: options?.forceModelProvider, + forceModelProvider: modelProvider, maxTokensCap: options?.maxTokensCap, promptCaching: options?.promptCaching, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) if (usesOpenAIResponsesApi(provider, modelProvider.model) && !options?.forceCompletions) { try { const stream = getOpenAIResponsesCompletionStream(messages, abortController, tools, { - forceModelProvider: options?.forceModelProvider, - openaiClient: options?.openaiClient, + forceModelProvider: modelProvider, + openaiClient, reasoningEffort: options?.reasoningEffort, - maxTokensCap: options?.maxTokensCap + maxTokensCap: options?.maxTokensCap, + info: options?.info }) as any return stream } catch (error) { @@ -1146,7 +1181,7 @@ export async function getCompletion( } // Use Completions API for other providers - const client = options?.openaiClient ?? workspaceAIClients.getOpenaiClient() + const client = openaiClient ?? workspaceAIClients.getOpenaiClient() // gpt-5.5+ refuse function tools here unless reasoning is off, so the Responses API // fallback turns it off where the model can rather than failing the turn. const reasoningEffort = @@ -1187,12 +1222,17 @@ export async function getCompletion( export async function getStreamedCompletionText( messages: ChatCompletionMessageParam[], abortController: AbortController, - options?: { maxTokensCap?: number } + // `workspace` and `info` send it for that workspace, with its AI config, rather than the tab's. + options?: { maxTokensCap?: number; workspace?: string; info?: CopilotInfo } ): Promise { + const modelProvider = modelFor(options?.info) const drain = async (forceCompletions: boolean) => { const stream = await getCompletion(messages, abortController, undefined, { forceCompletions, - maxTokensCap: options?.maxTokensCap + forceModelProvider: modelProvider, + maxTokensCap: options?.maxTokensCap, + workspace: options?.workspace, + info: options?.info }) let text = '' let finished = false @@ -1215,7 +1255,7 @@ export async function getStreamedCompletionText( } catch (error) { // The Responses API stream only fails once iterated, so the fallback to // chat completions for a deployment that doesn't serve it lives here. - const { provider, model } = getCurrentModel() + const { provider, model } = modelProvider if (abortController.signal.aborted || !usesOpenAIResponsesApi(provider, model)) { throw error } diff --git a/frontend/src/lib/components/copilot/loadCopilot.test.ts b/frontend/src/lib/components/copilot/loadCopilot.test.ts index 5bfcf1f547..a54d3be0ec 100644 --- a/frontend/src/lib/components/copilot/loadCopilot.test.ts +++ b/frontend/src/lib/components/copilot/loadCopilot.test.ts @@ -11,7 +11,12 @@ vi.mock('$lib/gen', () => ({ })) import { loadCopilot } from './loadCopilot' -import { copilotWorkspace } from '$lib/aiStore' +import { + copilotInfo, + copilotWorkspace, + getWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo +} from '$lib/aiStore' const config = { providers: { anthropic: { resource_path: 'u/admin/anthropic', models: ['m'] } } } @@ -34,16 +39,34 @@ describe('loadCopilot', () => { it('lets a re-requested workspace win back over the one that superseded it', async () => { const a1 = loadCopilot('a') const b = loadCopilot('b') - // A per-workspace cache would hand back `a1` here — which has already lost the - // apply race to `b`, so `a` would silently never be written. + // `a2` may share `a1`'s download but must apply it on its own token: `a1` already lost + // the apply race to `b`, so handing back `a1` itself would leave `a` never written. const a2 = loadCopilot('a') - expect(requests.map((r) => r.workspace)).toEqual(['a', 'b', 'a']) + expect(requests.map((r) => r.workspace)).toEqual(['a', 'b']) requests[0].resolve(config) requests[1].resolve(config) - requests[2].resolve(config) await Promise.all([a1, b, a2]) expect(get(copilotWorkspace)).toBe('a') }) + + // The config can change elsewhere (another tab, another admin): a refresh of the tab's config + // must also be what a session in that workspace sends with. + it('refreshes the workspace config sessions send with, keeping the old one until then', async () => { + const withModel = (model: string) => ({ + providers: { anthropic: { resource_path: 'u/admin/anthropic', models: [model] } } + }) + const sessionLoad = loadWorkspaceCopilotInfo('refreshed') + requests[0].resolve(withModel('old')) + await sessionLoad + const refresh = loadCopilot('refreshed') + await vi.waitFor(() => expect(requests).toHaveLength(2)) + expect(getWorkspaceCopilotInfo('refreshed')?.aiModels[0]?.model).toBe('old') + requests[1].resolve(withModel('new')) + await refresh + + expect(get(copilotInfo).aiModels[0]?.model).toBe('new') + expect(getWorkspaceCopilotInfo('refreshed')?.aiModels[0]?.model).toBe('new') + }) }) diff --git a/frontend/src/lib/components/copilot/loadCopilot.ts b/frontend/src/lib/components/copilot/loadCopilot.ts index 4b1e53a686..62a97e8dbf 100644 --- a/frontend/src/lib/components/copilot/loadCopilot.ts +++ b/frontend/src/lib/components/copilot/loadCopilot.ts @@ -1,5 +1,9 @@ -import { WorkspaceService } from '$lib/gen' -import { copilotWorkspace, setCopilotInfo } from '$lib/aiStore' +import { + applyCopilotInfo, + copilotWorkspace, + loadWorkspaceCopilotInfo, + setCopilotInfo +} from '$lib/aiStore' import { setAiClientWorkspace } from './aiClientWorkspace' import { writable } from 'svelte/store' @@ -44,9 +48,11 @@ export function loadCopilot(workspace: string): Promise { async function fetchAndApply(workspace: string, token: number) { setAiClientWorkspace(workspace) try { - const info = await WorkspaceService.getCopilotInfo({ workspace }) + // Through the per-workspace cache: a session in this workspace then sends with the config + // the tab shows. + const info = await loadWorkspaceCopilotInfo(workspace, true) if (token !== loadCopilotToken) return - setCopilotInfo(info) + applyCopilotInfo(info) copilotWorkspace.set(workspace) } catch (err) { if (token !== loadCopilotToken) return diff --git a/frontend/src/lib/components/dedicated_worker.ts b/frontend/src/lib/components/dedicated_worker.ts index 21ec971990..8fbdff7f85 100644 --- a/frontend/src/lib/components/dedicated_worker.ts +++ b/frontend/src/lib/components/dedicated_worker.ts @@ -20,9 +20,19 @@ export async function dedicatedWorkerTag(workspaceId: string, path: string): Pro // Same rule as `dedicated_worker_pattern_prefix()` in backend/windmill-common/src/worker.rs: // `f/dw/*` stands for every dedicated script under `f/dw/`. Flows are listed one by one. export function isDedicatedPattern(path: string): boolean { - return ( - path.endsWith('/*') && path.length > 2 && !path.startsWith('flow/') && !path.includes(':') - ) + return path.endsWith('/*') && path.length > 2 && !path.startsWith('flow/') && !path.includes(':') +} + +// One leading `/` is dropped; `//` and a lone `/` are kept as written, as +// `WorkspacedPath::dedicated` in backend/windmill-common/src/worker.rs reads an entry. +function canonicalPath(path: string): string { + return path.length > 1 && path[0] === '/' && path[1] !== '/' ? path.substring(1) : path +} + +export function canonicalTag(tag: string): string { + const parsed = parseTag(tag) + if (!parsed) return tag + return `${parsed.workspace}:${parsed.type === 'flow' ? 'flow/' : ''}${parsed.path}` } export function parseTag( @@ -32,10 +42,13 @@ export function parseTag( if (colonIndex === -1) return null const workspace = tag.substring(0, colonIndex) - const rest = tag.substring(colonIndex + 1) + const raw = tag.substring(colonIndex + 1) + const rest = canonicalPath(raw) if (rest.startsWith('flow/')) { - return { workspace, type: 'flow', path: rest.substring(5) } + // Only an entry written `flow/…` has its flow path read; `/flow/…` is a path read whole + const path = rest.substring(5) + return { workspace, type: 'flow', path: raw.startsWith('flow/') ? canonicalPath(path) : path } } else if (isDedicatedPattern(rest)) { return { workspace, type: 'pattern', path: rest } } else { @@ -45,7 +58,7 @@ export function parseTag( export async function computeHashedTag(rawTag: string): Promise { const parsed = parseTag(rawTag) - if (!parsed || parsed.type === 'pattern') return rawTag + if (!parsed || parsed.type === 'pattern') return canonicalTag(rawTag) const fullPath = parsed.type === 'flow' ? `flow/${parsed.path}` : parsed.path return dedicatedWorkerTag(parsed.workspace, fullPath) } diff --git a/frontend/src/lib/components/deploymentRequest/AiReview.svelte b/frontend/src/lib/components/deploymentRequest/AiReview.svelte index 0af4488718..33964f60cc 100644 --- a/frontend/src/lib/components/deploymentRequest/AiReview.svelte +++ b/frontend/src/lib/components/deploymentRequest/AiReview.svelte @@ -1,7 +1,12 @@